Clang-format struct initialization - indent with two spaces? - clang-format

I'm trying to format a C file with clang-format. I want indentations to be two space characters, which mostly works except for in global variable struct initialization. For this, it continues to produce lines which are indented with four spaces.
Here is my .clang-format file
BasedOnStyle: LLVM
ColumnLimit: '80'
IndentWidth: '2'
clang-format produces this surprising output
typedef struct {
int x;
} foo;
static foo bar{
1, // This line is being indented with 4 spaces!
};
And this is what I'd expect the file to look like:
typedef struct {
int x;
} foo;
static foo bar{
1, // This line is being indented with 2 spaces!
};
I've tried using a few different values for ConstructorInitializerIndentWidth, but that field doesn't appear to affect this pattern.
Is there a setting that I could provide to get this behavior?

Try ContinuationIndentWidth: 2. That worked for me, when I had that problem.

Related

clang-format function argument indent

Is there a way to configure clang-format to behave in this way? Notice how each parameter is on its own line and is indented by only 1 level as opposed to aligned with the function name. This is my preferred coding style, but I just can't get clang-format to do this.
int a_very_long_function_name(
int var_a,
double my_b,
char *str
) {
int d = 0;
/* ... */
return d;
}
As far as I know, this is not possible.
You can try all the different parameters with this nifty tool: https://zed0.co.uk/clang-format-configurator/
Should be possible now according to: https://clang.llvm.org/docs/ClangFormatStyleOptions.html
AlignAfterOpenBracket: BlockIndent

How do I find the SourceLocation of the commas between function arguments using libtooling?

My main goal is trying to get macros (or even just the text) before function parameters. For example:
void Foo(_In_ void* p, _Out_ int* x, _Out_cap_(2) int* y);
I need to gracefully handle things like macros that declare parameters (by ignoring them).
#define Example _In_ int x
void Foo(Example);
I've looked at Preprocessor record objects and used Lexer::getSourceText to get the macro names In, Out, etc, but I don't see a clean way to map them back to the function parameters.
My current solution is to record all the macro expansions in the file and then compare their SourceLocation to the ParamVarDecl SourceLocation. This mostly works except I don't know how to skip over things after the parameter.
void Foo(_In_ void* p _Other_, _In_ int y);
Getting the SourceLocation of the comma would work, but I can't find that anywhere.
The title of the questions asks for libclang, but as you use Lexer::getSourceText I assume that it's libTooling. The rest of my answer is viable only in terms of libTooling.
Solution 1
Lexer works on the level of tokens. Comma is also a token, so you can take the end location of a parameter and fetch the next token using Lexer::findNextToken.
Here is a ParmVarDecl (for function parameters) and CallExpr (for function arguments) visit functions that show how to use it:
template <class T> void printNextTokenLocation(T *Node) {
auto NodeEndLocation = Node->getSourceRange().getEnd();
auto &SM = Context->getSourceManager();
auto &LO = Context->getLangOpts();
auto NextToken = Lexer::findNextToken(NodeEndLocation, SM, LO);
if (!NextToken) {
return;
}
auto NextTokenLocation = NextToken->getLocation();
llvm::errs() << NextTokenLocation.printToString(SM) << "\n";
}
bool VisitParmVarDecl(ParmVarDecl *Param) {
printNextTokenLocation(Param);
return true;
}
bool VisitCallExpr(CallExpr *Call) {
for (auto *Arg : Call->arguments()) {
printNextTokenLocation(Arg);
}
return true;
}
For the following code snippet:
#define FOO(x) int x
#define BAR float d
#define MINUS -
#define BLANK
void foo(int a, double b ,
FOO(c) , BAR) {}
int main() {
foo( 42 ,
36.6 , MINUS 10 , BLANK 0.0 );
return 0;
}
it produces the following output (six locations for commas and two for parentheses):
test.cpp:6:15
test.cpp:6:30
test.cpp:7:19
test.cpp:7:24
test.cpp:10:17
test.cpp:11:12
test.cpp:11:28
test.cpp:11:43
This is quite a low-level and error-prone approach though. However, you can change the way you solve the original problem.
Solution 2
Clang stores information about expanded macros in its source locations. You can find related methods in SourceManager (for example, isMacroArgExpansion or isMacroBodyExpansion). As the result, you can visit ParmVarDecl nodes and check their locations for macro expansions.
I would strongly advice moving in the second direction.
I hope this information will be helpful. Happy hacking with Clang!
UPD speaking of attributes, unfortunately, you won't have a lot of choices. Clang does ignore any unknown attribute and this behaviour is not tweakable. If you don't want to patch Clang itself and add your attributes to Attrs.td, then you're limited indeed to tokens and the first approach.

