Skip to content

cogant.static

The cogant.static package runs static analysis on the ingested sources: AST parse, symbol extraction, type inference, import resolution, call-graph construction, and dataflow hints.

Package

cogant.static

COGANT static analysis pipeline: Python AST parsing and symbol extraction.

Provides tools for parsing Python source code, extracting symbols, resolving imports, building call graphs, inferring types, and analyzing data flow.

AssignmentDef dataclass

Variable assignment from AST.

Source code in py/cogant/static/parser.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass
class AssignmentDef:
    """Variable assignment from AST."""

    target_name: str
    """Variable name being assigned."""

    line_num: int
    """Line number of assignment."""

    annotation: str | None = None
    """Type annotation if present."""

    value: str | None = None
    """String representation of assigned value."""

    parent_scope: str | None = None
    """Scope containing assignment (module or function)."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

annotation = None class-attribute instance-attribute

Type annotation if present.

line_num instance-attribute

Line number of assignment.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

parent_scope = None class-attribute instance-attribute

Scope containing assignment (module or function).

target_name instance-attribute

Variable name being assigned.

value = None class-attribute instance-attribute

String representation of assigned value.

CallEdge dataclass

A function/method call relationship.

Source code in py/cogant/static/calls.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@dataclass
class CallEdge:
    """A function/method call relationship."""

    id: str
    """Unique edge identifier."""

    source_file: Path
    """File containing the call."""

    caller_id: str
    """Symbol ID of the calling function."""

    caller_name: str
    """Name of calling function/method."""

    callee_name: str
    """Name of called function/method."""

    callee_id: str | None = None
    """Symbol ID of called function (if resolved)."""

    line_num: int = 0
    """Line number of call."""

    is_method_call: bool = False
    """Whether this is a method call."""

    receiver: str | None = None
    """Object/module the method is called on."""

    args: list[str] = field(default_factory=list)
    """Argument values as strings."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

args = field(default_factory=list) class-attribute instance-attribute

Argument values as strings.

callee_id = None class-attribute instance-attribute

Symbol ID of called function (if resolved).

callee_name instance-attribute

Name of called function/method.

caller_id instance-attribute

Symbol ID of the calling function.

caller_name instance-attribute

Name of calling function/method.

id instance-attribute

Unique edge identifier.

is_method_call = False class-attribute instance-attribute

Whether this is a method call.

line_num = 0 class-attribute instance-attribute

Line number of call.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

receiver = None class-attribute instance-attribute

Object/module the method is called on.

source_file instance-attribute

File containing the call.

CallGraphBuilder

Extract function and method calls from Python source.

Source code in py/cogant/static/calls.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class CallGraphBuilder:
    """Extract function and method calls from Python source."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize call graph builder.

        Args:
            repo_root: Root path of repository.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()
        self.symbol_extractor = SymbolExtractor(repo_root)

    def extract_calls_from_file(self, file_path: Path) -> list[CallEdge]:
        """Extract all function/method calls from a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of CallEdge for all calls found.
        """
        try:
            source = Path(file_path).read_text(encoding="utf-8")
        except (OSError, UnicodeDecodeError) as e:
            logger.debug(f"Failed to read {file_path}: {e}")
            return []
        return self.extract_calls_from_source(source, file_path)

    def extract_calls_from_source(self, source: str, file_path: Path) -> list[CallEdge]:
        """Extract function/method calls from Python source code.

        Module-level functions are reported first, then class methods, each
        in source order. Every ``def`` and ``async def`` is visited once with
        its own visitor, so same-named defs (a property getter and setter,
        ``@overload`` variants) each contribute their own calls exactly once.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of CallEdge for all calls found.
        """
        try:
            tree = ast.parse(source)
        except (SyntaxError, ValueError) as e:
            logger.debug(f"Failed to extract calls from source: {e}")
            return []
        symbol_table = self.symbol_extractor.extract_from_source(source, file_path)

        calls: list[CallEdge] = []
        for node in tree.body:
            if isinstance(node, _DEF_NODES):
                calls.extend(_calls_in_def(node, file_path, "module", symbol_table))
        for node in tree.body:
            if isinstance(node, ast.ClassDef):
                for item in node.body:
                    if isinstance(item, _DEF_NODES):
                        calls.extend(_calls_in_def(item, file_path, node.name, symbol_table))
        return calls

__init__(repo_root=None)

Initialize call graph builder.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository.

None
Source code in py/cogant/static/calls.py
57
58
59
60
61
62
63
64
65
def __init__(self, repo_root: Path | None = None):
    """Initialize call graph builder.

    Args:
        repo_root: Root path of repository.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()
    self.symbol_extractor = SymbolExtractor(repo_root)

extract_calls_from_file(file_path)

Extract all function/method calls from a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[CallEdge]

List of CallEdge for all calls found.

Source code in py/cogant/static/calls.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def extract_calls_from_file(self, file_path: Path) -> list[CallEdge]:
    """Extract all function/method calls from a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of CallEdge for all calls found.
    """
    try:
        source = Path(file_path).read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError) as e:
        logger.debug(f"Failed to read {file_path}: {e}")
        return []
    return self.extract_calls_from_source(source, file_path)

extract_calls_from_source(source, file_path)

Extract function/method calls from Python source code.

Module-level functions are reported first, then class methods, each in source order. Every def and async def is visited once with its own visitor, so same-named defs (a property getter and setter, @overload variants) each contribute their own calls exactly once.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[CallEdge]

List of CallEdge for all calls found.

Source code in py/cogant/static/calls.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def extract_calls_from_source(self, source: str, file_path: Path) -> list[CallEdge]:
    """Extract function/method calls from Python source code.

    Module-level functions are reported first, then class methods, each
    in source order. Every ``def`` and ``async def`` is visited once with
    its own visitor, so same-named defs (a property getter and setter,
    ``@overload`` variants) each contribute their own calls exactly once.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of CallEdge for all calls found.
    """
    try:
        tree = ast.parse(source)
    except (SyntaxError, ValueError) as e:
        logger.debug(f"Failed to extract calls from source: {e}")
        return []
    symbol_table = self.symbol_extractor.extract_from_source(source, file_path)

    calls: list[CallEdge] = []
    for node in tree.body:
        if isinstance(node, _DEF_NODES):
            calls.extend(_calls_in_def(node, file_path, "module", symbol_table))
    for node in tree.body:
        if isinstance(node, ast.ClassDef):
            for item in node.body:
                if isinstance(item, _DEF_NODES):
                    calls.extend(_calls_in_def(item, file_path, node.name, symbol_table))
    return calls

ClassDef dataclass

Class definition from AST.

Source code in py/cogant/static/parser.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@dataclass
class ClassDef:
    """Class definition from AST."""

    name: str
    """Class name."""

    line_start: int
    """Starting line number."""

    line_end: int
    """Ending line number."""

    bases: list[str] = field(default_factory=list)
    """Base class names."""

    decorators: list[str] = field(default_factory=list)
    """List of decorator names."""

    docstring: str | None = None
    """Class docstring."""

    methods: list[FunctionDef] = field(default_factory=list)
    """Methods defined in class."""

    attributes: list[str] = field(default_factory=list)
    """Class attributes."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

attributes = field(default_factory=list) class-attribute instance-attribute

Class attributes.

bases = field(default_factory=list) class-attribute instance-attribute

Base class names.

decorators = field(default_factory=list) class-attribute instance-attribute

List of decorator names.

docstring = None class-attribute instance-attribute

Class docstring.

line_end instance-attribute

Ending line number.

line_start instance-attribute

Starting line number.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

methods = field(default_factory=list) class-attribute instance-attribute

Methods defined in class.

name instance-attribute

Class name.

DataFlowAnalyzer

Analyze data flow: track variable reads, writes, and mutations.

Source code in py/cogant/static/dataflow.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class DataFlowAnalyzer:
    """Analyze data flow: track variable reads, writes, and mutations."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize data flow analyzer.

        Args:
            repo_root: Root path of repository.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()

    def analyze_file(self, file_path: Path) -> list[DataFlowEdge]:
        """Analyze data flow in a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of DataFlowEdge for data flow relationships.
        """
        try:
            with open(file_path, encoding="utf-8") as f:
                source = f.read()
        except OSError as e:
            logger.debug(f"Failed to read {file_path}: {e}")
            return []

        return self.analyze_source(source, file_path)

    def analyze_source(self, source: str, file_path: Path) -> list[DataFlowEdge]:
        """Analyze data flow in Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of DataFlowEdge for data flow relationships.
        """
        flows: list[DataFlowEdge] = []

        try:
            tree = ast.parse(source)
        except SyntaxError as e:
            logger.debug(f"Syntax error parsing data flow in {file_path}: {e}")
            return flows
        except ValueError as e:
            logger.debug(f"Parse error parsing data flow in {file_path}: {e}")
            return flows

        # Module-level statements (no function bodies)
        module_stmts = [
            stmt
            for stmt in tree.body
            if not isinstance(
                stmt,
                ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef,
            )
        ]
        if module_stmts:
            visitor = DataFlowVisitor(file_path, "module", module_stmts)
            flows.extend(visitor.flows)

        # Top-level functions
        for node in tree.body:
            if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
                visitor = DataFlowVisitor(file_path, node.name, node.body)
                flows.extend(visitor.flows)
            elif isinstance(node, ast.ClassDef):
                # Analyze class body (attribute defaults, AnnAssigns)
                class_body_stmts = [
                    item
                    for item in node.body
                    if not isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
                ]
                if class_body_stmts:
                    visitor = DataFlowVisitor(file_path, node.name, class_body_stmts)
                    flows.extend(visitor.flows)

                # Analyze methods
                for item in node.body:
                    if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
                        context = f"{node.name}.{item.name}"
                        visitor = DataFlowVisitor(file_path, context, item.body)
                        flows.extend(visitor.flows)

        return flows

    def build_flow_graph(self, file_path: Path) -> DataFlowGraph:
        """Build a data flow graph from a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            DataFlowGraph instance.
        """
        edges = self.analyze_file(file_path)
        graph = DataFlowGraph()
        for edge in edges:
            graph.add_edge(edge)
        return graph

    def build_flow_graph_from_source(self, source: str, file_path: Path) -> DataFlowGraph:
        """Build a data flow graph from source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            DataFlowGraph instance.
        """
        edges = self.analyze_source(source, file_path)
        graph = DataFlowGraph()
        for edge in edges:
            graph.add_edge(edge)
        return graph

__init__(repo_root=None)

Initialize data flow analyzer.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository.

None
Source code in py/cogant/static/dataflow.py
170
171
172
173
174
175
176
177
def __init__(self, repo_root: Path | None = None):
    """Initialize data flow analyzer.

    Args:
        repo_root: Root path of repository.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()

analyze_file(file_path)

Analyze data flow in a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[DataFlowEdge]

List of DataFlowEdge for data flow relationships.

Source code in py/cogant/static/dataflow.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def analyze_file(self, file_path: Path) -> list[DataFlowEdge]:
    """Analyze data flow in a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of DataFlowEdge for data flow relationships.
    """
    try:
        with open(file_path, encoding="utf-8") as f:
            source = f.read()
    except OSError as e:
        logger.debug(f"Failed to read {file_path}: {e}")
        return []

    return self.analyze_source(source, file_path)

analyze_source(source, file_path)

Analyze data flow in Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[DataFlowEdge]

List of DataFlowEdge for data flow relationships.

Source code in py/cogant/static/dataflow.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def analyze_source(self, source: str, file_path: Path) -> list[DataFlowEdge]:
    """Analyze data flow in Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of DataFlowEdge for data flow relationships.
    """
    flows: list[DataFlowEdge] = []

    try:
        tree = ast.parse(source)
    except SyntaxError as e:
        logger.debug(f"Syntax error parsing data flow in {file_path}: {e}")
        return flows
    except ValueError as e:
        logger.debug(f"Parse error parsing data flow in {file_path}: {e}")
        return flows

    # Module-level statements (no function bodies)
    module_stmts = [
        stmt
        for stmt in tree.body
        if not isinstance(
            stmt,
            ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef,
        )
    ]
    if module_stmts:
        visitor = DataFlowVisitor(file_path, "module", module_stmts)
        flows.extend(visitor.flows)

    # Top-level functions
    for node in tree.body:
        if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
            visitor = DataFlowVisitor(file_path, node.name, node.body)
            flows.extend(visitor.flows)
        elif isinstance(node, ast.ClassDef):
            # Analyze class body (attribute defaults, AnnAssigns)
            class_body_stmts = [
                item
                for item in node.body
                if not isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
            ]
            if class_body_stmts:
                visitor = DataFlowVisitor(file_path, node.name, class_body_stmts)
                flows.extend(visitor.flows)

            # Analyze methods
            for item in node.body:
                if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
                    context = f"{node.name}.{item.name}"
                    visitor = DataFlowVisitor(file_path, context, item.body)
                    flows.extend(visitor.flows)

    return flows

build_flow_graph(file_path)

Build a data flow graph from a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
DataFlowGraph

DataFlowGraph instance.

Source code in py/cogant/static/dataflow.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def build_flow_graph(self, file_path: Path) -> DataFlowGraph:
    """Build a data flow graph from a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        DataFlowGraph instance.
    """
    edges = self.analyze_file(file_path)
    graph = DataFlowGraph()
    for edge in edges:
        graph.add_edge(edge)
    return graph

build_flow_graph_from_source(source, file_path)

Build a data flow graph from source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
DataFlowGraph

DataFlowGraph instance.

Source code in py/cogant/static/dataflow.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def build_flow_graph_from_source(self, source: str, file_path: Path) -> DataFlowGraph:
    """Build a data flow graph from source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        DataFlowGraph instance.
    """
    edges = self.analyze_source(source, file_path)
    graph = DataFlowGraph()
    for edge in edges:
        graph.add_edge(edge)
    return graph

DataFlowEdge dataclass

A data flow relationship between symbols.

Source code in py/cogant/static/dataflow.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@dataclass
class DataFlowEdge:
    """A data flow relationship between symbols."""

    id: str
    """Unique edge identifier."""

    source_symbol: str
    """Source symbol ID or name."""

    target_symbol: str
    """Target symbol ID or name."""

    edge_type: str
    """Edge type: reads, writes, mutates, depends_on."""

    file_path: Path
    """Source file path."""

    line_num: int
    """Line number where flow occurs."""

    context: str = "module"
    """Context (module, function name, class.method)."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

context = 'module' class-attribute instance-attribute

Context (module, function name, class.method).

edge_type instance-attribute

Edge type: reads, writes, mutates, depends_on.

file_path instance-attribute

Source file path.

id instance-attribute

Unique edge identifier.

line_num instance-attribute

Line number where flow occurs.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

source_symbol instance-attribute

Source symbol ID or name.

target_symbol instance-attribute

Target symbol ID or name.

FunctionDef dataclass

Function definition from AST.

Source code in py/cogant/static/parser.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass
class FunctionDef:
    """Function definition from AST."""

    name: str
    """Function name."""

    line_start: int
    """Starting line number."""

    line_end: int
    """Ending line number."""

    decorators: list[str] = field(default_factory=list)
    """List of decorator names."""

    args: list[str] = field(default_factory=list)
    """Parameter names."""

    return_annotation: str | None = None
    """Return type annotation if present."""

    docstring: str | None = None
    """Function docstring."""

    parent: str | None = None
    """Parent class name if method."""

    is_async: bool = False
    """Whether function is async."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

args = field(default_factory=list) class-attribute instance-attribute

Parameter names.

decorators = field(default_factory=list) class-attribute instance-attribute

List of decorator names.

docstring = None class-attribute instance-attribute

Function docstring.

is_async = False class-attribute instance-attribute

Whether function is async.

line_end instance-attribute

Ending line number.

line_start instance-attribute

Starting line number.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

name instance-attribute

Function name.

parent = None class-attribute instance-attribute

Parent class name if method.

return_annotation = None class-attribute instance-attribute

Return type annotation if present.

ImportAnalyzer

Analyze and resolve import statements.

Source code in py/cogant/static/imports.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
class ImportAnalyzer:
    """Analyze and resolve import statements."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize import analyzer.

        Args:
            repo_root: Root path of repository for local import resolution.
                Absolute imports (``import pkg.mod``) are resolved against
                it only when it is given; relative imports always resolve
                against the importing file.
        """
        self.repo_root = Path(repo_root or "/")
        self._resolve_absolute = repo_root is not None
        self.parser = PythonASTParser()
        self._stdlib_modules = self._load_stdlib_modules()

    def analyze_file(self, file_path: Path) -> list[ImportEdge]:
        """Analyze imports in a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of ImportEdge for all imports found.
        """
        module = self.parser.parse_file(file_path)
        return self._build_import_edges(file_path, module.imports)

    def analyze_source(self, source: str, file_path: Path) -> list[ImportEdge]:
        """Analyze imports in Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of ImportEdge for all imports found.
        """
        module = self.parser.parse_string(source, file_path)
        return self._build_import_edges(file_path, module.imports)

    def _build_import_edges(self, file_path: Path, import_defs: Any) -> list[ImportEdge]:
        """Build import edges from import definitions.

        Args:
            file_path: Source file path.
            import_defs: List of ImportDef from parser.

        Returns:
            List of ImportEdge.
        """
        edges = []

        for imp in import_defs:
            # Classify on the top-level package: ``os.path`` is stdlib because
            # ``os`` is. Relative imports are never stdlib.
            top_level = imp.module_name.split(".", 1)[0]
            is_stdlib = not imp.is_relative and top_level in self._stdlib_modules

            # Resolve relative imports, and absolute ones against repo_root,
            # before anything non-stdlib is called third-party.
            resolved_file = None
            if imp.is_relative:
                metadata = imp.metadata if isinstance(imp.metadata, dict) else {}
                resolved_file = self._resolve_local_import(
                    file_path,
                    imp.module_name,
                    True,
                    level=int(metadata.get("level", 1) or 1),
                    names=list(imp.names or []),
                )
            elif not is_stdlib and self._resolve_absolute:
                resolved_file = self._resolve_local_import(file_path, imp.module_name, False)
            is_local = resolved_file is not None
            is_third_party = not is_stdlib and not imp.is_relative and not is_local

            edge = ImportEdge(
                id=self._generate_import_id(file_path, imp.module_name),
                source_file=file_path,
                module_name=imp.module_name,
                is_relative=imp.is_relative,
                is_stdlib=is_stdlib,
                is_third_party=is_third_party,
                is_local=is_local,
                resolved_file=resolved_file,
                line_num=imp.line_num,
                imported_names=imp.names,
            )
            edges.append(edge)

        return edges

    def _resolve_local_import(
        self,
        source_file: Path,
        module_name: str,
        is_relative: bool,
        level: int = 1,
        names: list[str] | None = None,
    ) -> Path | None:
        """Try to resolve a local import to a file.

        Args:
            source_file: File containing the import.
            module_name: Module name to resolve (empty for ``from . import x``).
            is_relative: Whether import is relative.
            level: Number of leading dots of a relative import; each dot
                beyond the first moves up one package directory.
            names: Imported names; for ``from . import x`` a submodule
                ``x`` is preferred over the package itself.

        Returns:
            Resolved file path or None if not found.
        """
        if is_relative:
            base = source_file.parent
            for _ in range(max(level, 1) - 1):
                base = base.parent
            if not module_name:
                # ``from . import x``: x is a submodule or a package attribute.
                for name in names or []:
                    for candidate in (base / f"{name}.py", base / name / "__init__.py"):
                        if candidate.exists():
                            return candidate
                package_init = base / "__init__.py"
                return package_init if package_init.exists() else None
            target = base / module_name.replace(".", "/")
        else:
            # Absolute import
            target = self.repo_root / module_name.replace(".", "/")

        # Try as module (file.py)
        module_file = target.parent / f"{target.name}.py"
        if module_file.exists():
            return module_file

        # Try as package (directory with __init__.py)
        if (target / "__init__.py").exists():
            return target / "__init__.py"

        return None

    @staticmethod
    def _load_stdlib_modules() -> set[str]:
        """Load set of Python standard library module names.

        Returns:
            Set of stdlib module names: the running interpreter's
            ``sys.stdlib_module_names`` plus modules removed from recent
            Python versions that older code may still import.
        """
        # Core standard library modules
        stdlib = {
            "__future__",
            "abc",
            "aifc",
            "argparse",
            "array",
            "ast",
            "asyncio",
            "atexit",
            "audioop",
            "base64",
            "bdb",
            "binascii",
            "binhex",
            "bisect",
            "builtins",
            "bz2",
            "calendar",
            "cgi",
            "cgitb",
            "chunk",
            "cmath",
            "cmd",
            "code",
            "codecs",
            "codeop",
            "collections",
            "colorsys",
            "compileall",
            "concurrent",
            "configparser",
            "contextlib",
            "contextvars",
            "copy",
            "copyreg",
            "cProfile",
            "crypt",
            "csv",
            "ctypes",
            "curses",
            "dataclasses",
            "datetime",
            "dbm",
            "decimal",
            "difflib",
            "dis",
            "distutils",
            "doctest",
            "dummy_thread",
            "email",
            "encodings",
            "enum",
            "errno",
            "faulthandler",
            "fcntl",
            "filecmp",
            "fileinput",
            "fnmatch",
            "fractions",
            "ftplib",
            "functools",
            "gc",
            "getopt",
            "getpass",
            "gettext",
            "glob",
            "graphlib",
            "grp",
            "gzip",
            "hashlib",
            "heapq",
            "hmac",
            "html",
            "http",
            "idlelib",
            "imaplib",
            "imghdr",
            "imp",
            "importlib",
            "inspect",
            "io",
            "ipaddress",
            "itertools",
            "json",
            "keyword",
            "lib2to3",
            "linecache",
            "locale",
            "logging",
            "lzma",
            "mailbox",
            "mailcap",
            "marshal",
            "math",
            "mimetypes",
            "mmap",
            "modulefinder",
            "msilib",
            "msvcrt",
            "multiprocessing",
            "netrc",
            "nis",
            "nntplib",
            "numbers",
            "operator",
            "optparse",
            "os",
            "ossaudiodev",
            "parser",
            "pathlib",
            "pdb",
            "pickle",
            "pickletools",
            "pipes",
            "pkgutil",
            "platform",
            "plistlib",
            "poplib",
            "posix",
            "posixpath",
            "pprint",
            "profile",
            "pstats",
            "pty",
            "pwd",
            "py_compile",
            "pyclbr",
            "pydoc",
            "queue",
            "quopri",
            "random",
            "readline",
            "reprlib",
            "resource",
            "rlcompleter",
            "runpy",
            "sched",
            "secrets",
            "select",
            "selectors",
            "shelve",
            "shlex",
            "shutil",
            "signal",
            "site",
            "smtpd",
            "smtplib",
            "sndhdr",
            "socket",
            "socketserver",
            "spwd",
            "sqlite3",
            "ssl",
            "stat",
            "statistics",
            "string",
            "stringprep",
            "struct",
            "subprocess",
            "sunau",
            "symbol",
            "symtable",
            "sys",
            "sysconfig",
            "syslog",
            "tabnanny",
            "tarfile",
            "telnetlib",
            "tempfile",
            "termios",
            "test",
            "textwrap",
            "threading",
            "time",
            "timeit",
            "tkinter",
            "token",
            "tokenize",
            "tomllib",
            "trace",
            "traceback",
            "tracemalloc",
            "tty",
            "turtle",
            "turtledemo",
            "types",
            "typing",
            "unicodedata",
            "unittest",
            "urllib",
            "uu",
            "uuid",
            "venv",
            "warnings",
            "wave",
            "weakref",
            "webbrowser",
            "winreg",
            "winsound",
            "wsgiref",
            "xdrlib",
            "xml",
            "xmlrpc",
            "zipapp",
            "zipfile",
            "zipimport",
            "zlib",
        }

        return stdlib | set(sys.stdlib_module_names)

    @staticmethod
    def _generate_import_id(file_path: Path, module_name: str) -> str:
        """Generate stable import edge ID.

        Args:
            file_path: Source file path.
            module_name: Module being imported.

        Returns:
            Stable ID (SHA256 hash).
        """
        content = f"{file_path.resolve()}:import:{module_name}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

__init__(repo_root=None)

Initialize import analyzer.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository for local import resolution. Absolute imports (import pkg.mod) are resolved against it only when it is given; relative imports always resolve against the importing file.

None
Source code in py/cogant/static/imports.py
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(self, repo_root: Path | None = None):
    """Initialize import analyzer.

    Args:
        repo_root: Root path of repository for local import resolution.
            Absolute imports (``import pkg.mod``) are resolved against
            it only when it is given; relative imports always resolve
            against the importing file.
    """
    self.repo_root = Path(repo_root or "/")
    self._resolve_absolute = repo_root is not None
    self.parser = PythonASTParser()
    self._stdlib_modules = self._load_stdlib_modules()

analyze_file(file_path)

Analyze imports in a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[ImportEdge]

List of ImportEdge for all imports found.

Source code in py/cogant/static/imports.py
73
74
75
76
77
78
79
80
81
82
83
def analyze_file(self, file_path: Path) -> list[ImportEdge]:
    """Analyze imports in a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of ImportEdge for all imports found.
    """
    module = self.parser.parse_file(file_path)
    return self._build_import_edges(file_path, module.imports)

analyze_source(source, file_path)

Analyze imports in Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[ImportEdge]

List of ImportEdge for all imports found.

Source code in py/cogant/static/imports.py
85
86
87
88
89
90
91
92
93
94
95
96
def analyze_source(self, source: str, file_path: Path) -> list[ImportEdge]:
    """Analyze imports in Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of ImportEdge for all imports found.
    """
    module = self.parser.parse_string(source, file_path)
    return self._build_import_edges(file_path, module.imports)

ImportDef dataclass

Import statement from AST.

Source code in py/cogant/static/parser.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@dataclass
class ImportDef:
    """Import statement from AST."""

    module_name: str
    """Module being imported."""

    is_relative: bool
    """Whether import is relative."""

    names: list[str] = field(default_factory=list)
    """Specific names imported (for 'from X import Y')."""

    line_num: int = 0
    """Line number of import."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

