CS143 PA3 cool语法解析

代码

/*
*  cool.y
*              Parser definition for the COOL language.
*
*/
%{
  #include <iostream>
  #include "cool-tree.h"
  #include "stringtab.h"
  #include "utilities.h"
  
  extern char *curr_filename;
  
  
  /* Locations */
  #define YYLTYPE int              /* the type of locations */
  #define cool_yylloc curr_lineno  /* use the curr_lineno from the lexer
  for the location of tokens */
    
    extern int node_lineno;          /* set before constructing a tree node
    to whatever you want the line number
    for the tree node to be */
      
      
      #define YYLLOC_DEFAULT(Current, Rhs, N)         \
      Current = Rhs[1];                             \
      node_lineno = Current;
    
    
    #define SET_NODELOC(Current)  \
    node_lineno = Current;
    
    /* IMPORTANT NOTE ON LINE NUMBERS
    *********************************
    * The above definitions and macros cause every terminal in your grammar to 
    * have the line number supplied by the lexer. The only task you have to
    * implement for line numbers to work correctly, is to use SET_NODELOC()
    * before constructing any constructs from non-terminals in your grammar.
    * Example: Consider you are matching on the following very restrictive 
    * (fictional) construct that matches a plus between two integer constants. 
    * (SUCH A RULE SHOULD NOT BE  PART OF YOUR PARSER):
    
    plus_consts	: INT_CONST '+' INT_CONST 
    
    * where INT_CONST is a terminal for an integer constant. Now, a correct
    * action for this rule that attaches the correct line number to plus_const
    * would look like the following:
    
    plus_consts	: INT_CONST '+' INT_CONST 
    {
      // Set the line number of the current non-terminal:
      // ***********************************************
      // You can access the line numbers of the i'th item with @i, just
      // like you acess the value of the i'th exporession with $i.
      //
      // Here, we choose the line number of the last INT_CONST (@3) as the
      // line number of the resulting expression (@$). You are free to pick
      // any reasonable line as the line number of non-terminals. If you 
      // omit the statement @$=..., bison has default rules for deciding which 
      // line number to use. Check the manual for details if you are interested.
      @$ = @3;
      
      
      // Observe that we call SET_NODELOC(@3); this will set the global variable
      // node_lineno to @3. Since the constructor call "plus" uses the value of 
      // this global, the plus node will now have the correct line number.
      SET_NODELOC(@3);
      
      // construct the result node:
      $$ = plus(int_const($1), int_const($3));
    }
    
    */
    
    
    
    void yyerror(char *s);        /*  defined below; called for each parse error */
    extern int yylex();           /*  the entry point to the lexer  */
    
    /************************************************************************/
    /*                DONT CHANGE ANYTHING IN THIS SECTION                  */
    
    Program ast_root;	      /* the result of the parse  */
    Classes parse_results;        /* for use in semantic analysis */
    int omerrs = 0;               /* number of errors in lexing and parsing */
    %}
    
    /* A union of all the types that can be the result of parsing actions. */
    %union {
      Boolean boolean;
      Symbol symbol;
      Program program;
      Class_ class_;
      Classes classes;
      Feature feature;
      Features features;
      Formal formal;
      Formals formals;
      Case case_;
      Cases cases;
      Expression expression;
      Expressions expressions;
      char *error_msg;
    }
    
    /* 
    Declare the terminals; a few have types for associated lexemes.
    The token ERROR is never used in the parser; thus, it is a parse
    error when the lexer returns it.
    
    The integer following token declaration is the numeric constant used
    to represent that token internally.  Typically, Bison generates these
    on its own, but we give explicit numbers to prevent version parity
    problems (bison 1.25 and earlier start at 258, later versions -- at
    257)
    */
    %token CLASS 258 ELSE 259 FI 260 IF 261 IN 262 
    %token INHERITS 263 LET 264 LOOP 265 POOL 266 THEN 267 WHILE 268
    %token CASE 269 ESAC 270 OF 271 DARROW 272 NEW 273 ISVOID 274
    %token <symbol>  STR_CONST 275 INT_CONST 276 
    %token <boolean> BOOL_CONST 277
    %token <symbol>  TYPEID 278 OBJECTID 279 
    %token ASSIGN 280 NOT 281 LE 282 ERROR 283
    
    /*  DON'T CHANGE ANYTHING ABOVE THIS LINE, OR YOUR PARSER WONT WORK       */
    /**************************************************************************/
    
    /* Complete the nonterminal list below, giving a type for the semantic
    value of each non terminal. (See section 3.6 in the bison 
    documentation for details). */
    
    /* Declare types for the grammar's non-terminals. */
    %type <program> program
    %type <classes> class_list
    %type <class_> class
    
    /* You will want to change the following line. */
    %type <features> dummy_feature_list
    %type <feature> feature
    %type <formals> formal_list
    %type <formal> formal
    %type <expression> expression
    %type <expressions> expression_list
    %type <expressions> expressions
    %type <case_> case
    %type <cases> case_list
    %type <expression> let_list
    /* Precedence declarations go here. */
    %right ASSIGN
    %left NOT
    %nonassoc '<' '=' LE
    %left '+' '-'
    %left '*' '/'
    %left ISVOID
    %left '~'
    %left '@'
    %left '.'

    
    %%
    /* 
    Save the root of the abstract syntax tree in a global variable.
    */
    program	: class_list	{ @$ = @1; ast_root = program($1); }
    ;
    
    class_list
    : class			/* single class */
    { $$ = single_Classes($1);
    parse_results = $$; }
    | class_list class	/* several classes */
    { $$ = append_Classes($1,single_Classes($2)); 
    parse_results = $$; }
    | error ';' class_list
    { $$ = $3; }
    ;
    
    /* If no parent is specified, the class inherits from the Object class. */
    class	: CLASS TYPEID '{' dummy_feature_list '}' ';'
    { $$ = class_($2,idtable.add_string("Object"),$4,
    stringtable.add_string(curr_filename)); }
    | CLASS TYPEID INHERITS TYPEID '{' dummy_feature_list '}' ';'
    { $$ = class_($2,$4,$6,stringtable.add_string(curr_filename)); }
    ;
    
    /* Feature list may be empty, but no empty features in list. */
    dummy_feature_list:		/* empty */
    {  $$ = nil_Features(); }
    | dummy_feature_list feature ';'
    {  $$ = append_Features($1,single_Features($2)); }
    | error ';' dummy_feature_list
    {  $$ = $3; }
    ;

    feature : OBJECTID '(' formal_list ')' ':' TYPEID '{' expression '}' 
    {  $$ = method($1,$3,$6,$8); }
    | OBJECTID ':' TYPEID
    {  $$ = attr($1,$3,no_expr());}
    | OBJECTID ':' TYPEID ASSIGN expression 
    {  $$ = attr($1,$3,$5); }

    ;


    formal_list: /* empty */
    {  $$ = nil_Formals(); }
    | formal			/* single formal */
    {  $$ = single_Formals($1); }
    | formal_list ',' formal		/* several formals */
    {  $$ = append_Formals($1,single_Formals($3)); }
    ;

    formal : OBJECTID ':' TYPEID		/* single formal */
    {  $$ = formal($1,$3); }
    ;

    expression_list: 
    /* empty */
    {  $$ = nil_Expressions(); }
    | expression			/* single expression */
    {  $$ = single_Expressions($1); }
    | expression_list ',' expression		/* several expressions */
    {  $$ = append_Expressions($1,single_Expressions($3)); }
    ;

    expressions:  /* empty */
    {  $$ = nil_Expressions(); }
    |  expression ';' expressions		/* several expressions */
    {  $$ = append_Expressions(single_Expressions($1),$3); }
    ;

    expression : OBJECTID ASSIGN expression	/* assignment */ 
    {  $$ = assign($1,$3); }
    | expression '.' OBJECTID '(' expression_list ')'	/* method call */
    {  $$ = dispatch($1,$3,$5); }
    | OBJECTID '(' expression_list ')'	/* object creation */
    {  $$ = dispatch(object(idtable.add_string("self")),$1,$3);}
    | expression '@' TYPEID '.' OBJECTID '(' expression_list ')'	/* static method call */
    {  $$ = static_dispatch($1,$3,$5,$7);}
    | IF expression THEN expression ELSE expression FI	/* conditional */
    {  $$ = cond($2,$4,$6); }
    | WHILE expression LOOP expression POOL	/* loop */
    {  $$ = loop($2,$4); }
    | '{' expressions '}'		/* block */
    {  $$ = block($2); }
    | LET let_list
    {  $$ = $2; }
    | CASE expression OF case_list ESAC	/* case */
    {  $$ = typcase($2,$4);}
    | NEW TYPEID			/* object creation */
    {  $$ = new_($2); }
    | ISVOID expression			/* void check */
    {  $$ = isvoid($2); }
    | '(' expression ')'
    {  $$ = $2; }
    | expression '*' expression		/* multiplication */
    {  $$ = mul($1,$3); }
    | expression '/' expression		/* division */
    {  $$ = divide($1,$3); }
    | expression '+' expression		/* addition */
    {  $$ = plus($1,$3); }
    | expression '-' expression		/* subtraction */
    {  $$ = sub($1,$3); }
    | '~' expression			/* complement */
    {  $$ = neg($2); }
    | expression '<' expression		/* less than */
    {  $$ = lt($1,$3); }
    | expression LE expression		/* less than or equal */
    {  $$ = leq($1,$3); }
    | expression '=' expression		/* equality */
    {  $$ = eq($1,$3); }
    | NOT expression			/* negation */
    {  $$ = comp($2); }

    | OBJECTID			/* variable reference */
    {  $$ = object($1); }
    | INT_CONST			/* integer constant */
    {  $$ = int_const($1); }
    | STR_CONST			/* string constant */
    {  $$ = string_const($1); }
    | BOOL_CONST				/* boolean constant */
    {  $$ = bool_const($1); }
    ;

    case_list : case				/* single case */
    {  $$ = single_Cases($1); }
    | case_list case			/* several cases */
    {  $$ = append_Cases($1,single_Cases($2)); }
    ;
    
    case : OBJECTID ':' TYPEID DARROW expression ';'	/* single case */
    {  $$ = branch($1,$3,$5); }
    ;

    let_list : OBJECTID ':' TYPEID ASSIGN expression IN expression
    {  $$ = let($1,$3,$5,$7); }
    | OBJECTID ':' TYPEID IN expression
    {  $$ = let($1,$3,no_expr(),$5); }
    | OBJECTID ':' TYPEID ASSIGN expression ',' let_list
    {  $$ = let($1,$3,$5,$7); }
    | OBJECTID ':' TYPEID ',' let_list
    {  $$ = let($1,$3,no_expr(),$5); }
    | error ',' let_list
    {  $$ = $3; }
    ;

    /* end of grammar */
    %%
    
    /* This function is called automatically when Bison detects a parse error. */
    void yyerror(char *s)
    {
      extern int curr_lineno;
      
      cerr << "\"" << curr_filename << "\", line " << curr_lineno << ": " \
      << s << " at or near ";
      print_cool_token(yychar);
      cerr << endl;
      omerrs++;
      
      if(omerrs>50) {fprintf(stdout, "More than 50 errors\n"); exit(1);}
    }
    

