Strange Objective-C/C `enum` behavior - objective-c

I have this strange issue:
When I create an enum like this:
typedef enum {
kParcelStatusInTransit,
kParcelStatusArrived,
kParcelStatusDelivered,
kParcelStatusUnknown
} ParcelStatus;
I get an error: expected identifier before numeric constant
When I add even the smallest change to the members name, I get no error:
typedef enum {
kChangeParcelStatusInTransit,
kChangeParcelStatusArrived,
kChangeParcelStatusDelivered,
kChangeParcelStatusUnknown
} ParcelStatus;
How is this possible? What numeric constant is the error talking about? It makes no sense to me...

One of the constants has been #defined in another file. Because of this, the preprocessor replaces the identifier in the enum with its value. The compiler then sees this constant value and complains, since it expected an identifier.

Chances are that one of the named constants you're trying to define is already defined in another header, possibly in one of Apple's frameworks. You'll simply need to pick a different name for your constants.

It sounds like you are defining the enum more than once, either literally or by including the file incorrectly.

In addition I can say, compiling Your file with -E option and locating Your error code in a result file will help You to see what happened.
F.e.: cc -E myfile.c | grep -B 6 ParcelStatus

Related

NSErrorDomain + NS_ERROR_ENUM makes type lookup ambiguous. Why?

I have an error that used to look like this in Objective-C
NSString * const JKConfigurationErrorDomain;
typedef NS_ENUM(NSInteger, JKConfigurationCode) {
JKConfigurationCodeUnknown,
JKConfigurationCodeSomethingBad,
JKConfigurationCodeParsing,
};
Now, this is ugly to use in Swift. But since Swift 4, we can use NSErrorDomain and NS_ERROR_ENUM to make the imported error much nicer in Swift:
NSErrorDomain const JKConfigurationErrorDomain;
typedef NS_ERROR_ENUM(JKConfigurationErrorDomain, JKConfigurationCode) {
JKConfigurationCodeUnknown,
JKConfigurationErrorSomethingBad,
JKConfigurationErrorParsing,
};
This means I can now do stuff in Swift like this:
if let myError = error as? JKConfigurationError, myError.code = .somethingBad {
// handle it
}
instead of having to cast error to NSError, then check its .domain then look at the .code which is an integer, etc.
So far, so good. But my library is called JKConfiguration and there is already a JKConfiguration object (the center piece of the library) in there and as soon as I start using JKConfiguration anywhere in the library code I get an error:
'JKConfiguration' is ambiguous for type lookup in this context
I don't get it, why? What does NSErrorDomain or NS_ERROR_ENUM do such that the type lookup becomes ambiguous and how can I fix it?
What I tried already:
use NS_SWIFT_NAME on the NS_ERROR_ENUM typedef and rename it to something else. Looking at the generated Swift header, the rename works, but doesn't solve the issue
Change the name of the error domain (and thus of the generated error type in Swift). Seems to work according to the generated Swift header, but the issue still persists. Why is that?
The issue is not, as I initially thought, in the name of the error domain. Nor is it a problem with the library name. It’s a problem of the error enum‘s name, in the example above: JKConfigurationCode.
What the Compiler does for the enum cases of an NS_ERROR_ENUM is two-fold:
use the name of the enum and remove that prefix from all enum cases before importing them to swift
create an enum with the given name to hold those cases. If the given name ends with Code remove that suffix.
So that last part is the issue. It means that NS_ERROR_ENUM(AnyDomainName, JKConfigurationCode) generates an enum in Swift to hold the error codes with the name JKConfiguration (without the Code) prefix. But that type already exists in my example, which leads to the ambiguity.
So the solution is to change
NS_ERROR_ENUM(JKConfigurationErrorDomain, JKConfigurationCode)
to
NS_ERROR_ENUM(JKConfigurationErrorDomain, JKConfigurationSomethingCode)
Or similar.
Don’t forget to update all the prefixes of your enum cases though, as it seems the compiler won’t find them if the prefixes don’t match the enum name.
Why doesn’t NS_SWIFT_NAME work to rename the enum?
Best I can tell, NS_SWIFT_NAME causes the type to be renamed but not the cases. This leads to an empty type (Swift chooses a struct in that case) being generated for the error code as Swift doesn’t seem to find the cases. And the original container for the enum cases still has the offending name.