is_relative instance-attribute

Whether import is relative.

line_num = 0 class-attribute instance-attribute

Line number of import.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

module_name instance-attribute

Module being imported.

names = field(default_factory=list) class-attribute instance-attribute

Specific names imported (for 'from X import Y').

ImportEdge dataclass

An import relationship between modules.

Source code in py/cogant/static/imports.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass
class ImportEdge:
    """An import relationship between modules."""

    id: str
    """Unique edge identifier."""

    source_file: Path
    """File containing the import."""

    module_name: str
    """Module being imported."""

    is_relative: bool
    """Whether import is relative."""

    is_stdlib: bool
    """Whether module is from Python standard library."""

    is_third_party: bool
    """Whether module is from third-party package."""

    is_local: bool
    """Whether module is local to repository."""

    resolved_file: Path | None = None
    """Resolved file path if found."""

    resolved_module: str | None = None
    """Resolved module name."""

    line_num: int = 0
    """Line number of import statement."""

    imported_names: list[str] = field(default_factory=list)
    """Specific names imported (for 'from X import Y')."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

id instance-attribute

Unique edge identifier.

imported_names = field(default_factory=list) class-attribute instance-attribute

Specific names imported (for 'from X import Y').

is_local instance-attribute

Whether module is local to repository.

is_relative instance-attribute

Whether import is relative.

is_stdlib instance-attribute

Whether module is from Python standard library.

is_third_party instance-attribute

Whether module is from third-party package.

line_num = 0 class-attribute instance-attribute

Line number of import statement.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

module_name instance-attribute

Module being imported.

resolved_file = None class-attribute instance-attribute

Resolved file path if found.

resolved_module = None class-attribute instance-attribute

Resolved module name.

source_file instance-attribute

File containing the import.

PythonASTParser

Parse Python source files and extract AST information.

Source code in py/cogant/static/parser.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
class PythonASTParser:
    """Parse Python source files and extract AST information."""

    def parse_file(self, file_path: Path) -> PythonModule:
        """Parse a Python source file.

        Args:
            file_path: Path to Python file.

        Returns:
            PythonModule with extracted AST information.
        """
        module = PythonModule(file_path=file_path)

        try:
            with open(file_path, encoding="utf-8") as f:
                source = f.read()
        except Exception as e:
            module.errors.append(f"Failed to read file: {e}")
            return module

        try:
            tree = ast.parse(source, filename=str(file_path))
        except SyntaxError as e:
            module.errors.append(f"Syntax error: {e}")
            return module
        except Exception as e:
            module.errors.append(f"Parse error: {e}")
            return module

        # Extract module docstring (guard against empty files like bare __init__.py)
        if (
            tree.body
            and isinstance(tree.body[0], ast.Expr)
            and isinstance(tree.body[0].value, ast.Constant)
            and isinstance(tree.body[0].value.value, str)
        ):
            module.docstring = tree.body[0].value.value

        # Visit all nodes
        for node in tree.body:
            if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
                func = self._extract_function(node)
                if func:
                    module.functions.append(func)
            elif isinstance(node, ast.ClassDef):
                cls = self._extract_class(node)
                if cls:
                    module.classes.append(cls)
            elif isinstance(node, ast.Import | ast.ImportFrom):
                imports = self._extract_imports(node)
                module.imports.extend(imports)
            elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
                assign = self._extract_assignment(node)
                if assign:
                    module.assignments.append(assign)

        return module

    def parse_string(self, source: str, file_path: Path | None = None) -> PythonModule:
        """Parse Python source from string.

        Args:
            source: Python source code as string.
            file_path: Optional file path for reference.

        Returns:
            PythonModule with extracted AST information.
        """
        if file_path is None:
            file_path = Path("<string>")

        module = PythonModule(file_path=file_path)

        try:
            tree = ast.parse(source, filename=str(file_path))
        except SyntaxError as e:
            module.errors.append(f"Syntax error: {e}")
            return module
        except Exception as e:
            module.errors.append(f"Parse error: {e}")
            return module

        # Extract module docstring
        if (
            tree.body
            and isinstance(tree.body[0], ast.Expr)
            and isinstance(tree.body[0].value, ast.Constant)
            and isinstance(tree.body[0].value.value, str)
        ):
            module.docstring = tree.body[0].value.value

        # Visit all nodes
        for node in tree.body:
            if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
                func = self._extract_function(node)
                if func:
                    module.functions.append(func)
            elif isinstance(node, ast.ClassDef):
                cls = self._extract_class(node)
                if cls:
                    module.classes.append(cls)
            elif isinstance(node, ast.Import | ast.ImportFrom):
                imports = self._extract_imports(node)
                module.imports.extend(imports)
            elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
                assign = self._extract_assignment(node)
                if assign:
                    module.assignments.append(assign)

        return module

    def _extract_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> FunctionDef | None:
        """Extract function definition from AST node.

        Args:
            node: AST FunctionDef or AsyncFunctionDef node.

        Returns:
            FunctionDef or None if extraction failed.
        """
        try:
            # Extract decorators
            decorators = [self._ast_to_str(dec) for dec in node.decorator_list]

            # Extract argument names
            args = []
            for arg in node.args.args:
                args.append(arg.arg)

            # Extract return annotation
            return_annotation = None
            if node.returns:
                return_annotation = self._ast_to_str(node.returns)

            # Extract docstring
            docstring = None
            if (
                node.body
                and isinstance(node.body[0], ast.Expr)
                and isinstance(node.body[0].value, ast.Constant)
                and isinstance(node.body[0].value.value, str)
            ):
                docstring = node.body[0].value.value

            return FunctionDef(
                name=node.name,
                line_start=node.lineno,
                line_end=node.end_lineno or node.lineno,
                decorators=decorators,
                args=args,
                return_annotation=return_annotation,
                docstring=docstring,
                is_async=isinstance(node, ast.AsyncFunctionDef),
            )

        except Exception as e:
            logger.debug(f"Failed to extract function {getattr(node, 'name', '?')}: {e}")
            return None

    def _extract_class(self, node: ast.ClassDef) -> ClassDef | None:
        """Extract class definition from AST node.

        Args:
            node: AST ClassDef node.

        Returns:
            ClassDef or None if extraction failed.
        """
        try:
            # Extract base class names
            bases = [self._ast_to_str(base) for base in node.bases]

            # Extract decorators
            decorators = [self._ast_to_str(dec) for dec in node.decorator_list]

            # Extract docstring
            docstring = None
            if (
                node.body
                and isinstance(node.body[0], ast.Expr)
                and isinstance(node.body[0].value, ast.Constant)
                and isinstance(node.body[0].value.value, str)
            ):
                docstring = node.body[0].value.value

            # Extract methods
            methods = []
            for item in node.body:
                if isinstance(item, ast.FunctionDef) or isinstance(item, ast.AsyncFunctionDef):
                    method = self._extract_function(item)
                    if method:
                        method.parent = node.name
                        methods.append(method)

            # Extract class attributes
            attributes = []
            for item in node.body:
                if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
                    attributes.append(item.target.id)

            return ClassDef(
                name=node.name,
                line_start=node.lineno,
                line_end=node.end_lineno or node.lineno,
                bases=bases,
                decorators=decorators,
                docstring=docstring,
                methods=methods,
                attributes=attributes,
            )

        except Exception as e:
            logger.debug(f"Failed to extract class {getattr(node, 'name', '?')}: {e}")
            return None

    def _extract_imports(self, node: ast.Import | ast.ImportFrom) -> list[ImportDef]:
        """Extract import statements from AST node.

        Args:
            node: AST Import or ImportFrom node.

        Returns:
            List of ImportDef.
        """
        imports = []

        try:
            if isinstance(node, ast.Import):
                for alias in node.names:
                    imports.append(
                        ImportDef(
                            module_name=alias.name,
                            is_relative=False,
                            line_num=node.lineno,
                        )
                    )
            elif isinstance(node, ast.ImportFrom):
                module_name = node.module or ""
                is_relative = node.level > 0

                for alias in node.names:
                    imports.append(
                        ImportDef(
                            module_name=module_name,
                            is_relative=is_relative,
                            names=[alias.name],
                            line_num=node.lineno,
                            # Leading-dot count: ``from ..x`` is level 2.
                            metadata={"level": node.level},
                        )
                    )

        except Exception as e:
            logger.debug(f"Failed to extract imports: {e}")

        return imports

    def _extract_assignment(self, node: ast.Assign | ast.AnnAssign) -> AssignmentDef | None:
        """Extract assignment from AST node.

        Args:
            node: AST Assign or AnnAssign node.

        Returns:
            AssignmentDef or None if extraction failed.
        """
        try:
            if isinstance(node, ast.Assign):
                # Handle multiple targets (e.g., a = b = c)
                if node.targets and isinstance(node.targets[0], ast.Name):
                    target_name = node.targets[0].id
                    value_str = self._ast_to_str(node.value) if node.value else None

                    return AssignmentDef(
                        target_name=target_name,
                        line_num=node.lineno,
                        value=value_str,
                    )

            elif isinstance(node, ast.AnnAssign):
                if isinstance(node.target, ast.Name):
                    annotation_str = self._ast_to_str(node.annotation) if node.annotation else None
                    value_str = self._ast_to_str(node.value) if node.value else None

                    return AssignmentDef(
                        target_name=node.target.id,
                        line_num=node.lineno,
                        annotation=annotation_str,
                        value=value_str,
                    )

        except Exception as e:
            logger.debug(f"Failed to extract assignment: {e}")

        return None

    @staticmethod
    def _ast_to_str(node: ast.AST) -> str:
        """Convert AST node to string representation.

        Args:
            node: AST node.

        Returns:
            String representation of node.
        """
        try:
            return ast.unparse(node)
        except Exception:
            # Fallback for nodes that can't be unparsed
            if isinstance(node, ast.Name):
                return node.id
            elif isinstance(node, ast.Constant):
                return repr(node.value)
            elif isinstance(node, ast.Attribute):
                return f"{PythonASTParser._ast_to_str(node.value)}.{node.attr}"
            else:
                return type(node).__name__

parse_file(file_path)

Parse a Python source file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
PythonModule

PythonModule with extracted AST information.

Source code in py/cogant/static/parser.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def parse_file(self, file_path: Path) -> PythonModule:
    """Parse a Python source file.

    Args:
        file_path: Path to Python file.

    Returns:
        PythonModule with extracted AST information.
    """
    module = PythonModule(file_path=file_path)

    try:
        with open(file_path, encoding="utf-8") as f:
            source = f.read()
    except Exception as e:
        module.errors.append(f"Failed to read file: {e}")
        return module

    try:
        tree = ast.parse(source, filename=str(file_path))
    except SyntaxError as e:
        module.errors.append(f"Syntax error: {e}")
        return module
    except Exception as e:
        module.errors.append(f"Parse error: {e}")
        return module

    # Extract module docstring (guard against empty files like bare __init__.py)
    if (
        tree.body
        and isinstance(tree.body[0], ast.Expr)
        and isinstance(tree.body[0].value, ast.Constant)
        and isinstance(tree.body[0].value.value, str)
    ):
        module.docstring = tree.body[0].value.value

    # Visit all nodes
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
            func = self._extract_function(node)
            if func:
                module.functions.append(func)
        elif isinstance(node, ast.ClassDef):
            cls = self._extract_class(node)
            if cls:
                module.classes.append(cls)
        elif isinstance(node, ast.Import | ast.ImportFrom):
            imports = self._extract_imports(node)
            module.imports.extend(imports)
        elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
            assign = self._extract_assignment(node)
            if assign:
                module.assignments.append(assign)

    return module

parse_string(source, file_path=None)

Parse Python source from string.

Parameters:

Name Type Description Default
source str

Python source code as string.

required
file_path Path | None

Optional file path for reference.

None

Returns:

Type Description
PythonModule

PythonModule with extracted AST information.

Source code in py/cogant/static/parser.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def parse_string(self, source: str, file_path: Path | None = None) -> PythonModule:
    """Parse Python source from string.

    Args:
        source: Python source code as string.
        file_path: Optional file path for reference.

    Returns:
        PythonModule with extracted AST information.
    """
    if file_path is None:
        file_path = Path("<string>")

    module = PythonModule(file_path=file_path)

    try:
        tree = ast.parse(source, filename=str(file_path))
    except SyntaxError as e:
        module.errors.append(f"Syntax error: {e}")
        return module
    except Exception as e:
        module.errors.append(f"Parse error: {e}")
        return module

    # Extract module docstring
    if (
        tree.body
        and isinstance(tree.body[0], ast.Expr)
        and isinstance(tree.body[0].value, ast.Constant)
        and isinstance(tree.body[0].value.value, str)
    ):
        module.docstring = tree.body[0].value.value

    # Visit all nodes
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
            func = self._extract_function(node)
            if func:
                module.functions.append(func)
        elif isinstance(node, ast.ClassDef):
            cls = self._extract_class(node)
            if cls:
                module.classes.append(cls)
        elif isinstance(node, ast.Import | ast.ImportFrom):
            imports = self._extract_imports(node)
            module.imports.extend(imports)
        elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
            assign = self._extract_assignment(node)
            if assign:
                module.assignments.append(assign)

    return module

PythonModule dataclass

Complete parsed Python module.

Source code in py/cogant/static/parser.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
@dataclass
class PythonModule:
    """Complete parsed Python module."""

    file_path: Path
    """Source file path."""

    docstring: str | None = None
    """Module docstring."""

    functions: list[FunctionDef] = field(default_factory=list)
    """Module-level functions."""

    classes: list[ClassDef] = field(default_factory=list)
    """Module-level classes."""

    imports: list[ImportDef] = field(default_factory=list)
    """Import statements."""

    assignments: list[AssignmentDef] = field(default_factory=list)
    """Module-level assignments."""

    errors: list[str] = field(default_factory=list)
    """Parse errors encountered."""

assignments = field(default_factory=list) class-attribute instance-attribute

Module-level assignments.

classes = field(default_factory=list) class-attribute instance-attribute

Module-level classes.

docstring = None class-attribute instance-attribute

Module docstring.

errors = field(default_factory=list) class-attribute instance-attribute

Parse errors encountered.

file_path instance-attribute

Source file path.

functions = field(default_factory=list) class-attribute instance-attribute

Module-level functions.

imports = field(default_factory=list) class-attribute instance-attribute

Import statements.

SymbolExtractor

Extract symbols from parsed Python modules.

Source code in py/cogant/static/symbols.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
class SymbolExtractor:
    """Extract symbols from parsed Python modules."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize symbol extractor.

        Args:
            repo_root: Optional repository root for qualified name generation.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()

    def extract_from_file(self, file_path: Path) -> SymbolTable:
        """Extract symbols from a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            SymbolTable with extracted symbols.
        """
        # Parse file
        module = self.parser.parse_file(file_path)

        # Extract symbols
        return self._extract_from_module(module)

    def extract_from_source(self, source: str, file_path: Path) -> SymbolTable:
        """Extract symbols from Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference and qualified names.

        Returns:
            SymbolTable with extracted symbols.
        """
        # Parse source
        module = self.parser.parse_string(source, file_path)

        # Extract symbols
        return self._extract_from_module(module)

    def _extract_from_module(self, module: PythonModule) -> SymbolTable:
        """Extract symbols from parsed module.

        Args:
            module: Parsed Python module.

        Returns:
            SymbolTable with extracted symbols.
        """
        table = SymbolTable(file_path=module.file_path, errors=module.errors)

        # Get module qualified name
        module_qname = self._get_module_qname(module.file_path)

        # Extract module-level functions
        for func in module.functions:
            symbol = SymbolInfo(
                id=self._generate_symbol_id(module.file_path, func.name),
                name=func.name,
                qualified_name=f"{module_qname}.{func.name}",
                kind="function",
                file_path=module.file_path,
                line_start=func.line_start,
                line_end=func.line_end,
                scope="module",
                doc=func.docstring,
                decorators=func.decorators,
                metadata={
                    "is_async": func.is_async,
                    "parameters": func.args,
                    "return_annotation": func.return_annotation,
                },
            )
            table.symbols.append(symbol)

        # Extract classes and their methods
        for cls in module.classes:
            class_id = self._generate_symbol_id(module.file_path, cls.name)
            class_symbol = SymbolInfo(
                id=class_id,
                name=cls.name,
                qualified_name=f"{module_qname}.{cls.name}",
                kind="class",
                file_path=module.file_path,
                line_start=cls.line_start,
                line_end=cls.line_end,
                scope="module",
                doc=cls.docstring,
                decorators=cls.decorators,
                metadata={
                    "bases": cls.bases,
                    "attributes": cls.attributes,
                },
            )
            table.symbols.append(class_symbol)

            # Extract methods
            for method in cls.methods:
                method_id = self._generate_symbol_id(module.file_path, f"{cls.name}.{method.name}")
                method_symbol = SymbolInfo(
                    id=method_id,
                    name=method.name,
                    qualified_name=f"{module_qname}.{cls.name}.{method.name}",
                    kind="method",
                    file_path=module.file_path,
                    line_start=method.line_start,
                    line_end=method.line_end,
                    scope=cls.name,
                    parent_id=class_id,
                    doc=method.docstring,
                    decorators=method.decorators,
                    metadata={
                        "is_async": method.is_async,
                        "parameters": method.args,
                        "return_annotation": method.return_annotation,
                    },
                )
                table.symbols.append(method_symbol)

        # Extract module-level variables
        for assign in module.assignments:
            symbol = SymbolInfo(
                id=self._generate_symbol_id(module.file_path, assign.target_name),
                name=assign.target_name,
                qualified_name=f"{module_qname}.{assign.target_name}",
                kind="variable",
                file_path=module.file_path,
                line_start=assign.line_num,
                line_end=assign.line_num,
                scope="module",
                metadata={
                    "annotation": assign.annotation,
                    "value": assign.value,
                },
            )
            table.symbols.append(symbol)

        return table

    def _get_module_qname(self, file_path: Path) -> str:
        """Generate qualified name for a module.

        Args:
            file_path: Path to Python file.

        Returns:
            Qualified module name.
        """
        try:
            relative = file_path.relative_to(self.repo_root)
        except ValueError:
            # If file is not relative to repo root, use file name
            relative = file_path

        # Convert path to module name
        parts = list(relative.parts[:-1])  # Exclude filename
        parts.append(relative.stem)  # Add module name (without .py)

        # Filter out common prefixes
        parts = [p for p in parts if p not in {"src", "lib", "cogant"}]

        return ".".join(parts) if parts else relative.stem

    @staticmethod
    def _generate_symbol_id(file_path: Path, symbol_name: str) -> str:
        """Generate stable symbol ID.

        Args:
            file_path: Source file path.
            symbol_name: Symbol name or qualified name.

        Returns:
            Stable symbol ID (SHA256 hash).
        """
        # Create deterministic ID from file path and symbol name
        content = f"{file_path.resolve()}#{symbol_name}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

