1717from coretrace_python .cfg import CFGError
1818from coretrace_python .hir import nodes
1919from coretrace_python .ir .lowering import LoweringError , analyzable_functions , qualified_name
20- from coretrace_python .ir .model import Call , FunctionIR , Global , Symbol , Value
20+ from coretrace_python .ir .model import Call , FunctionIR , GetAttr , Global , Symbol , Value , WithEnter
2121from coretrace_python .ir .ssa import SSAAnalysis
2222from coretrace_python .semantic .scopes import BindingKind , ScopeAnalysis , ScopeTable
2323from coretrace_python .semantic .symbols import SymbolId
@@ -57,7 +57,9 @@ def __init__(
5757 definitions : Mapping [str , nodes .Function ],
5858 sites : Mapping [str , tuple [CallSite , ...]],
5959 unsupported : frozenset [str ],
60+ symbols : Mapping [str , Mapping [Value , SymbolId ]] | None = None ,
6061 ) -> None :
62+ self ._symbols = {name : MappingProxyType (dict (found )) for name , found in (symbols or {}).items ()}
6163 self .definitions : Mapping [str , nodes .Function ] = MappingProxyType (dict (definitions ))
6264 self .functions = tuple (definitions )
6365 self ._names = {function .span : name for name , function in definitions .items ()}
@@ -76,6 +78,11 @@ def __init__(
7678 def name_of (self , function : nodes .Function ) -> str :
7779 return self ._names [function .span ]
7880
81+ def symbols (self , name : str ) -> Mapping [Value , SymbolId ]:
82+ """Values of ``name`` that denote a symbol, including derived call-chain symbols."""
83+
84+ return self ._symbols .get (name , MappingProxyType ({}))
85+
7986 def sites (self , caller : str ) -> tuple [CallSite , ...]:
8087 return self ._sites .get (caller , ())
8188
@@ -91,26 +98,56 @@ def callers(self, name: str) -> frozenset[str]:
9198 return self ._callers .get (name , frozenset ())
9299
93100
101+ def derive_symbols (function : FunctionIR ) -> dict [Value , SymbolId ]:
102+ """Symbols of values: ``Symbol`` results, attributes of symbol values, results of
103+ calling a symbol (``sqlite3.connect(p)`` denotes ``python.sqlite3.connect``) and the
104+ values a ``with`` on such a result binds. Known functions and parameters derive nothing."""
105+
106+ symbols : dict [Value , SymbolId ] = {}
107+ changed = True
108+ while changed :
109+ changed = False
110+ for block in function .blocks :
111+ for instruction in block .instructions :
112+ if instruction .result is None or instruction .result in symbols :
113+ continue
114+ symbol : SymbolId | None = None
115+ if isinstance (instruction , Symbol ):
116+ symbol = instruction .symbol_id
117+ elif isinstance (instruction , GetAttr ) and instruction .object in symbols :
118+ symbol = symbols [instruction .object ].attribute (instruction .attribute )
119+ elif isinstance (instruction , Call | WithEnter ):
120+ origin = (
121+ instruction .callee if isinstance (instruction , Call ) else instruction .context
122+ )
123+ symbol = symbols .get (origin )
124+ if symbol is not None :
125+ symbols [instruction .result ] = symbol
126+ changed = True
127+ return symbols
128+
129+
94130def resolve_targets (
95131 function : FunctionIR , scopes : ScopeTable , known : frozenset [str ]
96- ) -> dict [Value , Target ]:
97- """Map every callee value of ``function`` to its target."""
132+ ) -> tuple [ dict [Value , Target ], dict [ Value , SymbolId ] ]:
133+ """Map every callee value of ``function`` to its target, and every symbol value ."""
98134
99135 module = scopes .module_scope
100- targets : dict [Value , Target ] = {}
136+ symbols = derive_symbols (function )
137+ targets : dict [Value , Target ] = {
138+ value : ExternalSymbol (symbol ) for value , symbol in symbols .items ()
139+ }
101140 for block in function .blocks :
102141 for instruction in block .instructions :
103- if isinstance (instruction , Symbol ):
104- targets [instruction .result ] = ExternalSymbol (instruction .symbol_id )
105- elif isinstance (instruction , Global ):
142+ if isinstance (instruction , Global ):
106143 binding = module .bindings .get (instruction .name )
107144 if (
108145 binding is not None
109146 and binding .kind is BindingKind .FUNCTION
110147 and instruction .name in known
111148 ):
112149 targets [instruction .result ] = KnownFunction (instruction .name )
113- return targets
150+ return targets , symbols
114151
115152
116153class CallGraphAnalysis (Analysis [CallGraph ]):
@@ -128,6 +165,7 @@ def compute(cls, ctx: AnalysisContext) -> CallGraph:
128165 name for name , function in definitions .items () if function in ctx .module .body
129166 )
130167 sites : dict [str , tuple [CallSite , ...]] = {}
168+ symbols : dict [str , Mapping [Value , SymbolId ]] = {}
131169 unsupported : set [str ] = set ()
132170 for name , function in definitions .items ():
133171 try :
@@ -136,7 +174,7 @@ def compute(cls, ctx: AnalysisContext) -> CallGraph:
136174 unsupported .add (name )
137175 sites [name ] = ()
138176 continue
139- targets = resolve_targets (ssa , scopes , known )
177+ targets , symbols [ name ] = resolve_targets (ssa , scopes , known )
140178 found : list [CallSite ] = []
141179 for block in ssa .blocks :
142180 for instruction in block .instructions :
@@ -151,4 +189,4 @@ def compute(cls, ctx: AnalysisContext) -> CallGraph:
151189 )
152190 )
153191 sites [name ] = tuple (found )
154- return CallGraph (definitions , sites , frozenset (unsupported ))
192+ return CallGraph (definitions , sites , frozenset (unsupported ), symbols )
0 commit comments