初解《Compiler Construction Principle and Practice》习题

2405阅读 0评论2008-06-18 nmap
分类:C/C++

    初解《Compiler Construction Principle and Practice》习题
   
    确实,
《Compiler Construction Principle and Practice》是入门学习编译原理的一部好
书,作者Kenneth C.Louden教授的写作风格独树一帜,以一个简易且十分有趣的tiny语言
作为贯穿整部书的脉络,围绕编译器的具体实现这一主题,展开论述,Louden教授还为tiny
语言发明了tiny machine虚拟机,只要有兼容ANSI C的编译器的朋友,就可以体验、学习
tiny语言。
    做了几个书中的习题,试解答其中简单一二,如有不当,望请批评。

习题2.1 为以下字符集编写正则表达式;若没有正则表达式,则说明原因:
    a. 以a开头和结尾的所有小写字母串。

答:
    该小写字母串的正则表达式为,"a"{lowcase}*"a"。
    其中lowcase表示所有的小写字母。

用lex测试了一番,还有些困难,可能是lex语法还是不熟悉,最终google一番资料才找到
解答,lex测试程序如下,其中not_letter表示非52个大小写字母,str为解答的字符串
正则表达式:


%{
/****************************************************************************
mylexer.l
ParserWizard generated Lex file.

Func: 测试《Compiler Construcion Principles And Practice》
     一书的习题2.1
    
Date: 2008年6月18日
****************************************************************************/


#include <stdio.h>

%}

/////////////////////////////////////////////////////////////////////////////

// declarations section


// place any declarations here


// 小写字母

lowcase        [a-z]

// 非字母

not_letter    [^a-zA-Z]

// 以小写a开始,也以它结尾的字符串

str            "a"{lowcase}*"a"{not_letter}

%%

/////////////////////////////////////////////////////////////////////////////

// rules section


// place your Lex rules here

{str}            {printf("yes,it's right\n");}
%%

/////////////////////////////////////////////////////////////////////////////

// programs section


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


参考资料:
[1]

《Lex - A Lexical Analyzer Generator》

M. E. Lesk and E. Schmidt

[2]

《正则表达式30分钟入门教程》

deerchao

[3]《Compiler Construction Principle and Practice》

Kenneth Louden

[4]《Lex and Yacc》2nd
John Levine

上一篇:地震的哀思
下一篇:《The C Programming Language》中的小瑕疵