clang-format: Do not add white spaces to include statement/method references - code-formatting

I'm using clang-format to format code.
I noticed that it adds white spaces to include statements and fully qualified method references.
Given the following ("correctly formatted") piece of code:
#include bli/bla/blub/_foo;
fun()
{
bli/bla/blub/_foo::bar();
}
When running it through clang-format, it turns it into this:
#include bli / bla / blub / _foo;
fun() { bli / bla / blub / _foo::bar(); }
I do not want the spaces to be added before and after the / since the path may not be modified. The curly bracket placements don't matter.
I'm not sure how to accomplish this, I've taken a look at the documentation here but I didn't see a respective style option. Any ideas/help on fixing this?

That code is not valid C++, so clang-format doesn't behave the way you might expect (I'm assuming C++ is what you're going for).
The statement #include bli/bla/blub/_foo; should have double quotes before and after the header path, and the semicolon omitted.
For fully qualifying symbols in C++, you have to use :: for the seperator, so bli/bla/blub/_foo::bar(); is not valid C++, either.
In the include statement, since double quotes are missing, clang-format sees bli/bla/blub/_foo as "bli divided by bla divided by blub divided by _foo::bar()" - just as any C/C++ compiler would - and adds spaces between / and the operands, which seems sensible.
If you feed clang-format with proper C++ code, for example:
#include "bli/bla/blub/_foo"
void fun()
{
bli::bla::blub::_foo::bar();
}
You'd get:
#include "bli/bla/blub/_foo"
void fun() {
bli::bla::blub::_foo::bar();
}

Related

yacc lex when parsing CNC GCODES

I have to parse motion control programs (CNC machines, GCODE)
It is GCODE plus similar looking code specific to hardware.
There are lots of commands that consist of a single letter and number, example:
C100Z0.5C100Z-0.5
C80Z0.5C80Z-0.5
So part of my (abreviated) lex (racc & rex actually) looks like:
A {[:A,text]}
B {[:B,text]}
...
Z {[:Z,text]}
So I find a command that takes ANY letter as an argument, and in racc started typing:
letter : A
| B
| C
......
Then I stopped, I haven't used yacc is 30 years, is there some kind of shortcut for the above? Have I gone horribly off course?
It is not clear what are you trying to accomplish. If you want to create Yacc rule that covers all letters you could create token for that:
%token letter_token
In lex you would find with regular expressions each letter and simply return letter_token:
Regex for letters {
return letter_token;
}
Now you can use letter_token in Yacc rules:
letter : letter_token
Also you haven't said what language you're using. But if you need, you can get specific character you assigned with letter_token, by defining union:
%union {
char c;
}
%token <c> letter_token
Let's say you want to read single characters, Lex part in assigning character to token would be:
[A-Z] {
yylval.c = *yytext;
return letter_token;
}
Feel free to ask any further questions, and read more here about How to create a Minimal, Complete, and Verifiable example.

How can you implement this multiline string literal macro in Swift?

