Lex and Yacc
Lex and Yacc
860378565
Lex , Yacc
.
Parser Generator
. .
Yacc Yacc .
""Yet Another Compiler Compiler Compiler Compiler .
. Yacc.
Bison Package Linux Unix
.
Yacc
Yacc .
translate.y
UNIX C C .
Yacc translate.y
translate.y C y.tab.c
LALR . y.tab.c LALR
C .
. (Lex and Yacc) ly
UNIX a.out
) (Parse translate.y
. a.out C .exe
.
exe .
Yacc
Compiler
y.tab.c
Yacc
Specification
translate.y
a.out
C
Compiler
y.tab.c
output
)a.out (exe
Input
:Yacc
Yacc 3 %%
. :
declarations
%%
translation rules
%%
supporting C-routines
:
Yacc .
. :
E E+T | T
T T*F | F
F (E) | digit
:declaration :
C #include { % }%
. Token Token .
.
Token %token .
:Translation rules
yacc %% .
:
>< left side > < alt 1 > | < alt 2 > | | < alt n
yacc :
} { semantic action 1
} { semantic action 2
} { semantic action n
Yacc
. token
.
Yacc .
.
semantic action C C
header Yacc .
.
.
yacc :
{%
>#include <ctype.h
}%
%token DIGIT
%%
: expr \n
} ;){ printf(%d\n,$1
line
;
} ;{ $$=$1+$3
} ;{ $$=$1*$3
} ;{ $$=$2
| DIGIT
;
%%
)(yylex
{
;int c
;)(c = getchar
) )if ( isdigit (c
{
; yyval=c - 0
5
;return DIGIT
}
;return c
}
> #include<ctype.h preprocessor C header
isdigit . %token DIGIT
Token .
.
; . semantic action $$
reduce . $1
: | . $3 ....
} ;{ $$=$1+$3
: expr \n
line
;
\n
. line . semantic action
.
. $1 expr
.
6
Lexical Analyser
. )( yylex yacc .
error recovery ...
. Token .
DIGIT yyval .
Yacc .
DIGIT Token .
Token .
. Yacc Lex
. Lex
yacc . Lex ll )(yylex
. Yacc . Lex
)( yylex Yacc
:
#include lex.yy.c
Lex Yacc .
#include lex.yy.c )( yylex Yacc Token .
Lex Yacc y.tab.c .
UNIX first.l
second.y .
:
lex first.l
yacc second.y
cc y.tab.c ly -ll
Lex .
:Lex
Lex .
:
Metacharacter
Matches
\n
newline
\n
ab
a|b
ab
(ab)+
][
character class
Expression
Matches
abc
abc
*abc
abc+
a(bc)+
a, abc
?)a(bc
one of:
][abc
][a-z
a, -, z
one of:
][a\-z
-az
one of:
][-az
a, b, c
a, b
whitespace
[ \t\n]+
anything except:
][^ab
a, ^, b
][a^b
a, |, b
][a|b
a, b
a|b
Lex
.
)( main
C . wrap
. :
{%
;int yylineno
}%
%%
;)printf("%4d\t%s", ++yylineno, yytext
^(.*)\n
%%
yylineno .
.
\n \n
. main
. Lex Yacc
.
Name
Function
Token
)int yylex(void
Token
char *yytext
yyleng
Token
yylval
1 0 .
)int yywrap(void
FILE *yyout
FILE *yyin
ECHO
Lex
.
{%
>#include <stdio.h
}%
number [0-9]+\.? | [0-9]*\.[0-9]+
%%
}*{ /* skip blanks /
;) { sscanf( yytext ,%lf, &yyval
] [
}{number
} ;return NUMBER
} ;]{ return yytext[0
\n |.
%%
)int yywrap(void
{
;return 1
}
)int main(void
{
10
;)(yylex
;return 0
}
)( wrap .
11