Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a compiler from lex and yacc grammar

Tags:

c

yacc

lex

I'm trying to generate a compiler so I can pass him a .c file after.

I've downloaded both YACC and LEX grammars from http://www.quut.com/c/ANSI-C-grammar-y.html and named them clexyacc.l and clexyacc.y

When generating it on terminal I did :

yacc -d clexyacc.y
lex clexyacc.l

All went fine. When I move on to the last part I get a few errors.

The last part is : cc lex.yy.c y.tab.c -oclexyacc.exe

But I get these errors :

y.tab.c:2261:16: warning: implicit declaration of function 'yylex' is invalid in
      C99 [-Wimplicit-function-declaration]
      yychar = YYLEX;
               ^
y.tab.c:1617:16: note: expanded from macro 'YYLEX'
# define YYLEX yylex ()
               ^
y.tab.c:2379:7: warning: implicit declaration of function 'yyerror' is invalid
      in C99 [-Wimplicit-function-declaration]
      yyerror (YY_("syntax error"));
      ^
clexyacc.y:530:6: error: conflicting types for 'yyerror'
void yyerror(const char *s)
     ^
y.tab.c:2379:7: note: previous implicit declaration is here
      yyerror (YY_("syntax error"));
      ^
2 warnings and 1 error generated.
like image 464
ChasingCars Avatar asked May 17 '14 23:05

ChasingCars


People also ask

Which grammar is used in yacc?

YACC is a program designed to compile a LALR (1) grammar. It is used to produce the source code of the syntactic analyzer of the language produced by LALR (1) grammar. The input of YACC is the rule or grammar and the output is a C program.

What is lex and yacc in system software?

Lex: reads a specification file containing regular expressions and generates a C routine that performs lexical analysis. Matches sequences that identify tokens. Yacc: reads a specification file that codifies the grammar of a language and generates a parsing routine.

How does lex and yacc work together?

lex and yacc often work well together for developing compilers. As noted, a program uses the lex-generated scanner by repeatedly calling the function yylex() . This name is convenient because a yacc-generated parser calls its lexical analyzer with this name.


1 Answers

The version of yacc you are using is producing C code which is invalid for C99.

The code it produces does not include declarations for the functions yylex or yyerror prior to calling them. This is producing the warnings. In the case of yyerror, it is also resulting in an implicit declaration which does not match the later actual definition.

You can get around it by including the following at the top of the .y file:

%{
int yylex();
void yyerror(const char *s);
%}

Or, you can switch to a more modern yacc compiler.

See also this: Simple yacc grammars give an error

like image 129
harmic Avatar answered Oct 17 '22 19:10

harmic