__init__(repo_root=None)

Initialize symbol extractor.

Parameters:

Name Type Description Default
repo_root Path | None

Optional repository root for qualified name generation.

None
Source code in py/cogant/static/symbols.py
125
126
127
128
129
130
131
132
def __init__(self, repo_root: Path | None = None):
    """Initialize symbol extractor.

    Args:
        repo_root: Optional repository root for qualified name generation.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()

extract_from_file(file_path)

Extract symbols from a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
SymbolTable

SymbolTable with extracted symbols.

Source code in py/cogant/static/symbols.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def extract_from_file(self, file_path: Path) -> SymbolTable:
    """Extract symbols from a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        SymbolTable with extracted symbols.
    """
    # Parse file
    module = self.parser.parse_file(file_path)

    # Extract symbols
    return self._extract_from_module(module)

extract_from_source(source, file_path)

Extract symbols from Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference and qualified names.

required

Returns:

Type Description
SymbolTable

SymbolTable with extracted symbols.

Source code in py/cogant/static/symbols.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def extract_from_source(self, source: str, file_path: Path) -> SymbolTable:
    """Extract symbols from Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference and qualified names.

    Returns:
        SymbolTable with extracted symbols.
    """
    # Parse source
    module = self.parser.parse_string(source, file_path)

    # Extract symbols
    return self._extract_from_module(module)

SymbolInfo dataclass

Information about a code symbol.

Source code in py/cogant/static/symbols.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@dataclass
class SymbolInfo:
    """Information about a code symbol."""

    id: str
    """Unique stable identifier."""

    name: str
    """Short name (e.g., 'foo')."""

    qualified_name: str
    """Fully qualified name (e.g., 'module.Class.method')."""

    kind: str
    """Symbol kind (function, class, method, variable)."""

    file_path: Path
    """Source file path."""

    line_start: int
    """Starting line number."""

    line_end: int
    """Ending line number."""

    scope: str
    """Scope context (module, class_name, function_name)."""

    parent_id: str | None = None
    """ID of parent symbol if nested."""

    doc: str | None = None
    """Docstring if available."""

    decorators: list[str] = field(default_factory=list)
    """List of decorators."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Language-specific metadata."""

decorators = field(default_factory=list) class-attribute instance-attribute

List of decorators.

doc = None class-attribute instance-attribute

Docstring if available.

file_path instance-attribute

Source file path.

id instance-attribute

Unique stable identifier.

kind instance-attribute

Symbol kind (function, class, method, variable).

line_end instance-attribute

Ending line number.

line_start instance-attribute

Starting line number.

metadata = field(default_factory=dict) class-attribute instance-attribute

Language-specific metadata.

name instance-attribute

Short name (e.g., 'foo').

parent_id = None class-attribute instance-attribute

ID of parent symbol if nested.

qualified_name instance-attribute

Fully qualified name (e.g., 'module.Class.method').

scope instance-attribute

Scope context (module, class_name, function_name).

SymbolTable dataclass

Collection of extracted symbols.

Source code in py/cogant/static/symbols.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass
class SymbolTable:
    """Collection of extracted symbols."""

    file_path: Path
    """Source file path."""

    symbols: list[SymbolInfo] = field(default_factory=list)
    """Extracted symbols."""

    errors: list[str] = field(default_factory=list)
    """Errors encountered during extraction."""

    def get_public_api(self) -> list[SymbolInfo]:
        """Get all public (non-underscore) symbols.

        Returns:
            List of public symbols.
        """
        return [s for s in self.symbols if not s.name.startswith("_")]

    def get_entry_points(self) -> list[SymbolInfo]:
        """Get symbols callable from outside (public functions and public methods).

        Returns:
            List of public functions and methods.
        """
        return [
            s
            for s in self.get_public_api()
            if s.kind in ("function", "method") or (s.kind == "class")
        ]

    def to_json(self) -> str:
        """Serialize symbol table to JSON.

        Returns:
            JSON string representation.
        """
        import json

        data = {
            "file_path": str(self.file_path),
            "symbols": [
                {
                    "id": s.id,
                    "name": s.name,
                    "qualified_name": s.qualified_name,
                    "kind": s.kind,
                    "line_start": s.line_start,
                    "line_end": s.line_end,
                    "scope": s.scope,
                    "parent_id": s.parent_id,
                    "doc": s.doc,
                    "decorators": s.decorators,
                    "metadata": s.metadata,
                }
                for s in self.symbols
            ],
            "errors": self.errors,
        }
        return json.dumps(data, indent=2)

errors = field(default_factory=list) class-attribute instance-attribute

Errors encountered during extraction.

file_path instance-attribute

Source file path.

symbols = field(default_factory=list) class-attribute instance-attribute

Extracted symbols.

get_entry_points()

Get symbols callable from outside (public functions and public methods).

Returns:

Type Description
list[SymbolInfo]

List of public functions and methods.

Source code in py/cogant/static/symbols.py
79
80
81
82
83
84
85
86
87
88
89
def get_entry_points(self) -> list[SymbolInfo]:
    """Get symbols callable from outside (public functions and public methods).

    Returns:
        List of public functions and methods.
    """
    return [
        s
        for s in self.get_public_api()
        if s.kind in ("function", "method") or (s.kind == "class")
    ]

get_public_api()

Get all public (non-underscore) symbols.

Returns:

Type Description
list[SymbolInfo]

List of public symbols.

Source code in py/cogant/static/symbols.py
71
72
73
74
75
76
77
def get_public_api(self) -> list[SymbolInfo]:
    """Get all public (non-underscore) symbols.

    Returns:
        List of public symbols.
    """
    return [s for s in self.symbols if not s.name.startswith("_")]

to_json()

Serialize symbol table to JSON.

Returns:

Type Description
str

JSON string representation.

Source code in py/cogant/static/symbols.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def to_json(self) -> str:
    """Serialize symbol table to JSON.

    Returns:
        JSON string representation.
    """
    import json

    data = {
        "file_path": str(self.file_path),
        "symbols": [
            {
                "id": s.id,
                "name": s.name,
                "qualified_name": s.qualified_name,
                "kind": s.kind,
                "line_start": s.line_start,
                "line_end": s.line_end,
                "scope": s.scope,
                "parent_id": s.parent_id,
                "doc": s.doc,
                "decorators": s.decorators,
                "metadata": s.metadata,
            }
            for s in self.symbols
        ],
        "errors": self.errors,
    }
    return json.dumps(data, indent=2)

TypeInferencer

Infer and extract type information from Python code.

Source code in py/cogant/static/types.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
class TypeInferencer:
    """Infer and extract type information from Python code."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize type inferencer.

        Args:
            repo_root: Root path of repository.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()
        self.symbol_extractor = SymbolExtractor(repo_root)

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def infer_types_from_file(self, file_path: Path) -> list[TypeInfo]:
        """Infer types for all symbols in a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of TypeInfo for symbols with inferred types.
        """
        try:
            with open(file_path, encoding="utf-8") as f:
                source = f.read()
        except OSError as e:
            logger.debug(f"Failed to read {file_path}: {e}")
            return []

        return self.infer_types_from_source(source, file_path)

    def infer_types_from_source(self, source: str, file_path: Path) -> list[TypeInfo]:
        """Infer types from Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of TypeInfo for symbols with inferred types.
        """
        try:
            tree = ast.parse(source)
        except SyntaxError as e:
            logger.debug(f"Syntax error in type inference for {file_path}: {e}")
            return []
        except ValueError as e:
            logger.debug(f"Parse error in type inference for {file_path}: {e}")
            return []

        try:
            symbol_table = self.symbol_extractor.extract_from_source(source, file_path)
        except (SyntaxError, ValueError) as e:
            logger.debug(f"Symbol extraction failed for {file_path}: {e}")
            symbol_table = None

        type_infos: list[TypeInfo] = []

        # Walk each top-level definition.
        for node in tree.body:
            if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
                type_infos.extend(self._infer_from_function(node, scope="module"))
            elif isinstance(node, ast.ClassDef):
                type_infos.extend(self._infer_from_class(node))
            elif isinstance(node, ast.Assign):
                info = self._infer_from_assign(node, scope="module")
                type_infos.extend(info)
            elif isinstance(node, ast.AnnAssign):
                ann_info = self._infer_from_annassign(node, scope="module")
                if ann_info is not None:
                    type_infos.append(ann_info)

        # Back-fill symbol_ids from the symbol table when possible.
        if symbol_table is not None:
            self._resolve_symbol_ids(type_infos, symbol_table)

        return type_infos

    # ------------------------------------------------------------------
    # AST walkers
    # ------------------------------------------------------------------

    def _infer_from_function(
        self,
        node: ast.FunctionDef | ast.AsyncFunctionDef,
        scope: str,
    ) -> list[TypeInfo]:
        """Return TypeInfos for a function/method: return type and params."""
        results: list[TypeInfo] = []

        qualified = node.name if scope == "module" else f"{scope}.{node.name}"

        # Return annotation
        return_annotation = self._annotation_to_str(node.returns) if node.returns else None
        inferred_return = return_annotation
        confidence = 1.0 if return_annotation else 0.0

        if inferred_return is None:
            fallback = self._infer_return_from_body(node)
            if fallback:
                inferred_return = fallback
                confidence = 0.6

        if inferred_return is not None:
            results.append(
                TypeInfo(
                    symbol_id="",
                    symbol_name=node.name,
                    symbol_kind="method" if scope != "module" else "function",
                    inferred_type=inferred_return,
                    annotation=return_annotation,
                    confidence=confidence,
                    metadata={
                        "is_async": isinstance(node, ast.AsyncFunctionDef),
                        "qualified_name": qualified,
                        "scope": scope,
                        "role": "return",
                    },
                )
            )

        # Parameter annotations
        all_args: list[ast.arg] = []
        all_args.extend(node.args.args)
        all_args.extend(getattr(node.args, "kwonlyargs", []))
        all_args.extend(getattr(node.args, "posonlyargs", []))
        if node.args.vararg is not None:
            all_args.append(node.args.vararg)
        if node.args.kwarg is not None:
            all_args.append(node.args.kwarg)

        for arg in all_args:
            if arg.annotation is None:
                continue
            ann_str = self._annotation_to_str(arg.annotation)
            results.append(
                TypeInfo(
                    symbol_id="",
                    symbol_name=arg.arg,
                    symbol_kind="parameter",
                    inferred_type=ann_str,
                    annotation=ann_str,
                    confidence=1.0,
                    metadata={
                        "parent": qualified,
                        "scope": qualified,
                        "role": "parameter",
                    },
                )
            )

        return results

    def _infer_from_class(self, node: ast.ClassDef) -> list[TypeInfo]:
        """Return TypeInfos for a class body and all its methods."""
        results: list[TypeInfo] = []

        # Class-level annotated attributes (``x: int = 0``)
        for item in node.body:
            if isinstance(item, ast.AnnAssign):
                info = self._infer_from_annassign(item, scope=node.name)
                if info is not None:
                    info.symbol_kind = "attribute"
                    info.metadata["class"] = node.name
                    results.append(info)
            elif isinstance(item, ast.Assign):
                results.extend(self._infer_from_assign(item, scope=node.name, kind="attribute"))

        # Method return types and parameters
        for item in node.body:
            if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
                results.extend(self._infer_from_function(item, scope=node.name))
                if item.name == "__init__":
                    results.extend(self._infer_init_attributes(item, node.name))

        return results

    def _infer_init_attributes(
        self,
        init: ast.FunctionDef | ast.AsyncFunctionDef,
        class_name: str,
    ) -> list[TypeInfo]:
        """Detect ``self.x = ...`` assignments in ``__init__``."""
        results: list[TypeInfo] = []
        for stmt in ast.walk(init):
            if isinstance(stmt, ast.Assign):
                for target in stmt.targets:
                    if (
                        isinstance(target, ast.Attribute)
                        and isinstance(target.value, ast.Name)
                        and target.value.id == "self"
                    ):
                        inferred = self._infer_literal_type(stmt.value)
                        if inferred is not None:
                            results.append(
                                TypeInfo(
                                    symbol_id="",
                                    symbol_name=target.attr,
                                    symbol_kind="attribute",
                                    inferred_type=inferred,
                                    annotation=None,
                                    confidence=0.7,
                                    metadata={
                                        "class": class_name,
                                        "scope": f"{class_name}.__init__",
                                        "source": "self-assignment",
                                    },
                                )
                            )
            elif isinstance(stmt, ast.AnnAssign):
                target = stmt.target
                if (
                    isinstance(target, ast.Attribute)
                    and isinstance(target.value, ast.Name)
                    and target.value.id == "self"
                ):
                    ann = self._annotation_to_str(stmt.annotation)
                    results.append(
                        TypeInfo(
                            symbol_id="",
                            symbol_name=target.attr,
                            symbol_kind="attribute",
                            inferred_type=ann,
                            annotation=ann,
                            confidence=1.0,
                            metadata={
                                "class": class_name,
                                "scope": f"{class_name}.__init__",
                                "source": "self-annotation",
                            },
                        )
                    )
        return results

    def _infer_from_assign(
        self,
        node: ast.Assign,
        scope: str,
        kind: str = "variable",
    ) -> list[TypeInfo]:
        """Handle plain ``x = value`` assignments outside of __init__."""
        results: list[TypeInfo] = []
        inferred = self._infer_literal_type(node.value)
        if inferred is None:
            return results
        for target in node.targets:
            if isinstance(target, ast.Name):
                results.append(
                    TypeInfo(
                        symbol_id="",
                        symbol_name=target.id,
                        symbol_kind=kind,
                        inferred_type=inferred,
                        annotation=None,
                        confidence=0.7,
                        metadata={
                            "scope": scope,
                            "value": self._safe_unparse(node.value),
                        },
                    )
                )
        return results

    def _infer_from_annassign(self, node: ast.AnnAssign, scope: str) -> TypeInfo | None:
        """Handle ``x: int`` or ``x: int = 5`` at module or class scope."""
        if not isinstance(node.target, ast.Name):
            return None
        ann = self._annotation_to_str(node.annotation)
        return TypeInfo(
            symbol_id="",
            symbol_name=node.target.id,
            symbol_kind="variable",
            inferred_type=ann,
            annotation=ann,
            confidence=1.0,
            metadata={
                "scope": scope,
                "has_value": node.value is not None,
                "value": self._safe_unparse(node.value) if node.value else None,
            },
        )

    # ------------------------------------------------------------------
    # Utilities
    # ------------------------------------------------------------------

    @staticmethod
    def _annotation_to_str(node: ast.AST | None) -> str | None:
        """Convert an annotation AST node to a display string."""
        if node is None:
            return None
        try:
            return ast.unparse(node)
        except (AttributeError, ValueError):
            if isinstance(node, ast.Name):
                return node.id
            if isinstance(node, ast.Constant):
                return repr(node.value)
            return type(node).__name__

    @staticmethod
    def _safe_unparse(node: ast.AST | None) -> str | None:
        """Best-effort :func:`ast.unparse`."""
        if node is None:
            return None
        try:
            return ast.unparse(node)
        except (AttributeError, ValueError):
            return None

    def _infer_return_from_body(self, func: ast.FunctionDef | ast.AsyncFunctionDef) -> str | None:
        """Very simple return-type heuristic."""
        if any(isinstance(dec, ast.Name) and dec.id == "property" for dec in func.decorator_list):
            return "Any"
        # Detect yield → Iterator
        for sub in ast.walk(func):
            if isinstance(sub, ast.Yield | ast.YieldFrom):
                return "Iterator"
        return None

    def _infer_literal_type(self, node: ast.AST | None) -> str | None:
        """Infer type from an AST literal expression."""
        if node is None:
            return None
        if isinstance(node, ast.Constant):
            if node.value is None:
                return "None"
            if isinstance(node.value, bool):
                return "bool"
            if isinstance(node.value, int):
                return "int"
            if isinstance(node.value, float):
                return "float"
            if isinstance(node.value, str):
                return "str"
            if isinstance(node.value, bytes):
                return "bytes"
            return type(node.value).__name__
        if isinstance(node, ast.List):
            return "list"
        if isinstance(node, ast.Tuple):
            return "tuple"
        if isinstance(node, ast.Set):
            return "set"
        if isinstance(node, ast.Dict):
            return "dict"
        if isinstance(node, ast.Call):
            callee = self._call_name(node.func)
            if callee in {
                "list",
                "dict",
                "set",
                "tuple",
                "str",
                "int",
                "float",
                "bool",
                "bytes",
                "frozenset",
            }:
                return callee
        return None

    @staticmethod
    def _call_name(node: ast.AST) -> str | None:
        """Return the name of a call callee if simple."""
        if isinstance(node, ast.Name):
            return node.id
        if isinstance(node, ast.Attribute):
            return node.attr
        return None

    def _resolve_symbol_ids(self, infos: list[TypeInfo], symbol_table: Any) -> None:
        """Populate ``symbol_id`` from the symbol table where possible."""
        by_name: dict[str, str] = {}
        for sym in symbol_table.symbols:
            by_name.setdefault(sym.name, sym.id)
        for info in infos:
            if not info.symbol_id and info.symbol_name in by_name:
                info.symbol_id = by_name[info.symbol_name]

__init__(repo_root=None)

Initialize type inferencer.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository.

None
Source code in py/cogant/static/types.py
59
60
61
62
63
64
65
66
67
def __init__(self, repo_root: Path | None = None):
    """Initialize type inferencer.

    Args:
        repo_root: Root path of repository.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()
    self.symbol_extractor = SymbolExtractor(repo_root)

infer_types_from_file(file_path)

Infer types for all symbols in a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[TypeInfo]

List of TypeInfo for symbols with inferred types.