实现流程

  1. 创建节点的API在cool-tree.h的末尾
  2. 定义语法规则,在handouts/cool-manual.pdf,照着写表达式就行
  3. 使用colordiff对自己编写的文件和老师给的lexer parser文件的输出结果进行对比,找出语法错误

注意事项

  1. 语法规则需要改写,比方说对[] * ? 这些符号
  2. 语法规则需要加error
  3. vscode 对语法解析进行调试(因为输入流是其他文件的输出流),见vscode 调试, 调试程序依赖输入流启动 然后按下F5,可以在.y文件中打断点 (bison记得加调试选项)

结果展示

老师用例

先对老师给的俩用例进行测试

make parser
make dotest

输出


Running parser on good.cl

./myparser good.cl 
#1
_program
  #1
  _class
    A
    Object
    "good.cl"
    (
    #2
    _method
      ana
      Int
      #3
      _plus
        #3
        _let
          x
          Int
          #3
          _int
            1
          : _no_type
          #3
          _let
            y
            Int
            #3
            _int
              5
            : _no_type
            #3
            _int
              2
            : _no_type
          : _no_type
        : _no_type
        #3
        _int
          3
        : _no_type
      : _no_type
    )
  #7
  _class
    BB__
    A
    "good.cl"
    (
    )

Running parser on bad.cl