Derive string from const enum

I have the following in my constants file:
typedef enum
{
AnimalTypeBear,
AnimalTypeCamel,
AnimalTypeCow,
AnimalTypeCount
}
AnimalType;
If I declare an AnimalType variable somewhere in my code like following and set it to AnimalTypeBear:
AnimalType animalType = 0;
Is there away to somehow derive the string "Bear" from that animalType variable or just in general to access the string of its corresponding constant type (in this case AnimalTypeBear).
Enums are constant expressions like #define. Enums at compile time will be "translated" into the code as constants (while #define will be evaluated before compilation). So basically it is not possible to reference the enum string in this way.
As suggested by others you can use a string array.
You cannot do this without code in (Objective-)C. If you want to be able to use actual enumeration literals as strings in your code, or during I/O, with language support then you need to use a language with enumeration type support such as Pascal or Ada.
If you are keen to have this and don't mind work as long as it is reusable then you need to learn about reading the symbol tables structures from a binary and make sure that the information is not stripped from your application. You'll see the debugger can show the correct literals, also if you use Xcode's "Product > Generate Output > Assembly File" menu item you'll see the literals are in there as strings. It will be a lot of work for you, but would be reusable once done.
After that give up and write some code - a simple static array of labels and an index operation. Yes, it's a maintenance headache if you ever change your enumeration.
Alternatively you can write some different code, say in Ruby... Xcode supports adding your own file "types" and running scripts to (pre-)process them. So you could define, say, a file type ".enum" and use a Ruby script to convert that into a C enumeration definition and code to provide the strings. Apple has examples of using Ruby to pre-process files in this way. Once you have your script Xcode will do the rest, on each compilation it will run your script to convert your ".enum" into ".m" (or ".c") and the compile the result. This approach is usually best though for files which contain only one thing, e.g. localised string file processing, you don't usually write your enum declarations in their own files.

How does compiler handle missing parameter names in Objective-C?

