CS152
Chris Pollett
Sep 20, 2021
id_list ::= id_list_prefix ; id_list_prefix ::= id_list_prefix , id | id
stmt ::= id := expr stmt ::= id (argument_list)
id_list ::= id id_list_tail id_list_tail ::= , id id_list_tail | ;
stmt ::= id stmt_list_tail stmt_list_tail ::= := expr | (argument_list)
stmt ::= if condition then_clause else_clause | other_stmt then_clause ::= then stmt else_clause ::= else stmt | empty-string
if C_1 then if C_2 then S_1 else S_2as either:
if C_1 then if C_2 then S_1 else S_2or
if C_1 then if C_2 then S_1 else S_2
stmt ::= balanced_stmt | unbalanced_stmt
balanced_stmt ::= if condition then balanced_stmt else balanced_stmt
| other_stmt
unbalanced_stmt ::= if condition then stmt
| if condition then balanced_stmt else unbalanced_stmt
else_clause ::= else stmt | empty-stringwe would prefer else stmt over empty-string which would mean we pairs else's with the nearest then.
Which of the following statements is true?
<factor> ::= (<expr>)|<number>
<number> ::= <digit> {<digit>}
<digit> ::= 0|1|2|3|4|5|6|7|8|9
We need First((<expr>)) and First(<number>) to be disjoint.A → B [C] D. C→ aE | bF. D→ cG.
%{// C code to insert verbatim at start of program
%}
/* Lex/Yacc Definitions */
%%
//Lex/Yacc code
%%
// more C code.
%{
#include <stdio.h>
int wordCount = 0;
%}
word [^ \t\n]+ /* make an abbreviation word for the expr
[^ \t\n]+ (make sure to delete this comment before runninf lex)*/
%%
[\t\n ]+ {printf("I see whitespace\n");} //what to do if see pattern
{word} {wordCount++;}
%%
int main()
{
yylex(); //call the lexer. Gets input from command line until ^D
printf("word count: %d", wordCount); return 0;
}
To compile:
lex -o lextest.c lextest.l #default output is lex.yy.c
gcc lextest.c -o lextest -ll #-ll not needed if use flex.
Suppose we put this file in yacctest.y
%{
#include <stdio.h>
int yylex();
int yyerror();
%}
%token ARTICLE NORMAL_NOUN PROPER_NOUN
%%
noun_phrase : PROPER_NOUN { printf("Proper Noun\n"); }
| ARTICLE NORMAL_NOUN {printf("Usual Noun\n"); }
%%
int main(int argc, char **argv)
{
extern FILE *yyin;
yyin = fopen(argv[1], "r"); //sets up lexer to use this file as input
yyparse();
fclose(yyin);
}
yacc -d yacctest.y
A|a|The|the {return ARTICLE;}
%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
A|a|The|the {return ARTICLE;}
dog|cat {return NORMAL_NOUN;}
Chris|Mary {return PROPER_NOUN;}
%%
lex -o lex.yy.c lex.yy.l
gcc -o yacctest y.tab.c lex.yy.c -ly -ll
The cat
>./yacctest eng.txt Usual Noun