Multiplication_or_dereference
目录
Multiplication or dereference
Software translation
In the U Language Project A separator based lexical analyzer is implemented in the Lexical Analyzer Design Document “The current * will be parsed as a multiplication sign, and when there is no pointer, there is no problem.”. Now we are ready to add pointers to this project. If you use * to dereference as in other languages, there are two options
-
When constructing an abstract syntax tree, handle ambiguity where * can be both a multiplication sign and a dereference
-
At the lexical analysis node, handle ambiguity where * can be both a multiplication sign and a dereference
How to solve * ambiguity
When the compiler sees an ambiguity where * processing can be both a multiplication sign and a dereference, it first does not directly interpret it as a semantic method of multiplication sign or dereference. Enumeration proves that
-
If it is directly interpreted as a multiplication sign, * ptr with * ptr=1 is a dereference ptr pointer, which is now incorrectly interpreted as a multiplication ptr
-
If it is directly interpreted as dereference, the * b of c=a * b is multiplied by b. It is now incorrectly interpreted as dereference b
Therefore, it is necessary to explain * according to different situations*
-
If at the beginning, because multiplication requires two operands, at the beginning, there is no operand on the left, so it can be interpreted as dereference
-
If it is not at the beginning, and if the * is not preceded by a symbol, such as a+* ptr, since the left side is not an operand, it can be interpreted as dereference
-
If it is not at the beginning, and if * is a symbol, such as a * b, because the left side is the operand, it can be interpreted as a multiplication sign
The above processing methods can be used in lexical analysis or building an abstract syntax tree, but during lexical analysis, a Boolean variable is used to set to true when a multiplication sign is found. If the Boolean variable is true, the multiplication sign is processed using the above method. For parts without a multiplication sign, the overhead of judging is only increased once.
A simpler approach
If * has ambiguity, in addition to handling ambiguity, you can also find a symbol without ambiguity, such as @, and the compiler can directly identify @ as a dereference when it sees it. However, this is different from mainstream practices and may increase learning costs