重慶分公司,新征程啟航
為企業提供網站建設、域名注冊、服務器等服務
為企業提供網站建設、域名注冊、服務器等服務
本篇文章給大家分享的是有關如何理解lex和yacc,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
我們提供的服務有:做網站、網站制作、微信公眾號開發、網站優化、網站認證、西平ssl等。為上1000家企事業單位解決了網站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的西平網站制作公司
一、背景
從零開始學習下lex和yacc
1. 基礎
lex只有狀態和狀態轉換,沒有棧,善于模式匹配;yacc能處理帶棧的FSA(有限狀態機),更適合更復雜的任務。
模式匹配原語
元字符 | 匹配說明 |
. | 任意字符( 除了換行) |
換行 | |
* | 0次或者多次重復前面的表達式 |
+ | 1次或者多次重復前面的表達式 |
? | 0次或者1次重復前面的表達式 |
^ | 行的開始 |
$ | 行的結尾 |
a|b | a or b |
(ab)+ | 1次或者多次重復組ab |
[...] | 任意一個出現的字符 |
一些匹配的例子
表達式 | 匹配說明 |
abc | abc |
abc* | ab, abc, abcc, abccc,..... |
abc+ | abc, abcc, baccc,...... |
a(bc)+ | abc, abcbc, abcbcbc,...... |
a(bc)? | a, abc |
[abc] | a, b, c |
[a-z] | a到z的任意字符 |
[a\-z] | a, -, z |
[-az] | -, a, z |
[a-zA-Z0-9]+ | 一個或者多個任何數字字母 |
[ \t\n] | witespace |
[^ab] | 除了a,b的任何字符 |
[a^b] | a, ^, b |
[a|b] | a, |, b |
a|b | a or b |
匹配規則:
1. 貪心: 兩個模式去匹同一個字符串,匹配上最長的模式
2. 順序優先: 兩個相同長度的模式, 匹配上先定義的模式
.l文件內容的格式被%%分成了三部分,如下:
....definitions.....
%%
.....rules....
%%
...subroutines...
其中rules是必須的,其他部分可選
一些內置函數以及變量
int yylex(void) | 調用分析器,返回 token |
char *yytext | 指定匹配的字符串 |
yyleng | 匹配上的字符串的長度 |
int yywrap(void) | 返回1 則結束了 |
FILE *yyout | 輸出文件,默認 stdout |
FILE *yyin | 輸入文件, 默認stdin |
INITIAL | initial start condition |
BEGIN condition | switch start condition |
ECHO | write mached string |
#define ECHO fwrite(yytext, yyleng, 1, yyout)
二、開始第一個例子
環境說明:
VMware Workstation 12 Pro, ubuntu17.04 ,lex2.6.1
輸出文件的內容并且在前面增加行號
lineno.l
%{ int yylineno; %} %% ^(.*)\n printf("%4d\t%s", ++yylineno, yytext); %% int main(int argc, char *argv[]) { FILE *fp = NULL; if (argc == 2) { fp = fopen(argv[1], "r"); if (NULL != fp) { yyin = fp; } } yylex(); if (NULL != fp) { fclose(fp); } return 0; }
使用lex將lineno.l文件轉換為.c文件
$ lex lineno.l $ls lex.yy.c lineno.l
使用gcc 將lex.yy.c編譯成可執行文件
$ gcc lex.yy.c -o lineno
/tmp/ccNgesbZ.o:在函數‘yylex’中:
lex.yy.c:(.text+0x55c):對‘yywrap’未定義的引用
/tmp/ccNgesbZ.o:在函數‘input’中:
lex.yy.c:(.text+0x116c):對‘yywrap’未定義的引用
collect2: error: ld returned 1 exit status
網上查詢說是要在.l文件中實現yywrap函數
修改后:
%{ int yylineno; %} %% ^(.*)\n printf("%4d\t%s", ++yylineno, yytext); %% int main(int argc, char *argv[]) { FILE *fp = NULL; yylineno = 0; if (argc == 2) { fp = fopen(argv[1], "r"); if (NULL != fp) { yyin = fp; } } yylex(); if (NULL != fp) { fclose(fp); } return 0; } int yywrap() { return 1; }
再次編譯成功
$gcc lex.yy.c -o lineno $lineno lineno.l
1 %{
2 int yylineno;
3 %}
4
5 %%
6 ^(.*)\n printf("%4d\t%s", ++yylineno, yytext);
7 %%
8
9 int main(int argc, char *argv[])
10 {
11 FILE *fp = NULL;
12 yylineno = 0;
13
14 if (argc == 2) {
15 fp = fopen(argv[1], "r");
16 if (NULL != fp) {
17 yyin = fp;
18 }
19 }
20
21 yylex();
22
23 if (NULL != fp) {
24 fclose(fp);
25 }
26
27 return 0;
28 }
29
30 int yywrap()
31 {
32 return 1;
33 }
以上就是如何理解lex和yacc,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注創新互聯行業資訊頻道。