Source code in py/cogant/static/types.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def infer_types_from_file(self, file_path: Path) -> list[TypeInfo]:
    """Infer types for all symbols in a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of TypeInfo for symbols with inferred types.
    """
    try:
        with open(file_path, encoding="utf-8") as f:
            source = f.read()
    except OSError as e:
        logger.debug(f"Failed to read {file_path}: {e}")
        return []

    return self.infer_types_from_source(source, file_path)

infer_types_from_source(source, file_path)

Infer types from Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[TypeInfo]

List of TypeInfo for symbols with inferred types.

Source code in py/cogant/static/types.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def infer_types_from_source(self, source: str, file_path: Path) -> list[TypeInfo]:
    """Infer types from Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of TypeInfo for symbols with inferred types.
    """
    try:
        tree = ast.parse(source)
    except SyntaxError as e:
        logger.debug(f"Syntax error in type inference for {file_path}: {e}")
        return []
    except ValueError as e:
        logger.debug(f"Parse error in type inference for {file_path}: {e}")
        return []

    try:
        symbol_table = self.symbol_extractor.extract_from_source(source, file_path)
    except (SyntaxError, ValueError) as e:
        logger.debug(f"Symbol extraction failed for {file_path}: {e}")
        symbol_table = None

    type_infos: list[TypeInfo] = []

    # Walk each top-level definition.
    for node in tree.body:
        if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
            type_infos.extend(self._infer_from_function(node, scope="module"))
        elif isinstance(node, ast.ClassDef):
            type_infos.extend(self._infer_from_class(node))
        elif isinstance(node, ast.Assign):
            info = self._infer_from_assign(node, scope="module")
            type_infos.extend(info)
        elif isinstance(node, ast.AnnAssign):
            ann_info = self._infer_from_annassign(node, scope="module")
            if ann_info is not None:
                type_infos.append(ann_info)

    # Back-fill symbol_ids from the symbol table when possible.
    if symbol_table is not None:
        self._resolve_symbol_ids(type_infos, symbol_table)

    return type_infos

TypeInfo dataclass

Type information for a symbol.

Source code in py/cogant/static/types.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass
class TypeInfo:
    """Type information for a symbol."""

    symbol_id: str
    """Symbol ID."""

    symbol_name: str
    """Symbol name."""

    symbol_kind: str
    """Symbol kind (function, variable, parameter, attribute)."""

    inferred_type: str | None = None
    """Inferred type."""

    annotation: str | None = None
    """Explicit type annotation."""

    is_mutable: bool = True
    """Whether the symbol is mutable."""

    confidence: float = 0.0
    """Confidence score (0.0 to 1.0)."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional type metadata."""

annotation = None class-attribute instance-attribute

Explicit type annotation.

confidence = 0.0 class-attribute instance-attribute

Confidence score (0.0 to 1.0).

inferred_type = None class-attribute instance-attribute

Inferred type.

is_mutable = True class-attribute instance-attribute

Whether the symbol is mutable.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional type metadata.

symbol_id instance-attribute

Symbol ID.

symbol_kind instance-attribute

Symbol kind (function, variable, parameter, attribute).

symbol_name instance-attribute

Symbol name.

Parser

cogant.static.parser

Python AST parsing for extracting code structure.

AssignmentDef dataclass

Variable assignment from AST.

Source code in py/cogant/static/parser.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass
class AssignmentDef:
    """Variable assignment from AST."""

    target_name: str
    """Variable name being assigned."""

    line_num: int
    """Line number of assignment."""

    annotation: str | None = None
    """Type annotation if present."""

    value: str | None = None
    """String representation of assigned value."""

    parent_scope: str | None = None
    """Scope containing assignment (module or function)."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

annotation = None class-attribute instance-attribute

Type annotation if present.

line_num instance-attribute

Line number of assignment.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

parent_scope = None class-attribute instance-attribute

Scope containing assignment (module or function).

target_name instance-attribute

Variable name being assigned.

value = None class-attribute instance-attribute

String representation of assigned value.

ClassDef dataclass

Class definition from AST.

Source code in py/cogant/static/parser.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@dataclass
class ClassDef:
    """Class definition from AST."""

    name: str
    """Class name."""

    line_start: int
    """Starting line number."""

    line_end: int
    """Ending line number."""

    bases: list[str] = field(default_factory=list)
    """Base class names."""

    decorators: list[str] = field(default_factory=list)
    """List of decorator names."""

    docstring: str | None = None
    """Class docstring."""

    methods: list[FunctionDef] = field(default_factory=list)
    """Methods defined in class."""

    attributes: list[str] = field(default_factory=list)
    """Class attributes."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

attributes = field(default_factory=list) class-attribute instance-attribute

Class attributes.

bases = field(default_factory=list) class-attribute instance-attribute

Base class names.

decorators = field(default_factory=list) class-attribute instance-attribute

List of decorator names.

docstring = None class-attribute instance-attribute

Class docstring.

line_end instance-attribute

Ending line number.

line_start instance-attribute

Starting line number.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

methods = field(default_factory=list) class-attribute instance-attribute

Methods defined in class.

name instance-attribute

Class name.

FunctionDef dataclass

Function definition from AST.

Source code in py/cogant/static/parser.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass
class FunctionDef:
    """Function definition from AST."""

    name: str
    """Function name."""

    line_start: int
    """Starting line number."""

    line_end: int
    """Ending line number."""

    decorators: list[str] = field(default_factory=list)
    """List of decorator names."""

    args: list[str] = field(default_factory=list)
    """Parameter names."""

    return_annotation: str | None = None
    """Return type annotation if present."""

    docstring: str | None = None
    """Function docstring."""

    parent: str | None = None
    """Parent class name if method."""

    is_async: bool = False
    """Whether function is async."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

args = field(default_factory=list) class-attribute instance-attribute

Parameter names.

decorators = field(default_factory=list) class-attribute instance-attribute

List of decorator names.

docstring = None class-attribute instance-attribute

Function docstring.

is_async = False class-attribute instance-attribute

Whether function is async.

line_end instance-attribute

Ending line number.

line_start instance-attribute

Starting line number.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

name instance-attribute

Function name.

parent = None class-attribute instance-attribute

Parent class name if method.

return_annotation = None class-attribute instance-attribute

Return type annotation if present.

ImportDef dataclass

Import statement from AST.

Source code in py/cogant/static/parser.py
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@dataclass
class ImportDef:
    """Import statement from AST."""

    module_name: str
    """Module being imported."""

    is_relative: bool
    """Whether import is relative."""

    names: list[str] = field(default_factory=list)
    """Specific names imported (for 'from X import Y')."""

    line_num: int = 0
    """Line number of import."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

is_relative instance-attribute

Whether import is relative.

line_num = 0 class-attribute instance-attribute

Line number of import.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

module_name instance-attribute

Module being imported.

names = field(default_factory=list) class-attribute instance-attribute

Specific names imported (for 'from X import Y').

PythonASTParser

Parse Python source files and extract AST information.

Source code in py/cogant/static/parser.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
class PythonASTParser:
    """Parse Python source files and extract AST information."""

    def parse_file(self, file_path: Path) -> PythonModule:
        """Parse a Python source file.

        Args:
            file_path: Path to Python file.

        Returns:
            PythonModule with extracted AST information.
        """
        module = PythonModule(file_path=file_path)

        try:
            with open(file_path, encoding="utf-8") as f:
                source = f.read()
        except Exception as e:
            module.errors.append(f"Failed to read file: {e}")
            return module

        try:
            tree = ast.parse(source, filename=str(file_path))
        except SyntaxError as e:
            module.errors.append(f"Syntax error: {e}")
            return module
        except Exception as e:
            module.errors.append(f"Parse error: {e}")
            return module

        # Extract module docstring (guard against empty files like bare __init__.py)
        if (
            tree.body
            and isinstance(tree.body[0], ast.Expr)
            and isinstance(tree.body[0].value, ast.Constant)
            and isinstance(tree.body[0].value.value, str)
        ):
            module.docstring = tree.body[0].value.value

        # Visit all nodes
        for node in tree.body:
            if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
                func = self._extract_function(node)
                if func:
                    module.functions.append(func)
            elif isinstance(node, ast.ClassDef):
                cls = self._extract_class(node)
                if cls:
                    module.classes.append(cls)
            elif isinstance(node, ast.Import | ast.ImportFrom):
                imports = self._extract_imports(node)
                module.imports.extend(imports)
            elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
                assign = self._extract_assignment(node)
                if assign:
                    module.assignments.append(assign)

        return module

    def parse_string(self, source: str, file_path: Path | None = None) -> PythonModule:
        """Parse Python source from string.

        Args:
            source: Python source code as string.
            file_path: Optional file path for reference.

        Returns:
            PythonModule with extracted AST information.
        """
        if file_path is None:
            file_path = Path("<string>")

        module = PythonModule(file_path=file_path)

        try:
            tree = ast.parse(source, filename=str(file_path))
        except SyntaxError as e:
            module.errors.append(f"Syntax error: {e}")
            return module
        except Exception as e:
            module.errors.append(f"Parse error: {e}")
            return module

        # Extract module docstring
        if (
            tree.body
            and isinstance(tree.body[0], ast.Expr)
            and isinstance(tree.body[0].value, ast.Constant)
            and isinstance(tree.body[0].value.value, str)
        ):
            module.docstring = tree.body[0].value.value

        # Visit all nodes
        for node in tree.body:
            if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
                func = self._extract_function(node)
                if func:
                    module.functions.append(func)
            elif isinstance(node, ast.ClassDef):
                cls = self._extract_class(node)
                if cls:
                    module.classes.append(cls)
            elif isinstance(node, ast.Import | ast.ImportFrom):
                imports = self._extract_imports(node)
                module.imports.extend(imports)
            elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
                assign = self._extract_assignment(node)
                if assign:
                    module.assignments.append(assign)

        return module

    def _extract_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> FunctionDef | None:
        """Extract function definition from AST node.

        Args:
            node: AST FunctionDef or AsyncFunctionDef node.

        Returns:
            FunctionDef or None if extraction failed.
        """
        try:
            # Extract decorators
            decorators = [self._ast_to_str(dec) for dec in node.decorator_list]

            # Extract argument names
            args = []
            for arg in node.args.args:
                args.append(arg.arg)

            # Extract return annotation
            return_annotation = None
            if node.returns:
                return_annotation = self._ast_to_str(node.returns)

            # Extract docstring
            docstring = None
            if (
                node.body
                and isinstance(node.body[0], ast.Expr)
                and isinstance(node.body[0].value, ast.Constant)
                and isinstance(node.body[0].value.value, str)
            ):
                docstring = node.body[0].value.value

            return FunctionDef(
                name=node.name,
                line_start=node.lineno,
                line_end=node.end_lineno or node.lineno,
                decorators=decorators,
                args=args,
                return_annotation=return_annotation,
                docstring=docstring,
                is_async=isinstance(node, ast.AsyncFunctionDef),
            )

        except Exception as e:
            logger.debug(f"Failed to extract function {getattr(node, 'name', '?')}: {e}")
            return None

    def _extract_class(self, node: ast.ClassDef) -> ClassDef | None:
        """Extract class definition from AST node.

        Args:
            node: AST ClassDef node.

        Returns:
            ClassDef or None if extraction failed.
        """
        try:
            # Extract base class names
            bases = [self._ast_to_str(base) for base in node.bases]

            # Extract decorators
            decorators = [self._ast_to_str(dec) for dec in node.decorator_list]

            # Extract docstring
            docstring = None
            if (
                node.body
                and isinstance(node.body[0], ast.Expr)
                and isinstance(node.body[0].value, ast.Constant)
                and isinstance(node.body[0].value.value, str)
            ):
                docstring = node.body[0].value.value

            # Extract methods
            methods = []
            for item in node.body:
                if isinstance(item, ast.FunctionDef) or isinstance(item, ast.AsyncFunctionDef):
                    method = self._extract_function(item)
                    if method:
                        method.parent = node.name
                        methods.append(method)

            # Extract class attributes
            attributes = []
            for item in node.body:
                if isinstance(item, ast.AnnAssign) and isinstance(item.target, ast.Name):
                    attributes.append(item.target.id)

            return ClassDef(
                name=node.name,
                line_start=node.lineno,
                line_end=node.end_lineno or node.lineno,
                bases=bases,
                decorators=decorators,
                docstring=docstring,
                methods=methods,
                attributes=attributes,
            )

        except Exception as e:
            logger.debug(f"Failed to extract class {getattr(node, 'name', '?')}: {e}")
            return None

    def _extract_imports(self, node: ast.Import | ast.ImportFrom) -> list[ImportDef]:
        """Extract import statements from AST node.

        Args:
            node: AST Import or ImportFrom node.

        Returns:
            List of ImportDef.
        """
        imports = []

        try:
            if isinstance(node, ast.Import):
                for alias in node.names:
                    imports.append(
                        ImportDef(
                            module_name=alias.name,
                            is_relative=False,
                            line_num=node.lineno,
                        )
                    )
            elif isinstance(node, ast.ImportFrom):
                module_name = node.module or ""
                is_relative = node.level > 0

                for alias in node.names:
                    imports.append(
                        ImportDef(
                            module_name=module_name,
                            is_relative=is_relative,
                            names=[alias.name],
                            line_num=node.lineno,
                            # Leading-dot count: ``from ..x`` is level 2.
                            metadata={"level": node.level},
                        )
                    )

        except Exception as e:
            logger.debug(f"Failed to extract imports: {e}")

        return imports

    def _extract_assignment(self, node: ast.Assign | ast.AnnAssign) -> AssignmentDef | None:
        """Extract assignment from AST node.

        Args:
            node: AST Assign or AnnAssign node.

        Returns:
            AssignmentDef or None if extraction failed.
        """
        try:
            if isinstance(node, ast.Assign):
                # Handle multiple targets (e.g., a = b = c)
                if node.targets and isinstance(node.targets[0], ast.Name):
                    target_name = node.targets[0].id
                    value_str = self._ast_to_str(node.value) if node.value else None

                    return AssignmentDef(
                        target_name=target_name,
                        line_num=node.lineno,
                        value=value_str,
                    )

            elif isinstance(node, ast.AnnAssign):
                if isinstance(node.target, ast.Name):
                    annotation_str = self._ast_to_str(node.annotation) if node.annotation else None
                    value_str = self._ast_to_str(node.value) if node.value else None

                    return AssignmentDef(
                        target_name=node.target.id,
                        line_num=node.lineno,
                        annotation=annotation_str,
                        value=value_str,
                    )

        except Exception as e:
            logger.debug(f"Failed to extract assignment: {e}")

        return None

    @staticmethod
    def _ast_to_str(node: ast.AST) -> str:
        """Convert AST node to string representation.

        Args:
            node: AST node.

        Returns:
            String representation of node.
        """
        try:
            return ast.unparse(node)
        except Exception:
            # Fallback for nodes that can't be unparsed
            if isinstance(node, ast.Name):
                return node.id
            elif isinstance(node, ast.Constant):
                return repr(node.value)
            elif isinstance(node, ast.Attribute):
                return f"{PythonASTParser._ast_to_str(node.value)}.{node.attr}"
            else:
                return type(node).__name__

parse_file(file_path)

Parse a Python source file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
PythonModule

PythonModule with extracted AST information.

Source code in py/cogant/static/parser.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
def parse_file(self, file_path: Path) -> PythonModule:
    """Parse a Python source file.

    Args:
        file_path: Path to Python file.

    Returns:
        PythonModule with extracted AST information.
    """
    module = PythonModule(file_path=file_path)

    try:
        with open(file_path, encoding="utf-8") as f:
            source = f.read()
    except Exception as e:
        module.errors.append(f"Failed to read file: {e}")
        return module

    try:
        tree = ast.parse(source, filename=str(file_path))
    except SyntaxError as e:
        module.errors.append(f"Syntax error: {e}")
        return module
    except Exception as e:
        module.errors.append(f"Parse error: {e}")
        return module

    # Extract module docstring (guard against empty files like bare __init__.py)
    if (
        tree.body
        and isinstance(tree.body[0], ast.Expr)
        and isinstance(tree.body[0].value, ast.Constant)
        and isinstance(tree.body[0].value.value, str)
    ):
        module.docstring = tree.body[0].value.value

    # Visit all nodes
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
            func = self._extract_function(node)
            if func:
                module.functions.append(func)
        elif isinstance(node, ast.ClassDef):
            cls = self._extract_class(node)
            if cls:
                module.classes.append(cls)
        elif isinstance(node, ast.Import | ast.ImportFrom):
            imports = self._extract_imports(node)
            module.imports.extend(imports)
        elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
            assign = self._extract_assignment(node)
            if assign:
                module.assignments.append(assign)

    return module

parse_string(source, file_path=None)

Parse Python source from string.

Parameters:

Name Type Description Default
source str

Python source code as string.

required
file_path Path | None

Optional file path for reference.

None

Returns:

Type Description
PythonModule

PythonModule with extracted AST information.

Source code in py/cogant/static/parser.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def parse_string(self, source: str, file_path: Path | None = None) -> PythonModule:
    """Parse Python source from string.

    Args:
        source: Python source code as string.
        file_path: Optional file path for reference.

    Returns:
        PythonModule with extracted AST information.
    """
    if file_path is None:
        file_path = Path("<string>")

    module = PythonModule(file_path=file_path)

    try:
        tree = ast.parse(source, filename=str(file_path))
    except SyntaxError as e:
        module.errors.append(f"Syntax error: {e}")
        return module
    except Exception as e:
        module.errors.append(f"Parse error: {e}")
        return module

    # Extract module docstring
    if (
        tree.body
        and isinstance(tree.body[0], ast.Expr)
        and isinstance(tree.body[0].value, ast.Constant)
        and isinstance(tree.body[0].value.value, str)
    ):
        module.docstring = tree.body[0].value.value

    # Visit all nodes
    for node in tree.body:
        if isinstance(node, ast.FunctionDef) or isinstance(node, ast.AsyncFunctionDef):
            func = self._extract_function(node)
            if func:
                module.functions.append(func)
        elif isinstance(node, ast.ClassDef):
            cls = self._extract_class(node)
            if cls:
                module.classes.append(cls)
        elif isinstance(node, ast.Import | ast.ImportFrom):
            imports = self._extract_imports(node)
            module.imports.extend(imports)
        elif isinstance(node, ast.Assign) or isinstance(node, ast.AnnAssign):
            assign = self._extract_assignment(node)
            if assign:
                module.assignments.append(assign)

    return module

PythonModule dataclass

Complete parsed Python module.

Source code in py/cogant/static/parser.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
@dataclass
class PythonModule:
    """Complete parsed Python module."""

    file_path: Path
    """Source file path."""

    docstring: str | None = None
    """Module docstring."""

    functions: list[FunctionDef] = field(default_factory=list)
    """Module-level functions."""

    classes: list[ClassDef] = field(default_factory=list)
    """Module-level classes."""

    imports: list[ImportDef] = field(default_factory=list)
    """Import statements."""

    assignments: list[AssignmentDef] = field(default_factory=list)
    """Module-level assignments."""

    errors: list[str] = field(default_factory=list)
    """Parse errors encountered."""

assignments = field(default_factory=list) class-attribute instance-attribute

Module-level assignments.

classes = field(default_factory=list) class-attribute instance-attribute

Module-level classes.

docstring = None class-attribute instance-attribute

Module docstring.

errors = field(default_factory=list) class-attribute instance-attribute

Parse errors encountered.

file_path instance-attribute

Source file path.

functions = field(default_factory=list) class-attribute instance-attribute

Module-level functions.

imports = field(default_factory=list) class-attribute instance-attribute

Import statements.

Symbols

cogant.static.symbols

Symbol extraction: build symbol table with qualified names, types, and scopes.

SymbolExtractor

Extract symbols from parsed Python modules.

