Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
72 lines (53 sloc) 1.41 KB

2.4 节的练习

2.4.1

为下列文法构造递归下降语法分析器

  1. S -> + S S | - S S | a
  2. S -> S ( S ) S | ε
  3. S -> 0 S 1 | 0 1

解答

1) S -> + S S | - S S | a

void S(){
    switch(lookahead){
        case "+":
            match("+"); S(); S();
            break;
        case "-":
            match("-"); S(); S();
            break;
        case "a":
            match("a");
            break;
        default:
            throw new SyntaxException();
    }
}
void match(Terminal t){
    if(lookahead = t){
        lookahead = nextTerminal();
    }else{
        throw new SyntaxException()
    }
}

2) S -> S ( S ) S | ε

void S(){
    if(lookahead == "("){
        S(); match("("); S(); match(")"); S();
    }
}

3) S -> 0 S 1 | 0 1

void S(){
    switch(lookahead){
        case "0":
            match("0"); S(); match("1");
            break;
        case "01":
            match("01");
            break;
        default:
            throw new SyntaxException();
    }
}

疑问

第二小题中,因为允许 ε, 所以在运行 lookahead = nextTerminal() 方法时,如果没找到任何终结符,则

查看当前指针后的所有字符是否是空串,是空串则完成词法解析,否则就报错。

这样对不对?