.quotation
{
color:#9900FF;
}
.comment
{
color:green;
}
.keyword
{
color:blue;
}
.prehead
{
color:red;
}
.codearea
{
text-align:left;
width:700px;
background:#f0f5f9;
margin:5px;
padding:5px;
border:#105f97 1px solid;
}
大家知道tiny是一个非科班出身的软件开发者,所以,我是没有正式学过编译原理的。在我的职业生涯里面多次想学,但是总有人告诉我那东西没有什么
用处(也是啊!难道我要写个编译器和VC竞争么?),所以我一直没有学。然而后来很多事情改变了我的看法,一方面是正则表达式的广泛用途,另外也是我的虚
拟机项目,我想在里面用自己做的编译器。还有就是我的前同事LEE做的虚拟机的广泛使用等等,让我感受到不管什么技术,总有用武之地。今天凌晨0点多的时候,我又在看《编译原理技术与工具(龙书)》和《编译原理和实践》,但是光看书不实践等于零,所以,我想我是不是可以做一个代码加亮工具呢?说做就做,到了清晨5点多的时候,我写完了。下面是代码:
htmlpre.lex文件,进行预处理把一些在HTML需要转码代码先转码:
%{
#include <stdio.h>
int yywrap();
%}
%%
"<" {printf("<");}
">" {printf(">");}
\t {printf(" ");}
" " {printf(" ");}
{printf(" ");}
%%
int main()
{
yylex();
return 0;
}
int yywrap()
{
return 1;
}
cpp.lex文件,进行代码加亮:
%{
/*
#
*/
#include <stdio.h>
#define FALSE 0
#define TRUE 1
int yywrap();
%}
DIGIT [0-9]
NUMBER {DIGIT}+
LETTER [a-zA-Z]
WORD {LETTER}+
WHITESPACE [ \t]+
DELIMITER [,(){}[]-+*%/="'~!&|<>?:;.#]
NL \r?\n
QUOTATION \"[^"\n]*\"
KEYWORD "auto"| "bool"| "break"| "case"| "catch"| "char"| "cerr"| "cin"| "class"| "const"| "continue"| "cout"| "default"| "delete"| "do"| "double"| "else"| "enum"| "explicit"| "extern"| "float"| "for"| "friend"| "goto"| "if"| "inline"| "int"| "long"| "namespace"| "new"| "operator"| "private"| "protected"| "public"| "register"| "return"| "short"| "signed"| "sizeof"| "static"| "struct"| "switch"| "template"| "this"| "throw"| "try"| "typedef"| "union"| "unsigned"| "virtual"| "void"| "volatile"| "while"| "__asm"| "__fastcall"| "__based"| "__cdecl"| "__pascal"| "__inline"| "__multiple_inheritance"| "__single_inheritance"| "__virtual_inheritance"
PREWORD "define"| "error"| "include"| "elif"| "if"| "line"| "else"| "ifdef"| "pragma"| "endif"| "ifndef"| "undef"| "if"| "else"| "endif"
PREDEF "#"{PREWORD}
LINECOMMENT "\/\/".*\n
%%
"/*" {
char c;
int done=FALSE;
printf("<span class=\"comment\">\n");
ECHO;
do
{
while((c=input())!='*')
{
if(c=='\n')
printf("<br/>\n");
else
putchar(c);
}
putchar(c);
while((c=input())=='*')
putchar(c);
if(c=='\n') printf("<br/>\n");
putchar(c);
if(c=='/') done=TRUE;
} while(!done);
printf("</span>\n");
}
{LINECOMMENT} {printf("<span class=\"comment\">%s</span><br/>\n",yytext);}
{QUOTATION} {printf("<span class=\"quotation\">%s</span>",yytext);}
{PREDEF} {printf("<span style=\"predef\">%s</span>",yytext);}
{KEYWORD} {printf("<span class=\"keyword\">%s</span>",yytext);}
{NL} {printf("<br/>\n");}
{WORD} {ECHO;}
{NUMBER} {ECHO;}
{WHITESPACE} {ECHO;}
%%
int main()
{
printf("<html>\n");
printf("<head>\n");
printf("<link href=\"mycpp.css\" rel=\"stylesheet\" type=\"text/css\">\n");
printf("</head>");
printf("<body>\n");
yylex();
printf("</body>");
printf("</html>");
return 0;
}
int yywrap()
{
return 1;
}
test.cpp文件,用来测试的加亮效果的小程序:
/*
* just test my code lighting tools
* by tinyfool
* 2005-04-15
*
* */
#include <stdio.h>
int main()
{
char x[]="xxx";
//printf(x);
return 0;
}
时间仓促,写得远非完美(字符串中的转码还不支持),但是也让我有了非常大的成就感,我会继续改进这个东西的。代码中的谬误和不良也请读者不吝赐教。