./myparser bad.cl
"bad.cl", line 15: syntax error at or near OBJECTID = b
"bad.cl", line 19: syntax error at or near OBJECTID = a
"bad.cl", line 23: syntax error at or near OBJECTID = inherts
"bad.cl", line 28: syntax error at or near ';'
Compilation halted due to lex and parse errors
make: [Makefile:57:dotest] 错误 1 (已忽略)

应该没错误

老师给的example

#!/bin/bash
# colordiff -u (lexer test.cl | psub) (./lexer test.cl | psub)

for file in /home/sjk/project/cool-compiler/examples/*.cl; do
    if [ -f "$file" ]; then
        echo "Running colordiff -u for file: $file"
        colordiff -u <(./myparser "$file") <( lexer "$file" | parser)
    fi
done

就是对目录下所有的cl文件进行编译,然后对比老师的lexer,parser的输出结果。

大部分都能通过用例

少数几个有问题的地方:

  1. 部分行号显示为0,这个是老师程序的bug
Running colordiff -u for file: /home/sjk/project/cool-compiler/examples/sort_list.cl
--- /dev/fd/63	2024-06-28 11:23:17.864209020 +0800
+++ /dev/fd/62	2024-06-28 11:23:17.864209020 +0800
@@ -193,14 +193,14 @@
     _attr
       xcar
       Int
-      #57
+      #0
       _no_expr
       : _no_type
     #58
     _attr
       xcdr
       List
-      #58
+      #0
       _no_expr
       : _no_type
     #62
@@ -557,7 +557,7 @@
     _attr
       l
       List
-      #118
+      #0
       _no_expr
       : _no_type
     #121
  1. life.cl 232行的将两个语句相加,加法运算符的行号出错了,这个我猜测是reduce的时候,先把expression的condition条件语句给reduce,然后再reduce加法运算符,导致行号出错。 我也不知道怎么解决。
Running colordiff -u for file: /home/sjk/project/cool-compiler/examples/sort_list.cl
--- /dev/fd/63	2024-06-28 11:23:17.864209020 +0800
+++ /dev/fd/62	2024-06-28 11:23:17.864209020 +0800
@@ -193,14 +193,14 @@
     _attr
       xcar
       Int
-      #57
+      #0
       _no_expr
       : _no_type
     #58
     _attr
       xcdr
       List
-      #58
+      #0
       _no_expr
       : _no_type
     #62
@@ -557,7 +557,7 @@
     _attr
       l
       List
-      #118
+      #0
       _no_expr
       : _no_type
     #121

容易出错的地方

  1. 函数参数expression_list,语句之间expressions,一个是 ,分隔,一个是 ;分隔
  2. expression_list是可以为空的,忘记写了
  3. error的地方,要写,不然bad.cl过不了
  4. neg和comp,难分清楚,哈哈,可以照着老师给的程序写
  5. * / + - 运算符的优先级,先声明的优先级低
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值