Is it possible to change behavior of clang-format for operator << (lessless) - clang-format

I encountered following problem. If I set following options in .clang-format
---
Language: Cpp
BreakBeforeBinaryOperators: None
...
And try to format code with operator <<, then I see this:
int main() {
int a = aaaaaaaaaaaaa + bbbbbbbbbbbb + ccccccccccccc + dddddddddd +
eeeeeeeee + ffffffff;
std::cout << aaaaaaaaaaaaa << bbbbbbbbbbbb << ccccccccccccc << dddddddddd
<< eeeeeeeee << ffffffff;
}
I.e. clang-format didn't obey BreakBeforeBinaryOperators settings for operator <<. At the same time I don't see any settings in documentation regarding this operator except for PenaltyBreakFirstLessLess which I think is not applicable here.
So, my question is: is it possible to somehow configure clang-format to format operator << in same way as all other binary operators?

Related

How to cut and convert bytes in micropython

I am trying to decode Can frames with micropython. I miss a lot of functions from python 3.x. I get 8 hex long bytes from the Rx SPI buffer of an MCP2515. For information, I'm on openMV IDE. I would like to extract the 1st and 2nd to make an integer, the 3rd and 4th to make another one, etc...
Along my researches, I found a function that convert a byte to signed integer (as the sign=True argument is not implemented in the from_byte function).
The main problem is that the solutions provided on others python's forum are only concerning python 3.x for pc but not micropython and a lot of solutions end with "function doesn't exist".
byte = b'\x12\x34\x56\x78\x9A\xBC\xDE\xFF'
def byte2int(bList, signed:bool=False):
if signed :
r = 0
for i in range(2):
d = 32 - ((i + 1) * 8)
r += bList[i] << d
return r
else : return int.from_bytes(byte, 'big')
Moreover, I don't think that I can trust the print function as print(b) return :
> print(b)
b'\x124Vx\x9a\xbc\xde\xff'
I don't understand why does the 3 vanished and was replaced by a 'V' after the 4 ! Sometime, my MCP2515 return some '|', '?', '.', '>', '<' or '=' when I print the can frames which are not hex characters !?
My hypothesis is that these are corrupted frames or SPI transmission.
Please, can someone help me to understand why micropython give me these messy results ?
Thank you very for your help.
I wrote something. Maybe not the best optimization possible, but I have to deal with micropython which is not as advanced than Python 3.x
This is a solution (surely not the most optimal). But it seems to work.
byte = b'\xFF\xC8\x56\x78\x9A\xBC\xDE\xFF'
byte2 = b'\x00\x00\x00#\x00\x00\x00\x00'
def extract(trame, signed:bool=False):
r = [0,0,0,0]
trame = [int(x) for x in bytearray(byte)]
for i in range(len(trame)/2):
val = (trame[i*2]<<8)+trame[i*2+1]
if signed and val > 0x8000 :
r[i] = -(65535-int(val)+1)
else :
r[i] = int(val)
return r
print(extract(byte, True))

bitwise operators in lua to create string

New user to LUA creating a protocol dissector for Wireshark.
referring to Lua - Bitwise Logical Operations,
I need a function in Lua to create a string based on a converted hex value:
local function HexToCircuitID(val)
-- input: 0x9D81
-- output: "630.1.01"
local e = ((val >> 4) & 0x3) + 1
local f = val & 0xF
local g = val >> 6
return string.format("%d.%d.%02d",e,f,g)
end
the interpreter has a problem with "unexpected symbol near '>' " for the first line with the right-shift operator.
Also, I'm not sure the string format function will operate the same as in C (new to Lua). This function is to create a ProtoField that appears as:
CircuitId: 630.1.01
where the actual value of the field is 0x9D81.
You can use bit.rshift(x, n) to right shift and bit.band(x1[,x2...]) to &.
The function then becomes:
local function HexToCircuitID(val)
-- input: 0x9D81
-- output: "630.1.01"
local e = bit.band(bit.rshift(val, 4), 0x3) + 1
local f = bit.band(val, 0xF)
local g = bit.rshift(val, 6)
--return string.format("%d.%d.%02d",e,f,g)
return string.format("%d.%d.%02d",g,f,e)
end
To get the order right I had to change e,f,g to g,f,e.
This will work in the latest version of Wireshark, which uses Lua 5.2. As Nifim mentioned, you have to use the bit library rather than bitwise operators, as they were introduced in Lua 5.3.

How to get the source text from line number using clang?