In my Objective-C code for my GPUImage framework, I have the following macro:
#define STRINGIZE(x) #x
#define STRINGIZE2(x) STRINGIZE(x)
#define SHADER_STRING(text) # STRINGIZE2(text)
which allows me to inline multiline vertex and fragment shaders as NSString literals within my custom filter subclasses, like this:
NSString *const kGPUImagePassthroughFragmentShaderString = SHADER_STRING
(
varying highp vec2 textureCoordinate;
uniform sampler2D inputImageTexture;
void main()
{
gl_FragColor = texture2D(inputImageTexture, textureCoordinate);
}
);
GPUImage needs this in order to provide formatted vertex and fragment shaders that are included in the body text of filter subclasses. Shipping them as separate files would make the framework unable to be compiled into a static library. Using the above macro, I can make these shaders able to be copied and pasted between the framework code and external shader files without a ridiculous amount of reformatting work.
Swift does away with compiler macros, and the documentation has this to say:
Complex macros are used in C and Objective-C but have no counterpart
in Swift. Complex macros are macros that do not define constants,
including parenthesized, function-like macros. You use complex macros
in C and Objective-C to avoid type-checking constraints or to avoid
retyping large amounts of boilerplate code. However, macros can make
debugging and refactoring difficult. In Swift, you can use functions
and generics to achieve the same results without any compromises.
Therefore, the complex macros that are in C and Objective-C source
files are not made available to your Swift code.
Per the line "In Swift, you can use functions and generics to achieve the same results without any compromises", is there a way in Swift to provide multiline string literals without resorting to a string of concatenation operations?
Alas Swift multiline strings are still not available, as far as I know. However when doing some research regarding this, I found a workaround which could be useful. It is a combination of these items:
A Quick Hack to Quote Swift Strings in a Playground - Describing how to make an service replacing and fixing texts
The comment by pyrtsa, regarding using "\n".join(...) to emulate the multiline strings
Setup an automated service
Using Automator you could set up an extra service with the following properties:
A single action of "Run Shell Script"
Tick off the "Output replaces selected text"
Change shell to /usr/bin/perl
Add the code excerpt below to the action window
Save as something like "Replace with quoted swift multiline join"
Code excerpt
print "\"\\n\".join([\n"; # Start a join operation
# For each line, reformat and print
while(<>) {
print " "; # A little indentation
chomp; # Loose the newline
s/([\\\"])/\\$1/g; # Replace \ and " with escaped variants
print "\"$_\""; # Add quotes around the line
print "," unless eof # Add a comma, unless it is the last line
print "\n"; # End the line, preserving original line count
}
print " ])"; # Close the join operation
You are of course free to use whatever shell and code you want, I chose perl as that is familiar to me, and here are some comments:
I used the "\n".join(...) version to create the multiline string, you could use the extension answer from Swift - Split string over multiple lines, or even the + variant, I'll leave that as an exercise for the user
I opted for a little indentation with spaces, and to replace the \ and " to make it a little sturdier
Comments are of course optional, and you could probably shorten the code somewhat. I tried to opt for clarity and readability
The code, as is, preserves spaces, but you could be edited if that is not wanted. Also left as an exercise for the user
Usage of service
Open up your playground or code editor, and insert/write some multline text:
Mark the text block
Execute Xcode (or similar) > Services > Replace with quoted swift multiline join
You now have a multiline string in proper swift coding. Here are an example of before and after text:
Here is my multiline text
example with both a " and
a \ within the text
"\n".join([
"Here is my multiline text ",
"example with both a \" and",
"a \\ within the text"
])
It looks like your end goal is to avoid including standalone shader files?
If so one technique would be to write a quick command line utility that generates a .swift file of string constants representing the shader functions in a certain folder.
Include the resulting .swift file in your project and you have no runtime penalty, and even easier debugging if you generate the code nicely.
Would probably take less than an hour, never need macros again for shaders.

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.

# sign as a prefix in Objective C

Can anyone explain for me what the purpose when we are doing like this
#if
// block of codes goes here
#endif
They're C preprocessor directives. http://en.wikipedia.org/wiki/C_preprocessor
They are preprocessor directives. Preprocessor directives are lines included in the code of our programs that are not program statements but directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements.
These preprocessor directives extend only across a single line of code. As soon as a newline character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at the end of a preprocessor directive. The only way a preprocessor directive can extend through more than one line is by preceding the newline character at the end of the line by a backslash ().
For more detail refer Preprocessor directives and Using Objective-C Preprocessor Directives
As mentioned by others, the tags prefixed with # are directives to the preprocessor that result in a modification of the code that goes on to be compiled. More specifically, the example you present relates to conditional compilation. A common use case would relate to compiling in DEBUG versus RELEASE mode, where selected code would be included or excluded by the preprocessor as follows:
#define DEBUG
#ifdef DEBUG
// block of codes goes here - only survives preprocessing if in DEBUG mode
#endif
In this case the code may log an output message or perform some other action that you would only want to occur in DEBUG mode. If you wish to compile in DEBUG mode, you define DEBUG; otherwise, you simple comment it out. Alternatively, the definition of DEBUG can be performed with a compiler switch. Further discussion of that, and use of the preprocessor for debug mode conditional compilation in general, see question 987637/define-debug-1.

How to program Lex and Yacc to parse a partial file

Let me tell with an example.
Suppose the contents of a text file are as follows:
function fun1 {
int a, b, c;
function fun2 {
int d, e;
char f g;
function fun3 {
int h, i;
}
}
In the above text file, the number of opening braces are not matching the number of closing braces. The file as a whole doesn't follow the syntax. However the partial functions fun2 and fun3 follows the syntax. Typically the text file is very large.
If the user wants to parse the entire file ie function fun1, then the program should output an error as the braces are not matching. However, if the user wants to parse only the partial file ie function fun2/fun3, then the program shouldn't throw out an error as the braces are matching.
I have a question now
1. Is there a way to let the Lex and Yacc load only a
partial file ? If so then how it needs to be done.
Are you using bison/flex or plain old yacc/lex ?
It's a long time I played with yacc.
The technical answer is different for both pair of tool.
With flex you'll have to deal with the buffer mechanism.
The final code will be cleaner.
With lex you'll have to do all by hand.
At least you have to redefine input and unput macro.
You can also try to play with yyin and fseek.
On the parser side you'll have to deal with error management (yyerrok macro) and error token
http://dinosaur.compilertools.net/bison/bison_9.html#SEC81