詞法分析

實做詞法分析

組合語言詞法分析

lex

安裝

sudo pacman -S flex

使用stdin輸入

lex

使用檔案輸入

lex file.l

多次lexing

如果要多次lexing需要採用yyrestart(fp)

void yyrestart(FILE *pt);

範例程式

%option noyywrap
%%
[0-9]+ number(yytext);
%%

void number(char *str){
  printf("hello world: %s\n", str);
}

int main() {
  yylex();
  return 0;
}

原始碼

範例二

digit ([0-9])
integer ({digit}+)
keywords int|float|byte|bool|func|return
delimiter [,()\[\]{}]

%%
{integer} {
  printf("int: %s\n", yytext);
}

{delimiter} {
  printf("de: %s\n", yytext);
}

{keywords} {
  printf("keywords: %s\n", yytext);
}

%%

int main() {
  yylex();
  return 0;
}

常見問題

出現undefined reference to `yywrap'無法編譯

使用flex要連結-lfl

gcc lex.yy.c -lfl  

或採用noyywrap

%option noyywrap

System Program