编译原理实验代码
❶ 编译原理 词法分析程序的设计与实现实验题
说他像苍蝇,是骂苍蝇呢还是骂他呢?
❷ 编译原理用C语言实现基于LR(1)或SLR(1)语法分析程序代码,最好还有报告,急。。。
这个是精简的语法分析程序,如果符合的话,hi我
给你实验报告
#include <stdio.h>
#include<dos.h>
#include<stdlib.h>
#include<string.h>
char a[50] ,b[50];
char ch;
int n1,i1=0,n=5;
int E();int T();int  E1();int T1();int F();
void main()                      /*递归分析*/
{
       int f,j=0;
       printf("请输入字符串(长度<50,以#号结束)\n");
       do{
              scanf("%c",&ch);
              a[j]=ch;
              j++;
       }while(ch!='#');
       n1=j;
       ch=b[0]=a[0];
       f=E();
       if (f==0) return;
       if (ch=='#')     printf("accept\n");
       else       printf("error\n");
}
int E() // E→TE'
{  int f,t;
        f=T();
       if (f==0) return(0);
       t=E1();
       if (t==0) return(0);
              else return(1);
}
int T() // T→FT'
{   int f,t;
        f=F();
       if (f==0) return(0);
       t=T1(); 
       if (t==0) return(0);
              else return(1);
}
int  E1()/*E’*/ // E'→+TE'
{   int f;
       if(ch=='+') {  
              b[i1]=ch;
              ch=a[++i1];
              f=T();
              if (f==0) return(0);
              E1();
              return(1);
       }
       return(1);
}
int T1()/*T’*/ // T'→*FT'
{
       int f,t;
       if(ch=='*') { 
              b[i1]=ch;
              ch=a[++i1];
              f=F();
              if (f==0) return(0);
              t=T1();
              if (t==0) return(0);
              else return(1);}
       a[i1]=ch;
       return(1);
}
int F() // F→(E)
{   int f;
       if(ch=='(') { 
              b[i1]=ch;
              ch=a[++i1];
              f=E();
              if (f==0) return(0);
              if(ch==')') {
                     b[i1]=ch; 
                     ch=a[++i1];
              }
               else {
                      printf("error\n");
                      return(0);
               }
       }
       else if(ch=='i') { 
              b[i1]=ch;
               ch=a[++i1]; 
       }
          else {printf("error\n");return(0);}
         return(1);
}
❸ 求编译原理的词法分析器源码
/*		我上编译原理课时的第一次作业就是这个,flex源码. 		*/
%{
#include<math.h>
int num_lines=0;
%}
DIGIT [0-9]
ID		[a-zA-Z_][a-zA-Z0-9]*
%%
"#include"	{
						printf("<包含头文件,请手动合并文件\\>\n");
						fprintf(yyout,"<包含头文件,请手动合并文件\\>\n");
						}
{DIGIT}+	{
						printf("(3整数, \"%s\")\n", yytext);
						fprintf(yyout,"(3整数, \"%s\")\n", yytext);
						}
{DIGIT}+"."{DIGIT}*		{
												printf("(3浮点数, \" %s\")\n",yytext);
												fprintf(yyout,"(3浮点数, \" %s\")\n",yytext);
												}
auto |
break |
case |
char |
const |
continue |
default |
do |
double |
else |
enum |
extern |
float |
for |
goto |
if |
int |
long |
register |
return |
short |
signed |
sizeof |
static |
struct |
switch |
typedef |
union |
unsigned |
void |
volatile |
while		{
					fprintf(yyout,"(1, \"%s\")\n",yytext);
					fprintf(yyout,"(1, \"%s\")\n",yytext);
					}
{ID}		{
					printf("(2, \"%s\")\n",yytext);
					fprintf(yyout,"(2, \"%s\")\n",yytext);
					}
"+" |
"++" |
"+=" |
"-" |
"--" |
"-=" |
"->" |
"*" |
"**" |
"*=" |
"/" |
"/=" |
"="	|
"==" |
">" |
">>" |
">=" |
">>=" |
"<" |
"<<" |
"<=" |
"<<=" |
"!" |
"!=" |
"%" |
"%=" |
"&" |
"&&" |
"&=" |
"|" |
"||" |
"|=" |
"^" |
"^=" 	{
				printf("(4, \"%s\")\n",yytext);
				fprintf(yyout,"(4, \"%s\")\n",yytext);
				}
