I just returned to school yesterday and did not do anything for a long time. I learned how to use flex and bison.
Logo language is a simple drawing language, because it is easy to use and interesting, many elementary schools were also used as computer enlightenment courses earlier.
Currently, this program has implemented basic commands and supports nested loops. Function definition is not implemented.
The following are lexical files for flex.
% {
Typedef char * string;
# Define yystype string
# Include "2_tab.cpp.h"
# Include <stdio. h>
# Include <string. h>
# Include <stdlib. h>
# Include <Io. h>
# Include <math. h>
Extern char * yylval;
%}
Char [A-Za-Z]
Num [0-9]
Other [^ A-Za-z0-9/[/]
Others {Other} +
Command {Char} +
Number {num} +
Left /[
Right/]
%
{Command} {yylval = strdup (yytext); return command ;}
{Number} {yylval = strdup (yytext); return number ;}
{Left} {yylval = strdup (yytext); return left ;}
{Right} {yylval = strdup (yytext); return right ;}
{Other }{}
%
Int yywrap ()
{
Return 1;
}
The following is the syntax definition file used by bison.
% {
Typedef char * string;
# Define yystype string
# Include "cpp2c. H"
# Include <stdio. h>
# Include <stdlib. h>
# Include <malloc. h>
Int yylex ();
Int yyerror (char * MSG)
{
Printf ("error encountered: % s/n", MSG );
Return 1;
}
Extern file * yyin;
%}
% Token number
% Token command
% Token left
% Token right
%
Cmds: cmds cmd
| Cmd
;
CMD: Command numbers {addcmd ($1 );}
| Command number left cmds right {int I = atoi ($2); loopend (I );}
;
Left: Left {loopstart ();}
;
Right: Right
;
Numbers:/* empty */
| Numbers number {double D = atof ($2); getparam (d );}
| Number {double D = atof ($1); getparam (d );}
;
%
Void logoparse ()
{
Start ();
Yyparse ();
End ();
}
Note that the match definition of the non-terminator numbers will cause the "Import/Contract conflict" Warning of bison. This warning can be ignored because bison performs the import operation by default when such a conflict occurs.
The test file is as follows (a peony program found on the Internet)
Undraw/* pick up */
Home
Draw/* pen writing */
RT 30 RT 180
For 12
[
For 12
[
For 12
[
For 60
[
FD 1
RT 3
]
Lt 180
RT 30
]
RT 30
]
RT 30
]
Lt 30 lt 180
Run the program on the following page: