2015-11-21 69 views
0

我正在lex和c中創建一個布爾表達式計算器,但是我在查找代碼中的錯誤時遇到問題。布爾表達式計算器錯誤

當我運行代碼的parser.c文件拋出error("expected end-of-file")。這意味着程序不會讀取文件字符的結尾,而且我也找不到錯誤的位置。

我附上了下面有問題的代碼。如果爲了解決這個問題,你需要看到更多的代碼,請讓我知道,我也很樂意發佈他們。我一直堅持這個問題幾個星期沒有,任何幫助將不勝感激。

Lexer.h

#ifndef ____lexer__ 
#define ____lexer__ 

#include <stdio.h> 

#define AND 258 
#define OR 259 
#define NOT 260 
#define TRUE 261 
#define FALSE 262 

#define DONE 300 
#define NONE (-1) 

int lexan(); 

extern int value; 
extern int lineNo; 
extern char lexbuf[]; 
extern FILE *fileSource; 
#endif /* defined(____lexer__) */ 

lexer.lex

%{ 
    #include <ctype.h> 
    #include <unistd.h> 
    #include "lexer.h" 
    #include "error.h" 

    int value; 
    int lineNo; 
%} 

%option noyywrap 

%% 
['''\t']* {} 
['\n']* { lineNo++; } 

<<EOF>> { 
    return DONE; 
} 

"True" {return (TRUE);} 
"False" {return (FALSE);} 
"or" {return (OR);} 
"and" {return (AND);} 
"not" {return (NOT);} 
.|\n { 
    value = NONE; 
    int temp = (int)(yytext[0]); 
    return (temp); 
} 
%% 

int lexan() 
{ 
    yyin = fileSource; 
    int result = yylex(); 
    return result; 
} 

parser.c

#include <stdlib.h> 

#include "parser.h" 
#include "lexer.h" 
#include "error.h" 
#include "interpreter.h" 

static int lookahead; 

static void stmts(); 
static void stmt(); 
static void assign(); 
static void expr(); 
static void match(); 

void parse() 
{ 
    lookahead = lexan(); 
    stmts(); 
    lookahead = lexan(); 
    if(lookahead != DONE) 
     error("expected end-of-file"); 
} 

static void stmts() 
{ 
    while (lookahead != DONE) 
    { 
     if(lookahead == AND || lookahead == OR || lookahead == NOT || lookahead == TRUE || lookahead == FALSE) 
     { 
      stmt(); 
     } 
     else 
      break; 
    } 
} 

static void stmt() 
{ 
    switch (lookahead) 
    { 
     case AND: 
      emit(AND); 
      match(AND); 
      break; 
     case OR: 
      emit(OR); 
      match(OR); 
      break; 
     case NOT: 
      emit(NOT); 
      match(NOT); 
      break; 
     default: 
      assign(); 
    } 
} 

static void assign() 
{ 
    switch (lookahead) 
    { 
     case TRUE: 
      emit(TRUE); 
      match(TRUE); 
      break; 
     case FALSE: 
      emit(FALSE); 
      match(FALSE); 
     default: 
      error("syntax error"); 
    } 
} 

void match(int t) 
{ 
    if (lookahead == t) 
    { 
     lookahead = lexan(); 
    } 
    else 
     error("syntax error"); 
} 

回答

0

你眼前的問題是,lookahead已經DONE如果stmts()成功返回。在碰到EOF後再次調用yylex是未定義的行爲,但您確實不想執行該調用,因爲邏輯不正確;當stmts()返回時,lookahead尚未匹配,因此調用者應嘗試匹配它,而不是用新的令牌覆蓋它。

修復這是你的問題最少的,但。 stmtsstmt的邏輯也是錯誤的;你需要重讀你用來編寫遞歸下降解析器的任何指南/文本。

順便說一句,如果您沒有<<EOF>>規則,yylex將在輸入結束時返回0。您應該考慮使用此行爲而不是生成自定義返回碼。