"{" |
"}" |
"(" |
")" |
";" |
","	|
"'" |
"\"" |
"." |
"?" |
"[" |
"]" |
"\\" |
":" 	{
    	printf("(5, \"%s\")\n",yytext);
    	fprintf(yyout,"(5, \"%s\")\n",yytext);
    }
\n  {
			++num_lines;
			}
"/*"[^(*/)\n]*"*/"
(" ")+
[\t]+ 
 .		{
 			 printf("(不能识别字符, \"%s\")\n",yytext);
 			fprintf(yyout,"(不能识别字符, \"%s\")\n",yytext);
 		}
%%
main(argc,argv)
int argc;
char **argv;
{
	++argv,--argc;
	if(argc>0)	
		yyin=fopen(argv[0],"r");
	else
		yyin=stdin;
	yyout=fopen("output.txt","w");
	yylex();
	fclose(yyout);
}
int yywrap()
{
	return 1;
}
/*  附:我们第一次作业的要求。
实验一:用高级语言编写词法分析器(用lex生成)一、实验目的:编制一个识别C语言子集的词法分析器。从输入的源程序中,识别出各个具有独立意义的记号,即基本保留字、标识符、常数、运算符、分隔符五大类。并依次输出各个记号的内部编码及记号符号自身值。(遇到错误时可显示“Error”,然后跳过错误部分继续显示)二、实验过程和指导:(一)准备:1.阅读课本有关章节,明确语言的词法,写出基本保留字、标识符、常数、运算符、分隔符和程序例。2.初步编制好程序。3.准备好多组测试数据。(二)程序要求:程序输入/输出示例:如源程序为C语言。输入如下一段:main(){   int a,b;   a = 10;   b = a + 20;}要求输出如下:(2,”main”)(5,”(“)(5,”)“)(5,”{“)(1,”int”)(2,”a”)(5,”,”)(2,”b”)(5,”;”)(2,”a”)(4,”=”)(3,”10”)(5,”;”)(2,”b”)(4,”=”)(2,”a”)(4,”+”)(3,”20”)(5,”;”)(5,”)“} 
要求(满足以下要求可获得70%该题的得分):识别保留字:if、int、for、while、do、return、break、continue其他的都识别为标识符;常数为无符号整形数;运算符包括:+、-、*、/、=、>、<、>=、<=、!=分隔符包括:,、;、{、}、(、)以上为参考,具体可自行增删。 三、实验检查:1.程序:输入:测试数据(以文件形式);输出:二元组(以文件形式)。2.实验报告:(1)功能描述:该程序具有什么功能?(2)状态转换图。(2)程序结构描述:函数调用格式、参数含义、返回值描述、函数功能;函数之间的调用关系图、程序总体执行流程图。(4)源程序代码。(5)实验过程记录:出错次数、出错严重程度、解决办法摘要。(6)实验总结:你在编程过程中花时多少?多少时间在纸上设计?多少时间上机输入和调试?多少时间在思考问题?遇到了哪些难题?你是怎么克服的?你对你的程序的评价?你的收获有哪些?
另可附加:关键字 有符号数 符号表填写 行号记录,等
*/
❹ 编译原理 语义分析 算术表达式求值代码
java字符串算术表达式求值:importjava.util.ArrayList;importjava.util.Stack;/****@authoryhh**/publicclassCalculate{/***将字符串转化成List*@paramstr*@return*/publicArrayListgetStringList(Stringstr){ArrayListresult=newArrayList();Stringnum="";for(inti=0;igetPostOrder(ArrayListinOrderList){ArrayListresult=newArrayList();Stackstack=newStack();for(inti=0;ipostOrder){Stackstack=newStack();for(inti=0;i
❺ 编译原理实验二 算术表达式扩充
你是需要解释分析过程,还是需要用代码写出你的程序的分析过程?
❻ 有人知道编译原理实验之词法分析器用C++怎么做吗
#include "globals.h"
#include "util.h"
#include "scan.h"
#include "parse.h"
static TokenType token; /* holds current token */
/* function prototypes for recursive calls */
static TreeNode * stmt_sequence(void);
static TreeNode * statement(void);
static TreeNode * if_stmt(void);
static TreeNode * repeat_stmt(void);
static TreeNode * assign_stmt(void);
static TreeNode * read_stmt(void);
static TreeNode * write_stmt(void);
static TreeNode * exp(void);
static TreeNode * simple_exp(void);
static TreeNode * term(void);
static TreeNode * factor(void);
static void syntaxError(char * message)
{ fprintf(listing,"\n>>> ");
  fprintf(listing,"Syntax error at line %d: %s",lineno,message);
  Error = TRUE;
}
static void match(TokenType expected)
{ if (token == expected) token = getToken();
  else {
    syntaxError("unexpected token -> ");
    printToken(token,tokenString);
    fprintf(listing,"      ");
  }
}
TreeNode * stmt_sequence(void)
{ TreeNode * t = statement();
  TreeNode * p = t;
  while ((token!=ENDFILE) && (token!=END) &&
         (token!=ELSE) && (token!=UNTIL))
  { TreeNode * q;
    match(SEMI);
    q = statement();
    if (q!=NULL) {
      if (t==NULL) t = p = q;
      else /* now p cannot be NULL either */
      { p->sibling = q;
        p = q;
      }
    }
  }
  return t;
}
TreeNode * statement(void)
{ TreeNode * t = NULL;
  switch (token) {
    case IF : t = if_stmt(); break;
    case REPEAT : t = repeat_stmt(); break;
    case ID : t = assign_stmt(); break;
    case READ : t = read_stmt(); break;
    case WRITE : t = write_stmt(); break;
    default : syntaxError("unexpected token -> ");
              printToken(token,tokenString);
              token = getToken();
              break;
  } /* end case */
  return t;
}
TreeNode * if_stmt(void)
{ TreeNode * t = newStmtNode(IfK);
  match(IF);
  if (t!=NULL) t->child[0] = exp();
  match(THEN);
  if (t!=NULL) t->child[1] = stmt_sequence();
  if (token==ELSE) {
    match(ELSE);
    if (t!=NULL) t->child[2] = stmt_sequence();
  }
  match(END);
  return t;
}
TreeNode * repeat_stmt(void)
{ TreeNode * t = newStmtNode(RepeatK);
  match(REPEAT);
  if (t!=NULL) t->child[0] = stmt_sequence();
  match(UNTIL);
  if (t!=NULL) t->child[1] = exp();
  return t;
}
TreeNode * assign_stmt(void)
{ TreeNode * t = newStmtNode(AssignK);
  if ((t!=NULL) && (token==ID))
    t->attr.name = String(tokenString);
  match(ID);
  match(ASSIGN);
  if (t!=NULL) t->child[0] = exp();
  return t;
}
TreeNode * read_stmt(void)
{ TreeNode * t = newStmtNode(ReadK);
  match(READ);
  if ((t!=NULL) && (token==ID))
    t->attr.name = String(tokenString);
  match(ID);
  return t;
}
TreeNode * write_stmt(void)
{ TreeNode * t = newStmtNode(WriteK);
  match(WRITE);
  if (t!=NULL) t->child[0] = exp();
  return t;
}
TreeNode * exp(void)
{ TreeNode * t = simple_exp();
  if ((token==LT)||(token==EQ)) {
    TreeNode * p = newExpNode(OpK);
    if (p!=NULL) {
      p->child[0] = t;
      p->attr.op = token;
      t = p;
    }
    match(token);
    if (t!=NULL)
      t->child[1] = simple_exp();
  }
  return t;
}
TreeNode * simple_exp(void)
{ TreeNode * t = term();
  while ((token==PLUS)||(token==MINUS))
  { TreeNode * p = newExpNode(OpK);
    if (p!=NULL) {
      p->child[0] = t;
      p->attr.op = token;
      t = p;
      match(token);
      t->child[1] = term();
    }
  }
  return t;
}
TreeNode * term(void)
{ TreeNode * t = factor();
  while ((token==TIMES)||(token==OVER))
  { TreeNode * p = newExpNode(OpK);
    if (p!=NULL) {
      p->child[0] = t;
      p->attr.op = token;
      t = p;
      match(token);
      p->child[1] = factor();
    }
  }
  return t;
}
TreeNode * factor(void)
{ TreeNode * t = NULL;
  switch (token) {
    case NUM :
      t = newExpNode(ConstK);
      if ((t!=NULL) && (token==NUM))
        t->attr.val = atoi(tokenString);
      match(NUM);
      break;
    case ID :
      t = newExpNode(IdK);
      if ((t!=NULL) && (token==ID))
        t->attr.name = String(tokenString);
      match(ID);
      break;
    case LPAREN :
      match(LPAREN);
      t = exp();
      match(RPAREN);
      break;
    default:
      syntaxError("unexpected token -> ");
      printToken(token,tokenString);
      token = getToken();
      break;
    }
  return t;
}
/****************************************/
/* the primary function of the parser   */
/****************************************/
/* Function parse returns the newly 
 * constructed syntax tree
 */
TreeNode * parse(void)
{ TreeNode * t;
  token = getToken();
  t = stmt_sequence();
  if (token!=ENDFILE)
    syntaxError("Code ends before file\n");
  return t;
}
上面是一个语法分析器的主代码部分它可以识别类似下面的代码,但是由于篇幅有限,上面的代码不是完整代码,完整代码太长,还有好几个文件。
read x; { input an integer }
if 0 < x then { don't compute if x <= 0 }
  fact := 1;
  repeat
    fact := fact * x;
    x := x - 1
  until x = 0;
  write fact  { output factorial of x }
end
❼ 急求:编译原理判断文法类型的C语言源代码!!!!!!
#include <stdio.h>
#include <string.h>  
#include <stdlib.h>
/**//*全局变量定义*/
char inputString[10]; /**//*用来存储用户输入的字符串,最长为20个字符*/
char stack[10];       /**//*用来进行语法分析的栈结构*/
int  base=0;          /**//*栈底指针*/
int  top=1;           /**//*栈顶指针*/
char VT[4]={'a','d','b','e'};   /**//*用来存放5个终结符*/
char chanShengShi[10];          /**//*用来存放预测分析表M[A,a]中的一条产生式*/
int firstCharIntex=0;           /**//*如果a匹配产生式,则每次firstCharIntex 自增 1 */ 
/**//*firstCharIntex用来存放用户输入串的第一个元素的下标*/
/**//*自定义函数声明*/
char pop() ;       /**//*弹出栈顶元素*/
int push(char) ;       /**//*向栈内添加一个元素,成功返回1,若栈已满则返回0*/
int search(char temp)  ;    /**//*查找非终结符集合VT中是否存在变量temp,存在返回1,不存在返回0*/
int M(char A, char a)  ;    /**//* 若预测分析表M[A,a]中存在产生式,
							则将该产生式赋给字符数组chanShengShi[10],并返回 1,
							若M[A,a]中无定义产生式则返回 0
							*/
								
void init()  ;              /**//*初始化数组inputString[10] 、栈 stack[10] 和 chanShengShi[10]*/ 
int yuCeFenXi()  ;          /**//* 进行输入串的预测分析的主功能函数,
							若输入串满足文法则返回 1,不满足则返回0
																*/
void printStack();          /**//*打印栈内元素    */
void printinputString();    /**//*打印用户输入串  */                          
/**//*进入主函数*/
void main()
{
	system("cls");    
	yuCeFenXi();   /**//*调用语法预测分析函数*/
	system("pause");
}                            
/**//*函数的定义*/   
int yuCeFenXi()
{
	char X;     /**//*X变量存储每次弹出的栈顶元素*/
	char a;     /**//*a变量存储用户输入串的第一个元素*/
	int i;
	int counter=1;  /**//*该变量记录语法分析的步骤数*/
	
	init();         /**//*初始化数组*/
	printf("wen fa  :     \n");   /**//*输出文法做为提示*/
	printf("S -> aH         \n");
	printf("H -> aMd | d    \n");
	printf("M -> Ab |   \n");
	printf("A -> aM | e     \n");
	
	printf("\ninput string ,'#' is a end sign  !!(aaabd#)  \n");  /**//*提示用户输入将要测试的字符串*/
	scanf("%s",inputString);
	
	push('#');  
	push('S');
	
	printf("\nCounter-----Stack---------------Input string \n");  /**//*输出结果提示语句*/
	
	while(1)                       /**//*while循环为语法分析主功能语句块*/
	{
		printf(" ");
		printf("  %d",counter);      /**//*输出分析步骤数*/
		printf("         ");         /**//*输出格式控制语句*/
		printStack();                /**//*输出当前栈内所有元素*/
		X=pop();                     /**//*弹出栈顶元素赋给变量X*/
		printinputString();          /**//*输出当前用户输入的字符串*/
		if( search(X)==0 )           /**//*在终结符集合VT中查找变量X的值,存在返回 1,否则返回 0*/
		{
			if(X == '#')               /**//*栈已经弹空,语法分析结果正确,返回 1*/
			{
				printf("success  \n");  /**//*语法分析结束,输入字符串符合文法定义*/
				return 1;
			}
			else  
			{
				a = inputString[firstCharIntex];
				if( M(X,a)==1 )          /**//*查看预测分析表M[A,a]是否存在产生式,存在返回1,不存在返回0*/
				{
					for(i=0;i<10;i++)     /**//* '$'为产生式的结束符,for循环找出该产生式的最后一个元素的下标*/
					{
						if( chanShengShi[i]=='$' )     break;  
					}
					i-- ;            /**//*因为 '$' 不是产生式,只是一个产生式的结束标志,所以i自减1*/
					
					while(i>=0)
					{
						push( chanShengShi[i] );  /**//*将当前产生式逆序压入栈内*/
						i-- ;    
					}
				}
				else
				{
					printf(" error(1) !!\n");   /**//*若预测分析表M[A,a]不存在产生式,说明语法错误*/
					return 0;
				}        
			}        
		}
		else       /**//*说明X为终结符*/
		{
			if( X==inputString[firstCharIntex] )  /**//*如果X等于a,说明a匹配*/
			{
				firstCharIntex++;  /**//*输入串的第一个元素被约去,下一个元素成为新的头元素*/
			}
			else
			{
				printf(" error(2) !! \n");
				return 0;    
			}            
		}    
		counter++;    
	}
}                     
void init()
{
	int i;
	for(i=0;i<10;i++)
	{
		inputString[i]=NULL;    /**//*初始化数组inputString[10] */
		stack[i]=NULL;        /**//*初始化栈stack[10]         */
		chanShengShi[i]=NULL; /**//*初始化数组chanShengShi[10]*/
	}
}
int M(char A, char a)     /**//*文法定义因实际情况而定,该文法为课本例题的文法*/
{                         /**//*该函数模拟预测分析表中的二维数组              */
	if( A=='S'&& a=='a' ) { strcpy(&chanShengShi[0],"aH$");  return 1; }
	if( A=='H'&& a=='a' ) { strcpy(&chanShengShi[0],"aMd$"); return 1; }
	if( A=='H'&& a=='d' ) { strcpy(&chanShengShi[0],"d$");   return 1; }
	if( A=='M'&& a=='a' ) { strcpy(&chanShengShi[0],"Ab$");  return 1; }
	if( A=='M'&& a=='d' ) { strcpy(&chanShengShi[0],"$");    return 1; }
	if( A=='M'&& a=='b' ) { strcpy(&chanShengShi[0],"$");    return 1; }
	if( A=='M'&& a=='e' ) { strcpy(&chanShengShi[0],"Ab$");  return 1; }
	if( A=='A'&& a=='a' ) { strcpy(&chanShengShi[0],"aM$");  return 1; }
	if( A=='A'&& a=='e' ) { strcpy(&chanShengShi[0],"e$");   return 1; }
	else return 0; /**//*没有定义产生式则返回0*/    
}
char pop()          /**//*弹出栈顶元素,用topChar返回*/
{
	char topChar;
	topChar=stack[--top]; 
	return topChar;
}
int push(char ch)
{
	if( top>9 ) 
	{
		printf(" error : stack overflow ");      /**//*栈空间溢出*/
		return 0;
	}    
	else
	{
		stack[top]=ch;  /**//*给栈顶空间赋值*/
		top++;
		return 1;
	}  
}
int search(char temp)
{
	int i,flag=0;       /**//*flag变量做为标志,若找到temp则赋1,否则赋0*/
	for(i=0;i<4;i++)
	{
		if( temp==VT[i] ) /**//*终结符集合中存在temp*/
		{
			flag=1;    
			break;
		}    
	}
	
	if(flag==1) return 1;  /**//*flag==1说明已找到等于temp的元素*/
	else return 0;
	
}
void printStack()         /**//*输出栈内内容*/
{
	int temp;
	for(temp=1;temp<top;temp++)
	{
		printf("%c",stack[temp]);    
	}    
}
void printinputString()   /**//*输出用户输入的字符串*/
{
	int temp=firstCharIntex    ;
	printf("                     ");  /**//*该句控制输出格式*/
	do{
		printf("%c",inputString[temp]);
		temp++;
	}while(inputString[temp-1]!='#');
	printf(" \n");     
}
❽ 编译原理课程设计-词法分析器设计(C语言)
#include"stdio.h"/*定义I/O库所用的某些宏和变量*/
#include"string.h"/*定义字符串库函数*/
#include"conio.h"/*提供有关屏幕窗口操作函数*/
#include"ctype.h"/*分类函数*/
charprog[80]={'
