I’m designing a compiler by hand (don’t ask).
A source file for this new language can import a class T in package P that it wishes to use with
import P.T;
or it can use import-on-demand access to all classes in package P using the statement
import P.*;
An identifier appearing in a ClassType declaration (i.e. the identifier MyClass in the declaration MyClass x = … ) is resolved by the following rules:
- it can be a class declared in the current package
- it can be an explicitly imported class
- it can be an implicitly imported class (import on demand)
I don’t know how real compilers handle this situation. I’m looking for a way to implement identification for ClassTypes in miniJava programs with import statements.
Keep track of all three types (local, explicit import,
*import) in separate data structures (adding entries as you encounter the declarations and imports in the program) and when you need to look up a type identifier, check each of those data structures.If you have a priority order (e.g. local declarations shadow (hide) imported classes), then simply check the three in that order and stop once you found something (rather like a lexical scope chain). If it is an error to have ambiguous names, then check all three and keep a list of everything you found; if the list has other than exactly one element afterward, signal an error (and list the found items in the error message).
In the case of the
*import, it is not obvious whether any givenimport ....*provides a given class name. For that, simply try each one in turn as a sub-case (givenimport P.*looking upMyClass, formP.MyClassand check if that exists). It is especially important in this case to check all the*imports so that you do not silently choose one option given an ambiguous name.