Source code in py/cogant/static/symbols.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
class SymbolExtractor:
    """Extract symbols from parsed Python modules."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize symbol extractor.

        Args:
            repo_root: Optional repository root for qualified name generation.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()

    def extract_from_file(self, file_path: Path) -> SymbolTable:
        """Extract symbols from a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            SymbolTable with extracted symbols.
        """
        # Parse file
        module = self.parser.parse_file(file_path)

        # Extract symbols
        return self._extract_from_module(module)

    def extract_from_source(self, source: str, file_path: Path) -> SymbolTable:
        """Extract symbols from Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference and qualified names.

        Returns:
            SymbolTable with extracted symbols.
        """
        # Parse source
        module = self.parser.parse_string(source, file_path)

        # Extract symbols
        return self._extract_from_module(module)

    def _extract_from_module(self, module: PythonModule) -> SymbolTable:
        """Extract symbols from parsed module.

        Args:
            module: Parsed Python module.

        Returns:
            SymbolTable with extracted symbols.
        """
        table = SymbolTable(file_path=module.file_path, errors=module.errors)

        # Get module qualified name
        module_qname = self._get_module_qname(module.file_path)

        # Extract module-level functions
        for func in module.functions:
            symbol = SymbolInfo(
                id=self._generate_symbol_id(module.file_path, func.name),
                name=func.name,
                qualified_name=f"{module_qname}.{func.name}",
                kind="function",
                file_path=module.file_path,
                line_start=func.line_start,
                line_end=func.line_end,
                scope="module",
                doc=func.docstring,
                decorators=func.decorators,
                metadata={
                    "is_async": func.is_async,
                    "parameters": func.args,
                    "return_annotation": func.return_annotation,
                },
            )
            table.symbols.append(symbol)

        # Extract classes and their methods
        for cls in module.classes:
            class_id = self._generate_symbol_id(module.file_path, cls.name)
            class_symbol = SymbolInfo(
                id=class_id,
                name=cls.name,
                qualified_name=f"{module_qname}.{cls.name}",
                kind="class",
                file_path=module.file_path,
                line_start=cls.line_start,
                line_end=cls.line_end,
                scope="module",
                doc=cls.docstring,
                decorators=cls.decorators,
                metadata={
                    "bases": cls.bases,
                    "attributes": cls.attributes,
                },
            )
            table.symbols.append(class_symbol)

            # Extract methods
            for method in cls.methods:
                method_id = self._generate_symbol_id(module.file_path, f"{cls.name}.{method.name}")
                method_symbol = SymbolInfo(
                    id=method_id,
                    name=method.name,
                    qualified_name=f"{module_qname}.{cls.name}.{method.name}",
                    kind="method",
                    file_path=module.file_path,
                    line_start=method.line_start,
                    line_end=method.line_end,
                    scope=cls.name,
                    parent_id=class_id,
                    doc=method.docstring,
                    decorators=method.decorators,
                    metadata={
                        "is_async": method.is_async,
                        "parameters": method.args,
                        "return_annotation": method.return_annotation,
                    },
                )
                table.symbols.append(method_symbol)

        # Extract module-level variables
        for assign in module.assignments:
            symbol = SymbolInfo(
                id=self._generate_symbol_id(module.file_path, assign.target_name),
                name=assign.target_name,
                qualified_name=f"{module_qname}.{assign.target_name}",
                kind="variable",
                file_path=module.file_path,
                line_start=assign.line_num,
                line_end=assign.line_num,
                scope="module",
                metadata={
                    "annotation": assign.annotation,
                    "value": assign.value,
                },
            )
            table.symbols.append(symbol)

        return table

    def _get_module_qname(self, file_path: Path) -> str:
        """Generate qualified name for a module.

        Args:
            file_path: Path to Python file.

        Returns:
            Qualified module name.
        """
        try:
            relative = file_path.relative_to(self.repo_root)
        except ValueError:
            # If file is not relative to repo root, use file name
            relative = file_path

        # Convert path to module name
        parts = list(relative.parts[:-1])  # Exclude filename
        parts.append(relative.stem)  # Add module name (without .py)

        # Filter out common prefixes
        parts = [p for p in parts if p not in {"src", "lib", "cogant"}]

        return ".".join(parts) if parts else relative.stem

    @staticmethod
    def _generate_symbol_id(file_path: Path, symbol_name: str) -> str:
        """Generate stable symbol ID.

        Args:
            file_path: Source file path.
            symbol_name: Symbol name or qualified name.

        Returns:
            Stable symbol ID (SHA256 hash).
        """
        # Create deterministic ID from file path and symbol name
        content = f"{file_path.resolve()}#{symbol_name}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

__init__(repo_root=None)

Initialize symbol extractor.

Parameters:

Name Type Description Default
repo_root Path | None

Optional repository root for qualified name generation.

None
Source code in py/cogant/static/symbols.py
125
126
127
128
129
130
131
132
def __init__(self, repo_root: Path | None = None):
    """Initialize symbol extractor.

    Args:
        repo_root: Optional repository root for qualified name generation.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()

extract_from_file(file_path)

Extract symbols from a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
SymbolTable

SymbolTable with extracted symbols.

Source code in py/cogant/static/symbols.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def extract_from_file(self, file_path: Path) -> SymbolTable:
    """Extract symbols from a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        SymbolTable with extracted symbols.
    """
    # Parse file
    module = self.parser.parse_file(file_path)

    # Extract symbols
    return self._extract_from_module(module)

extract_from_source(source, file_path)

Extract symbols from Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference and qualified names.

required

Returns:

Type Description
SymbolTable

SymbolTable with extracted symbols.

Source code in py/cogant/static/symbols.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def extract_from_source(self, source: str, file_path: Path) -> SymbolTable:
    """Extract symbols from Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference and qualified names.

    Returns:
        SymbolTable with extracted symbols.
    """
    # Parse source
    module = self.parser.parse_string(source, file_path)

    # Extract symbols
    return self._extract_from_module(module)

SymbolInfo dataclass

Information about a code symbol.

Source code in py/cogant/static/symbols.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@dataclass
class SymbolInfo:
    """Information about a code symbol."""

    id: str
    """Unique stable identifier."""

    name: str
    """Short name (e.g., 'foo')."""

    qualified_name: str
    """Fully qualified name (e.g., 'module.Class.method')."""

    kind: str
    """Symbol kind (function, class, method, variable)."""

    file_path: Path
    """Source file path."""

    line_start: int
    """Starting line number."""

    line_end: int
    """Ending line number."""

    scope: str
    """Scope context (module, class_name, function_name)."""

    parent_id: str | None = None
    """ID of parent symbol if nested."""

    doc: str | None = None
    """Docstring if available."""

    decorators: list[str] = field(default_factory=list)
    """List of decorators."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Language-specific metadata."""

decorators = field(default_factory=list) class-attribute instance-attribute

List of decorators.

doc = None class-attribute instance-attribute

Docstring if available.

file_path instance-attribute

Source file path.

id instance-attribute

Unique stable identifier.

kind instance-attribute

Symbol kind (function, class, method, variable).

line_end instance-attribute

Ending line number.

line_start instance-attribute

Starting line number.

metadata = field(default_factory=dict) class-attribute instance-attribute

Language-specific metadata.

name instance-attribute

Short name (e.g., 'foo').

parent_id = None class-attribute instance-attribute

ID of parent symbol if nested.

qualified_name instance-attribute

Fully qualified name (e.g., 'module.Class.method').

scope instance-attribute

Scope context (module, class_name, function_name).

SymbolTable dataclass

Collection of extracted symbols.

Source code in py/cogant/static/symbols.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass
class SymbolTable:
    """Collection of extracted symbols."""

    file_path: Path
    """Source file path."""

    symbols: list[SymbolInfo] = field(default_factory=list)
    """Extracted symbols."""

    errors: list[str] = field(default_factory=list)
    """Errors encountered during extraction."""

    def get_public_api(self) -> list[SymbolInfo]:
        """Get all public (non-underscore) symbols.

        Returns:
            List of public symbols.
        """
        return [s for s in self.symbols if not s.name.startswith("_")]

    def get_entry_points(self) -> list[SymbolInfo]:
        """Get symbols callable from outside (public functions and public methods).

        Returns:
            List of public functions and methods.
        """
        return [
            s
            for s in self.get_public_api()
            if s.kind in ("function", "method") or (s.kind == "class")
        ]

    def to_json(self) -> str:
        """Serialize symbol table to JSON.

        Returns:
            JSON string representation.
        """
        import json

        data = {
            "file_path": str(self.file_path),
            "symbols": [
                {
                    "id": s.id,
                    "name": s.name,
                    "qualified_name": s.qualified_name,
                    "kind": s.kind,
                    "line_start": s.line_start,
                    "line_end": s.line_end,
                    "scope": s.scope,
                    "parent_id": s.parent_id,
                    "doc": s.doc,
                    "decorators": s.decorators,
                    "metadata": s.metadata,
                }
                for s in self.symbols
            ],
            "errors": self.errors,
        }
        return json.dumps(data, indent=2)

errors = field(default_factory=list) class-attribute instance-attribute

Errors encountered during extraction.

file_path instance-attribute

Source file path.

symbols = field(default_factory=list) class-attribute instance-attribute

Extracted symbols.

get_entry_points()

Get symbols callable from outside (public functions and public methods).

Returns:

Type Description
list[SymbolInfo]

List of public functions and methods.

Source code in py/cogant/static/symbols.py
79
80
81
82
83
84
85
86
87
88
89
def get_entry_points(self) -> list[SymbolInfo]:
    """Get symbols callable from outside (public functions and public methods).

    Returns:
        List of public functions and methods.
    """
    return [
        s
        for s in self.get_public_api()
        if s.kind in ("function", "method") or (s.kind == "class")
    ]

get_public_api()

Get all public (non-underscore) symbols.

Returns:

Type Description
list[SymbolInfo]

List of public symbols.

Source code in py/cogant/static/symbols.py
71
72
73
74
75
76
77
def get_public_api(self) -> list[SymbolInfo]:
    """Get all public (non-underscore) symbols.

    Returns:
        List of public symbols.
    """
    return [s for s in self.symbols if not s.name.startswith("_")]

to_json()

Serialize symbol table to JSON.

Returns:

Type Description
str

JSON string representation.

Source code in py/cogant/static/symbols.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def to_json(self) -> str:
    """Serialize symbol table to JSON.

    Returns:
        JSON string representation.
    """
    import json

    data = {
        "file_path": str(self.file_path),
        "symbols": [
            {
                "id": s.id,
                "name": s.name,
                "qualified_name": s.qualified_name,
                "kind": s.kind,
                "line_start": s.line_start,
                "line_end": s.line_end,
                "scope": s.scope,
                "parent_id": s.parent_id,
                "doc": s.doc,
                "decorators": s.decorators,
                "metadata": s.metadata,
            }
            for s in self.symbols
        ],
        "errors": self.errors,
    }
    return json.dumps(data, indent=2)

Types

cogant.static.types

Type inference: extract type annotations and infer basic types.

This module walks Python source with the raw ast library (rather than only the pre-parsed :class:~cogant.static.parser.PythonModule) so that it can see argument annotations, class attribute annotations, and assignments inside __init__. It produces :class:TypeInfo records suitable for attaching to graph nodes.

The inferencer is intentionally conservative: explicit annotations get confidence 1.0, literal-based heuristics get 0.7, and the simple @property fallback gets 0.6. When no information is available the symbol is skipped rather than being given a guessed type.

TypeInferencer

Infer and extract type information from Python code.

Source code in py/cogant/static/types.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
class TypeInferencer:
    """Infer and extract type information from Python code."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize type inferencer.

        Args:
            repo_root: Root path of repository.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()
        self.symbol_extractor = SymbolExtractor(repo_root)

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    def infer_types_from_file(self, file_path: Path) -> list[TypeInfo]:
        """Infer types for all symbols in a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of TypeInfo for symbols with inferred types.
        """
        try:
            with open(file_path, encoding="utf-8") as f:
                source = f.read()
        except OSError as e:
            logger.debug(f"Failed to read {file_path}: {e}")
            return []

        return self.infer_types_from_source(source, file_path)

    def infer_types_from_source(self, source: str, file_path: Path) -> list[TypeInfo]:
        """Infer types from Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of TypeInfo for symbols with inferred types.
        """
        try:
            tree = ast.parse(source)
        except SyntaxError as e:
            logger.debug(f"Syntax error in type inference for {file_path}: {e}")
            return []
        except ValueError as e:
            logger.debug(f"Parse error in type inference for {file_path}: {e}")
            return []

        try:
            symbol_table = self.symbol_extractor.extract_from_source(source, file_path)
        except (SyntaxError, ValueError) as e:
            logger.debug(f"Symbol extraction failed for {file_path}: {e}")
            symbol_table = None

        type_infos: list[TypeInfo] = []

        # Walk each top-level definition.
        for node in tree.body:
            if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
                type_infos.extend(self._infer_from_function(node, scope="module"))
            elif isinstance(node, ast.ClassDef):
                type_infos.extend(self._infer_from_class(node))
            elif isinstance(node, ast.Assign):
                info = self._infer_from_assign(node, scope="module")
                type_infos.extend(info)
            elif isinstance(node, ast.AnnAssign):
                ann_info = self._infer_from_annassign(node, scope="module")
                if ann_info is not None:
                    type_infos.append(ann_info)

        # Back-fill symbol_ids from the symbol table when possible.
        if symbol_table is not None:
            self._resolve_symbol_ids(type_infos, symbol_table)

        return type_infos

    # ------------------------------------------------------------------
    # AST walkers
    # ------------------------------------------------------------------

    def _infer_from_function(
        self,
        node: ast.FunctionDef | ast.AsyncFunctionDef,
        scope: str,
    ) -> list[TypeInfo]:
        """Return TypeInfos for a function/method: return type and params."""
        results: list[TypeInfo] = []

        qualified = node.name if scope == "module" else f"{scope}.{node.name}"

        # Return annotation
        return_annotation = self._annotation_to_str(node.returns) if node.returns else None
        inferred_return = return_annotation
        confidence = 1.0 if return_annotation else 0.0

        if inferred_return is None:
            fallback = self._infer_return_from_body(node)
            if fallback:
                inferred_return = fallback
                confidence = 0.6

        if inferred_return is not None:
            results.append(
                TypeInfo(
                    symbol_id="",
                    symbol_name=node.name,
                    symbol_kind="method" if scope != "module" else "function",
                    inferred_type=inferred_return,
                    annotation=return_annotation,
                    confidence=confidence,
                    metadata={
                        "is_async": isinstance(node, ast.AsyncFunctionDef),
                        "qualified_name": qualified,
                        "scope": scope,
                        "role": "return",
                    },
                )
            )

        # Parameter annotations
        all_args: list[ast.arg] = []
        all_args.extend(node.args.args)
        all_args.extend(getattr(node.args, "kwonlyargs", []))
        all_args.extend(getattr(node.args, "posonlyargs", []))
        if node.args.vararg is not None:
            all_args.append(node.args.vararg)
        if node.args.kwarg is not None:
            all_args.append(node.args.kwarg)

        for arg in all_args:
            if arg.annotation is None:
                continue
            ann_str = self._annotation_to_str(arg.annotation)
            results.append(
                TypeInfo(
                    symbol_id="",
                    symbol_name=arg.arg,
                    symbol_kind="parameter",
                    inferred_type=ann_str,
                    annotation=ann_str,
                    confidence=1.0,
                    metadata={
                        "parent": qualified,
                        "scope": qualified,
                        "role": "parameter",
                    },
                )
            )

        return results

    def _infer_from_class(self, node: ast.ClassDef) -> list[TypeInfo]:
        """Return TypeInfos for a class body and all its methods."""
        results: list[TypeInfo] = []

        # Class-level annotated attributes (``x: int = 0``)
        for item in node.body:
            if isinstance(item, ast.AnnAssign):
                info = self._infer_from_annassign(item, scope=node.name)
                if info is not None:
                    info.symbol_kind = "attribute"
                    info.metadata["class"] = node.name
                    results.append(info)
            elif isinstance(item, ast.Assign):
                results.extend(self._infer_from_assign(item, scope=node.name, kind="attribute"))

        # Method return types and parameters
        for item in node.body:
            if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
                results.extend(self._infer_from_function(item, scope=node.name))
                if item.name == "__init__":
                    results.extend(self._infer_init_attributes(item, node.name))

        return results

    def _infer_init_attributes(
        self,
        init: ast.FunctionDef | ast.AsyncFunctionDef,
        class_name: str,
    ) -> list[TypeInfo]:
        """Detect ``self.x = ...`` assignments in ``__init__``."""
        results: list[TypeInfo] = []
        for stmt in ast.walk(init):
            if isinstance(stmt, ast.Assign):
                for target in stmt.targets:
                    if (
                        isinstance(target, ast.Attribute)
                        and isinstance(target.value, ast.Name)
                        and target.value.id == "self"
                    ):
                        inferred = self._infer_literal_type(stmt.value)
                        if inferred is not None:
                            results.append(
                                TypeInfo(
                                    symbol_id="",
                                    symbol_name=target.attr,
                                    symbol_kind="attribute",
                                    inferred_type=inferred,
                                    annotation=None,
                                    confidence=0.7,
                                    metadata={
                                        "class": class_name,
                                        "scope": f"{class_name}.__init__",
                                        "source": "self-assignment",
                                    },
                                )
                            )
            elif isinstance(stmt, ast.AnnAssign):
                target = stmt.target
                if (
                    isinstance(target, ast.Attribute)
                    and isinstance(target.value, ast.Name)
                    and target.value.id == "self"
                ):
                    ann = self._annotation_to_str(stmt.annotation)
                    results.append(
                        TypeInfo(
                            symbol_id="",
                            symbol_name=target.attr,
                            symbol_kind="attribute",
                            inferred_type=ann,
                            annotation=ann,
                            confidence=1.0,
                            metadata={
                                "class": class_name,
                                "scope": f"{class_name}.__init__",
                                "source": "self-annotation",
                            },
                        )
                    )
        return results

    def _infer_from_assign(
        self,
        node: ast.Assign,
        scope: str,
        kind: str = "variable",
    ) -> list[TypeInfo]:
        """Handle plain ``x = value`` assignments outside of __init__."""
        results: list[TypeInfo] = []
        inferred = self._infer_literal_type(node.value)
        if inferred is None:
            return results
        for target in node.targets:
            if isinstance(target, ast.Name):
                results.append(
                    TypeInfo(
                        symbol_id="",
                        symbol_name=target.id,
                        symbol_kind=kind,
                        inferred_type=inferred,
                        annotation=None,
                        confidence=0.7,
                        metadata={
                            "scope": scope,
                            "value": self._safe_unparse(node.value),
                        },
                    )
                )
        return results

    def _infer_from_annassign(self, node: ast.AnnAssign, scope: str) -> TypeInfo | None:
        """Handle ``x: int`` or ``x: int = 5`` at module or class scope."""
        if not isinstance(node.target, ast.Name):
            return None
        ann = self._annotation_to_str(node.annotation)
        return TypeInfo(
            symbol_id="",
            symbol_name=node.target.id,
            symbol_kind="variable",
            inferred_type=ann,
            annotation=ann,
            confidence=1.0,
            metadata={
                "scope": scope,
                "has_value": node.value is not None,
                "value": self._safe_unparse(node.value) if node.value else None,
            },
        )

    # ------------------------------------------------------------------
    # Utilities
    # ------------------------------------------------------------------

    @staticmethod
    def _annotation_to_str(node: ast.AST | None) -> str | None:
        """Convert an annotation AST node to a display string."""
        if node is None:
            return None
        try:
            return ast.unparse(node)
        except (AttributeError, ValueError):
            if isinstance(node, ast.Name):
                return node.id
            if isinstance(node, ast.Constant):
                return repr(node.value)
            return type(node).__name__

    @staticmethod
    def _safe_unparse(node: ast.AST | None) -> str | None:
        """Best-effort :func:`ast.unparse`."""
        if node is None:
            return None
        try:
            return ast.unparse(node)
        except (AttributeError, ValueError):
            return None

    def _infer_return_from_body(self, func: ast.FunctionDef | ast.AsyncFunctionDef) -> str | None:
        """Very simple return-type heuristic."""
        if any(isinstance(dec, ast.Name) and dec.id == "property" for dec in func.decorator_list):
            return "Any"
        # Detect yield → Iterator
        for sub in ast.walk(func):
            if isinstance(sub, ast.Yield | ast.YieldFrom):
                return "Iterator"
        return None

    def _infer_literal_type(self, node: ast.AST | None) -> str | None:
        """Infer type from an AST literal expression."""
        if node is None:
            return None
        if isinstance(node, ast.Constant):
            if node.value is None:
                return "None"
            if isinstance(node.value, bool):
                return "bool"
            if isinstance(node.value, int):
                return "int"
            if isinstance(node.value, float):
                return "float"
            if isinstance(node.value, str):
                return "str"
            if isinstance(node.value, bytes):
                return "bytes"
            return type(node.value).__name__
        if isinstance(node, ast.List):
            return "list"
        if isinstance(node, ast.Tuple):
            return "tuple"
        if isinstance(node, ast.Set):
            return "set"
        if isinstance(node, ast.Dict):
            return "dict"
        if isinstance(node, ast.Call):
            callee = self._call_name(node.func)
            if callee in {
                "list",
                "dict",
                "set",
                "tuple",
                "str",
                "int",
                "float",
                "bool",
                "bytes",
                "frozenset",
            }:
                return callee
        return None

    @staticmethod
    def _call_name(node: ast.AST) -> str | None:
        """Return the name of a call callee if simple."""
        if isinstance(node, ast.Name):
            return node.id
        if isinstance(node, ast.Attribute):
            return node.attr
        return None

    def _resolve_symbol_ids(self, infos: list[TypeInfo], symbol_table: Any) -> None:
        """Populate ``symbol_id`` from the symbol table where possible."""
        by_name: dict[str, str] = {}
        for sym in symbol_table.symbols:
            by_name.setdefault(sym.name, sym.id)
        for info in infos:
            if not info.symbol_id and info.symbol_name in by_name:
                info.symbol_id = by_name[info.symbol_name]

__init__(repo_root=None)

Initialize type inferencer.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository.

None
Source code in py/cogant/static/types.py
59
60
61
62
63
64
65
66
67
def __init__(self, repo_root: Path | None = None):
    """Initialize type inferencer.

    Args:
        repo_root: Root path of repository.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()
    self.symbol_extractor = SymbolExtractor(repo_root)

