many multiple alternatives errors with my C grammar - c

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
;

Related

Why doesn't YACC generate shift-reduce conflict?

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.

How to find a substring

Given a text file containing a string, I would find some specific substrings/sequences inside this string.
Bison file .y (Declaration+Rules)
%token <cval> AMINO
%token STARTCODON STOPCODON
%type <cval> seq
%%
series: STARTCODON seq STOPCODON {printf("%s", $2);}
seq: AMINO
| seq AMINO
;
%%
Here I want to print every sequence between STARTCODON and STOPCODON
Flex file .l (Rules)
%%
("ATG")+ {return STARTCODON;}
("TAA"|"TAG"|"TGA")+ {return STOPCODON;}
("GCT"|"GCC"|"GCA"|"GCG")+ {yylval.cval = 'A';
return AMINO;}
("CGT"|"CGC"|"CGA"|"CGG"|"AGA"|"AGG")+ {yylval.cval = 'R';
return AMINO;}
.
.
.
[ \t]+ /*ignore whitespace*/
\n /*ignore end of line*/
. {printf("-");}
%%
When I run the code I get only the output of the rule . {printf("-");}.
I am new Flex/Bison, I suspect that:
The bison rule series: STARTCODON seq STOPCODON {printf("%s", $2);} is not correct.
Flex doesn't subdivide correctly the entire string into tokens of 3 characters.
EDIT:
(Example) Input file: DnaSequence.txt:
Input string:cccATGAATTATTAGzzz, where lower characters (ccc, zzz) produce the (right) output -, ATG is the STARTCODON, AATTAT is the sequence of two AMINO (AAT TAT), and TAG is the STOPCODON.
This input string produces the (wrong) output ---.
EDIT:
Following the suggestions of #JohnBollinger I have added <<EOF>> {return ENDTXT;} in the Flex file, and the rule finalseries: series ENDTXT; in the Bison file.
Now it's returning the yyerror's error message, indicating a parsing error.
I suppose that we need a STARTTXT token, but I don't know how to implement it.
I am new Flex/Bison, I suspect that:
The bison rule series: STARTCODON seq STOPCODON {printf("%s", $2);} is not correct.
The rule is syntactically acceptable. It would be semantically correct if the value of token 2 were a C string, in which case it would cause that value to be printed to the standard output, but your Flex file appears to assume that type <cval> is char, which is not a C string, nor directly convertible to one.
Flex doesn't subdivide correctly the entire string into tokens of 3 characters.
Your Flex input looks OK to me, actually. And the example input / output you present indicates that Flex is indeed recognizing all your triplets from ATG to TAG, else the rule for . would be triggered more than three times.
The datatype problem is a detail that you'll need to sort out, but the main problem is that your production for seq does not set its semantic value. How that results in (seemingly) nothing being printed when the series production is used for a reduction depends on details that you have not disclosed, and probably involves undefined behavior.
If <cval> were declared as a string (char *), and if your lexer set its values as strings rather than as characters, then setting the semantic value might look something like this:
seq: AMINO { $$ = calloc(MAX_AMINO_ACIDS + 1, 1); /* check for allocation failure ... */
strcpy($$, $1); }
| seq AMINO { $$ = $1; strcat($$, $2); }
;
You might consider sticking with char as the type for the semantic value of AMINO, and defining seq to have a different type (i.e. char *). That way, your changes could be restricted to the grammar file. That would, however, call for a different implementation of the semantic actions in the production for seq.
Finally, note that although you say
Here I want to print every sequence between STARTCODON and STOPCODON
your grammar, as presented, has series as its start symbol. Thus, once it reduces the token sequence to a series, it expects to be done. If additional tokens follow (say those of another series) then that would be erroneous. If that's something you need to support then you'll need a higher-level start symbol representing a sequence of multiple series.

Bison/Flex print value of terminal from alternative

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).

bison:why do the result is wrong when print a constant in a action?

I have the grammatical:
%token T_SHARE
%token T_COMMENT T_PUBLIC T_WRITEABLE T_PATH T_GUESTOK T_VALID_USERS
T_WRITE_LIST T_CREATE_MODE T_DIRECTORY_MODE
%union
{
int number;
char *string;
}
%token <string> T_STRING
%token <number> T_NUMBER T_STATE
%%
parameters:
|parameters parameter
;
parameter:
section_share
|comment
....
section_share:
'[' T_SHARE ']' {section_print(T_SHARE);}
;
comment:
T_COMMENT '=' T_STRING {print(2);parameter_print(T_COMMENT);}
;
the function print is:
void print(int arg)
{
printf("%d\n", arg);
}
but it prints the argument `2' of print to other values that like "8508438", without rule. why?
It's very hard to understand what you are trying to ask, but I think you are confusing tokens' numeric codes with their semantic values. In particular, there is nothing special about the print(2) call in the action associated with your 'comment' rule. It is copied literally to the generated parser, so, given the definition of the print() function, a literal '2' should be printed each time that rule fires. I think that's what you say you observe.
If instead you want to print the semantic value associated with a symbol in the rule, then the syntax has the form $n, where the number after the dollar sign is the number of the wanted symbol in the rule, counting from 1. Thus, in the 'comment' rule, the semantic value associated with the T_STRING symbol can be referenced as $3. For example:
comment:
T_COMMENT '=' T_STRING { printf("The string is %s\n", $3); }
;
Semantic values of primitive tokens must be set by your lexical analyzer to be available; semantic values of non-terminals must be set by actions in your grammar. Note also that mid-rule actions get included in the count.
Although token symbols such as your T_COMMENT can be used directly in actions, it is not typically useful to do so. These symbols will be resolved by the C preprocessor to numbers characteristic of the specific symbol. The resulting token codes have nothing to do with the specific values parsed.

Left-recursive error with my C grammar

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.

Resources