Ignore comma inside #define macro call - objective-c

I created a special console log function macro. It works successfully except when there's a comma in the parameter, even if it's part of another expression, i.e. not another argument. I think it's due to the fact that macros are expanded at the pre-processing stage, so the semantic analysis hasn't occurred yet to understand that the comma is not another argument. Here is what I mean:
#define FANCY_LOG(message) [MyLogger logDebug:message withClassAndMethodName: __PRETTY_FUNCTION__ lineNumber: __LINE__];
+(BOOL)logDebug:(NSString *)message withClassAndMethodName:(const char *)name lineNumber:(int)lineNumber;
These work:
FANCY_LOG(#"Hello world");
FANCY_LOG([NSString stringWithFormat:#"Hello!"]);
This does not work:
FANCY_LOG([NSString stringWithFormat:#"Hello %#!", planet]);
Although the comma obviously is part of the NSString expression, the macro interprets it as another argument, I get the following error:
Too many arguments provided to function-like macro invocation
Here's what I have tried unsuccessfully (and variants of these):
#define FANCY_LOG(...) [MyLogger logDebug:##__VA_ARGS___ withClassAndMethodName: __PRETTY_FUNCTION__ lineNumber: __LINE__];
#define FANCY_LOG(message) [MyLogger logDebug:#message withClassAndMethodName: __PRETTY_FUNCTION__ lineNumber: __LINE__];

You are doing that wrong. First of all there are lots of great ready solutions so you do not have reinvent the wheel (don't remember for sure but I think CocoaLumberjack is best).
And your logger can look like this (I've got rusty with Objective C):
+(void) function:(char *)methodName
inLine:(int)line
logs:(NSString *)format, ...;
...
#define FANCY_LOG(...) [MyLogger function: __PRETTY_FUNCTION__ \
inLine: __LINE__ \
logs: __VA_ARGS__]
// then usage:
FANCY_LOG(#"Hello %#!", planet);

Related

Why can't I use yytext inside yyerror (Yacc)

Im having some trouble with my analizer. I.m trying to use yytext inside my yyerror but it shows me this error, can you help me?
You can't use yytext in your parser because it is defined by the lexer.
Indeed, you normally shouldn't use yytext in your parser because its value is not meaningful to the parse. Your attempt to use it to provide context in error messages is just about the only reasonable use, and even then there is a certain ambiguity because you can't tell whether the erroneous token is the one currently in yytext or the previous token, which was overwritten when the parser obtained its lookahead token.
In any case, if you want to refer to yytext inside your parser, you'll need to declare it, which will normally require putting
extern char* yytext;
into your bison grammar file. Since the only place you can reasonably use yytext is yyerror, you might change the definition of that function to:
void yyerror(const char* msg) {
extern char* yytext;
fprintf(stderr, "%s at line %d near '%s'\n", msg, nLineas, yytext);
}
Note that you can get flex to track line numbers automatically, so you don't need to track your own nLineas variable. Just add
%option yylineno
at the top of your flex file, and the global variable yylineno will automatically be maintained during lexical analysis. If you want to use yylineno in your parser, you'll need to add an an extern declaration for it as well:
extern int yylineno;
Again, using yylineno in the parser may be imprecise because it might refer to the line number of the token following the error, which might be on a different line from the error (and might even be separated from the error by many lines of comments).
As an alternative to using external declarations of yytext and yylineno, you are free to put the implementation of yyerror inside the scanner definition instead of the grammar definition. Your grammar file should already have a forward declaration of yyerror, so it doesn't matter which file it's placed in. If you put it into the scanner file, global scanner variables will already be declared.

How to disable a specific warning in g++

First of all I don't know why "g++ -std=c++0x -Wall" would give me warning: invalid suffix on literal; C++11 requires a space between literal and string macro [-Wliteral-suffix] on the following program:
#include <iostream>
#define BEGIN "<b>"
#define END "</b>"
#pragma GCC diagnostic ignored "-Wliteral-suffix"
int main()
{
std::cout << "hello " BEGIN"world"END "\n";
}
Second, I followed gcc doc to ignore "-Wliteral-suffix" but still got the warning. How do I suppress the warning? And why does the compiler warn in the first place?
Ok, to summarize: the failure to suppress the warning is a known gcc bug (gcc.gnu.org/bugzilla/show_bug.cgi?id=61653). Since you cannot (and really, should not) suppress the warning, the easiest fix is to put a space between the literal and the #define string. You can safely do this; it won't change the output text.
The reason this is no longer allowed is because characters directly after a literal string are treated as user-defined literals, which is a new feature in C++11. User-defined literals are considered to be part of the same single token as the literal they modify, thus END will not be subject to replacement by the earlier #define.

A code doesn't work but the equivalent code works

#define CLog( s, ... ) NSLog( #"%#", [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#define PO(x) CLog(##x ": %#", x)
Then I do:
NSString * hello =[NSString stringWithFormat:#"%#, %#",theCatalogData.id,#(theCatalogData.images.count)];
PO(hello);
Works
Of course, a shortened version of this is simply:
PO([NSString stringWithFormat:#"%#, %#",theCatalogData.id,#(theCatalogData.images.count)]);
That doesn't work. I wonder why.
No emergency. No problem. The longer equivalent works anyway. I just want to understand how the compiler parses the macro to see why things don't work.
Since the pre-processor does not really understand syntax in itself, macro parameters containing commas will cause problems.
In the second case, since the parameter contains two commas outside of quotes, the compiler thinks the macro is getting 3 parameters instead of one, and since the macro takes only one parameter, the compiler will complain.
A simplified test case similar to your second case;
#define TEST(a,b,c) a
TEST([d e:#"%#, %#", f, g])
will expand to;
[d e:#"%#, %#"
which shows that the a parameter only contains all characters up to the first un-quoted comma.
In your case, you define the TEST macro to take one parameter and since the pre-processor considers it 3, compilation will fail.

Xcode - replace function with regex and two-digit capture group (back reference)

I would like to use the Xcode's find in project option to normalize the signatures of methods.
I wrote the find expression:
^\s*([+-])\s*\((\w+)\s*(\*?)\s*\)\s*(\w+)(\s*(:)\s*(\()\s*(\w+)\s*(\*?)\s*(\))\s*(\w+))?
and the replacement expression:
\1 \(\2\3\)\4\6\7\8\9\10\11
The test string is:
+(NSString *) testFunction : (NSInteger ) arg1
and the desired result:
+ (NSString*)testFunction:(NSInteger)arg1
Unfortunatelly Xcode isn't able to recognize te two digit capture group \10 and translates it to \1 and '0' character and so long. How to solve this problem or bug?
Thanks in advance,
MichaƂ
I believe #trojanfoe is correct; regexes can only have nine capture groups. This is waaay more than you need for your particular example, though.
^\s*([+-])\s*\((\w+)\s*(\*?)\s*\)\s*(\w+)(\s*(:)\s*(\()\s*(\w+)\s*(\*?)\s*(\))\s*(\w+))?
\1 \(\2\3\)\4\6\7\8\9\10\11
The first thing I notice is that you're not using \5, so there's no reason to capture it at all. Next, I notice that \6 corresponds to the regex (:), so you can avoid capturing it and replace \6 with : in the output. \7 corresponds to (\(), so you can replace \7 with ( in the output. ...Iterating this approach yields a much simpler pair of regexes: one for zero-argument methods and one for one-argument methods.
^\s*([+-])\s*\((\w+)\s*(\*?)\s*\)\s*(\w+)
\1 \(\2\3\)\4
^([+-] \(\w+\*?\)\w+)\s*:\s*\(\s*(\w+)\s*(\*?)\s*\)\s*(\w+)
\1:\(\2\3\)\4
Notice that I can capture the whole regex [+-] \(\w+\*?\)\w+ without all those noisy \s*s, because it's been normalized already by the first regex's pass.
However, this whole idea is a huge mistake. Consider the following Objective-C method declarations:
-(const char *)toString;
-(id)initWithA: (A) a andB: (B) b andC: (C) c;
-(NSObject **)pointerptr;
-(void)performBlock: (void (^)(void)) block;
-(id)stringWithFormat: (const char *) fmt, ...;
None of these are going to be parsed correctly by your regex. The first one contains a two-word type const char instead of a single word; the second has more than one parameter; the third has a double pointer; the fourth has a very complicated type instead of a single word; and the fifth has not only const char but a variadic argument list. I could go on, through out parameters and arrays and __attribute__ syntax, but surely you're beginning to see why regexes are a bad match for this problem.
What you're really looking for is an indent program (named after GNU indent, which unfortunately doesn't do Objective-C). The best-known and best-supported Objective-C indent program is called uncrustify; get it here.

ATI OpenCL printf extension issue with char* argument passed to a function

I use OpenCL on an ATI card with the printf extension enabled. I've written a function to print out variables:
void printVar(constant char* name, float var)
{
printf("%s: %f\r\n", name, var);
}
This code works as expected when compiled as plain C, but if i invoke it in OpenCL with
printVar("foo", 0.123);
the result is always some random char followed by 0.123 instead of "foo: 0.123". I guess the compiler has problems with recognizing the char* string, is there a workaround or a fix so i can get the function working?
As I mentioned in my comment I also get the same behavior, however I can suggest a simple workaround for the use case you showed, I.e. when the string is known at compile time we could just use a define statement instead:
#define PRINTVAR(N,X) (printf(N ": %f\r\n", X))