compiler-constructionbisonyacclexparser-generator

Can Bison verify scope as well as syntax?


I am using Lex/Bison to create a simple scripting language which translates into C. A trans-compiler.

I know Bison can verify syntax, but what about scoping? Can it verify the an identifier that is being used was declared before? Does that have to be done manually? And if so, at which step?

E.g. This is syntax-wise correct. But is should not compile because message is in the wrong scope. In addition, message2 was never declared.

String s1
if (s1=='knock on door')
   String message1='Hello';

print message1;
print message2;

Solution

  • Parsers (however produced) typically cannot check scoping rules.

    To do scope checking in general, in general you have to build the entire AST and then verify the identifiers are well-scoped. For languages which have static scoping with scopes introduced before variable use, you might be able to do this only the fly in rules. For languages with namespaces, the namespace declaration might occur anywhere, and you can't do it without collecting that namespace and thus the entire program. (The namespace declaration might not even be in the same file as the use; now you have parse an entirely different file).

    As a consequence, the usual way scope checking is done is after parsing, over the program tree. Normally if you are going to do anything beyond parsing, you need the tree, and the full symbol table anyway, so this isn't really much of an annoyance.

    Some early compilers didn't have the luxury of holding the entire tree in memory. Either they had languages with scope declarations before use, or they were implemented in multiple passes.