【发布时间】:2017-08-22 16:07:43
【问题描述】:
在我将在这里展示我所做的之前是我尝试做的任务(我是新手,所以我不确定我是否做得很好)。
1. Implement lexical analyzer (using FLEX), as follows:
- Lexical analyzer supplies services next_token(), back_token()
- Lexical analyzer reads text from the input file and identifies tokens. This
happens when function next_token() is called.
- When a token is identified in the input text, it should be stored in a data
structure. For each token, the following attributes are saved:
* token type
* token lexeme
* number of the line in the input text in which this token was found.
- Blanks, tabs, new lines – are not tokens, and should be ignored
- For each token, print (on a separate line) its type (e.g. rel_op , number , etc.)
and lexeme
- Each operation, keyword, separation sign and each type of number should be
implemented as a token of a different kind
- Kinds of tokens are coded with integer numbers, for example:
# define ID_tok 1
# define COMMA_tok 2
使用 Flex 我已经写了这个:
%{
#include<stdio.h>
int line=1;
# define ID_tok 1
# define COMMA_tok 2
#define REL_OP_tok 3
#define NUMBER_tok 4
#define KEYWORDS_tok 5
%}
binary_ar_op "*"|"/"|"+"|"-"
rel_op "=="|"!="|">"|"<"|"<="|">="
id [a-z][a-z0-9]*
number ["+"|"-"]?[0-9]*("."[0-9]+)?
keywords "prabegin"|"parend"|"task"|"begin"|"end"|"integer"|"real"|"do"|"until"|"od"|"send"|"accept"
%%
\n {line++; printf("\n%d:",line);}
{binary_ar_op}+ {printf( "An binary_ar_op: %s (%d) at line(%d)\n", yytext,
atoi( yytext ),line);}
{rel_op}+ {printf( "An rel_op: %s (%d) at line(%d)\n", yytext,
atoi( yytext ),line);}
{id}+ {printf( "An id: %s (%d) at line(%d)\n", yytext,
atoi( yytext ),line);}
{number}+ {printf( "An number: %s (%d) at line(%d)\n", yytext,
atoi( yytext ),line);}
%%
int yywrap()
{
return 1;
}
main()
{
printf("Enter a string of data\n");
yylex();
}
如您所见,我已经定义了我所支持的所有类型,我不明白如何实现 next 和 back,一些指导应该很棒,我还保存了行号,但我猜他们的意思不是什么我写, 我也不明白他们写的定义部分。
我知道这个问题看起来很奇怪,但是我之前没有任何指导或解释就得到了这个作业,所以我是自己学习的,我并不完全理解(虽然我知道这个理论,谢谢!)。
【问题讨论】:
标签: c flex-lexer lex lexical-analysis lexical