How to align a designated initializer in C99 with clang-format?

I am using clang-format 4.0.0 to align a personal project of mine.
I am using the following configurations for clang-format.
Language: Cpp
BreakBeforeBraces: Allman
ColumnLimit: 120
TabWidth: 4
IndentWidth: 4
UseTab: ForContinuationAndIndentation
The sample code below is aligned using the above configuration.
struct test
{
int a;
int b;
int c;
};
struct test T = {
.a = 1, .b = 2, .c = 3,
};
Is there any way to align the initialization part like the one shown below.
Basically I am looking for a way to place all the initializers in separate lines.
struct test T =
{
.a = 1,
.b = 2,
.c = 3,
};
Using clang-format 6.0.0, the formatting is what you ask for. In fact, there no longer seems to be any way to get the single-line formatting that you don't like.

clang-format: Align asterisk (*) of pointer declaration with variable name

I am using the following options in my .clang-format file:
AlignConsecutiveDeclarations: true
PointerAlignment: Right
The current formatting result is the following:
char * var1;
SomeOtherType *var2;
int var3;
The result I was expecting would be:
char *var1; //note the changed position of *
SomeOtherType *var2;
int var3;
How can I configure clang-format to align the asterix (*) with the variable name rather then with the type when I am
using the AlignConsecutiveDeclarations option?
PointerAlignment: Right is unfortunately not implemented yet.
See https://github.com/llvm/llvm-project/blob/master/clang/lib/Format/WhitespaceManager.cpp#L643
void WhitespaceManager::alignConsecutiveDeclarations() {
if (!Style.AlignConsecutiveDeclarations)
return;
// FIXME: Currently we don't handle properly the PointerAlignment: Right
// The * and & are not aligned and are left dangling. Something has to be done
// about it, but it raises the question of alignment of code like:
// const char* const* v1;
// float const* v2;
// SomeVeryLongType const& v3;
AlignTokens(Style, [](Change const &C) { return C.IsStartOfDeclName; },
Changes);
}
It's fixed now!
The review https://reviews.llvm.org/D27651 has been re-applied in https://reviews.llvm.org/D103245 and committed in https://reviews.llvm.org/rG3e333cc82e42e1e2ecc974d896489eebe1a5edc2.
This change will be included in LLVM 13 release.

Printing the same character several times without a loop

I would like to "beautify" the output of one of my Dart scripts, like so:
-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------
<Paragraph>
And I wonder if there is a particularly simple and/or optimized way of printing the same character x times in Dart. In Python, print "-" * x would print the "-" character x times.
Learning from this answer, for the purpose of this question, I wrote the following minimal code, which makes use of the core Iterable class:
main() {
// Obtained with '-'.codeUnitAt(0)
const int FILLER_CHAR = 45;
String headerTxt;
Iterable headerBox;
headerTxt = 'OpenPGP signing notes from key `CD42FF00`';
headerBox = new Iterable.generate(headerTxt.length, (e) => FILLER_CHAR);
print(new String.fromCharCodes(headerBox));
print(headerTxt);
print(new String.fromCharCodes(headerBox));
// ...
}
This gives the expected output, but is there a better way in Dart to print a character (or string) x times? In my example, I want to print the "-" character headerTxt.length times.
The original answer is from 2014, so there must have been some updates to the Dart language: a simple string multiplied by an int works.
main() {
String title = 'Dart: Strings can be "multiplied"';
String line = '-' * title.length
print(line);
print(title);
print(line);
}
And this will be printed as:
---------------------------------
Dart: Strings can be "multiplied"
---------------------------------
See Dart String's multiply * operator docs:
Creates a new string by concatenating this string with itself a number of times.
The result of str * n is equivalent to str + str + ...(n times)... + str.
Returns an empty string if times is zero or negative.
I use this way.
void main() {
print(new List.filled(40, "-").join());
}
So, your case.
main() {
const String FILLER = "-";
String headerTxt;
String headerBox;
headerTxt = 'OpenPGP signing notes from key `CD42FF00`';
headerBox = new List.filled(headerTxt.length, FILLER).join();
print(headerBox);
print(headerTxt);
print(headerBox);
// ...
}
Output:
-----------------------------------------
OpenPGP signing notes from key `CD42FF00`
-----------------------------------------

Resources