uncrustify: function definition argument indenting on separate line - uncrustify

I have this:
char *
foo(a,b)
int a;
int b;
{
...
}
I want this:
char *
foo(a,b)
int a;// indented
int b;// indented
{
...
}
The indenting works for function body code but I cannot find an option to make this style of argument (old style code being resurrected) indented.
Which directive can do this? I have tried all that seem remotely appropriate.

Related

uncrustify: can I control where it decides to break apart lines?

I've been trying out uncrustify and while I've gotten a lot of mileage out of how configurable it is, I found it occasionally decides to break apart lines in ways I don't agree with.
Some examples:
void functionWithLongName(int parameter1, int parameter2, int parameter3, int parameter4) {
}
..becomes:
void functionWithLongName(int parameter1, int parameter2, int parameter3, int
parameter4) {
}
I'd rather have it be:
void functionWithLongName(int parameter1, int parameter2, int parameter3,
int parameter4) {
}
...as I'd prefer for it not to break apart the type and variable name, as well as any qualifiers.
Another example:
ClassName::ClassName(int importantValue) : memberVariable1(0), memberVariable2(importantValue), memberVariable3(0) {}
...becomes:
ClassName::ClassName(int importantValue) : memberVariable1(0), memberVariable2(
importantValue), memberVariable3(0) {}
But I don't want it to break between the parentheses of one of these initializers. I'd much prefer something like:
ClassName::ClassName(int importantValue) : memberVariable1(0),
memberVariable2(importantValue), memberVariable3(0) {}
Going through crustify's docs I haven't found settings that lets me specify this. Is there a way to do this?
In case it helps, here is my current uncrustify config file.
It looks like the problem was having ls_code_width set to true. Once I set it to false, uncrustify now seems to try to maintain groupings.

Determine types from a variadic function's arguments in C

