|
| 1 | +"""Module-level names whose value is known (architecture §18): the names bound once and |
| 2 | +never rebound, and among them the ones bound to an immutable collection of constants, |
| 3 | +which an allowlist reads.""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from collections.abc import Mapping |
| 8 | +from types import MappingProxyType |
| 9 | +from typing import ClassVar |
| 10 | + |
| 11 | +from coretrace_python.analysis import Analysis, AnalysisContext, AnyAnalysis |
| 12 | +from coretrace_python.cfg import CFGError |
| 13 | +from coretrace_python.hir import nodes |
| 14 | +from coretrace_python.ir.lowering import ( |
| 15 | + MODULE_BODY, |
| 16 | + LoweringError, |
| 17 | + PyIRAnalysis, |
| 18 | + analyzable_functions, |
| 19 | +) |
| 20 | +from coretrace_python.ir.model import ( |
| 21 | + BuildDict, |
| 22 | + BuildList, |
| 23 | + BuildSet, |
| 24 | + BuildTuple, |
| 25 | + Call, |
| 26 | + Constant, |
| 27 | + ForNext, |
| 28 | + Instruction, |
| 29 | + SetGlobal, |
| 30 | + StoreLocal, |
| 31 | + Symbol, |
| 32 | + Value, |
| 33 | +) |
| 34 | +from coretrace_python.semantic.symbols import SymbolId |
| 35 | + |
| 36 | +FROZENSET = SymbolId("python.builtins.frozenset") |
| 37 | + |
| 38 | + |
| 39 | +def module_bindings(ctx: AnalysisContext) -> tuple[Mapping[str, Instruction], Mapping[Value, Instruction]]: |
| 40 | + """The module-level names bound once and never rebound, by no other statement of the |
| 41 | + module body, no function assigning them as ``global``, no definition of that name, |
| 42 | + each with the instruction that makes its value; and the definitions of the module |
| 43 | + body's values. A module that does not lower entirely has none.""" |
| 44 | + |
| 45 | + try: |
| 46 | + functions = [ctx.get(PyIRAnalysis, function) for function in analyzable_functions(ctx.module)] |
| 47 | + except (LoweringError, CFGError): |
| 48 | + return MappingProxyType({}), MappingProxyType({}) |
| 49 | + body = next((function for function in functions if function.name == MODULE_BODY), None) |
| 50 | + if body is None: |
| 51 | + return MappingProxyType({}), MappingProxyType({}) |
| 52 | + defs = {i.result: i for block in body.blocks for i in block.instructions if i.result is not None} |
| 53 | + stored: dict[str, list[Value | None]] = {} |
| 54 | + for block in body.blocks: |
| 55 | + for instruction in block.instructions: |
| 56 | + if isinstance(instruction, StoreLocal): |
| 57 | + stored.setdefault(instruction.name, []).append(instruction.value) |
| 58 | + if isinstance(block.terminator, ForNext): |
| 59 | + # A ``for`` binds its target to each item. |
| 60 | + stored.setdefault(block.terminator.target, []).append(None) |
| 61 | + rebound = { |
| 62 | + i.name for function in functions for block in function.blocks for i in block.instructions |
| 63 | + if isinstance(i, SetGlobal) |
| 64 | + } |
| 65 | + rebound |= {s.name for s in ctx.module.body if isinstance(s, nodes.Function | nodes.Class)} |
| 66 | + bound: dict[str, Instruction] = {} |
| 67 | + for name, values in stored.items(): |
| 68 | + value = values[0] if len(values) == 1 and name not in rebound else None |
| 69 | + made = defs.get(value) if value is not None else None |
| 70 | + if made is not None: |
| 71 | + bound[name] = made |
| 72 | + return MappingProxyType(bound), MappingProxyType(defs) |
| 73 | + |
| 74 | + |
| 75 | +def constant_members(display: Instruction | None, defs: Mapping[Value, Instruction]) -> bool: |
| 76 | + """Whether ``display`` is a tuple, list or set display whose items are all constants, |
| 77 | + or a dict display whose keys are, with nothing unpacked into it: the members a |
| 78 | + membership test reads.""" |
| 79 | + |
| 80 | + if isinstance(display, BuildList | BuildTuple | BuildSet): |
| 81 | + return not display.unpacked and all(isinstance(defs.get(e), Constant) for e in display.elements) |
| 82 | + if isinstance(display, BuildDict): |
| 83 | + return not display.unpacked and all(isinstance(defs.get(key), Constant) for key, _ in display.items) |
| 84 | + return False |
| 85 | + |
| 86 | + |
| 87 | +def converts(call: Call, defs: Mapping[Value, Instruction], symbols: frozenset[SymbolId]) -> Value | None: |
| 88 | + """The one positional argument of ``call`` when it calls one of ``symbols`` with |
| 89 | + nothing else (``frozenset(x)``), otherwise ``None``.""" |
| 90 | + |
| 91 | + callee = defs.get(call.callee) |
| 92 | + if not isinstance(callee, Symbol) or callee.symbol_id not in symbols: |
| 93 | + return None |
| 94 | + if len(call.arguments) != 1 or call.keywords or call.starred: |
| 95 | + return None |
| 96 | + return call.arguments[0] |
| 97 | + |
| 98 | + |
| 99 | +class ModuleCollectionsAnalysis(Analysis[frozenset[str]]): |
| 100 | + """The module-level names bound once and never rebound (``module_bindings``) to an |
| 101 | + immutable collection of constants: a tuple display, or ``frozenset`` of a display |
| 102 | + whose members are constants (``constant_members``). A list, a set or a dict can still |
| 103 | + change after it is bound, so it is not one.""" |
| 104 | + |
| 105 | + name: ClassVar[str] = "abstract.module_collections" |
| 106 | + requires: ClassVar[frozenset[AnyAnalysis]] = frozenset({PyIRAnalysis}) |
| 107 | + |
| 108 | + @classmethod |
| 109 | + def compute(cls, ctx: AnalysisContext) -> frozenset[str]: |
| 110 | + bound, defs = module_bindings(ctx) |
| 111 | + found: set[str] = set() |
| 112 | + for name, made in bound.items(): |
| 113 | + collection: Instruction | None = made |
| 114 | + if isinstance(made, Call): |
| 115 | + argument = converts(made, defs, frozenset({FROZENSET})) |
| 116 | + collection = defs.get(argument) if argument is not None else None |
| 117 | + elif not isinstance(made, BuildTuple): |
| 118 | + continue |
| 119 | + if constant_members(collection, defs): |
| 120 | + found.add(name) |
| 121 | + return frozenset(found) |
0 commit comments