Strumenta / pylasu

Apache License 2.0
24 stars 4 forks source link

Symbol Resolution - Add support for anonymous symbols and type-based lookup #7

Closed loradd closed 2 years ago

loradd commented 2 years ago

The current Scope implementation does not support symbol storage and lookup for anonymous symbols, i.e. looking up symbols using features other than names. #5

loradd commented 2 years ago

Possible implementation for Scope supporting typed symbol lookup. Given that multiple symbols could have the same type, the return type uniqueness constraint has been relaxed, i.e. List[Symbol] rather than Dict[str, Symbol].

@dataclass
class Scope:
    # local symbols
    symbols: List[Symbol] = field(default_factory=list)
    # parent scope
    parent: Optional['Scope'] = field(default=None)

    def lookup(self, symbol_name: str = None, symbol_type: type = Symbol) -> List[Symbol]:
        # retrieve symbols in the current scope
        local_symbols: List[Symbol] = self.__symbols(symbol_name, symbol_type)
        # retrieve symbols in the upper scopes
        upper_symbols: List[Symbol] = self.parent.lookup(symbol_name, symbol_type) if self.parent else []
        # concatenate symbols with locals first
        return local_symbols + upper_symbols

    def __symbols(self, symbol_name: str = None, symbol_type: type = Symbol) -> List[Symbol]:
        # retrieve symbols with the given name, type or both
        return [symbol for symbol in self.symbols if self.__check_symbol_name(symbol, symbol_name) and self.__check_symbol_type(symbol, symbol_type)]

    def __check_symbol_name(self, symbol: Symbol, symbol_name: str = None) -> bool:
        # compare symbol name, ignore test if undefined
        return symbol.name == symbol_name if symbol_name else True

    def __check_symbol_type(self, symbol: Symbol, symbol_type: type = None) -> bool:
        # compare symbol type, ignore test if undefined
        return isinstance(symbol, symbol_type) if symbol_type else True
loradd commented 2 years ago

@alessiostalla @ftomassetti What do you think about this?

ftomassetti commented 2 years ago

I do not see anything wrong

alessiostalla commented 2 years ago

Looks fine to me

loradd commented 2 years ago

I believe supporting anonymous symbol resolution was an inconvenient choice. The current implementation returns lists of symbols and makes understanding whether or not a given symbol has been shadowed harder in practice. I propose to fallback onto a trade-off solution: supporting type hints in symbol lookup, while requiring symbols to be named.