infer_types_from_file(file_path)

Infer types for all symbols in a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[TypeInfo]

List of TypeInfo for symbols with inferred types.

Source code in py/cogant/static/types.py
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def infer_types_from_file(self, file_path: Path) -> list[TypeInfo]:
    """Infer types for all symbols in a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of TypeInfo for symbols with inferred types.
    """
    try:
        with open(file_path, encoding="utf-8") as f:
            source = f.read()
    except OSError as e:
        logger.debug(f"Failed to read {file_path}: {e}")
        return []

    return self.infer_types_from_source(source, file_path)

infer_types_from_source(source, file_path)

Infer types from Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[TypeInfo]

List of TypeInfo for symbols with inferred types.

Source code in py/cogant/static/types.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def infer_types_from_source(self, source: str, file_path: Path) -> list[TypeInfo]:
    """Infer types from Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of TypeInfo for symbols with inferred types.
    """
    try:
        tree = ast.parse(source)
    except SyntaxError as e:
        logger.debug(f"Syntax error in type inference for {file_path}: {e}")
        return []
    except ValueError as e:
        logger.debug(f"Parse error in type inference for {file_path}: {e}")
        return []

    try:
        symbol_table = self.symbol_extractor.extract_from_source(source, file_path)
    except (SyntaxError, ValueError) as e:
        logger.debug(f"Symbol extraction failed for {file_path}: {e}")
        symbol_table = None

    type_infos: list[TypeInfo] = []

    # Walk each top-level definition.
    for node in tree.body:
        if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
            type_infos.extend(self._infer_from_function(node, scope="module"))
        elif isinstance(node, ast.ClassDef):
            type_infos.extend(self._infer_from_class(node))
        elif isinstance(node, ast.Assign):
            info = self._infer_from_assign(node, scope="module")
            type_infos.extend(info)
        elif isinstance(node, ast.AnnAssign):
            ann_info = self._infer_from_annassign(node, scope="module")
            if ann_info is not None:
                type_infos.append(ann_info)

    # Back-fill symbol_ids from the symbol table when possible.
    if symbol_table is not None:
        self._resolve_symbol_ids(type_infos, symbol_table)

    return type_infos

TypeInfo dataclass

Type information for a symbol.

Source code in py/cogant/static/types.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass
class TypeInfo:
    """Type information for a symbol."""

    symbol_id: str
    """Symbol ID."""

    symbol_name: str
    """Symbol name."""

    symbol_kind: str
    """Symbol kind (function, variable, parameter, attribute)."""

    inferred_type: str | None = None
    """Inferred type."""

    annotation: str | None = None
    """Explicit type annotation."""

    is_mutable: bool = True
    """Whether the symbol is mutable."""

    confidence: float = 0.0
    """Confidence score (0.0 to 1.0)."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional type metadata."""

annotation = None class-attribute instance-attribute

Explicit type annotation.

confidence = 0.0 class-attribute instance-attribute

Confidence score (0.0 to 1.0).

inferred_type = None class-attribute instance-attribute

Inferred type.

is_mutable = True class-attribute instance-attribute

Whether the symbol is mutable.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional type metadata.

symbol_id instance-attribute

Symbol ID.

symbol_kind instance-attribute

Symbol kind (function, variable, parameter, attribute).

symbol_name instance-attribute

Symbol name.

Imports

cogant.static.imports

Import resolution and analysis: classify imports and build import graph.

ImportAnalyzer

Analyze and resolve import statements.

Source code in py/cogant/static/imports.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
class ImportAnalyzer:
    """Analyze and resolve import statements."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize import analyzer.

        Args:
            repo_root: Root path of repository for local import resolution.
                Absolute imports (``import pkg.mod``) are resolved against
                it only when it is given; relative imports always resolve
                against the importing file.
        """
        self.repo_root = Path(repo_root or "/")
        self._resolve_absolute = repo_root is not None
        self.parser = PythonASTParser()
        self._stdlib_modules = self._load_stdlib_modules()

    def analyze_file(self, file_path: Path) -> list[ImportEdge]:
        """Analyze imports in a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of ImportEdge for all imports found.
        """
        module = self.parser.parse_file(file_path)
        return self._build_import_edges(file_path, module.imports)

    def analyze_source(self, source: str, file_path: Path) -> list[ImportEdge]:
        """Analyze imports in Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of ImportEdge for all imports found.
        """
        module = self.parser.parse_string(source, file_path)
        return self._build_import_edges(file_path, module.imports)

    def _build_import_edges(self, file_path: Path, import_defs: Any) -> list[ImportEdge]:
        """Build import edges from import definitions.

        Args:
            file_path: Source file path.
            import_defs: List of ImportDef from parser.

        Returns:
            List of ImportEdge.
        """
        edges = []

        for imp in import_defs:
            # Classify on the top-level package: ``os.path`` is stdlib because
            # ``os`` is. Relative imports are never stdlib.
            top_level = imp.module_name.split(".", 1)[0]
            is_stdlib = not imp.is_relative and top_level in self._stdlib_modules

            # Resolve relative imports, and absolute ones against repo_root,
            # before anything non-stdlib is called third-party.
            resolved_file = None
            if imp.is_relative:
                metadata = imp.metadata if isinstance(imp.metadata, dict) else {}
                resolved_file = self._resolve_local_import(
                    file_path,
                    imp.module_name,
                    True,
                    level=int(metadata.get("level", 1) or 1),
                    names=list(imp.names or []),
                )
            elif not is_stdlib and self._resolve_absolute:
                resolved_file = self._resolve_local_import(file_path, imp.module_name, False)
            is_local = resolved_file is not None
            is_third_party = not is_stdlib and not imp.is_relative and not is_local

            edge = ImportEdge(
                id=self._generate_import_id(file_path, imp.module_name),
                source_file=file_path,
                module_name=imp.module_name,
                is_relative=imp.is_relative,
                is_stdlib=is_stdlib,
                is_third_party=is_third_party,
                is_local=is_local,
                resolved_file=resolved_file,
                line_num=imp.line_num,
                imported_names=imp.names,
            )
            edges.append(edge)

        return edges

    def _resolve_local_import(
        self,
        source_file: Path,
        module_name: str,
        is_relative: bool,
        level: int = 1,
        names: list[str] | None = None,
    ) -> Path | None:
        """Try to resolve a local import to a file.

        Args:
            source_file: File containing the import.
            module_name: Module name to resolve (empty for ``from . import x``).
            is_relative: Whether import is relative.
            level: Number of leading dots of a relative import; each dot
                beyond the first moves up one package directory.
            names: Imported names; for ``from . import x`` a submodule
                ``x`` is preferred over the package itself.

        Returns:
            Resolved file path or None if not found.
        """
        if is_relative:
            base = source_file.parent
            for _ in range(max(level, 1) - 1):
                base = base.parent
            if not module_name:
                # ``from . import x``: x is a submodule or a package attribute.
                for name in names or []:
                    for candidate in (base / f"{name}.py", base / name / "__init__.py"):
                        if candidate.exists():
                            return candidate
                package_init = base / "__init__.py"
                return package_init if package_init.exists() else None
            target = base / module_name.replace(".", "/")
        else:
            # Absolute import
            target = self.repo_root / module_name.replace(".", "/")

        # Try as module (file.py)
        module_file = target.parent / f"{target.name}.py"
        if module_file.exists():
            return module_file

        # Try as package (directory with __init__.py)
        if (target / "__init__.py").exists():
            return target / "__init__.py"

        return None

    @staticmethod
    def _load_stdlib_modules() -> set[str]:
        """Load set of Python standard library module names.

        Returns:
            Set of stdlib module names: the running interpreter's
            ``sys.stdlib_module_names`` plus modules removed from recent
            Python versions that older code may still import.
        """
        # Core standard library modules
        stdlib = {
            "__future__",
            "abc",
            "aifc",
            "argparse",
            "array",
            "ast",
            "asyncio",
            "atexit",
            "audioop",
            "base64",
            "bdb",
            "binascii",
            "binhex",
            "bisect",
            "builtins",
            "bz2",
            "calendar",
            "cgi",
            "cgitb",
            "chunk",
            "cmath",
            "cmd",
            "code",
            "codecs",
            "codeop",
            "collections",
            "colorsys",
            "compileall",
            "concurrent",
            "configparser",
            "contextlib",
            "contextvars",
            "copy",
            "copyreg",
            "cProfile",
            "crypt",
            "csv",
            "ctypes",
            "curses",
            "dataclasses",
            "datetime",
            "dbm",
            "decimal",
            "difflib",
            "dis",
            "distutils",
            "doctest",
            "dummy_thread",
            "email",
            "encodings",
            "enum",
            "errno",
            "faulthandler",
            "fcntl",
            "filecmp",
            "fileinput",
            "fnmatch",
            "fractions",
            "ftplib",
            "functools",
            "gc",
            "getopt",
            "getpass",
            "gettext",
            "glob",
            "graphlib",
            "grp",
            "gzip",
            "hashlib",
            "heapq",
            "hmac",
            "html",
            "http",
            "idlelib",
            "imaplib",
            "imghdr",
            "imp",
            "importlib",
            "inspect",
            "io",
            "ipaddress",
            "itertools",
            "json",
            "keyword",
            "lib2to3",
            "linecache",
            "locale",
            "logging",
            "lzma",
            "mailbox",
            "mailcap",
            "marshal",
            "math",
            "mimetypes",
            "mmap",
            "modulefinder",
            "msilib",
            "msvcrt",
            "multiprocessing",
            "netrc",
            "nis",
            "nntplib",
            "numbers",
            "operator",
            "optparse",
            "os",
            "ossaudiodev",
            "parser",
            "pathlib",
            "pdb",
            "pickle",
            "pickletools",
            "pipes",
            "pkgutil",
            "platform",
            "plistlib",
            "poplib",
            "posix",
            "posixpath",
            "pprint",
            "profile",
            "pstats",
            "pty",
            "pwd",
            "py_compile",
            "pyclbr",
            "pydoc",
            "queue",
            "quopri",
            "random",
            "readline",
            "reprlib",
            "resource",
            "rlcompleter",
            "runpy",
            "sched",
            "secrets",
            "select",
            "selectors",
            "shelve",
            "shlex",
            "shutil",
            "signal",
            "site",
            "smtpd",
            "smtplib",
            "sndhdr",
            "socket",
            "socketserver",
            "spwd",
            "sqlite3",
            "ssl",
            "stat",
            "statistics",
            "string",
            "stringprep",
            "struct",
            "subprocess",
            "sunau",
            "symbol",
            "symtable",
            "sys",
            "sysconfig",
            "syslog",
            "tabnanny",
            "tarfile",
            "telnetlib",
            "tempfile",
            "termios",
            "test",
            "textwrap",
            "threading",
            "time",
            "timeit",
            "tkinter",
            "token",
            "tokenize",
            "tomllib",
            "trace",
            "traceback",
            "tracemalloc",
            "tty",
            "turtle",
            "turtledemo",
            "types",
            "typing",
            "unicodedata",
            "unittest",
            "urllib",
            "uu",
            "uuid",
            "venv",
            "warnings",
            "wave",
            "weakref",
            "webbrowser",
            "winreg",
            "winsound",
            "wsgiref",
            "xdrlib",
            "xml",
            "xmlrpc",
            "zipapp",
            "zipfile",
            "zipimport",
            "zlib",
        }

        return stdlib | set(sys.stdlib_module_names)

    @staticmethod
    def _generate_import_id(file_path: Path, module_name: str) -> str:
        """Generate stable import edge ID.

        Args:
            file_path: Source file path.
            module_name: Module being imported.

        Returns:
            Stable ID (SHA256 hash).
        """
        content = f"{file_path.resolve()}:import:{module_name}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

__init__(repo_root=None)

Initialize import analyzer.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository for local import resolution. Absolute imports (import pkg.mod) are resolved against it only when it is given; relative imports always resolve against the importing file.

None
Source code in py/cogant/static/imports.py
59
60
61
62
63
64
65
66
67
68
69
70
71
def __init__(self, repo_root: Path | None = None):
    """Initialize import analyzer.

    Args:
        repo_root: Root path of repository for local import resolution.
            Absolute imports (``import pkg.mod``) are resolved against
            it only when it is given; relative imports always resolve
            against the importing file.
    """
    self.repo_root = Path(repo_root or "/")
    self._resolve_absolute = repo_root is not None
    self.parser = PythonASTParser()
    self._stdlib_modules = self._load_stdlib_modules()

analyze_file(file_path)

Analyze imports in a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[ImportEdge]

List of ImportEdge for all imports found.

Source code in py/cogant/static/imports.py
73
74
75
76
77
78
79
80
81
82
83
def analyze_file(self, file_path: Path) -> list[ImportEdge]:
    """Analyze imports in a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of ImportEdge for all imports found.
    """
    module = self.parser.parse_file(file_path)
    return self._build_import_edges(file_path, module.imports)

analyze_source(source, file_path)

Analyze imports in Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[ImportEdge]

List of ImportEdge for all imports found.

Source code in py/cogant/static/imports.py
85
86
87
88
89
90
91
92
93
94
95
96
def analyze_source(self, source: str, file_path: Path) -> list[ImportEdge]:
    """Analyze imports in Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of ImportEdge for all imports found.
    """
    module = self.parser.parse_string(source, file_path)
    return self._build_import_edges(file_path, module.imports)

ImportEdge dataclass

An import relationship between modules.

Source code in py/cogant/static/imports.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@dataclass
class ImportEdge:
    """An import relationship between modules."""

    id: str
    """Unique edge identifier."""

    source_file: Path
    """File containing the import."""

    module_name: str
    """Module being imported."""

    is_relative: bool
    """Whether import is relative."""

    is_stdlib: bool
    """Whether module is from Python standard library."""

    is_third_party: bool
    """Whether module is from third-party package."""

    is_local: bool
    """Whether module is local to repository."""

    resolved_file: Path | None = None
    """Resolved file path if found."""

    resolved_module: str | None = None
    """Resolved module name."""

    line_num: int = 0
    """Line number of import statement."""

    imported_names: list[str] = field(default_factory=list)
    """Specific names imported (for 'from X import Y')."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

id instance-attribute

Unique edge identifier.

imported_names = field(default_factory=list) class-attribute instance-attribute

Specific names imported (for 'from X import Y').

is_local instance-attribute

Whether module is local to repository.

is_relative instance-attribute

Whether import is relative.

is_stdlib instance-attribute

Whether module is from Python standard library.

is_third_party instance-attribute

Whether module is from third-party package.

line_num = 0 class-attribute instance-attribute

Line number of import statement.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

module_name instance-attribute

Module being imported.

resolved_file = None class-attribute instance-attribute

Resolved file path if found.

resolved_module = None class-attribute instance-attribute

Resolved module name.

source_file instance-attribute

File containing the import.

Calls

cogant.static.calls

Call graph extraction: find function/method calls and build call relationships.

CallEdge dataclass

A function/method call relationship.

Source code in py/cogant/static/calls.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@dataclass
class CallEdge:
    """A function/method call relationship."""

    id: str
    """Unique edge identifier."""

    source_file: Path
    """File containing the call."""

    caller_id: str
    """Symbol ID of the calling function."""

    caller_name: str
    """Name of calling function/method."""

    callee_name: str
    """Name of called function/method."""

    callee_id: str | None = None
    """Symbol ID of called function (if resolved)."""

    line_num: int = 0
    """Line number of call."""

    is_method_call: bool = False
    """Whether this is a method call."""

    receiver: str | None = None
    """Object/module the method is called on."""

    args: list[str] = field(default_factory=list)
    """Argument values as strings."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

args = field(default_factory=list) class-attribute instance-attribute

Argument values as strings.

callee_id = None class-attribute instance-attribute

Symbol ID of called function (if resolved).

callee_name instance-attribute

Name of called function/method.

caller_id instance-attribute

Symbol ID of the calling function.

caller_name instance-attribute

Name of calling function/method.

id instance-attribute

Unique edge identifier.

is_method_call = False class-attribute instance-attribute

Whether this is a method call.

line_num = 0 class-attribute instance-attribute

Line number of call.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

receiver = None class-attribute instance-attribute

Object/module the method is called on.

source_file instance-attribute

File containing the call.

CallExtractorVisitor

Bases: NodeVisitor

AST visitor to extract function/method calls.

Source code in py/cogant/static/calls.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class CallExtractorVisitor(ast.NodeVisitor):
    """AST visitor to extract function/method calls."""

    def __init__(
        self,
        file_path: Path,
        function_name: str,
        scope: str,
        symbol_table: Any,
    ):
        """Initialize call extractor visitor.

        Args:
            file_path: Source file path.
            function_name: Name of the function being analyzed.
            scope: Scope context (module or class name).
            symbol_table: SymbolTable for callee resolution.
        """
        self.file_path = file_path
        self.function_name = function_name
        self.scope = scope
        self.symbol_table = symbol_table
        self.calls: list[CallEdge] = []

    def visit_Call(self, node: ast.Call) -> None:
        """Visit function call node.

        Args:
            node: AST Call node.
        """
        call_edge = self._extract_call(node)
        if call_edge:
            self.calls.append(call_edge)

        self.generic_visit(node)

    def _extract_call(self, node: ast.Call) -> CallEdge | None:
        """Extract call information from AST Call node.

        Args:
            node: AST Call node.

        Returns:
            CallEdge or None if extraction failed.
        """
        try:
            callee_name = None
            receiver = None
            is_method_call = False

            # Handle different call types
            if isinstance(node.func, ast.Name):
                # Simple function call: foo()
                callee_name = node.func.id
            elif isinstance(node.func, ast.Attribute):
                # Method call: obj.method()
                is_method_call = True
                callee_name = node.func.attr
                receiver = self._ast_to_str(node.func.value)
            else:
                # Complex call expression
                callee_name = self._ast_to_str(node.func)

            if not callee_name:
                return None

            # Extract arguments
            args = [self._ast_to_str(arg) for arg in node.args]

            # Try to resolve callee ID
            callee_id = None
            for sym in self.symbol_table.symbols:
                if sym.name == callee_name:
                    callee_id = sym.id
                    break

            # Create caller ID
            caller_id = self._generate_caller_id(self.function_name, self.scope)

            return CallEdge(
                id=self._generate_call_id(
                    self.file_path, self.function_name, callee_name, node.lineno
                ),
                source_file=self.file_path,
                caller_id=caller_id,
                caller_name=self.function_name,
                callee_name=callee_name,
                callee_id=callee_id,
                line_num=node.lineno,
                is_method_call=is_method_call,
                receiver=receiver,
                args=args,
            )

        except Exception as e:
            logger.debug(f"Failed to extract call: {e}")
            return None

    @staticmethod
    def _ast_to_str(node: ast.AST) -> str:
        """Convert AST node to string.

        Args:
            node: AST node.

        Returns:
            String representation.
        """
        try:
            return ast.unparse(node)
        except Exception:
            if isinstance(node, ast.Name):
                return node.id
            elif isinstance(node, ast.Constant):
                return repr(node.value)
            elif isinstance(node, ast.Attribute):
                return f"{CallExtractorVisitor._ast_to_str(node.value)}.{node.attr}"
            else:
                return type(node).__name__

    @staticmethod
    def _generate_caller_id(function_name: str, scope: str) -> str:
        """Generate caller symbol ID.

        Args:
            function_name: Function name.
            scope: Scope context.

        Returns:
            Caller ID.
        """
        content = f"{scope}#{function_name}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

    @staticmethod
    def _generate_call_id(file_path: Path, caller: str, callee: str, line_num: int) -> str:
        """Generate call edge ID.

        Args:
            file_path: Source file path.
            caller: Caller function name.
            callee: Callee function name.
            line_num: Line number of call.

        Returns:
            Call edge ID.
        """
        content = f"{file_path}:{caller}→{callee}:{line_num}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

__init__(file_path, function_name, scope, symbol_table)

Initialize call extractor visitor.

Parameters:

Name Type Description Default
file_path Path

Source file path.

required
function_name str

Name of the function being analyzed.

required
scope str

Scope context (module or class name).

required
symbol_table Any

SymbolTable for callee resolution.

required
Source code in py/cogant/static/calls.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def __init__(
    self,
    file_path: Path,
    function_name: str,
    scope: str,
    symbol_table: Any,
):
    """Initialize call extractor visitor.

    Args:
        file_path: Source file path.
        function_name: Name of the function being analyzed.
        scope: Scope context (module or class name).
        symbol_table: SymbolTable for callee resolution.
    """
    self.file_path = file_path
    self.function_name = function_name
    self.scope = scope
    self.symbol_table = symbol_table
    self.calls: list[CallEdge] = []

