Getting clang-format to format args/params conditionally or with preference - clang-format

I'm new to using clang-format (version 6.0.0) and was wondering how to get sort of preferential alignment. Specifically I would like the following.
If params can fit on a single line, do that:
int f( int a, int b, int c) {
If not, then try to stack params (bin packing):
int f( int a,
int b,
int c) {
If one or more of the stacked parameters still do not fit in specified column boundary, just break to new line.
int f(
int a, int b, int c) {
So far I've only figured out how to get one of these formats but not how to get multiple in this sort of preferred priority order. It seems I must stick to Align or AlwaysBreak. Is there any way to get the sort of param ordering specified here?
Here is my .clang-format
Language: Cpp
AlignAfterOpenBracket: Align
AllowAllParametersOfDeclarationOnNextLine: false
BinPackParameters: false

I think your requirements as expressed above are kind-of contradictory. Consider the last case ("If one or more of the stacked parameters still do not fit in specified column boundary, just break to new line"). If a "stacked" parameter doesn't fit in the column boundary, then "just break to new line" will certainly not fit on a single line because that line contains even more than just the really long stacked parameter.
Using clang-format 6.0.0, I tried reproducing your issue using the following input file:
// If params can fit on a single line, do that
int f( int a, int b, int c)
{
return do_something();
}
// If not, then try to stack params (bin packing)
int g( int aLongerName, int bLongerName, int cLongerName, int dLongerName, int eLongerName)
{
return do_something();
}
// If one or more of the stacked parameters still do not fit in the
// specified column boundary, just break to new line
int g( int aLongerName, int bLongerName, int cReaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaallyLongName)
{
return do_something();
}
Then, using the .clang-format file you provide, the output is:
// If params can fit on a single line, do that:
int f(int a, int b, int c) { return do_something(); }
// If not, then try to stack params (bin packing)
int g(int aLongerName,
int bLongerName,
int cLongerName,
int dLongerName,
int eLongerName) {
return do_something();
}
// If one or more of the stacked parameters still do not fit in the
// specified column boundary, just break to new line
int g(
int aLongerName,
int bLongerName,
int cReaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaallyLongName) {
return do_something();
}
This actually seems very close to what you're asking for, except for the last case splitting parameters onto several lines, which is necessary given the length of the parameters. If this isn't what you want, can you please provide a better explanation/example of how you want this to look?

Related

How to calculate this String text ="2+3-5+1" using Split method? [duplicate]

This question already has answers here:
Calculate string value in javascript, not using eval
(12 answers)
Closed 4 months ago.
When the text was '2+3+5+1', the logic was easy
Split('+') so the string is converted to an array.
loop over the array and calculate the sum.
check the code below
void main() {
const text = '2+3+5+1';
final array = text.split('+');
int res =0;
for (var i=0; i<= array.length -1; i++){
res+=int.parse(array[i]);;
}
print(array);
print(res);
}
Now this String "2+3-5+1" contains minus.
how to get the right response using split method?
I am using dart.
note: I don't want to use any library (math expression) to solve this exercice.
Use the .replace() method.
text = text.replace("-", "+-");
When you run through the loop, it will calculate (-).
You can split your string using regex text.split(/\+|\-/).
This of course will fail if any space is added to the string (not to mention *, / or even decimal values).
const text = '20+3-5+10';
const arr = text.split(/\+|\-/)
let tot = 0
for (const num of arr) {
const pos = text.indexOf(num)
if (pos === 0) {
tot = parseInt(num)
} else {
switch (text.substr(text.indexOf(num) - 1, 1)) {
case '+':
tot += parseInt(num)
break
case '-':
tot -= parseInt(num)
break
}
}
}
console.log(tot)
I see 2 maybe 3 options, definitely there are hundreds
You don't use split and you just iterate through the string and just add or subtract on the way. As an example
You have '2+3-5+1'. You iterate until the second operator (+ or -) on your case. When you find it you just do the operation that you have iterated through and then you just keep going. You can do it recursive or not, doesn't matter
"2+3-5+1" -> "5-5+1" -> "0+1" -> 1
You use split on + for instance and you get [ '2', '3-5', '1' ] then you go through them with a loop with 2 conditions like
if(isNaN(x)) res+= x since you know it's been divided with a +
if(!isNaN(x)) res+= x.split('-')[0] - x.split('-')[1]
isNaN -> is not a number
Ofc you can make it look nicer. If you have parenthesis though, none of this will work
You can also use regex like split(/[-+]/) or more complex, but you'll have to find a way to know what operation follows each digit. One easy approach would be to iterate through both arrays. One of numbers and one of operators
"2+3-5+1".split(/[-+]/) -> [ '2', '3', '5', '1' ]
"2+3-5+1".split(/[0-9]*/).filter(x => x) -> [ '+', '-', '+' ]
You could probably find better regex, but you get the idea
You can ofc use a map or a switch for multiple operators

How to make an operation similar to _mm_extract_epi8 with non-immediate input?

What I want is extracting a value from vector using a variable scalar index.
Like _mm_extract_epi8 / _mm256_extract_epi8 but with non-immediate input.
(There are some results in the vector, the one with the given index is found out to be the true result, the rest are discarded)
Especially, if index is in a GPR, the easiest way is probably to store val to memory and then movzx it into another GPR. Sample implementation using C:
uint8_t extract_epu8var(__m256i val, int index) {
union {
__m256i m256;
uint8_t array[32];
} tmp;
tmp.m256 = val;
return tmp.array[index];
}
Godbolt translation (note that a lot of overhead happens for stack alignment -- if you don't have an aligned temporary storage area, you could just vmovdqu instead of vmovdqa): https://godbolt.org/z/Gj6Eadq9r
So far the best option seem to be using _mm_shuffle_epi8 for SSE
uint8_t extract_epu8var(__m128i val, int index) {
return (uint8_t)_mm_cvtsi128_si32(
_mm_shuffle_epi8(val, _mm_cvtsi32_si128(index)));
}
Unfortunately this does not scale well for AVX. vpshufb does not shuffle across lanes. There is a cross lane shuffle _mm256_permutevar8x32_epi32, but the resulting stuff seem to be complicated:
uint8_t extract_epu8var(__m256i val, int index) {
int index_low = index & 0x3;
int index_high = (index >> 2);
return (uint8_t)(_mm256_cvtsi256_si32(_mm256_permutevar8x32_epi32(
val, _mm256_zextsi128_si256(_mm_cvtsi32_si128(index_high))))
>> (index_low << 3));
}

Comment not being used in trade MQL4

Unfortunately I am not able to post the code I am debugging as it is not mine and I am bound not to show it... BUT I will describe it as detailed as possible.
There are 4 strategies base on 4 indicators, custom, and not-custom ones. So basically instead of 4 different EAs running in 4 different charts with the same 4 indicators each... The client asked me to optimise them by putting them all in one to run 4 into 1 EAs in the same chart.
EVERYTHING is the same. They are tested as well that they are the same. They open the same trades, on the same moments. Nothing is changed 100%. The only thing I did (for this part of the debugging, because obviously I had a lot more to do before that) is to copy functions and code. And I seperated all different strategies with an "if" as input
input bool strategy1enabled = true; etc... so he/she can disable/enable individual strategies if wanted.
everything works BUT....
All but 1 strategies, does not show the Comment on the trades.
All 4 use the same Buy/Sell/CloseOrder functions so I just input the values to keep the code shorter.
//---
bool OrdClose (int ticket_number, double lt, int slp)
{
return OrderClose(ticket_number,lt,iClose(NULL,0,0),slp,clrViolet);
}
//---
int Buy(double lt, int slp, int slss, int tpft, string cmt, int mgc)
{
return OrderSend(NULL,OP_BUY,lt,Ask,slp,Ask-slss*Point,Ask+tpft*Point,cmt,mgc,0,clrDarkBlue);
}
//---
int Sell(double lt, int slp, int slss, int tpft, string cmt, int mgc)
{
return OrderSend(NULL,OP_SELL,lt,Bid,slp,Bid+slss*Point,Bid-tpft*Point,cmt,mgc,0,clrDarkRed);
}
1 strategy just refuses to put comment. Any ideas why? When used seperated WITH THE SAME CODE and the EXACT SAME functions... comment shows...
EDIT:
2021.05.04 18:30:48.670 The_Big_Holla_v1_8_EA CADJPY,H1: open #85710545 buy 0.06 CADJPY at 88.755 sl: 88.655 tp: 88.955 ok
2021.05.04 18:30:48.462 The_Big_Holla_v1_8_EA CADJPY,H1: Holla v4.9 || GreedInjectionMode
2021.05.04 18:30:48.462 The_Big_Holla_v1_8_EA CADJPY,H1: Holla v4.9 || GreedInjectionMode
Comment is passed properly and checked before being passed to function and before OrderSend within function:
The function:
int Sell(double lt, int slp, int slss, int tpft, string cmt, int mgc)
{
Print(cmt);
return OrderSend(NULL,OP_SELL,lt,Bid,slp,Bid+slss*Point,Bidtpft*Point,cmt,mgc,0,clrDarkRed);
}
How the function is called:
Print(EACommentInj);
ticket_val_inj = Buy(lotsizeInj,slippageInj,stoplossInj,takeprofitInj,EACommentInj,MagicInj);
This is how it is initialised and it NEVER changes. It is mentioned only where it is passed. Where I showed you above.
const string EACommentInjGreed = "Holla v4.9 || GreedInjectionMode Greed Mode";
Although this is undocumented, the "string comment=NULL" parameter of the trade function OrderSend() in MQL4 is limited to 31 characters. If this limit is exceeded then the string is rejected as a whole and treated as NULL.
In your code, just before the OrderSend() function, add the following line:
cmt=StringSubstr(cmt,0,31);

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 work with char types in Dart? (Print alphabet)

I am trying to learn the Dart language, by transposing the exercices given by my school for C programming.
The very first exercice in our C pool is to write a function print_alphabet() that prints the alphabet in lowercase; it is forbidden to print the alphabet directly.
In POSIX C, the straightforward solution would be:
#include <unistd.h>
void print_alphabet(void)
{
char c;
c = 'a';
while (c <= 'z')
{
write(STDOUT_FILENO, &c, 1);
c++;
}
}
int main(void)
{
print_alphabet();
return (0);
}
However, as far as I know, the current version of Dart (1.1.1) does not have an easy way of dealing with characters. The farthest I came up with (for my very first version) is this:
void print_alphabet()
{
var c = "a".codeUnits.first;
var i = 0;
while (++i <= 26)
{
print(c.toString());
c++;
}
}
void main() {
print_alphabet();
}
Which prints the ASCII value of each character, one per line, as a string ("97" ... "122"). Not really what I intended…
I am trying to search for a proper way of doing this. But the lack of a char type like the one in C is giving me a bit of a hard time, as a beginner!
Dart does not have character types.
To convert a code point to a string, you use the String constructor String.fromCharCode:
int c = "a".codeUnitAt(0);
int end = "z".codeUnitAt(0);
while (c <= end) {
print(String.fromCharCode(c));
c++;
}
For simple stuff like this, I'd use "print" instead of "stdout", if you don't mind the newlines.
There is also:
int char_a = 'a'.codeUnitAt(0);
print(String.fromCharCodes(new Iterable.generate(26, (x) => char_a + x)));
or, using newer list literal syntax:
int char_a = 'a'.codeUnitAt(0);
int char_z = 'z'.codeUnitAt(0);
print(String.fromCharCodes([for (var i = char_a; i <= char_z; i++) i]));
As I was finalizing my post and rephrasing my question’s title, I am no longer barking up the wrong tree thanks to this question about stdout.
It seems that one proper way of writing characters is to use stdout.writeCharCode from the dart:io library.
import 'dart:io';
void ft_print_alphabet()
{
var c = "a".codeUnits.first;
while (c <= "z".codeUnits.first)
stdout.writeCharCode(c++);
}
void main() {
ft_print_alphabet();
}
I still have no clue about how to manipulate character types, but at least I can print them.

Resources