Chase Down My Dream

Life, Dream

  • Home
  • About
  • Sample Page
Twitter Facebook Sina RSS
Tag Archives: Lex

Play with Lex(Flex), the Lexical-Analyzer Generator

Posted on February 25, 2009 by stingrey
4 Comments

这学期开始学习编译原理,于是开始接触到一些好玩的工具,Lex(Lexical compiler)和Yacc(Yet Another Compiler Compiler),这两个都是UNIX下很著名的工具(Linux下是Flex和Bison)。最近主要是在学习词法分析,因此主要就玩玩Lex。Lex主要功能就是是生成一个词法分析器,然后将输入的各种符号,转化成相应的token,这些token被用来做后阶段的处理。
一个Lex文件的语法结构很简单,只要按照格式写就可以了。

declarations%%translation rules%%auxiliary procedures

当然在declaration部分还可以添加

%{  ............%}

这部分的内容会被直接拷贝进Lex编译完后的.c文件里,因此可以用来处理一些变量。在declaration定义一些正则表达式,用在 translation rules做规则匹配。在auxiliary procedures部分可以像写C代码一样写些东西,以函数yylex()开头就可以了,这个函数是Lex用来词法分析的主函数。 按照入门教程,写了个数词的程序。

%{    int wordCount = 0;%}

chars [A-Za-z_'."]
numbers ([0-9])+
delim [" "tn]
ws {delim}+
words {chars}+

%%
{words} {printf("Words:%sn",yytext);wordCount++;}
{ws} {}
{numbers} {printf("Number:%sn",yytext);}
%%
int main()
{
    yylex();
    printf("Number of words:%dn", wordCount);
    return 0;
}
int yywrap(){return 1;}

用Lex编译成lex.yy.c之后,再用gcc编译成可执行文件就可以了。在flex中貌似要求加上最后那个yywrap()这个函数,否则会有警告或者错误(不过据说可以在lex文件直接加个选项)。昨天调试时,输了n长的段子,可以最后没有显示词数,无比郁闷。后来想起来是自己没有按ctrl+d提供eof……

Categories: Hello Program | Tags: Lex
  • Recent Posts

    • 一年了,我回来了
    • Un Senso Di Te
    • 好雨时节
    • 虎年来在追昔时
    • 无题
  • Recent Comments

    • hzqtc on 一年了,我回来了
    • aaahexing on Un Senso Di Te
    • RainFlying on 好雨时节
    • Stingrey on 秦时明月,侠骨柔情
    • hzqtc on 被拒了~
  • Archives

    • November 2011
    • June 2010
    • April 2010
    • February 2010
    • December 2009
    • November 2009
    • October 2009
    • September 2009
    • August 2009
    • July 2009
    • June 2009
    • May 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • September 2008
    • July 2008
  • Categories

    • C#
    • Google App Engine
    • Hello Program
    • Linux
    • Linux and Windows
    • Micolog
    • Misc
    • Mojo
    • Music and Movie
    • Windows
    • 另一个自己
    • 玩意儿
    • 生活
  • Meta

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
© Chase Down My Dream. Proudly Powered by WordPress | Nest Theme by YChong