visit_Call(node)

Visit function call node.

Parameters:

Name Type Description Default
node Call

AST Call node.

required
Source code in py/cogant/static/calls.py
159
160
161
162
163
164
165
166
167
168
169
def visit_Call(self, node: ast.Call) -> None:
    """Visit function call node.

    Args:
        node: AST Call node.
    """
    call_edge = self._extract_call(node)
    if call_edge:
        self.calls.append(call_edge)

    self.generic_visit(node)

CallGraphBuilder

Extract function and method calls from Python source.

Source code in py/cogant/static/calls.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
class CallGraphBuilder:
    """Extract function and method calls from Python source."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize call graph builder.

        Args:
            repo_root: Root path of repository.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()
        self.symbol_extractor = SymbolExtractor(repo_root)

    def extract_calls_from_file(self, file_path: Path) -> list[CallEdge]:
        """Extract all function/method calls from a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of CallEdge for all calls found.
        """
        try:
            source = Path(file_path).read_text(encoding="utf-8")
        except (OSError, UnicodeDecodeError) as e:
            logger.debug(f"Failed to read {file_path}: {e}")
            return []
        return self.extract_calls_from_source(source, file_path)

    def extract_calls_from_source(self, source: str, file_path: Path) -> list[CallEdge]:
        """Extract function/method calls from Python source code.

        Module-level functions are reported first, then class methods, each
        in source order. Every ``def`` and ``async def`` is visited once with
        its own visitor, so same-named defs (a property getter and setter,
        ``@overload`` variants) each contribute their own calls exactly once.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of CallEdge for all calls found.
        """
        try:
            tree = ast.parse(source)
        except (SyntaxError, ValueError) as e:
            logger.debug(f"Failed to extract calls from source: {e}")
            return []
        symbol_table = self.symbol_extractor.extract_from_source(source, file_path)

        calls: list[CallEdge] = []
        for node in tree.body:
            if isinstance(node, _DEF_NODES):
                calls.extend(_calls_in_def(node, file_path, "module", symbol_table))
        for node in tree.body:
            if isinstance(node, ast.ClassDef):
                for item in node.body:
                    if isinstance(item, _DEF_NODES):
                        calls.extend(_calls_in_def(item, file_path, node.name, symbol_table))
        return calls

__init__(repo_root=None)

Initialize call graph builder.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository.

None
Source code in py/cogant/static/calls.py
57
58
59
60
61
62
63
64
65
def __init__(self, repo_root: Path | None = None):
    """Initialize call graph builder.

    Args:
        repo_root: Root path of repository.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()
    self.symbol_extractor = SymbolExtractor(repo_root)

extract_calls_from_file(file_path)

Extract all function/method calls from a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[CallEdge]

List of CallEdge for all calls found.

Source code in py/cogant/static/calls.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def extract_calls_from_file(self, file_path: Path) -> list[CallEdge]:
    """Extract all function/method calls from a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of CallEdge for all calls found.
    """
    try:
        source = Path(file_path).read_text(encoding="utf-8")
    except (OSError, UnicodeDecodeError) as e:
        logger.debug(f"Failed to read {file_path}: {e}")
        return []
    return self.extract_calls_from_source(source, file_path)

extract_calls_from_source(source, file_path)

Extract function/method calls from Python source code.

Module-level functions are reported first, then class methods, each in source order. Every def and async def is visited once with its own visitor, so same-named defs (a property getter and setter, @overload variants) each contribute their own calls exactly once.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[CallEdge]

List of CallEdge for all calls found.

Source code in py/cogant/static/calls.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def extract_calls_from_source(self, source: str, file_path: Path) -> list[CallEdge]:
    """Extract function/method calls from Python source code.

    Module-level functions are reported first, then class methods, each
    in source order. Every ``def`` and ``async def`` is visited once with
    its own visitor, so same-named defs (a property getter and setter,
    ``@overload`` variants) each contribute their own calls exactly once.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of CallEdge for all calls found.
    """
    try:
        tree = ast.parse(source)
    except (SyntaxError, ValueError) as e:
        logger.debug(f"Failed to extract calls from source: {e}")
        return []
    symbol_table = self.symbol_extractor.extract_from_source(source, file_path)

    calls: list[CallEdge] = []
    for node in tree.body:
        if isinstance(node, _DEF_NODES):
            calls.extend(_calls_in_def(node, file_path, "module", symbol_table))
    for node in tree.body:
        if isinstance(node, ast.ClassDef):
            for item in node.body:
                if isinstance(item, _DEF_NODES):
                    calls.extend(_calls_in_def(item, file_path, node.name, symbol_table))
    return calls

Dataflow

cogant.static.dataflow

Data flow analysis: track variable reads/writes and build data flow edges.

This module extracts READ, WRITE, MUTATE, and DEPENDS_ON relationships from Python source. It drives several translation rules that need to know which symbols a function modifies or observes.

The analyzer works at two levels:

  • DataFlowAnalyzer — top-level orchestrator. Walks a parsed module and launches a DataFlowVisitor for module-level code, every function body, and every method body.
  • DataFlowVisitor — an :class:ast.NodeVisitor that records reads/writes inside a single scope. It understands simple assignments, annotated assignments, augmented assignments, attribute writes, attribute reads, free Name loads, function calls, and return statements.

All operations are resilient: malformed source or unexpected AST shapes are logged at debug level and skipped rather than aborting extraction.

DataFlowAnalyzer

Analyze data flow: track variable reads, writes, and mutations.

Source code in py/cogant/static/dataflow.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
class DataFlowAnalyzer:
    """Analyze data flow: track variable reads, writes, and mutations."""

    def __init__(self, repo_root: Path | None = None):
        """Initialize data flow analyzer.

        Args:
            repo_root: Root path of repository.
        """
        self.repo_root = Path(repo_root or "/")
        self.parser = PythonASTParser()

    def analyze_file(self, file_path: Path) -> list[DataFlowEdge]:
        """Analyze data flow in a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            List of DataFlowEdge for data flow relationships.
        """
        try:
            with open(file_path, encoding="utf-8") as f:
                source = f.read()
        except OSError as e:
            logger.debug(f"Failed to read {file_path}: {e}")
            return []

        return self.analyze_source(source, file_path)

    def analyze_source(self, source: str, file_path: Path) -> list[DataFlowEdge]:
        """Analyze data flow in Python source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            List of DataFlowEdge for data flow relationships.
        """
        flows: list[DataFlowEdge] = []

        try:
            tree = ast.parse(source)
        except SyntaxError as e:
            logger.debug(f"Syntax error parsing data flow in {file_path}: {e}")
            return flows
        except ValueError as e:
            logger.debug(f"Parse error parsing data flow in {file_path}: {e}")
            return flows

        # Module-level statements (no function bodies)
        module_stmts = [
            stmt
            for stmt in tree.body
            if not isinstance(
                stmt,
                ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef,
            )
        ]
        if module_stmts:
            visitor = DataFlowVisitor(file_path, "module", module_stmts)
            flows.extend(visitor.flows)

        # Top-level functions
        for node in tree.body:
            if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
                visitor = DataFlowVisitor(file_path, node.name, node.body)
                flows.extend(visitor.flows)
            elif isinstance(node, ast.ClassDef):
                # Analyze class body (attribute defaults, AnnAssigns)
                class_body_stmts = [
                    item
                    for item in node.body
                    if not isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
                ]
                if class_body_stmts:
                    visitor = DataFlowVisitor(file_path, node.name, class_body_stmts)
                    flows.extend(visitor.flows)

                # Analyze methods
                for item in node.body:
                    if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
                        context = f"{node.name}.{item.name}"
                        visitor = DataFlowVisitor(file_path, context, item.body)
                        flows.extend(visitor.flows)

        return flows

    def build_flow_graph(self, file_path: Path) -> DataFlowGraph:
        """Build a data flow graph from a Python file.

        Args:
            file_path: Path to Python file.

        Returns:
            DataFlowGraph instance.
        """
        edges = self.analyze_file(file_path)
        graph = DataFlowGraph()
        for edge in edges:
            graph.add_edge(edge)
        return graph

    def build_flow_graph_from_source(self, source: str, file_path: Path) -> DataFlowGraph:
        """Build a data flow graph from source code.

        Args:
            source: Python source code.
            file_path: Path for reference.

        Returns:
            DataFlowGraph instance.
        """
        edges = self.analyze_source(source, file_path)
        graph = DataFlowGraph()
        for edge in edges:
            graph.add_edge(edge)
        return graph

__init__(repo_root=None)

Initialize data flow analyzer.

Parameters:

Name Type Description Default
repo_root Path | None

Root path of repository.

None
Source code in py/cogant/static/dataflow.py
170
171
172
173
174
175
176
177
def __init__(self, repo_root: Path | None = None):
    """Initialize data flow analyzer.

    Args:
        repo_root: Root path of repository.
    """
    self.repo_root = Path(repo_root or "/")
    self.parser = PythonASTParser()

analyze_file(file_path)

Analyze data flow in a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
list[DataFlowEdge]

List of DataFlowEdge for data flow relationships.

Source code in py/cogant/static/dataflow.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def analyze_file(self, file_path: Path) -> list[DataFlowEdge]:
    """Analyze data flow in a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        List of DataFlowEdge for data flow relationships.
    """
    try:
        with open(file_path, encoding="utf-8") as f:
            source = f.read()
    except OSError as e:
        logger.debug(f"Failed to read {file_path}: {e}")
        return []

    return self.analyze_source(source, file_path)

analyze_source(source, file_path)

Analyze data flow in Python source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
list[DataFlowEdge]

List of DataFlowEdge for data flow relationships.

Source code in py/cogant/static/dataflow.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
def analyze_source(self, source: str, file_path: Path) -> list[DataFlowEdge]:
    """Analyze data flow in Python source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        List of DataFlowEdge for data flow relationships.
    """
    flows: list[DataFlowEdge] = []

    try:
        tree = ast.parse(source)
    except SyntaxError as e:
        logger.debug(f"Syntax error parsing data flow in {file_path}: {e}")
        return flows
    except ValueError as e:
        logger.debug(f"Parse error parsing data flow in {file_path}: {e}")
        return flows

    # Module-level statements (no function bodies)
    module_stmts = [
        stmt
        for stmt in tree.body
        if not isinstance(
            stmt,
            ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef,
        )
    ]
    if module_stmts:
        visitor = DataFlowVisitor(file_path, "module", module_stmts)
        flows.extend(visitor.flows)

    # Top-level functions
    for node in tree.body:
        if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
            visitor = DataFlowVisitor(file_path, node.name, node.body)
            flows.extend(visitor.flows)
        elif isinstance(node, ast.ClassDef):
            # Analyze class body (attribute defaults, AnnAssigns)
            class_body_stmts = [
                item
                for item in node.body
                if not isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
            ]
            if class_body_stmts:
                visitor = DataFlowVisitor(file_path, node.name, class_body_stmts)
                flows.extend(visitor.flows)

            # Analyze methods
            for item in node.body:
                if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef):
                    context = f"{node.name}.{item.name}"
                    visitor = DataFlowVisitor(file_path, context, item.body)
                    flows.extend(visitor.flows)

    return flows

build_flow_graph(file_path)

Build a data flow graph from a Python file.

Parameters:

Name Type Description Default
file_path Path

Path to Python file.

required

Returns:

Type Description
DataFlowGraph

DataFlowGraph instance.

Source code in py/cogant/static/dataflow.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def build_flow_graph(self, file_path: Path) -> DataFlowGraph:
    """Build a data flow graph from a Python file.

    Args:
        file_path: Path to Python file.

    Returns:
        DataFlowGraph instance.
    """
    edges = self.analyze_file(file_path)
    graph = DataFlowGraph()
    for edge in edges:
        graph.add_edge(edge)
    return graph

build_flow_graph_from_source(source, file_path)

Build a data flow graph from source code.

Parameters:

Name Type Description Default
source str

Python source code.

required
file_path Path

Path for reference.

required

Returns:

Type Description
DataFlowGraph

DataFlowGraph instance.

Source code in py/cogant/static/dataflow.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def build_flow_graph_from_source(self, source: str, file_path: Path) -> DataFlowGraph:
    """Build a data flow graph from source code.

    Args:
        source: Python source code.
        file_path: Path for reference.

    Returns:
        DataFlowGraph instance.
    """
    edges = self.analyze_source(source, file_path)
    graph = DataFlowGraph()
    for edge in edges:
        graph.add_edge(edge)
    return graph

DataFlowEdge dataclass

A data flow relationship between symbols.

Source code in py/cogant/static/dataflow.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
@dataclass
class DataFlowEdge:
    """A data flow relationship between symbols."""

    id: str
    """Unique edge identifier."""

    source_symbol: str
    """Source symbol ID or name."""

    target_symbol: str
    """Target symbol ID or name."""

    edge_type: str
    """Edge type: reads, writes, mutates, depends_on."""

    file_path: Path
    """Source file path."""

    line_num: int
    """Line number where flow occurs."""

    context: str = "module"
    """Context (module, function name, class.method)."""

    metadata: dict[str, Any] = field(default_factory=dict)
    """Additional metadata."""

context = 'module' class-attribute instance-attribute

Context (module, function name, class.method).

edge_type instance-attribute

Edge type: reads, writes, mutates, depends_on.

file_path instance-attribute

Source file path.

id instance-attribute

Unique edge identifier.

line_num instance-attribute

Line number where flow occurs.

metadata = field(default_factory=dict) class-attribute instance-attribute

Additional metadata.

source_symbol instance-attribute

Source symbol ID or name.

target_symbol instance-attribute

Target symbol ID or name.

DataFlowGraph dataclass

Directed graph of data flow relationships.

Source code in py/cogant/static/dataflow.py
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
@dataclass
class DataFlowGraph:
    """Directed graph of data flow relationships."""

    edges: list[DataFlowEdge] = field(default_factory=list)
    """List of data flow edges."""

    nodes: set[str] = field(default_factory=set)
    """Set of all node names."""

    def add_edge(self, edge: DataFlowEdge) -> None:
        """Add an edge to the graph.

        Args:
            edge: DataFlowEdge to add.
        """
        self.edges.append(edge)
        self.nodes.add(edge.source_symbol)
        self.nodes.add(edge.target_symbol)

    def find_sources(self) -> list[str]:
        """Find nodes with no incoming data flow (entry points).

        Returns:
            List of source node names.
        """
        sources_with_incoming = {e.target_symbol for e in self.edges}
        return sorted([n for n in self.nodes if n not in sources_with_incoming])

    def find_sinks(self) -> list[str]:
        """Find nodes with no outgoing data flow (final consumers).

        Returns:
            List of sink node names.
        """
        sinks_with_outgoing = {e.source_symbol for e in self.edges}
        return sorted([n for n in self.nodes if n not in sinks_with_outgoing])

    def get_taint_paths(self, source: str, sink: str) -> list[list[str]]:
        """Find all paths from source to sink node.

        Args:
            source: Source node name.
            sink: Sink node name.

        Returns:
            List of paths (each path is a list of node names).
        """
        # Build adjacency list
        adj: dict[str, set[str]] = {}
        for node in self.nodes:
            adj[node] = set()
        for edge in self.edges:
            adj[edge.source_symbol].add(edge.target_symbol)

        # DFS to find all paths
        all_paths: list[list[str]] = []

        def dfs(current: str, target: str, path: list[str]) -> None:
            """Depth-first search for paths.

            Args:
                current: Current node.
                target: Target node.
                path: Current path.
            """
            if current == target:
                all_paths.append(path[:])
                return
            if current not in adj:
                return
            for neighbor in adj[current]:
                if neighbor not in path:  # Prevent cycles
                    path.append(neighbor)
                    dfs(neighbor, target, path)
                    path.pop()

        if source in self.nodes:
            dfs(source, sink, [source])

        return all_paths

    def to_dict(self) -> dict[str, Any]:
        """Serialize graph to dictionary.

        Returns:
            Dictionary representation of the graph.
        """
        return {
            "nodes": sorted(self.nodes),
            "edges": [
                {
                    "id": e.id,
                    "source": e.source_symbol,
                    "target": e.target_symbol,
                    "type": e.edge_type,
                    "file": str(e.file_path),
                    "line": e.line_num,
                    "context": e.context,
                }
                for e in self.edges
            ],
        }

edges = field(default_factory=list) class-attribute instance-attribute

List of data flow edges.

nodes = field(default_factory=set) class-attribute instance-attribute

Set of all node names.

add_edge(edge)

Add an edge to the graph.

Parameters:

Name Type Description Default
edge DataFlowEdge

DataFlowEdge to add.

required
Source code in py/cogant/static/dataflow.py
72
73
74
75
76
77
78
79
80
def add_edge(self, edge: DataFlowEdge) -> None:
    """Add an edge to the graph.

    Args:
        edge: DataFlowEdge to add.
    """
    self.edges.append(edge)
    self.nodes.add(edge.source_symbol)
    self.nodes.add(edge.target_symbol)

find_sinks()

Find nodes with no outgoing data flow (final consumers).

Returns:

Type Description
list[str]

List of sink node names.

Source code in py/cogant/static/dataflow.py
91
92
93
94
95
96
97
98
def find_sinks(self) -> list[str]:
    """Find nodes with no outgoing data flow (final consumers).

    Returns:
        List of sink node names.
    """
    sinks_with_outgoing = {e.source_symbol for e in self.edges}
    return sorted([n for n in self.nodes if n not in sinks_with_outgoing])

find_sources()

Find nodes with no incoming data flow (entry points).

Returns:

Type Description
list[str]

List of source node names.

Source code in py/cogant/static/dataflow.py
82
83
84
85
86
87
88
89
def find_sources(self) -> list[str]:
    """Find nodes with no incoming data flow (entry points).

    Returns:
        List of source node names.
    """
    sources_with_incoming = {e.target_symbol for e in self.edges}
    return sorted([n for n in self.nodes if n not in sources_with_incoming])

get_taint_paths(source, sink)

Find all paths from source to sink node.

Parameters:

Name Type Description Default
source str

Source node name.

required
sink str

Sink node name.

required

Returns:

Type Description
list[list[str]]

List of paths (each path is a list of node names).

Source code in py/cogant/static/dataflow.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def get_taint_paths(self, source: str, sink: str) -> list[list[str]]:
    """Find all paths from source to sink node.

    Args:
        source: Source node name.
        sink: Sink node name.

    Returns:
        List of paths (each path is a list of node names).
    """
    # Build adjacency list
    adj: dict[str, set[str]] = {}
    for node in self.nodes:
        adj[node] = set()
    for edge in self.edges:
        adj[edge.source_symbol].add(edge.target_symbol)

    # DFS to find all paths
    all_paths: list[list[str]] = []

    def dfs(current: str, target: str, path: list[str]) -> None:
        """Depth-first search for paths.

        Args:
            current: Current node.
            target: Target node.
            path: Current path.
        """
        if current == target:
            all_paths.append(path[:])
            return
        if current not in adj:
            return
        for neighbor in adj[current]:
            if neighbor not in path:  # Prevent cycles
                path.append(neighbor)
                dfs(neighbor, target, path)
                path.pop()

    if source in self.nodes:
        dfs(source, sink, [source])

    return all_paths

to_dict()

Serialize graph to dictionary.

Returns:

Type Description
dict[str, Any]

Dictionary representation of the graph.

Source code in py/cogant/static/dataflow.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def to_dict(self) -> dict[str, Any]:
    """Serialize graph to dictionary.

    Returns:
        Dictionary representation of the graph.
    """
    return {
        "nodes": sorted(self.nodes),
        "edges": [
            {
                "id": e.id,
                "source": e.source_symbol,
                "target": e.target_symbol,
                "type": e.edge_type,
                "file": str(e.file_path),
                "line": e.line_num,
                "context": e.context,
            }
            for e in self.edges
        ],
    }

DataFlowVisitor

Bases: NodeVisitor

AST visitor to extract data flow edges from one scope.

A visitor is scoped to one function, method, class body, or the module body. It tracks which names have been written (assigned) and which have been read, and emits DataFlowEdge instances describing each flow.

Handled node kinds:

  • ast.Assign — plain assignment; targets are WRITES, sources are READS from each RHS name.
  • ast.AugAssign — augmented assignment (x += 1); target is both READ and MUTATED.
  • ast.AnnAssign — annotated assignment (x: int = 5); target is a WRITE, RHS names are READS. Handles x: int without a value too.
  • ast.Attribute in Store context — attribute writes (self.x = 1) produce a WRITE edge to the dotted name.
  • ast.Attribute in Load context — attribute reads produce a READ edge.
  • ast.Name in Load context — a free-standing name read (e.g. a loop condition) produces a READ edge.
  • ast.Call — argument names are READ; method calls on self additionally emit a MUTATES edge to self.<attr> if the callee is on an attribute (potential mutation).
  • ast.Return — return value names are READ against the synthetic <return> target.
