編譯原理學習:TINY語言詞法掃描程式實現,tiny詞法

來源:互聯網
上載者:User

編譯原理學習:TINY語言詞法掃描程式實現,tiny詞法

最近對解釋型程式(類似python或者是linux裡的bc計算機)非常感興趣,就開始學習一下編譯原理。今天自己實現了TINY語言的詞法掃描程式。大部分參考《編譯原理及實踐》一書。但是我做了一些小小的改進。

先說一下TINY語言:

1、注釋:放在一對大括弧內。書上的注釋不能嵌套,我做了一點改進,允許嵌套。

2、關鍵字:read write if end repeat until else

3、類型:只支援整型和布爾型。

4、計算:+ - * / ( ) < = :=,其中:=為賦值運算,=為判斷。沒有〈和<= >=

一個樣本的TINY語言程式:

test.tine: (選自《編譯原理及實踐》)

{ Sample program  in TINY language -  computes factorial}read x; { input an integer }if 0 < x then { don't compute if x <= 0 }fact := 1;repeatfact := fact * x;x := x - 1;until x = 0;write fact { output factorial of x }end

在globals.h中,涉及到一些類型的聲明:

#ifndef GLOBALS_H#define GLOBALS_H#include <stdio.h>typedef enum {ENDFILE, ERROR,IF, THEN, ELSE, END, REPEAT, UNTIL, READ, WRITE,ID, NUM,ASSIGN, EQ, LT, PLUS, MINUS, TIMES, OVER, LPAREN, RPAREN, SEMI} TokenType;extern lineno;/* The max size of identifier of reserved word */#define MAXTOKENLEN 50#endif

用於產生詞法掃描的flex輸入,這是程式的核心部分:

tiny.l

%{#include <stdio.h>#include <string.h>#include "globals.h"#include "util.h"char tokenString[MAXTOKENLEN + 1];%}digit[0-9]number{digit}+letter[a-zA-Z]identifier{letter}[a-zA-Z0-9]*newline\nwhitespace[ \t]%%"if"{return IF;}"then"{return THEN;}"else"{return ELSE;}"end"{return END;}"repeat"{return REPEAT;}"until"{return UNTIL;}"read"{return READ;}"write"{return WRITE;}":="{return ASSIGN;}"="{return EQ;}"<"{return LT;}"+"{return PLUS;}"-"{return MINUS;}"*"{return TIMES;}"/"{return OVER;}"("{return LPAREN;}")"{return RPAREN;}";"{return SEMI;}{number}{return NUM;}{identifier}<span style="white-space:pre"></span>{return ID;}{newline}{lineno++;}{whitespace}<span style="white-space:pre"></span>{ /* Do nothing */ }"{"{ char c;  int count = 1;  do  {  c = input();  if (c == EOF) break;  else if (c == '\n') lineno++;  else if (c == '{') count++;  else if (c == '}') count--;  } while (count != 0);}.{return ERROR;}%%TokenType getToken(void){TokenType currentToken;currentToken = yylex();strncpy(tokenString, yytext, MAXTOKENLEN);printf("%d: ", lineno);printToken(currentToken, tokenString);return currentToken;}

printToken函數在util.c中實現:

util.h:

#ifndef UTIL_H#define UTIL_H#include "globals.h"void printToken(TokenType token, char* tokenString);TokenType getToken(void);#endif

util.c:

#include "util.h"#include <stdio.h>#include "globals.h"void printToken(TokenType token, char* tokenString){switch(token){case IF:case THEN:case ELSE:case END:case REPEAT:case UNTIL:case READ:case WRITE:printf("\treversed word: %s\n", tokenString);break;case ID:printf("\tidentifier: %s\n", tokenString);break;case NUM:printf("\tnumber: %s\n", tokenString);break;case ASSIGN:case EQ:case LT:case PLUS:case MINUS:case TIMES:case OVER:case LPAREN:case RPAREN:case SEMI:printf("\toperator: %s\n", tokenString);}}

這就是所有的檔案了!最後,是makefile檔案:

scanner.exe: main.o lex.yy.o util.ogcc main.o lex.yy.o util.o -o scanner.exe -lflmain.o: main.c globals.h util.hgcc main.c -cutil.o: util.c util.h globals.hgcc util.c -clex.yy.o: tiny.lflex tiny.lgcc lex.yy.c -c

於是,一個簡單的詞法掃描程式就完成了。

由於使用的是預設的輸入,所以這個程式直接支援從鍵盤輸入,運行效果如下:


當然,也可以使用重新導向操作,使用效果如下:




編譯原理課程設計-詞法分析器設計(C語言)

#include "stdio.h" /*定義I/O庫所用的某些宏和變數*/
#include "string.h" /*定義字串庫函數*/
#include "conio.h" /*提供有關螢幕視窗操作函數*/
#include "ctype.h" /*分類函數*/
char prog[80]={'\0'},
token[8]; /*存放構成單詞符號的字串*/
char ch;
int syn, /*存放單詞字元的種別碼*/
n,
sum, /*存放整數型單詞*/
m,p; /*p是緩衝區prog的指標,m是token的指標*/
char *rwtab[6]={"begin","if","then","while","do","end"};
void scaner(){
m=0;
sum=0;
for(n=0;n<8;n++)
token[n]='\0';
ch=prog[p++];
while(ch==' ')
ch=prog[p++];
if(isalpha(ch)) /*ch為字母字元*/{
while(isalpha(ch)||isdigit(ch)) /*ch 為字母字元或者數字字元*/{
token[m++]=ch;
ch=prog[p++];}
token[m++]='\0';
ch=prog[p--];
syn=10;
for(n=0;n<6;n++)
if(strcmp(token,rwtab[n])==0) /*字串的比較*/{
syn=n+1;
break;}}
else
if(isdigit(ch)) /*ch是數字字元*/{
while(isdigit(ch)) /*ch是數字字元*/{
sum=sum*10+ch-'0';
ch=prog[p++];}
ch=prog[p--];
syn=11;}
else
swit......餘下全文>>

 
編譯原理詞法剖析器

#include <iostream>
#include <ctype.h>
#include <fstream>
#include <string.h>
#include <malloc.h>

using namespace std;

ifstream fp("source.txt",ios::in);
char cbuffer;
char *key[13]={"if","else","for","while","do","return","break","continue","int","void"
,"main","const","printf"}; //關鍵字
char *border[7]={ "," , ";" , "{" , "}" , "(" , ")" ,"//"}; //分界符
char *arithmetic[6]={"+" , "-" , "*" , "/" , "++" , "--"}; //運算子
char *relation[7]={"<" , "<=" , "=" , ">" , ">=" , "==" ,"!="}; //關係運算子
char *lableconst[80]; //標識符
int constnum=40;
int lableconstnum=0;
int linenum=1; //統計常數和標識符數量
int search(char searchchar[],int wordtype)
{

int i=0,t=0;
switch (wordtype)
{
case 1:
{ for (i=0;i<=12;i++) //關鍵字
{
if (strcmp(key[i],searchchar)==0)
return(i+1);
}
return(0);}
case 2:
{
for (i=0;i<=6;i++) &#......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.