fool2fish / dragon-book-exercise-answers

Compilers Principles, Techniques, & Tools (purple dragon book) second edition exercise answers. 编译原理(紫龙书)第2版习题答案。

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

2.6.2 treats '!' and '=' as valid relational operators

nicolasying opened this issue · comments


{// handle relation sign

  if("<=!>".indexOf(peek) > -1){

    StringBuffer b = new StringBuffer();

    b.append(peek);

    peek = (char)stream.read();

    if(peek == '='){

      b.append(peek);

    }

    return new Rel(b.toString());

  }
}

Should the original string be:

3 ! 2 = 1

'!' and '-' will be recognised by Rel, as it enters this if block, and
peek = (char)stream.read() would put peek = ' ', therefore new Rel("!") and new Rel("=") is to be returned.

So a simple solution may be to check after the if(peek == '=') block what b is like, and throw error if the b is now "!" or "=", and peek != '='.