Source code in py/cogant/static/dataflow.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
class DataFlowVisitor(ast.NodeVisitor):
    """AST visitor to extract data flow edges from one scope.

    A visitor is scoped to one function, method, class body, or the module
    body. It tracks which names have been written (assigned) and which have
    been read, and emits ``DataFlowEdge`` instances describing each flow.

    Handled node kinds:

    * ``ast.Assign`` — plain assignment; targets are WRITES, sources are
      READS from each RHS name.
    * ``ast.AugAssign`` — augmented assignment (``x += 1``); target is both
      READ and MUTATED.
    * ``ast.AnnAssign`` — annotated assignment (``x: int = 5``); target is a
      WRITE, RHS names are READS. Handles ``x: int`` without a value too.
    * ``ast.Attribute`` in Store context — attribute writes (``self.x = 1``)
      produce a WRITE edge to the dotted name.
    * ``ast.Attribute`` in Load context — attribute reads produce a READ
      edge.
    * ``ast.Name`` in Load context — a free-standing name read (e.g. a loop
      condition) produces a READ edge.
    * ``ast.Call`` — argument names are READ; method calls on ``self``
      additionally emit a MUTATES edge to ``self.<attr>`` if the callee is
      on an attribute (potential mutation).
    * ``ast.Return`` — return value names are READ against the synthetic
      ``<return>`` target.
    """

    def __init__(
        self,
        file_path: Path,
        context: str,
        body: list[ast.stmt],
    ):
        """Initialize data flow visitor.

        Args:
            file_path: Source file path.
            context: Context (function/method name or ``"module"``).
            body: AST body nodes to analyze.
        """
        self.file_path = file_path
        self.context = context
        self.flows: list[DataFlowEdge] = []
        self._assignments: dict[str, int] = {}
        self._reads: set[str] = set()
        # Track which Name nodes have already been emitted as reads via an
        # enclosing construct so we don't double-count them when generic_visit
        # eventually reaches them.
        self._handled_nodes: set[int] = set()

        for node in body:
            self.visit(node)

    # ------------------------------------------------------------------
    # Statement-level handlers
    # ------------------------------------------------------------------

    def visit_Assign(self, node: ast.Assign) -> None:
        """Handle a plain assignment statement.

        Args:
            node: AST Assign node.
        """
        # Extract targets (may be Name, Attribute, Tuple/List unpack, Subscript)
        target_names = self._extract_targets(node.targets)

        # Extract RHS names as reads
        source_names = self._extract_loads(node.value)
        # Mark value subtree as handled so generic_visit doesn't re-emit it
        self._mark_handled(node.value)

        for target in target_names:
            self._assignments[target] = node.lineno
            self._emit_write(target, node.lineno)
            for source in source_names:
                self._emit(
                    source_symbol=source,
                    target_symbol=target,
                    edge_type="depends_on",
                    line_num=node.lineno,
                )
                self._reads.add(source)
                self._emit(
                    source_symbol=source,
                    target_symbol=self.context,
                    edge_type="reads",
                    line_num=node.lineno,
                )

        # Don't recurse into target subtrees — they are stores, not loads.
        for target_node in node.targets:
            self._mark_handled(target_node)

    def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
        """Handle an annotated assignment (``x: int = 5`` or ``x: int``).

        Args:
            node: AST AnnAssign node.
        """
        target_names = self._extract_targets([node.target])

        source_names: set[str] = set()
        if node.value is not None:
            source_names = self._extract_loads(node.value)
            self._mark_handled(node.value)

        for target in target_names:
            self._assignments[target] = node.lineno
            self._emit_write(target, node.lineno)
            for source in source_names:
                self._emit(
                    source_symbol=source,
                    target_symbol=target,
                    edge_type="depends_on",
                    line_num=node.lineno,
                )
                self._reads.add(source)
                self._emit(
                    source_symbol=source,
                    target_symbol=self.context,
                    edge_type="reads",
                    line_num=node.lineno,
                )

        self._mark_handled(node.target)
        if node.annotation is not None:
            self._mark_handled(node.annotation)

    def visit_AugAssign(self, node: ast.AugAssign) -> None:
        """Handle an augmented assignment (``x += 1``).

        Args:
            node: AST AugAssign node.
        """
        target_name = self._target_name(node.target)
        sources = self._extract_loads(node.value)
        self._mark_handled(node.value)

        if target_name:
            # Target is read (augmented side)
            self._reads.add(target_name)
            self._emit(
                source_symbol=target_name,
                target_symbol=self.context,
                edge_type="reads",
                line_num=node.lineno,
            )
            # RHS sources are reads
            for source in sources:
                self._reads.add(source)
                self._emit(
                    source_symbol=source,
                    target_symbol=target_name,
                    edge_type="depends_on",
                    line_num=node.lineno,
                )
                self._emit(
                    source_symbol=source,
                    target_symbol=self.context,
                    edge_type="reads",
                    line_num=node.lineno,
                )

            # Target is mutated
            self._emit(
                source_symbol=self.context,
                target_symbol=target_name,
                edge_type="mutates",
                line_num=node.lineno,
            )
            self._emit_write(target_name, node.lineno)

        self._mark_handled(node.target)

    def visit_Return(self, node: ast.Return) -> None:
        """Handle a return statement.

        Args:
            node: AST Return node.
        """
        if node.value is not None:
            names = self._extract_loads(node.value)
            self._mark_handled(node.value)
            for name in names:
                self._reads.add(name)
                self._emit(
                    source_symbol=name,
                    target_symbol="<return>",
                    edge_type="reads",
                    line_num=node.lineno,
                )

    def visit_Call(self, node: ast.Call) -> None:
        """Handle a function or method call.

        Args:
            node: AST Call node.
        """
        # Argument names are reads
        for arg in node.args:
            names = self._extract_loads(arg)
            self._mark_handled(arg)
            for name in names:
                self._reads.add(name)
                self._emit(
                    source_symbol=name,
                    target_symbol="<call>",
                    edge_type="reads",
                    line_num=node.lineno,
                )
        # Keyword arguments are reads
        for kw in node.keywords:
            if kw.value is not None:
                names = self._extract_loads(kw.value)
                self._mark_handled(kw.value)
                for name in names:
                    self._reads.add(name)
                    self._emit(
                        source_symbol=name,
                        target_symbol="<call>",
                        edge_type="reads",
                        line_num=node.lineno,
                    )

        # Method call on an attribute (``obj.method(...)``) is a potential
        # mutation of ``obj``.
        if isinstance(node.func, ast.Attribute):
            receiver = self._attribute_root(node.func.value)
            if receiver:
                self._emit(
                    source_symbol=self.context,
                    target_symbol=receiver,
                    edge_type="mutates",
                    line_num=node.lineno,
                )
            self._mark_handled(node.func)
        elif isinstance(node.func, ast.Name):
            self._mark_handled(node.func)

        # Allow generic_visit for anything we didn't explicitly handle (e.g.
        # nested calls inside arguments).
        self.generic_visit(node)

    def visit_Name(self, node: ast.Name) -> None:
        """Handle a bare ``Name`` load (e.g., ``if x:``).

        Args:
            node: AST Name node.
        """
        if id(node) in self._handled_nodes:
            return
        if isinstance(node.ctx, ast.Load):
            self._reads.add(node.id)
            self._emit(
                source_symbol=node.id,
                target_symbol=self.context,
                edge_type="reads",
                line_num=node.lineno,
            )

    def visit_Attribute(self, node: ast.Attribute) -> None:
        """Handle an ``Attribute`` access.

        Stores (e.g., ``self.x = 1``) are handled by :meth:`visit_Assign`;
        this covers loads (``return self.x``).

        Args:
            node: AST Attribute node.
        """
        if id(node) in self._handled_nodes:
            return
        if isinstance(node.ctx, ast.Load):
            dotted = self._ast_to_dotted(node)
            if dotted:
                self._reads.add(dotted)
                self._emit(
                    source_symbol=dotted,
                    target_symbol=self.context,
                    edge_type="reads",
                    line_num=node.lineno,
                )
            # Stop recursion so inner Name doesn't double-count.
            self._mark_handled(node.value)

    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    def _emit_write(self, target: str, line_num: int) -> None:
        """Emit a WRITE edge from current scope to target."""
        self._emit(
            source_symbol=self.context,
            target_symbol=target,
            edge_type="writes",
            line_num=line_num,
        )

    def _emit(
        self,
        source_symbol: str,
        target_symbol: str,
        edge_type: str,
        line_num: int,
    ) -> None:
        """Append a DataFlowEdge to the flows list."""
        edge = DataFlowEdge(
            id=self._generate_flow_id(source_symbol, target_symbol, edge_type, line_num),
            source_symbol=source_symbol,
            target_symbol=target_symbol,
            edge_type=edge_type,
            file_path=self.file_path,
            line_num=line_num,
            context=self.context,
        )
        self.flows.append(edge)

    def _extract_targets(self, targets: list[ast.expr]) -> set[str]:
        """Extract target names from assignment targets.

        Handles ``Name``, ``Attribute``, and ``Tuple``/``List`` unpacking.
        """
        names: set[str] = set()
        for target in targets:
            if isinstance(target, ast.Name):
                names.add(target.id)
            elif isinstance(target, ast.Attribute):
                dotted = self._ast_to_dotted(target)
                if dotted:
                    names.add(dotted)
            elif isinstance(target, ast.Tuple | ast.List):
                for elt in target.elts:
                    if isinstance(elt, ast.Name):
                        names.add(elt.id)
                    elif isinstance(elt, ast.Attribute):
                        dotted = self._ast_to_dotted(elt)
                        if dotted:
                            names.add(dotted)
            elif isinstance(target, ast.Subscript):
                # ``arr[0] = v`` — treat base name as target
                base = self._attribute_root(target.value)
                if base:
                    names.add(base)
        return names

    def _target_name(self, target: ast.expr) -> str | None:
        """Return a single target name for an AugAssign target."""
        if isinstance(target, ast.Name):
            return target.id
        if isinstance(target, ast.Attribute):
            return self._ast_to_dotted(target)
        return None

    @staticmethod
    def _extract_loads(node: ast.AST | None) -> set[str]:
        """Extract names that are *loaded* inside an expression subtree.

        Includes simple ``Name`` loads and dotted attribute loads so that
        ``self.x`` appears alongside ``y``.
        """
        if node is None:
            return set()

        names: set[str] = set()

        class Collector(ast.NodeVisitor):
            """Collect Name/Attribute loads."""

            def visit_Name(self, inner: ast.Name) -> None:
                """Record plain identifier loads (e.g. ``x``) into the outer name set."""
                if isinstance(inner.ctx, ast.Load):
                    names.add(inner.id)

            def visit_Attribute(self, inner: ast.Attribute) -> None:
                """Record dotted attribute loads (e.g. ``self.x``) into the outer name set."""
                if isinstance(inner.ctx, ast.Load):
                    dotted = DataFlowVisitor._ast_to_dotted_static(inner)
                    if dotted:
                        names.add(dotted)
                    # Don't descend further — we already have the full chain.
                    return
                self.generic_visit(inner)

        Collector().visit(node)
        return names

    def _mark_handled(self, node: ast.AST | None) -> None:
        """Mark a subtree as already-handled to prevent double emission."""
        if node is None:
            return
        for sub in ast.walk(node):
            self._handled_nodes.add(id(sub))

    def _ast_to_dotted(self, node: ast.AST) -> str | None:
        """Return a dotted-string representation of an attribute chain."""
        return self._ast_to_dotted_static(node)

    @staticmethod
    def _ast_to_dotted_static(node: ast.AST) -> str | None:
        """Static variant of ``_ast_to_dotted`` (used by closures)."""
        if isinstance(node, ast.Name):
            return node.id
        if isinstance(node, ast.Attribute):
            base = DataFlowVisitor._ast_to_dotted_static(node.value)
            if base is None:
                return None
            return f"{base}.{node.attr}"
        return None

    def _attribute_root(self, node: ast.AST) -> str | None:
        """Return the root name of an attribute/subscript chain."""
        while isinstance(node, ast.Attribute | ast.Subscript):
            node = node.value
        if isinstance(node, ast.Name):
            return node.id
        return None

    @staticmethod
    def _generate_flow_id(source: str, target: str, flow_type: str, line_num: int) -> str:
        """Generate a deterministic flow edge ID.

        Args:
            source: Source symbol name.
            target: Target symbol name.
            flow_type: Edge type (reads/writes/mutates/depends_on).
            line_num: Line number where the flow occurs.

        Returns:
            16-char hex identifier.
        """
        content = f"{source}→{target}:{flow_type}:{line_num}"
        hash_obj = hashlib.sha256(content.encode())
        return hash_obj.hexdigest()[:16]

__init__(file_path, context, body)

Initialize data flow visitor.

Parameters:

Name Type Description Default
file_path Path

Source file path.

required
context str

Context (function/method name or "module").

required
body list[stmt]

AST body nodes to analyze.

required
Source code in py/cogant/static/dataflow.py
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def __init__(
    self,
    file_path: Path,
    context: str,
    body: list[ast.stmt],
):
    """Initialize data flow visitor.

    Args:
        file_path: Source file path.
        context: Context (function/method name or ``"module"``).
        body: AST body nodes to analyze.
    """
    self.file_path = file_path
    self.context = context
    self.flows: list[DataFlowEdge] = []
    self._assignments: dict[str, int] = {}
    self._reads: set[str] = set()
    # Track which Name nodes have already been emitted as reads via an
    # enclosing construct so we don't double-count them when generic_visit
    # eventually reaches them.
    self._handled_nodes: set[int] = set()

    for node in body:
        self.visit(node)

visit_AnnAssign(node)

Handle an annotated assignment (x: int = 5 or x: int).

Parameters:

Name Type Description Default
node AnnAssign

AST AnnAssign node.

required
Source code in py/cogant/static/dataflow.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
    """Handle an annotated assignment (``x: int = 5`` or ``x: int``).

    Args:
        node: AST AnnAssign node.
    """
    target_names = self._extract_targets([node.target])

    source_names: set[str] = set()
    if node.value is not None:
        source_names = self._extract_loads(node.value)
        self._mark_handled(node.value)

    for target in target_names:
        self._assignments[target] = node.lineno
        self._emit_write(target, node.lineno)
        for source in source_names:
            self._emit(
                source_symbol=source,
                target_symbol=target,
                edge_type="depends_on",
                line_num=node.lineno,
            )
            self._reads.add(source)
            self._emit(
                source_symbol=source,
                target_symbol=self.context,
                edge_type="reads",
                line_num=node.lineno,
            )

    self._mark_handled(node.target)
    if node.annotation is not None:
        self._mark_handled(node.annotation)

visit_Assign(node)

Handle a plain assignment statement.

Parameters:

Name Type Description Default
node Assign

AST Assign node.

required
Source code in py/cogant/static/dataflow.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def visit_Assign(self, node: ast.Assign) -> None:
    """Handle a plain assignment statement.

    Args:
        node: AST Assign node.
    """
    # Extract targets (may be Name, Attribute, Tuple/List unpack, Subscript)
    target_names = self._extract_targets(node.targets)

    # Extract RHS names as reads
    source_names = self._extract_loads(node.value)
    # Mark value subtree as handled so generic_visit doesn't re-emit it
    self._mark_handled(node.value)

    for target in target_names:
        self._assignments[target] = node.lineno
        self._emit_write(target, node.lineno)
        for source in source_names:
            self._emit(
                source_symbol=source,
                target_symbol=target,
                edge_type="depends_on",
                line_num=node.lineno,
            )
            self._reads.add(source)
            self._emit(
                source_symbol=source,
                target_symbol=self.context,
                edge_type="reads",
                line_num=node.lineno,
            )

    # Don't recurse into target subtrees — they are stores, not loads.
    for target_node in node.targets:
        self._mark_handled(target_node)

visit_Attribute(node)

Handle an Attribute access.

Stores (e.g., self.x = 1) are handled by :meth:visit_Assign; this covers loads (return self.x).

Parameters:

Name Type Description Default
node Attribute

AST Attribute node.

required
Source code in py/cogant/static/dataflow.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def visit_Attribute(self, node: ast.Attribute) -> None:
    """Handle an ``Attribute`` access.

    Stores (e.g., ``self.x = 1``) are handled by :meth:`visit_Assign`;
    this covers loads (``return self.x``).

    Args:
        node: AST Attribute node.
    """
    if id(node) in self._handled_nodes:
        return
    if isinstance(node.ctx, ast.Load):
        dotted = self._ast_to_dotted(node)
        if dotted:
            self._reads.add(dotted)
            self._emit(
                source_symbol=dotted,
                target_symbol=self.context,
                edge_type="reads",
                line_num=node.lineno,
            )
        # Stop recursion so inner Name doesn't double-count.
        self._mark_handled(node.value)

visit_AugAssign(node)

Handle an augmented assignment (x += 1).

Parameters:

Name Type Description Default
node AugAssign

AST AugAssign node.

required
Source code in py/cogant/static/dataflow.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
def visit_AugAssign(self, node: ast.AugAssign) -> None:
    """Handle an augmented assignment (``x += 1``).

    Args:
        node: AST AugAssign node.
    """
    target_name = self._target_name(node.target)
    sources = self._extract_loads(node.value)
    self._mark_handled(node.value)

    if target_name:
        # Target is read (augmented side)
        self._reads.add(target_name)
        self._emit(
            source_symbol=target_name,
            target_symbol=self.context,
            edge_type="reads",
            line_num=node.lineno,
        )
        # RHS sources are reads
        for source in sources:
            self._reads.add(source)
            self._emit(
                source_symbol=source,
                target_symbol=target_name,
                edge_type="depends_on",
                line_num=node.lineno,
            )
            self._emit(
                source_symbol=source,
                target_symbol=self.context,
                edge_type="reads",
                line_num=node.lineno,
            )

        # Target is mutated
        self._emit(
            source_symbol=self.context,
            target_symbol=target_name,
            edge_type="mutates",
            line_num=node.lineno,
        )
        self._emit_write(target_name, node.lineno)

    self._mark_handled(node.target)

visit_Call(node)

Handle a function or method call.

Parameters:

Name Type Description Default
node Call

AST Call node.

required
Source code in py/cogant/static/dataflow.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def visit_Call(self, node: ast.Call) -> None:
    """Handle a function or method call.

    Args:
        node: AST Call node.
    """
    # Argument names are reads
    for arg in node.args:
        names = self._extract_loads(arg)
        self._mark_handled(arg)
        for name in names:
            self._reads.add(name)
            self._emit(
                source_symbol=name,
                target_symbol="<call>",
                edge_type="reads",
                line_num=node.lineno,
            )
    # Keyword arguments are reads
    for kw in node.keywords:
        if kw.value is not None:
            names = self._extract_loads(kw.value)
            self._mark_handled(kw.value)
            for name in names:
                self._reads.add(name)
                self._emit(
                    source_symbol=name,
                    target_symbol="<call>",
                    edge_type="reads",
                    line_num=node.lineno,
                )

    # Method call on an attribute (``obj.method(...)``) is a potential
    # mutation of ``obj``.
    if isinstance(node.func, ast.Attribute):
        receiver = self._attribute_root(node.func.value)
        if receiver:
            self._emit(
                source_symbol=self.context,
                target_symbol=receiver,
                edge_type="mutates",
                line_num=node.lineno,
            )
        self._mark_handled(node.func)
    elif isinstance(node.func, ast.Name):
        self._mark_handled(node.func)

    # Allow generic_visit for anything we didn't explicitly handle (e.g.
    # nested calls inside arguments).
    self.generic_visit(node)

visit_Name(node)

Handle a bare Name load (e.g., if x:).

Parameters:

Name Type Description Default
node Name

AST Name node.

required
Source code in py/cogant/static/dataflow.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
def visit_Name(self, node: ast.Name) -> None:
    """Handle a bare ``Name`` load (e.g., ``if x:``).

    Args:
        node: AST Name node.
    """
    if id(node) in self._handled_nodes:
        return
    if isinstance(node.ctx, ast.Load):
        self._reads.add(node.id)
        self._emit(
            source_symbol=node.id,
            target_symbol=self.context,
            edge_type="reads",
            line_num=node.lineno,
        )

visit_Return(node)

Handle a return statement.

Parameters:

Name Type Description Default
node Return

AST Return node.

required
Source code in py/cogant/static/dataflow.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def visit_Return(self, node: ast.Return) -> None:
    """Handle a return statement.

    Args:
        node: AST Return node.
    """
    if node.value is not None:
        names = self._extract_loads(node.value)
        self._mark_handled(node.value)
        for name in names:
            self._reads.add(name)
            self._emit(
                source_symbol=name,
                target_symbol="<return>",
                edge_type="reads",
                line_num=node.lineno,
            )

Examples

The static parser, symbol extractor, type / import resolver, call-graph builder, and dataflow helpers are exercised by: