Use Flex to produce a program that uses stdin as its file source; i.e., instead
ID: 3578406 • Letter: U
Question
Use Flex to produce a program that uses stdin as its file source; i.e., instead of a hand-coded lexer that reads files, let Flex do the hard work using stdin as the input source... you just print out each token's string on a line followed by its token type, all the while counting the non-"bad" tokens. Any file should be usable without crashing... like your executable itself.
Create a file called "help.lex" and be sure it can be run through Flex. Make sure your Flex input tells Flex to produce "help.c" as the output.
Use this fictional language called "help", which contains the following lexical elements
Keywords: "help", "go", "north", "south", "east", "west", "use" and "enter"
Identifiers: one or more contiguous alpha characters that make a nonkeyword string
Numbers: come in three varieties, each led by an optional '+' or '' sign Integers: one or more digits Reals: one or more digits, a decimal point and one or more additional digits Fractions: one or more digits, a '/' and one or more digits
Comments: begin with "//" and continue until the End Of Line (not including the newline) or End Of File (not including the EOF), whichever comes first
Period: a statement terminator '.'. Keep in mind, the period in a real is part of the number token, not a period token.
Newline: In this language, the newline affects syntax, so it is a token, too. All other whitespace should be entirely ignored/unreported.
Please note that the language does NOT allow any uppercase letters.
The output should use theseToken ID's
TOKEN_HELP
TOKEN_GO
TOKEN_NORTH
TOKEN_SOUTH
TOKEN_EAST
TOKEN_WEST
TOKEN_USE
TOKEN_ENTER
TOKEN_IDENTIFIER
TOKEN_NUMBER
TOKEN_NEWLINE
TOKEN_PERIOD
TOKEN_COMMENT
TOKEN_BAD (these are always a single character long)
Explanation / Answer
int num_lines = zero, num_chars = 0;
%%
++num_lines; ++num_chars;
. ++num_chars;
%%
main()
want this for the decision to atof() below */
#include <math.h>
%}
DIGIT [0-9]
ID [a-z][a-z0-9]*
%%
+ ]*"}" /* eat up one-line comments */
[ ]+ /* eat up whitespace */
. printf( "Unrecognized character: %s ", yytext );
%%
main( argc, argv )
int argc;
char **argv;
overlook program name */
if ( argc > zero )
yyin = fopen( argv[0], "r" );
else
yyin = stdin;
yylex();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.