I'd like a step by step explanation on how to parse the arguments of a variadic function
so that when calling va_arg(ap, TYPE); I pass the correct data TYPE of the argument being passed.
Currently I'm trying to code printf.
I am only looking for an explanation preferably with simple examples but not the solution to printf since I want to solve it myself.
Here are three examples which look like what I am looking for:
https://stackoverflow.com/a/1689228/3206885
https://stackoverflow.com/a/5551632/3206885
https://stackoverflow.com/a/1722238/3206885
I know the basics of what typedef, struct, enum and union do but can't figure out some practical application cases like the examples in the links.
What do they really mean? I can't wrap my brain around how they work.
How can I pass the data type from a union to va_arg like in the links examples? How does it match?
with a modifier like %d, %i ... or the data type of a parameter?
Here's what I've got so far:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "my.h"
typedef struct s_flist
{
char c;
(*f)();
} t_flist;
int my_printf(char *format, ...)
{
va_list ap;
int i;
int j;
int result;
int arg_count;
char *cur_arg = format;
char *types;
t_flist flist[] =
{
{ 's', &my_putstr },
{ 'i', &my_put_nbr },
{ 'd', &my_put_nbr }
};
i = 0;
result = 0;
types = (char*)malloc( sizeof(*format) * (my_strlen(format) / 2 + 1) );
fparser(types, format);
arg_count = my_strlen(types);
while (format[i])
{
if (format[i] == '%' && format[i + 1])
{
i++;
if (format[i] == '%')
result += my_putchar(format[i]);
else
{
j = 0;
va_start(ap, format);
while (flist[j].c)
{
if (format[i] == flist[j].c)
result += flist[i].f(va_arg(ap, flist[i].DATA_TYPE??));
j++;
}
}
}
result += my_putchar(format[i]);
i++;
}
va_end(ap);
return (result);
}
char *fparser(char *types, char *str)
{
int i;
int j;
i = 0;
j = 0;
while (str[i])
{
if (str[i] == '%' && str[i + 1] &&
str[i + 1] != '%' && str[i + 1] != ' ')
{
i++;
types[j] = str[i];
j++;
}
i++;
}
types[j] = '\0';
return (types);
}
You can't get actual type information from va_list. You can get what you're looking for from format. What it seems you're not expecting is: none of the arguments know what the actual types are, but format represents the caller's idea of what the types should be. (Perhaps a further hint: what would the actual printf do if a caller gave it format specifiers that didn't match the varargs passed in? Would it notice?)
Your code would have to parse the format string for "%" format specifiers, and use those specifiers to branch into reading the va_list with specific hardcoded types. For example, (pseudocode) if (fspec was "%s") { char* str = va_arg(ap, char*); print out str; }. Not giving more detail because you explicitly said you didn't want a complete solution.
You will never have a type as a piece of runtime data that you can pass to va_arg as a value. The second argument to va_arg must be a literal, hardcoded specification referring to a known type at compile time. (Note that va_arg is a macro that gets expanded at compile time, not a function that gets executed at runtime - you couldn't have a function taking a type as an argument.)
A couple of your links suggest keeping track of types via an enum, but this is only for the benefit of your own code being able to branch based on that information; it is still not something that can be passed to va_arg. You have to have separate pieces of code saying literally va_arg(ap, int) and va_arg(ap, char*) so there's no way to avoid a switch or a chain of ifs.
The solution you want to make, using the unions and structs, would start from something like this:
typedef union {
int i;
char *s;
} PRINTABLE_THING;
int print_integer(PRINTABLE_THING pt) {
// format and print pt.i
}
int print_string(PRINTABLE_THING pt) {
// format and print pt.s
}
The two specialized functions would work fine on their own by taking explicit int or char* params; the reason we make the union is to enable the functions to formally take the same type of parameter, so that they have the same signature, so that we can define a single type that means pointer to that kind of function:
typedef int (*print_printable_thing)(PRINTABLE_THING);
Now your code can have an array of function pointers of type print_printable_thing, or an array of structs that have print_printable_thing as one of the structs' fields:
typedef struct {
char format_char;
print_printable_thing printing_function;
} FORMAT_CHAR_AND_PRINTING_FUNCTION_PAIRING;
FORMAT_CHAR_AND_PRINTING_FUNCTION_PAIRING formatters[] = {
{ 'd', print_integer },
{ 's', print_string }
};
int formatter_count = sizeof(formatters) / sizeof(FORMAT_CHAR_AND_PRINTING_FUNCTION_PAIRING);
(Yes, the names are all intentionally super verbose. You'd probably want shorter ones in the real program, or even anonymous types where appropriate.)
Now you can use that array to select the correct formatter at runtime:
for (int i = 0; i < formatter_count; i++)
if (current_format_char == formatters[i].format_char)
result += formatters[i].printing_function(current_printable_thing);
But the process of getting the correct thing into current_printable_thing is still going to involve branching to get to a va_arg(ap, ...) with the correct hardcoded type. Once you've written it, you may find yourself deciding that you didn't actually need the union nor the array of structs.

How can I skip includes using libclang?

I am using libclang to parse a objective c source code file. The following code finds all Objective-C instance method declarations, but it also finds declarations in the includes:
enum CXCursorKind curKind = clang_getCursorKind(cursor);
CXString curKindName = clang_getCursorKindSpelling(curKind);
const char *funcDecl="ObjCInstanceMethodDecl";
if(strcmp(clang_getCString(curKindName),funcDecl)==0{
}
How can I skip everything, which comes from header includes? I am only interested in my own Objective-C instance method declarations in the source file, not in any of the includes.
e.g. the following should not be included
...
Location: /System/Library/Frameworks/Foundation.framework/Headers/NSObject.h:15:9:315
Type:
TypeKind: Invalid
CursorKind: ObjCInstanceMethodDecl
...
Answering this question because I couldn't believe that hard-coding paths comparisons was the only solution, and indeed, there is a clang_Location_isFromMainFile function that does exactly what you want, so that you can filter unwanted results in the visitor, like this :
if (clang_Location_isFromMainFile (clang_getCursorLocation (cursor)) == 0) {
return CXChildVisit_Continue;
}
The only way I know would be to skip unwanted paths during the AST visit. You can for example put something like the following in your visitor function. Returning CXChildVisit_Continue avoids visiting the entire file.
CXFile file;
unsigned int line, column, offset;
CXString fileName;
char * canonicalPath = NULL;
clang_getExpansionLocation (clang_getCursorLocation (cursor),
&file, &line, &column, &offset);
fileName = clang_getFileName (file);
if (clang_getCString (fileName)) {
canonicalPath = realpath (clang_getCString (fileName), NULL);
}
clang_disposeString (fileName);
if (strcmp(canonicalPath, "/canonical/path/to/your/source/file") != 0) {
return CXChildVisit_Continue;
}
Also, why compare CursorKindSpelling instead of the CursorKind directly?

Structure of a block declaration

When declaring a block what's the rationale behind using this syntax (i.e. surrounding brackets and caret on the left)?
(^myBlock)
For example:
int (^myBlock)(int) = ^(int num) {
return num * multiplier;
};
C BLOCKS: Syntax and Usage
Variables pointing to blocks take on the exact same syntax as variables pointing to functions, except * is substituted for ^. For example, this is a function pointer to a function taking an int and returning a float:
float (*myfuncptr)(int);
and this is a block pointer to a block taking an int and returning a float:
float (^myblockptr)(int);
As with function pointers, you'll likely want to typedef those types, as it can get relatively hairy otherwise. For example, a pointer to a block returning a block taking a block would be something like void (^(^myblockptr)(void (^)()))();, which is nigh impossible to read. A simple typedef later, and it's much simpler:
typedef void (^Block)();
Block (^myblockptr)(Block);
Declaring blocks themselves is where we get into the unknown, as it doesn't really look like C, although they resemble function declarations. Let's start with the basics:
myvar1 = ^ returntype (type arg1, type arg2, and so on) {
block contents;
like in a function;
return returnvalue;
};
This defines a block literal (from after = to and including }), explicitly mentions its return type, an argument list, the block body, a return statement, and assigns this literal to the variable myvar1.
A literal is a value that can be built at compile-time. An integer literal (The 3 in int a = 3;) and a string literal (The "foobar" in const char *b = "foobar";) are other examples of literals. The fact that a block declaration is a literal is important later when we get into memory management.
Finding a return statement in a block like this is vexing to some. Does it return from the enclosing function, you may ask? No, it returns a value that can be used by the caller of the block. See 'Calling blocks'. Note: If the block has multiple return statements, they must return the same type.
Finally, some parts of a block declaration are optional. These are:
The argument list. If the block takes no arguments, the argument list can be skipped entirely.
Examples:
myblock1 = ^ int (void) { return 3; }; // may be written as:
myblock2 = ^ int { return 3; }
The return type. If the block has no return statement, void is assumed. If the block has a return statement, the return type is inferred from it. This means you can almost always just skip the return type from the declaration, except in cases where it might be ambiguous.
Examples:
myblock3 = ^ void { printf("Hello.\n"); }; // may be written as:
myblock4 = ^ { printf("Hello.\n"); };
// Both succeed ONLY if myblock5 and myblock6 are of type int(^)(void)
myblock5 = ^ int { return 3; }; // can be written as:
myblock6 = ^ { return 3; };
source: http://thirdcog.eu/pwcblocks/
I think the rationale is that it looks like a function pointer:
void (*foo)(int);
Which should be familiar to any C programmer.

Expected identifier or '(' before '.' token

I'm new to Objective-C so I'm using a book to get to grips with it. I'm at a bit where it's explaining structs and I can't for the life of me get them to work.
I have the following code:
int main (int argc, char *argv[])
{
struct node
{
int nodeID;
int x;
int y;
BOOL isActive;
};
typedef struct node myNode;
myNode.nodeID = 1;
}
and I'm getting the error written in the title. Every time I search for this error online I found different variations such as 'before '>' token' or 'before '}' token' but i can't find anything with the '.' token and it's really frustrating and I assume it's somethings ridiculously trivial and basic. Any help would be appreciated.
I believe you're trying to modify the actual type itself. nodeA is now the type of that struct, much like int. You need to do something like nodeA myNode, then you would be able to perform myNode.nodeID = 1 without error.
I've got it sorted now, I used the following and it seems to be fixed now:
int main (int argc, char *argv[])
{
struct node
{
int nodeID;
int x;
int y;
BOOL isActive;
};
struct node myNode;
myNode.nodeID = 1;
myNode.x = 100;
myNode.y = 200;
myNode.isActive = TRUE;
}
Thanks for all your help Darth! :)
I think the problem with the original code was, it was trying to make myNode a type name using typedef. Thus, myNode is NOT a variable that assignment can happen to. Rather, it was another alias for struct node.