I have run into someone else's code that declares methods like this:
- (void) method:(id)a:(NSString*)b { }
The compiler accepts this code, giving just a warning:
'a' used as the name of the previous parameter rather than as part of the selector
The code declares various functions with this type and then invokes them through NSSelectorFromString, using the signature "methodname::". So it's all consistent.
I wonder if that method signature is just a mistake or if there's more to it. Since it's used consistently in the code, I don't think this is a typo. I don't know the author so I can't tell if this is code of a genius or the opposite.
Is 'b' an anonymous parameter? (If so, shouldn't it rather be written with a blank between the "a" and ":" to indicate this better?) I can't find anything about anon parms in the ObjC docs, though.
Will there be any change in behavior if I change the syntax to giving the second parameter a name, and fixing the signature reference accordingly? I plan to make this change to get rid of the warnings, but I wonder I might create an issue that I'm not aware of.
Everything you describe is pretty much correct. It's very bad style, but technically it's just a two-argument selector which happens to have no text before the second :. I wouldn't call b an anonymous argument since you can still give it a name, it just doesn't have any descriptive text before it as part of the selector's name.
Yes, there should probably be a space after the a.
If you want to rename it, you can use Xcode's standard Refactor->Rename functionality and just insert some text before the second :. It will update all the references and you should encounter no problems.
You can use the signature method::, even though it is not recommended by most people.
Just insert a space character before each : separating the parameters, and the compiler is happy:
- (void) method:(id)a :(NSString*)b
On page 16 "Message Syntax" of The Objective-C Programming Language
this is called an "unlabeled argument", or an "argument without keyword".
Of course you can change it to
- (void) method:(id)a withB:(NSString*)b
but this changes the selector to method:withB:.

Obiective-C, find global variable at Runtime?

I am curious to know if there is any way to find a global variable at runtime, much like NSClassFromString. The variable, a BOOL, is defined in a static library and I found the name by using "nm" which gave this output: "0001924d b _gStartSessionCalled". When debugging in XCode I can add an expression "gStartSessionCalled" and see the value change as the app is running.
What I want to do is find the value of gStartSessionCalled and also change the value. I know it's kind of weird to do this but please disregard the reason why.
The lowercase letter "b" in the nm output
0001924d b _gStartSessionCalled
indicates that gStartSessionCalled is a local (non-external) symbol. It could for example be defined as
static BOOL gStartSessionCalled;
in your library. As far as I know, you cannot access local symbols from outside the object file in which it they are defined.
The debugger can use the symbol table to find the address and display the variable, but the linker refuses to link against a local symbol from a different object file.
A global variable is not an Objective-C specific construct. It is plain C and you can access every global variable when knowing its name by declaring it like
extern <type> <name>;
e.g. in your case
extern BOOL gStartSessionCalled;
…
gStartSessionCalled = YES;
Update:
If you do not know the name of the variable at compile time, you still may find the symbols address at runtime using something like dlsym. I don't know if it is the same on MacOS as on Linux, but there will be something similar.

Write a compiler for a language that looks ahead and multiple files?

In my language I can use a class variable in my method when the definition appears below the method. It can also call methods below my method and etc. There are no 'headers'. Take this C# example.
class A
{
public void callMethods() { print(); B b; b.notYetSeen();
public void print() { Console.Write("v = {0}", v); }
int v=9;
}
class B
{
public void notYetSeen() { Console.Write("notYetSeen()\n"); }
}
How should I compile that? what i was thinking is:
pass1: convert everything to an AST
pass2: go through all classes and build a list of define classes/variable/etc
pass3: go through code and check if there's any errors such as undefined variable, wrong use etc and create my output
But it seems like for this to work I have to do pass 1 and 2 for ALL files before doing pass3. Also it feels like a lot of work to do until I find a syntax error (other than the obvious that can be done at parse time such as forgetting to close a brace or writing 0xLETTERS instead of a hex value). My gut says there is some other way.
Note: I am using bison/flex to generate my compiler.
My understanding of languages that handle forward references is that they typically just use the first pass to build a list of valid names. Something along the lines of just putting an entry in a table (without filling out the definition) so you have something to point to later when you do your real pass to generate the definitions.
If you try to actually build full definitions as you go, you would end up having to rescan repatedly, each time saving any references to undefined things until the next pass. Even that would fail if there are circular references.
I would go through on pass one and collect all of your class/method/field names and types, ignoring the method bodies. Then in pass two check the method bodies only.
I don't know that there can be any other way than traversing all the files in the source.
I think that you can get it down to two passes - on the first pass, build the AST and whenever you find a variable name, add it to a list that contains that blocks' symbols (it would probably be useful to add that list to the corresponding scope in the tree). Step two is to linearly traverse the tree and make sure that each symbol used references a symbol in that scope or a scope above it.
My description is oversimplified but the basic answer is -- lookahead requires at least two passes.
The usual approach is to save B as "unknown". It's probably some kind of type (because of the place where you encountered it). So you can just reserve the memory (a pointer) for it even though you have no idea what it really is.
For the method call, you can't do much. In a dynamic language, you'd just save the name of the method somewhere and check whether it exists at runtime. In a static language, you can save it in under "unknown methods" somewhere in your compiler along with the unknown type B. Since method calls eventually translate to a memory address, you can again reserve the memory.
Then, when you encounter B and the method, you can clear up your unknowns. Since you know a bit about them, you can say whether they behave like they should or if the first usage is now a syntax error.
So you don't have to read all files twice but it surely makes things more simple.
Alternatively, you can generate these header files as you encounter the sources and save them somewhere where you can find them again. This way, you can speed up the compilation (since you won't have to consider unchanged files in the next compilation run).
Lastly, if you write a new language, you shouldn't use bison and flex anymore. There are much better tools by now. ANTLR, for example, can produce a parser that can recover after an error, so you can still parse the whole file. Or check this Wikipedia article for more options.