I have a left-recursive error with my C grammar which can be found here
http://www.archive-host.com/files/1959502/24fe084677d7655eb57ba66e1864081450017dd9/cAST.txt.
When I replace
initializer
: assignment_expression
| '{' initializer_list '}'
;
with
initializer
: assignment_expression
| '{' initializer_list '}'
| initializer_list
;
I did this because I am trying to do this code in Ctrl-D
int k [2] = 1,4;
However this code does work with the first version
int k [2] = {1,4};
Is there a way to do without the { } please?
To do this, you'd need to introduce context sensitivity (or something on that order).
The problem is that 1,4 already has a defined meaning. It's an expression using the comma operator that evaluates the 1, discards the result, then evaluates the 4, which is the value of the expression as a whole.
As such, to make this work, you'd have to use a different syntax for initializers than for normal expressions (and in the process, depart pretty widely from C as it's current defined). From a purely grammatical viewpoint, that almost certainly does not need to be done with context sensitivity, but it will involve basically defining the syntax for initializers separately from/in parallel with the syntax for normal expressions, instead of using a common syntax for both.
Related
Trying to understand shift-reduce conflicts and fix them.
I have following YACC code, for which I was expecting shift-reduce conflict but Bison doesn't generate any such warnings
%%
lang_cons: /* empty */
| declaraion // SEMI_COLON
| func
;
declaraion : keyword ID
;
func : keyword ID SEMI_COLON
;
keyword : INT
| FLOAT
;
%%
But if I uncomment SEMI_COLON in 2nd rule (i.e, | declaraion SEMI_COLON ), I get shift-reduce conflict. I was expecting reduce-reduce conflict in this case. Please help me understand this mess!
PS: Consider input,
1) int varName
2) int func;
If you give bison the -v command line flag, it will produce an .output file containing the generated state machine, which will probably help you see what is going on.
Note that bison actually parses the augmented grammar, which consists of your grammar with the additional rule
start': start END
where END is a special token whose code is 0, indicating the end of input, and start is whatever your grammar uses as a start symbol. (That ensures that the bison parser will not silently ignore garbage at the end of an otherwise valid input.)
That makes your original grammar unambiguous; after varName is seen, the lookahead will be either END, in which case declaration is reduced, or ';', which will be shifted (followed by a reduction of func when the following END is seen).
In your second grammar, the conflict involves the choice between reducing declaration or shifting the semicolon. If the semicolon were part of declaration, then you would see a reduce/reduce conflict.
This program compiles (C with diab):
int main()
{
("----");
}
Why is it not considered a compiler error ? (Is it because it supports some other feature that needs this syntax)?
What does it compile to?
It compiles for the same reason that 1;, "----";, or 1 + 2 + 3 + 4; would compile: because an expression, followed by a semicolon, is a valid statement.
Turning expressions into statements with a semicolon is needed for a lot of parts of C to work. For example:
do_stuff_to(x);
is a function call, which has a value, but can be useful as a statement in its own right.
Even something like
x = y;
(that is, an assignment) is actually an expression. This one in particular is quite useful in statement position.
The relevant parts of the C grammar are:
statement
: labeled_statement
| compound_statement
| expression_statement
| selection_statement
| iteration_statement
| jump_statement
;
that is, a statement can be one of many things, including an expression_statement; and
expression_statement
: ';'
| expression ';'
;
that is, an expression_statement is either a semicolon or an expression, followed by a semicolon.
What this program compiles to is implementation-dependent. A compiler is free to compile the string into the data segment of the program, or it is free to simply ignore it. On my machine, GCC does not even put the string in the compiled executable at all, even with no optimization level.
Compilers are also not required to warn about this construct, but GCC does, when given the flag -Wunused-value. This warning can be helpful sometimes, because this particular construction is not useful at all.
test.c: In function ‘main’:
test.c:2:5: warning: statement with no effect [-Wunused-value]
("----");
^
I have written a simple grammar:
operations :
/* empty */
| operations operation ';'
| operations operation_id ';'
;
operation :
NUM operator NUM
{
printf("%d\n%d\n",$1, $3);
}
;
operation_id :
WORD operator WORD
{
printf("%s\n%s\n%s\n",$1, $3, $<string>2);
}
;
operator :
'+' | '-' | '*' | '/'
{
$<string>$ = strdup(yytext);
}
;
As you can see, I have defined an operator that recognizes one of 4 symbols. Now, I want to print this symbol in operation_id. Problem is, that logic in operator works only for last symbol in alternative.
So if I write a/b; it prints ab/ and that's cool. But for other operations, eg. a+b; it prints aba. What am I doing wrong?
*I ommited new lines symbols in example output.
This non-terminal from your grammar is just plain wrong.
operator :
'+' | '-' | '*' | '/' { $<string>$ = strdup(yytext); }
;
First, in yacc/bison, each production has an action. That rule has four productions, of which only the last has an associated action. It would be clearer to write it like this:
operator : '+'
| '-'
| '*'
| '/' { $<string>$ = strdup(yytext); }
;
which makes it a bit more obvious that the action only applies to the reduction from the token '/'.
The action itself is incorrect as well. yytext should never be used outside of a lexer action, because its value isn't reliable; it will be the value at the time the most recent lexer action was taken, but since the parser usually (but not always) reads one token ahead, it will usually (but not always) be the string associated with the next token. That's why the usual advice is to make a copy of yytext, but the idea is to copy it in the lexer rule, assigning the copy to the appropriate member of yylval so that the parser can use the semantic value of the token.
You should avoid the use of $<type>$ =. A non-terminal can only have one type, and it should be declared in the prologue to the bison file:
%type <string> operator
Finally, you will find that it is very rarely useful to have a non-terminal which recognizes different operators, because the different operators are syntactically different. In a more complete expression grammar, you'd need to distinguish between a + b * c, which is the sum of a and the product of b and c, and a * b + c, which is the sum of c and the product of a and b. That can be done by using different non-terminals for the sum and product syntaxes, or by using different productions for an expression non-terminal and disambiguating with precedence rules, but in both cases you will not be able to use an operator non-terminal which produces + and * indiscriminately.
For what its worth, here is the explanation of why a+b results in the output of aba:
The production operator : '+' has no explicit action, so it ends up using the default action, which is $$ = $1.
However, the lexer rule which returns '+' (presumably -- I'm guessing here) never sets yylval. So yylval still has the value it was last assigned.
Presumably (another guess), the lexer rule which produces WORD correctly sets yylval.string = strdup(yytext);. So the semantic value of the '+' token is the semantic value of the previous WORD token, which is to say a pointer to the string "a".
So when the rule
operation_id :
WORD operator WORD
{
printf("%s\n%s\n%s\n",$1, $3, $<string>2);
}
;
executes, $1 and $2 both have the value "a" (two pointers to the same string), and $3 has the value "b".
Clearly, it is semantically incorrect for $2 to have the value "a", but there is another error waiting to occur. As written, your parser leaks memory because you never free() any of the strings created by strdup. That's not very satisfactory, and at some point you will want to fix the actions so that semantic values are freed when they are no longer required. At that point, you will discover that having two semantic values pointing at the same block of allocated memory makes it highly likely that free() will be called twice on the same memory block, which is Undefined Behaviour (and likely to produce very difficult-to-diagnose bugs).
...
IF LP assignment-expression RP marker statement {
backpatch($3.tlist,$5.instr);
$$.nextList = mergeList($3.flist,$6.nextList);
}
|IF LP assignment-expression RP marker statement ELSE Next statement {
backpatch($3.tlist,$5.instr);
backpatch($3.flist,$8.instr);
YYSTYPE::BackpatchList *temp = mergeList($6.nextList,$8.nextList);
$$.nextList = mergeList(temp,$9.nextList);
}
...
Assignment-expression is any assignment expression that is possible using the C operators =, +=, -=, *=, /=.
LP = (
RP = )
marker and Next are both EMPTY rule
The problem with above grammar rule and implementation is that it can't generate correct code when expression is as
bool a;
if(a){
printf("hi");
}
else{
prinf("die");
}
It expects that assignment-expression must contain relop or OR or AND to generate correct code .
Since in this case we do comparison for relop same case apply to OR and AND.
But as in above code doesn't contain any thing out of this , So it's unable to generate correct code.
The correct code can be generated by using following rule but this leads to two reduce-reduce conflict .
...
IF LP assignment-expression {
if($3.flist == NULL && $3.tlist == NULL)
...
} RP marker statement {
...
}
|IF LP assignment-expression{
if($3.flist == NULL && $3.tlist == NULL)
...
} RP marker statement ELSE Next statement {
...
}
...
What are the modification I should do in the grammar rule so that it will work as expected ?
I tried IF ELSE grammar rule
from here as well as from dragon book but unable to solve this .
Whole grammar can be found here Github
In order to insert the mid-rule action, you need to left-factor; otherwise, the bison-generated parser cannot decide which of the two MRAs to reduce. (Even though they are presumably identical, bison doesn't know that.)
if_prefix: "if" '(' expression ')' { $$ = $3; /* Normalize the flist */ }
if: if_prefix marker statement { ... }
| if_prefix marker statement "else" Next statement { ... }
(You could left factor differently; that's just one suggestion.)
It looks like your grammar has an incorrect definition of expression.
An assignment expression is only one of many non-terminals that should be able to reduce to an expression. For an if/then/else construction you generally need to allow any expression to occur between the parens. Your first example, as you point out, is perfectly valid C but doesn't contain an assignment.
In your grammar, you have this line:
/*Expression list**/
expression:
assignment-expression{}
|expression COMMA assignment-expression{}
;
However, an expression should be able to have more than assignment-expressions. Not being terribly familiar with yacc/bison, I would guess you need to change this to something like the following:
/*Expression **/
expression:
assignment-expression{}
|logical-OR-expression{}
|logical-AND-expression{}
|inclusive-OR-expression{}
|exclusive-OR-expression{}
|inclusive-AND-expression{}
|equality-expression{}
|relational-expression{}
|additive-expression{}
|multiplicative-expression{}
|exponentiation-expression{}
|unary-expression{}
|postfix-expression{}
|primary-expression{}
|expression COMMA expression{}
;
I can't really validate that this is going to work for you, and it may be imperfect, but hopefully you get the idea. Each different type of expression needs to be able to reduce to an expression. You have something very similar for statement earlier in your grammar, so this should hopefully make sense.
It might be helpful to do some reading or watch some tutorials on how LR grammars work.
I am trying to write a C grammar with Antlwork, and for that I used this one http://stuff.mit.edu/afs/athena/software/antlr_v3.2/examples-v3/java/C/C.g where I tried to make it more simple by removing many blocks I don't use and the backtracking. And here is what I have : http://www.archive-host.com/files/1956778/24fe084677d7655eb57ba66e1864081450017dd9/CNew.txt
Then when I do ctrl+D, I get a lot of warning and errors like these:
[21:20:54] warning(200): C:\CNew.g:188:2: Decision can match input such as "'{' '}'" using multiple alternatives: 1, 2
As a result, alternative(s) 2 were disabled for that input
[21:20:54] warning(200): C:\CNew.g:210:2: Decision can match input such as "'for' '('" using multiple alternatives: 2, 3
As a result, alternative(s) 3 were disabled for that input
[21:20:54] error(201): C:\CNew.g:210:2: The following alternatives can never be matched: 3
[21:20:54] error(208): C:\CNew.g:250:1: The following token definitions can never be matched because prior tokens match the same input: CHAR
I don't really understand why I have all these warnings, there should not be conflicts.
but I still have this error
[22:02:55] error(208): C:\Users\Seiya\Desktop\projets\TRAD\Gram\CNew.g:238:1: The following token definitions can never be matched because prior tokens match the same input: CONSTANT [22:17:18] error(208): CNew.g:251:1: The following token definitions can never be matched because prior tokens match the same input: CHAR [22:17:18] error(208): C:\Users\Seiya\Desktop\projets\TRAD\Gram\CNew.g:251:1: The following token definitions can never be matched because prior tokens match the same input: CHAR
That means the lexer can never create the tokens CHAR and INT because some other lexer rule, CONSTANT, matches the same input. What you need to do is change CONSTANT into a parser rule.
In other words, change these two rules:
primary_expression
: ID
| CONSTANT
| '(' expression ')'
;
CONSTANT
: INT
| CHAR
;
into the following:
primary_expression
: ID
| constant
| '(' expression ')'
;
constant
: INT
| CHAR
;