I am using clang matcher to obtain the result nodes. From the result nodes, I am able to get the line number, let us say 17. Now, I would like to get the entire source code in that line. Please help.
Let me explain in detail. I have a clang matcher that finds the floating literal in the source code. For example, line 17, sr = 2.0 * rt_urand_Upu32_Yd_f_pw_snf(u); is the source code, then it matches the 2.0. This is my matcher:
const auto PA = floatLiteral(
isExpansionInMainFile(),
unless(hasAncestor(arraySubscriptExpr()))
).bind("pa");
MatchFinder MatchFinder;
MatchFinder.addMatcher(PA, &Handler);
MatchFinder.matchAST(Context);
From the matcher, I am able to obtain the node where it got matched. I am able to retrieve the line number (line 17) and column number (6). Please find my code below:
const clang::FloatingLiteral* Variable = Result.Nodes.getNodeAs<clang::FloatingLiteral>("pa");
clang::SourceRange loc = Variable16->getSourceRange();
locStart = srcMgr.getPresumedLoc(loc.getBegin());
locEnd = srcMgr.getPresumedLoc(loc.getEnd());
std::cout << locStart.getLine()<< ":" << locEnd.getLine() << std::endl;
std::cout << locStart.getColumn() <<":" << locEnd.getColumn() << std::endl;
Now, if I try to retrieve the source code I am getting only the partial data. After doing some research in online, I tried to retrieve the source code in two ways. First approach is using lexer, please find the code below:
llvm::StringRef ref = Lexer::getSourceText(CharSourceRange::getCharRange(statement->getSourceRange()), srcMgr, LangOptions());
cout << ref.str() << endl;
Second approach is using rewriter, please find the code below:
clang::Rewriter rewriter;
rewriter.setSourceMgr(Result.Context->getSourceManager(),Result.Context->getLangOpts());
cout<<rewriter.getRewrittenText (loc)<<endl;
To my understanding, it seems that I need the sourcerange starting from column 0 of line 17 to end of column in line 17. The AST matcher only matches specific node, so my question is:
1) is it possible to get the final column number of line 17?
2) is there any other approach to get the source code from line number?
3) is there any other approach to get the source code from matcher?
Thanks for the help.
There is no direct way to get the last column of a line , but there is a solution to get the beginning of the line . I assume that you have the SourceManager(SM) and the SourceLocation(SL)
SM.translateLineCol(SM.getMainFileID(),SM.getSpellingLineNumber(SL),1);
If you really want to get the end of specific line you can set the column number to a incredible number , like 1000 . If the line has less than 1000 characters , it will stuck at last character , but if the line has more than 1000 characters , it will not appear at the end of line , so this solution is not stable . The example is getting the end location of line 17.
SM.translateLineCol(SM.getMainFileID(),17,1000);
By Using the solution above , you can get source code by using Rewriter(Rw) . For example , if you want to get the code in line 17 , and store it in string result
SourceLocation thisline=SM.translateLineCol(SM.getMainFileID(),17,1); // get the beginning of line 17
SourceLocation nextline=SM.translateLineCol(SM.getMainFileID(),18,1); // get the beginning of line 18
string result = Rw.getRewrittenText(SourceRange(thisline,nextline));
Yes , if you have proper SourceRange and Rewriter , you can use getRewrittenText() from match result .

Sage notebook limit representation

In Sage notebook, I want to print the standard mathematical notation for the limit of a function.
I expect something like this:
f = x+1
latex(limit(f, x=0)) + '=' + lim(f, x=0)
to print a properly formatted 'lim x->0 x+1 = 1'
naturally, I figured it out shortly after posting the question, always seems to work that way. here's the code from my notes-book:
show("NOTE: how to print lim")
# raw latex
f = (x^2-1)/(x-1)
Lf = LatexExpr(r'\lim_{x\to\infty}') + latex(f)
show(Lf)
# dummy limit
from sage.calculus.calculus import dummy_limit as lim
Lf = lim(f, x, 0)
out = latex(Lf) + "=" + latex(limit(f, x=0))
show(out)
Not very elegant, really wish the limit had a better way to represent itself in unevaluated form.

HowTo parse numbers from string with BOOST methods?

Problem: Visual C++ 10 project (using MFC and Boost libraries). In one of my methods I'm reading simple test.txt file.
Here is what inside of the file (std::string):
12 asdf789, 54,19 1000 nsfewer:22!13
Then I need to convert all digits to int only with boost methods. For example, I have a list of different characters which I have to parse:
( ’ ' )
( [ ], ( ), { }, ⟨ ⟩ )
( : )
( , )
( ! )
( . )
( - )
( ? )
( ‘ ’, “ ”, « » )
( ; )
( / )
And after conversation I must have some kind of a massive of int's values, like this one:
12,789,54,19,1000,22,13
Maybe some one already did this job?
PS. I'm new for boost.
Thanks!
Update
Here is my sample:
std::vector<int> v;
rule<> r = int_p[append(v)] >> *(',' >> int_p[append(v)]);
parse(data.c_str(), r, space_p);
All I have to do, is to add additional escape characters (,'[](){}:!...) in my code, but did not find how to do that!
Easy way out is regex.
Hard way out is using spirit
Middle-of-the-road is using algorithm::string::split, with the correct separators, and then looping over all individual parts using lexical_cast<>(). That way you can filter out the integers.
But again, regex will be much more robust plus it's much cleaner than all sorts of primitive string manipulation hacking.
In addition to regex, boost::spirit, and manually parsing the text, you can use AXE parser generator with VC++ 2010. The AXE rule would look something like this (not tested):
std::vector<unsigned> v;
auto text_rule = *(*(axe::r_any() - axe::r_numstr()) & ~axe::r_numstr()
>> axe::e_push_back(v)) & axe::r_end();
// test it
std::string str("12 asdf789, 54,19 1000 nsfewer:22!13");
text_rule(str.begin(), str.end());
// print result
std::for_each(v.begin(), v.end(), [](unsigned i) { std::cout << i << '\n'; });
The basic idea it to skip all input characters which don't match the number string rule (r_numstr).

Resources