satya-das / cppparser

A library to parse C/C++ source as AST
MIT License
270 stars 33 forks source link

Operator precedence is incorrect with '>' #13

Closed mfairclough closed 2 years ago

mfairclough commented 2 years ago

(a > b || c) is being parsed as (a > (b || c)) when it should be ((a > b) || c). Similarly, (a > b && c) is being parsed as (a > (b && c)) rather than ((a > b) && c). It appears to just be the > operator. The other comparison operators seem to be OK.

satya-das commented 2 years ago

Thanks for reporting this. Unfortunately, this is a known issue and it is done this way to correctly parse templates. Following is the code in parser.y:

// tknLT and tknGT are used instead of '<', and '>' because otherwise parsing template and template args is very difficult.
%left tknLT /*tknGT*/ tknLessEq tknGreaterEq

As you can see, I had to comment out the operator precedence code for greater-than operator. May be this can be enabled and another solution for template parsing can be used. But as of now I can suggest to use explicit use of parentheses to overcome this, if that is doable. I will also "warn" that expression parsing probably needs improvements, at least it has not been the top of the priority to parse correctly, just that parsing of valid C++ expressions should not give error. Development of CppParser is mainly driven by requirement of my cib project where the function body is of least importance and understanding the interface of a C++ library is the main requirement. Having said that I intend to make CppParser a general purpose C++ parsing library and I may work on to fix the problem you reported, but I cannot commit that it will surely be done. I will welcome any suggestion and pull request to address this :).

mfairclough commented 2 years ago

Thanks for the reply. So far I'm finding that this solution (putting tknGT back into the list) works for my use case, including some uses of templates. Can you show an example where templates would not be parsed correctly?

satya-das commented 2 years ago

Can you show an example where templates would not be parsed correctly?

I will have to dig a bit deeper for this, I will do that. But in the meanwhile you can try running all the tests, e.g. run ninja test or make test depending on whether you use ninja or make. You will see some tests will fail. I will come back with a more direct example.

satya-das commented 2 years ago

Sorry for taking long time to address this. The commit 015afeb0 fixes the precedence issue. Please retest with latest master.