php-parser-py 2.1.0__py3-none-win_amd64.whl → 3.0.2__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. php_parser_py/__init__.py +1 -7
  2. php_parser_py/_bookkeeping.py +2 -45
  3. php_parser_py/_graph/__init__.py +0 -2
  4. php_parser_py/_graph/_ast.py +18 -43
  5. php_parser_py/_graph/_containment.py +36 -0
  6. php_parser_py/_graph/_edge.py +12 -6
  7. php_parser_py/_graph/_modifier.py +0 -7
  8. php_parser_py/_graph/_node.py +25 -42
  9. php_parser_py/_graph/_node_id.py +2 -25
  10. php_parser_py/_mapping/_build.py +32 -26
  11. php_parser_py/_mapping/_contract.py +4 -4
  12. php_parser_py/_mapping/_declared.py +12 -5
  13. php_parser_py/_mapping/_serialize.py +4 -20
  14. php_parser_py/_node_fields.py +60 -58
  15. php_parser_py/_parser.py +1 -101
  16. php_parser_py/_printer.py +2 -3
  17. php_parser_py/_resources/parse.php +8 -9
  18. php_parser_py/_resources/print.php +9 -8
  19. php_parser_py/_runtime/_binary.py +3 -1
  20. php_parser_py/_runtime/_bundle.py +96 -18
  21. php_parser_py/_runtime/_runner.py +40 -50
  22. php_parser_py/_types.py +18 -0
  23. php_parser_py/_version.py +1 -2
  24. php_parser_py-3.0.2.dist-info/METADATA +91 -0
  25. php_parser_py-3.0.2.dist-info/RECORD +39 -0
  26. php_parser_py-2.1.0.dist-info/METADATA +0 -73
  27. php_parser_py-2.1.0.dist-info/RECORD +0 -38
  28. {php_parser_py-2.1.0.dist-info → php_parser_py-3.0.2.dist-info}/WHEEL +0 -0
  29. {php_parser_py-2.1.0.dist-info → php_parser_py-3.0.2.dist-info}/licenses/LICENSE +0 -0
  30. {php_parser_py-2.1.0.dist-info → php_parser_py-3.0.2.dist-info}/licenses/PHP-LICENSE +0 -0
  31. {php_parser_py-2.1.0.dist-info → php_parser_py-3.0.2.dist-info}/licenses/PHP-Parser-LICENSE +0 -0
  32. {php_parser_py-2.1.0.dist-info → php_parser_py-3.0.2.dist-info}/licenses/Zend-Engine-LICENSE +0 -0
php_parser_py/__init__.py CHANGED
@@ -6,9 +6,6 @@ and manipulation of PHP code.
6
6
 
7
7
  from __future__ import annotations
8
8
 
9
- from importlib.metadata import version as _distribution_version
10
-
11
- __version__ = _distribution_version("php-parser-py")
12
9
  __all__ = [
13
10
  "AST",
14
11
  "Edge",
@@ -26,14 +23,11 @@ __all__ = [
26
23
  "ParseError",
27
24
  "RunnerError",
28
25
  "NodeNotInFileError",
29
- "parse_code",
30
- "parse_file",
31
- "parse_project",
32
26
  ]
33
27
 
34
28
  from ._exceptions import NodeNotInFileError, ParseError, RunnerError
35
29
  from ._graph import AST, Edge, Modifier, Node
36
- from ._parser import Parser, parse_code, parse_file, parse_project
30
+ from ._parser import Parser
37
31
  from ._printer import ExtendedPrinter, Printer, StandardPrinter
38
32
  from ._types import ParseProvenance, PrintMode, PrintRequest, SkippedFile
39
33
  from ._version import PHPVersion
@@ -29,9 +29,6 @@ ATTRIBUTE_KEYS_PROPERTY = "pppyAttributeKeys"
29
29
  # rebuild them. Written by build, consumed and omitted by serialize.
30
30
  LIST_LENGTHS_PROPERTY = "pppyListLengths"
31
31
 
32
- # Name of the child list PHP-Parser's printer requires on declarations.
33
- ATTR_GROUPS = "attrGroups"
34
-
35
32
  # Property names the mapping writes for its own records; no JSON key and
36
33
  # no caller attribute may use them.
37
34
  BOOKKEEPING_PROPERTIES = frozenset({ATTRIBUTE_KEYS_PROPERTY, LIST_LENGTHS_PROPERTY})
@@ -48,24 +45,12 @@ def declared_fields(node_type: object) -> Mapping[str, str]:
48
45
  node_type: A node's JSON ``nodeType``.
49
46
 
50
47
  Returns:
51
- Field name to ``CHILD``, ``SCALAR`` or ``EITHER`` in declaration
52
- order; empty for a type the bundled PHP-Parser does not declare.
48
+ Field name to ``CHILD``, ``LIST``, ``SCALAR`` or ``EITHER`` in
49
+ declaration order; empty for a type the bundled PHP-Parser does not declare.
53
50
  """
54
51
  return NODE_FIELDS.get(node_type, {}) if isinstance(node_type, str) else {}
55
52
 
56
53
 
57
- def has_attr_groups(node_type: str) -> bool:
58
- """Whether the node type declares an ``attrGroups`` child field.
59
-
60
- Args:
61
- node_type: PHP-Parser node type (e.g. ``"Stmt_Function"``).
62
-
63
- Returns:
64
- True when the bundled PHP-Parser declares ``attrGroups`` on it.
65
- """
66
- return ATTR_GROUPS in declared_fields(node_type)
67
-
68
-
69
54
  def _is_scalar_field(props: Mapping[str, Any], key: str, recorded: list[str]) -> bool:
70
55
  """Whether ``key`` names a scalar field of the node, by its declared kind.
71
56
 
@@ -119,32 +104,4 @@ def attribute_update(props: Mapping[str, Any], key: str, value: Any) -> dict[str
119
104
  update: dict[str, Any] = {key: value}
120
105
  if key not in recorded:
121
106
  update[ATTRIBUTE_KEYS_PROPERTY] = [*recorded, key]
122
- if _ends_attr_groups_default(props):
123
- update[LIST_LENGTHS_PROPERTY] = {
124
- **props.get(LIST_LENGTHS_PROPERTY, {}),
125
- ATTR_GROUPS: 0,
126
- }
127
107
  return update
128
-
129
-
130
- def _ends_attr_groups_default(props: Mapping[str, Any]) -> bool:
131
- """Whether writing the attribute record would strip ``attrGroups``.
132
-
133
- The attribute-key record's absence marks a synthetic node, which
134
- serialize gives an empty ``attrGroups`` list; writing the record ends
135
- that. The empty list is then recorded as a child-list length, the same
136
- as build records one, unless the node records or stores it already. An
137
- ``attrGroups`` attribute does not hold the child field's place.
138
-
139
- Args:
140
- props: The node's stored properties before the write.
141
-
142
- Returns:
143
- True when the caller should record an empty ``attrGroups`` list.
144
- """
145
- return (
146
- ATTRIBUTE_KEYS_PROPERTY not in props
147
- and ATTR_GROUPS not in props
148
- and ATTR_GROUPS not in props.get(LIST_LENGTHS_PROPERTY, {})
149
- and has_attr_groups(props.get("nodeType", ""))
150
- )
@@ -1,7 +1,5 @@
1
1
  """Graph layer: AST querying, node/edge wrappers, and mutation."""
2
2
 
3
- # pylint: disable=duplicate-code # __all__ mirrors the package re-export list.
4
-
5
3
  from __future__ import annotations
6
4
 
7
5
  __all__ = [
@@ -10,9 +10,9 @@ from cpg2py import AbcGraphQuerier, Storage
10
10
  from .._exceptions import NodeNotInFileError
11
11
  from .._types import PARENT_OF_EDGE, PROJECT_ROOT_ID, ParseProvenance, SkippedFile
12
12
  from .._version import PHPVersion
13
+ from ._containment import containing_file_id
13
14
  from ._edge import Edge
14
15
  from ._node import Node
15
- from ._node_id import NodeId
16
16
 
17
17
 
18
18
  class AST(AbcGraphQuerier[Node, Edge]):
@@ -50,7 +50,16 @@ class AST(AbcGraphQuerier[Node, Edge]):
50
50
  root_node_id: ID of the root node. Defaults to "project".
51
51
  provenance: Parse provenance of the graph. Default None marks
52
52
  the provenance unknown.
53
+
54
+ Raises:
55
+ TypeError: If ``provenance`` is neither None nor a
56
+ ``ParseProvenance``.
53
57
  """
58
+ if provenance is not None and not isinstance(provenance, ParseProvenance):
59
+ raise TypeError(
60
+ "AST provenance must be a ParseProvenance or None, got "
61
+ f"{type(provenance).__name__}"
62
+ )
54
63
  super().__init__(storage)
55
64
  self._root_node_id = root_node_id
56
65
  self._provenance = provenance
@@ -230,7 +239,7 @@ class AST(AbcGraphQuerier[Node, Edge]):
230
239
  """Return the project node (root of the AST).
231
240
 
232
241
  The project node has ID "project" and is always present when the AST
233
- was created by parse_file or parse_project.
242
+ was created by ``Parser.parse_file`` or ``Parser.parse_project``.
234
243
 
235
244
  Returns:
236
245
  Project Node instance.
@@ -262,15 +271,14 @@ class AST(AbcGraphQuerier[Node, Edge]):
262
271
  def get_file_node(self, node_id: str) -> Node:
263
272
  """Get the file node that contains the given node.
264
273
 
265
- Uses the AST ID convention: file node ID is the file hash (16 hex
266
- digits); nodes inside that file have ID ``file_hash + "_" + counter``.
267
- Resolves by structure first, then falls back to ancestors() traversal.
274
+ Follows PARENT_OF edges upward to the nearest File node.
268
275
 
269
276
  Args:
270
277
  node_id: ID of any node in the AST.
271
278
 
272
279
  Returns:
273
- File Node instance containing the given node.
280
+ File Node instance containing the given node; the node itself
281
+ when it is a File node.
274
282
 
275
283
  Raises:
276
284
  KeyError: If the node ID is not in the graph.
@@ -279,40 +287,7 @@ class AST(AbcGraphQuerier[Node, Edge]):
279
287
  node = self.node(node_id)
280
288
  if node.node_type == "File":
281
289
  return node
282
-
283
- if node_id == self._root_node_id:
284
- raise NodeNotInFileError(node_id, "Project node has no containing file.")
285
-
286
- result = self._try_file_by_id_prefix(node_id)
287
- if result is not None:
288
- return result
289
-
290
- return self._find_file_ancestor(node)
291
-
292
- def _try_file_by_id_prefix(self, node_id: str) -> Node | None:
293
- """Try to find the file node via the ``NodeId`` prefix convention.
294
-
295
- Returns None when the ID does not match the convention or the file is
296
- not present.
297
- """
298
- parsed = NodeId.parse(node_id)
299
- if parsed is None or not parsed.file_hash:
300
- return None
301
-
302
- try:
303
- candidate = self.node(parsed.file_hash)
304
- except KeyError:
305
- return None
306
- return candidate if candidate.node_type == "File" else None
307
-
308
- def _find_file_ancestor(self, node: Node) -> Node:
309
- """Find first File ancestor of a node via traversal.
310
-
311
- Raises NodeNotInFileError if no File ancestor exists.
312
- """
313
- for ancestor in self.ancestors(node):
314
- if ancestor.node_type == "File":
315
- result: Node = ancestor
316
- return result
317
-
318
- raise NodeNotInFileError(node.id, "No File node among ancestors.")
290
+ file_id = containing_file_id(self._graph, node_id)
291
+ if file_id is None:
292
+ raise NodeNotInFileError(node_id, "No File node among ancestors.")
293
+ return self.node(file_id)
@@ -0,0 +1,36 @@
1
+ """Containing-file resolution shared by ``AST`` and ``Node``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from cpg2py import Storage
6
+
7
+ from .._types import PARENT_OF_EDGE
8
+
9
+
10
+ def containing_file_id(storage: Storage, node_id: str) -> str | None:
11
+ """Find the File node above a node by following PARENT_OF edges upward.
12
+
13
+ Containment is the only source: a node ID carries no file identity for a
14
+ node a caller created or moved. Other edge types are not followed.
15
+
16
+ Args:
17
+ storage: Graph store holding the node.
18
+ node_id: ID of a node in ``storage``.
19
+
20
+ Returns:
21
+ The ID of the nearest File ancestor, or None when the node is a File
22
+ node, the project root or detached from every file.
23
+ """
24
+ parent_id: str
25
+ visited = {node_id}
26
+ pending = [node_id]
27
+ while pending:
28
+ current = pending.pop()
29
+ for parent_id, _, edge_type in storage.in_edges(current):
30
+ if edge_type != PARENT_OF_EDGE or parent_id in visited:
31
+ continue
32
+ visited.add(parent_id)
33
+ if storage.get_node_prop(parent_id, "nodeType") == "File":
34
+ return parent_id
35
+ pending.append(parent_id)
36
+ return None
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Any
6
6
 
7
- from cpg2py import AbcEdgeQuerier, Storage
7
+ from cpg2py import AbcEdgeQuerier, EdgeNotFoundError, Storage
8
8
 
9
9
  from .._types import PARENT_OF_EDGE
10
10
 
@@ -47,13 +47,19 @@ class Edge(AbcEdgeQuerier):
47
47
  return self._edge_id[2]
48
48
 
49
49
  @property
50
- def all_properties(self) -> dict[str, Any]:
50
+ def properties(self) -> dict[str, Any]:
51
51
  """Return all edge properties.
52
52
 
53
53
  Returns:
54
54
  Dictionary of edge properties.
55
+
56
+ Raises:
57
+ EdgeNotFoundError: If the edge was removed from its graph.
55
58
  """
56
- return self._storage.get_edge_props(self._edge_id) or {}
59
+ props: dict[str, Any] | None = super().properties
60
+ if props is None:
61
+ raise EdgeNotFoundError(*self._edge_id)
62
+ return props
57
63
 
58
64
  # Dict-like access methods
59
65
 
@@ -71,7 +77,7 @@ class Edge(AbcEdgeQuerier):
71
77
  Raises:
72
78
  KeyError: If property doesn't exist.
73
79
  """
74
- props = self.all_properties
80
+ props = self.properties
75
81
  if key not in props:
76
82
  raise KeyError(f"Property '{key}' not found in edge {self._edge_id}")
77
83
  return props[key]
@@ -87,7 +93,7 @@ class Edge(AbcEdgeQuerier):
87
93
  Returns:
88
94
  True if property exists, False otherwise.
89
95
  """
90
- return key in self.all_properties
96
+ return key in self.properties
91
97
 
92
98
  def get(self, key: str, default: Any = None) -> Any:
93
99
  """Get property value with default fallback.
@@ -99,4 +105,4 @@ class Edge(AbcEdgeQuerier):
99
105
  Returns:
100
106
  Property value or default.
101
107
  """
102
- return self.all_properties.get(key, default)
108
+ return self.properties.get(key, default)
@@ -81,13 +81,6 @@ class Modifier:
81
81
  """
82
82
  if not self._storage.contains_node(node_id):
83
83
  raise KeyError(f"Node not found: {node_id!r}")
84
- # Storage.remove_node drops only the removed node's adjacency list;
85
- # remove_edge is the only API that also cleans the other endpoint.
86
- incident = dict.fromkeys(
87
- (*self._storage.in_edges(node_id), *self._storage.out_edges(node_id))
88
- )
89
- for edge_id in incident:
90
- self._storage.remove_edge(edge_id)
91
84
  self._storage.remove_node(node_id)
92
85
 
93
86
  # -- Edge Operations --
@@ -4,10 +4,10 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Any
6
6
 
7
- from cpg2py import AbcNodeQuerier, Storage
7
+ from cpg2py import AbcNodeQuerier, NodeNotFoundError, Storage
8
8
 
9
9
  from .._bookkeeping import attribute_update
10
- from ._node_id import NodeId
10
+ from ._containment import containing_file_id
11
11
 
12
12
 
13
13
  class Node(AbcNodeQuerier):
@@ -60,13 +60,13 @@ class Node(AbcNodeQuerier):
60
60
  Returns:
61
61
  Node type string.
62
62
  """
63
- value = self.get_property("nodeType")
63
+ value = self.get("nodeType")
64
64
  if isinstance(value, str):
65
65
  return value
66
66
  raise TypeError(f"Invalid nodeType for node {self._nid}: {value!r}")
67
67
 
68
68
  @property
69
- def all_properties(self) -> dict[str, Any]:
69
+ def properties(self) -> dict[str, Any]:
70
70
  """Return all stored properties for this node.
71
71
 
72
72
  Includes scalar fields, flattened attributes and bookkeeping
@@ -74,8 +74,14 @@ class Node(AbcNodeQuerier):
74
74
 
75
75
  Returns:
76
76
  Dictionary of the node's stored properties.
77
+
78
+ Raises:
79
+ NodeNotFoundError: If the node was removed from its graph.
77
80
  """
78
- return self.properties or {}
81
+ props: dict[str, Any] | None = super().properties
82
+ if props is None:
83
+ raise NodeNotFoundError(self._nid)
84
+ return props
79
85
 
80
86
  # Attribute writes
81
87
 
@@ -97,7 +103,7 @@ class Node(AbcNodeQuerier):
97
103
  name, the printer-set ``__format_wrap_parens`` marker, or
98
104
  the name of a scalar field of this node.
99
105
  """
100
- self.set_properties(attribute_update(self.all_properties, key, value))
106
+ self.set_properties(attribute_update(self.properties, key, value))
101
107
 
102
108
  # Dict-like access methods
103
109
 
@@ -115,7 +121,7 @@ class Node(AbcNodeQuerier):
115
121
  Raises:
116
122
  KeyError: If property doesn't exist.
117
123
  """
118
- props = self.all_properties
124
+ props = self.properties
119
125
  if key not in props:
120
126
  raise KeyError(f"Property '{key}' not found in node {self._nid}")
121
127
  return props[key]
@@ -131,7 +137,7 @@ class Node(AbcNodeQuerier):
131
137
  Returns:
132
138
  True if property exists, False otherwise.
133
139
  """
134
- return key in self.all_properties
140
+ return key in self.properties
135
141
 
136
142
  def get(self, key: str, default: Any = None) -> Any:
137
143
  """Get property value with default fallback.
@@ -143,7 +149,7 @@ class Node(AbcNodeQuerier):
143
149
  Returns:
144
150
  Property value or default.
145
151
  """
146
- return self.all_properties.get(key, default)
152
+ return self.properties.get(key, default)
147
153
 
148
154
  # PHP-Parser standard attributes (metadata properties)
149
155
 
@@ -160,7 +166,7 @@ class Node(AbcNodeQuerier):
160
166
  TypeError: If property is not an int or an ASCII integer
161
167
  string (optional leading ``-``).
162
168
  """
163
- value = self.get_property(name)
169
+ value = self.get(name)
164
170
  # bool is an int subtype but never a valid position value.
165
171
  if isinstance(value, int) and not isinstance(value, bool):
166
172
  return value
@@ -209,7 +215,7 @@ class Node(AbcNodeQuerier):
209
215
  Returns:
210
216
  List of PHP-Parser Comment JSON objects (may be empty).
211
217
  """
212
- props = self.all_properties
218
+ props = self.properties
213
219
  if "comments" not in props:
214
220
  # PHP-Parser omits the attribute when a node has no comments.
215
221
  return []
@@ -244,35 +250,12 @@ class Node(AbcNodeQuerier):
244
250
 
245
251
  def _path_property(self, prop_name: str) -> str | None:
246
252
  # File and Project nodes carry the path themselves; every other
247
- # node resolves it from its containing file via ID prefix convention.
248
- if self.node_type in ("File", "Project"):
249
- value = self.get_property(prop_name)
250
- return value if isinstance(value, str) else None
251
- return self._get_file_property(prop_name)
252
-
253
- def _get_file_property(self, prop_name: str) -> str | None:
254
- """Get a path property from the containing file node via ID prefix convention.
255
-
256
- Node IDs follow the pattern: file_hash_1, file_hash_2, etc.
257
- This method extracts the file_hash prefix and retrieves the property from that file node.
258
-
259
- Args:
260
- prop_name: Property name to retrieve ("relativePath" or "absolutePath").
261
-
262
- Returns:
263
- Property value from the file node, or None if not found.
264
- """
265
- parsed = NodeId.parse(self._nid)
266
- if parsed is None or not parsed.file_hash:
267
- return None
268
-
269
- file_id = parsed.file_hash
270
- if not self._storage.contains_node(file_id):
271
- return None
272
-
273
- file_props = self._storage.get_node_props(file_id)
274
- if not file_props or file_props.get("nodeType") != "File":
275
- return None
276
-
277
- value = file_props.get(prop_name)
253
+ # node reads it from the File node above it.
254
+ owner = self._nid
255
+ if self.node_type not in ("File", "Project"):
256
+ file_id = containing_file_id(self._storage, self._nid)
257
+ if file_id is None:
258
+ return None
259
+ owner = file_id
260
+ value = self._storage.get_node_prop(owner, prop_name)
278
261
  return value if isinstance(value, str) else None
@@ -9,8 +9,8 @@ from dataclasses import dataclass
9
9
  class NodeId:
10
10
  """Encapsulates the ``{file_hash}_{counter}`` node-ID scheme.
11
11
 
12
- Single home for the ID convention used both when allocating IDs during
13
- mapping and when parsing IDs back into file scope.
12
+ Single home for the ID convention used when allocating IDs during
13
+ mapping.
14
14
 
15
15
  Attributes:
16
16
  file_hash: File-scope prefix; empty string for code-only parsing.
@@ -31,26 +31,3 @@ class NodeId:
31
31
  if self.file_hash:
32
32
  return f"{self.file_hash}_{self.counter}"
33
33
  return f"node_{self.counter}"
34
-
35
- @classmethod
36
- def parse(cls, node_id: str) -> NodeId | None:
37
- """Split a stored ID into its prefix and counter.
38
-
39
- Inverse of :pyattr:`value`. Splits at the last underscore.
40
-
41
- Args:
42
- node_id: Node ID string.
43
-
44
- Returns:
45
- NodeId when the ID matches ``{prefix}_{digits}``; None otherwise.
46
- """
47
- last_underscore = node_id.rfind("_")
48
- if last_underscore == -1:
49
- return None
50
- counter = node_id[last_underscore + 1 :]
51
- if not counter.isdigit():
52
- return None
53
- prefix = node_id[:last_underscore]
54
- if prefix == "node":
55
- return cls("", int(counter))
56
- return cls(prefix, int(counter))
@@ -53,9 +53,13 @@ def build(
53
53
  under a synthetic code root (``Parser.parse_code`` projects it).
54
54
 
55
55
  Raises:
56
- ValueError: From ``Modifier.add_node`` on a duplicate ID, or when a
56
+ ValueError: From ``Modifier.add_node`` on a duplicate ID; when a
57
57
  node's attribute key equals its ``nodeType`` or a scalar field,
58
- or a node key uses a bookkeeping property name.
58
+ or a node key uses a bookkeeping property name; when a tree
59
+ item or child is not a node object with a string ``nodeType``;
60
+ when a file lies outside the project root;
61
+ when a file statement lacks the end-position attributes
62
+ PHP-Parser always emits.
59
63
  """
60
64
  builder = _Builder(target_php)
61
65
  if layout.project_path is None:
@@ -122,7 +126,7 @@ class _Builder:
122
126
  record.file_hash,
123
127
  "File",
124
128
  absolutePath=str(record.path),
125
- relativePath=_relative_path(record.path, project_path),
129
+ relativePath=str(record.path.relative_to(project_path)),
126
130
  startLine=1,
127
131
  startFilePos=0,
128
132
  startTokenPos=0,
@@ -150,13 +154,10 @@ class _Builder:
150
154
  ]
151
155
  while stack:
152
156
  data, current_slot, parent = stack.pop()
153
- if not isinstance(data, dict) or "nodeType" not in data:
154
- continue
157
+ node = _require_node(data)
155
158
  node_id = self._allocate_id()
156
- properties, child_fields = self._split_fields(data)
157
- node_type = properties.pop("nodeType")
158
- if not isinstance(node_type, str):
159
- continue
159
+ properties, child_fields = self._split_fields(node)
160
+ node_type = str(properties.pop("nodeType"))
160
161
  modifier.add_node(node_id, node_type, **properties)
161
162
  if parent is not None and current_slot is not None:
162
163
  self._link_child(modifier, parent, node_id, current_slot)
@@ -201,13 +202,14 @@ class _Builder:
201
202
  # Compute the file node's end positions from statement attributes.
202
203
  ends = dict(_FILE_END_DEFAULTS)
203
204
  for stmt in stmts:
204
- attrs = stmt.get("attributes", {})
205
- if not isinstance(attrs, dict):
206
- continue
207
- for key, current in list(ends.items()):
208
- val = attrs.get(key)
209
- if isinstance(val, int) and val > current:
210
- ends[key] = val
205
+ attrs = stmt.get("attributes")
206
+ if not isinstance(attrs, dict) or not ends.keys() <= attrs.keys():
207
+ raise ValueError(
208
+ f"Statement lacks the position attributes {sorted(ends)}: "
209
+ f"{stmt.get('nodeType')!r}."
210
+ )
211
+ for key, current in ends.items():
212
+ ends[key] = max(current, attrs[key])
211
213
  return ends
212
214
 
213
215
  def _reset_scope(self, prefix: str) -> None:
@@ -222,28 +224,32 @@ class _Builder:
222
224
  return node_id.value
223
225
 
224
226
 
227
+ def _require_node(data: object) -> dict[str, object]:
228
+ # A work item is a node object whose nodeType names its type.
229
+ if not isinstance(data, dict) or not isinstance(data.get("nodeType"), str):
230
+ raise ValueError(
231
+ f"Expected a node object with a string nodeType, got {data!r}."
232
+ )
233
+ return data
234
+
235
+
225
236
  def _child_work(
226
237
  child_fields: list[tuple[str, object]], parent_id: str
227
238
  ) -> list[tuple[object, EdgeSlot, str]]:
228
239
  # Expand classified child fields into (data, slot, parent) work items.
240
+ # A null child has no node: its list slot is kept by the recorded list
241
+ # length, its single slot by the absent edge.
229
242
  items: list[tuple[object, EdgeSlot, str]] = []
230
243
  for field_name, value in child_fields:
231
244
  if isinstance(value, list):
232
245
  for idx, item in enumerate(value):
233
- items.append((item, EdgeSlot(field_name, idx), parent_id))
234
- else:
246
+ if item is not None:
247
+ items.append((item, EdgeSlot(field_name, idx), parent_id))
248
+ elif value is not None:
235
249
  items.append((value, EdgeSlot(field_name), parent_id))
236
250
  return items
237
251
 
238
252
 
239
- def _relative_path(file_path: Path, project_path: Path) -> str:
240
- # Path of file relative to project, falling back to the file name.
241
- try:
242
- return str(file_path.relative_to(project_path))
243
- except ValueError:
244
- return file_path.name
245
-
246
-
247
253
  def _require_distinct_keys(node_data: dict[str, object]) -> None:
248
254
  # Scalar fields, flattened attributes and bookkeeping share one property
249
255
  # namespace; a name two of them would write cannot be stored losslessly.
@@ -10,7 +10,7 @@ from __future__ import annotations
10
10
  from dataclasses import dataclass
11
11
 
12
12
  from .._bookkeeping import declared_fields
13
- from .._node_fields import CHILD, SCALAR
13
+ from .._node_fields import CHILD, LIST, SCALAR
14
14
 
15
15
  PROJECT_SENTINEL_POSITIONS: dict[str, int] = {
16
16
  "startLine": -1,
@@ -54,7 +54,7 @@ def _classify_field(node_type: object, key: str, value: object) -> bool:
54
54
 
55
55
  Applied by ``build`` during construction; ``serialize`` reads the
56
56
  stored result and never calls it. The kind the node type declares
57
- decides: a ``CHILD`` field is a child field whatever it
57
+ decides: a ``CHILD`` or ``LIST`` field is a child field whatever it
58
58
  stores (null, an empty list and an all-null list included), a
59
59
  ``SCALAR`` field is not. Only a field declared as either a scalar or a
60
60
  node, and a name the type does not declare (a custom node type), take
@@ -73,6 +73,6 @@ def _classify_field(node_type: object, key: str, value: object) -> bool:
73
73
  if key == "attributes":
74
74
  return False
75
75
  kind = declared_fields(node_type).get(key)
76
- if kind in (CHILD, SCALAR):
77
- return kind == CHILD
76
+ if kind in (CHILD, LIST, SCALAR):
77
+ return kind != SCALAR
78
78
  return _holds_node(value)
@@ -2,7 +2,9 @@
2
2
 
3
3
  A child field never occupies a stored property, so an absent edge is the
4
4
  only trace of a null child, and ``pppyListLengths`` the only trace of an
5
- empty list. Export reads the node type's declared kinds to put both back.
5
+ empty list. Export reads the node type's declared kinds to put both back: a
6
+ field declared as a list that cannot be null is an empty list when nothing
7
+ records otherwise.
6
8
  """
7
9
 
8
10
  from __future__ import annotations
@@ -10,7 +12,7 @@ from __future__ import annotations
10
12
  from typing import Any
11
13
 
12
14
  from .._bookkeeping import declared_fields
13
- from .._node_fields import CHILD
15
+ from .._node_fields import CHILD, LIST
14
16
 
15
17
  _LEADING_KEYS = ("nodeType", "attributes")
16
18
 
@@ -20,7 +22,9 @@ def complete_declared_fields(
20
22
  ) -> None:
21
23
  """Add every declared child field the edges left out, in declared order.
22
24
 
23
- A child field with no edge was null, or a list of the recorded length.
25
+ A child field with no edge was a list of the recorded length when its
26
+ length is recorded, else an empty list when it is declared as a list
27
+ that cannot be null, else null.
24
28
  The result is reordered in place: ``nodeType``, ``attributes``, the
25
29
  declared fields in table order, then any other key.
26
30
 
@@ -31,9 +35,12 @@ def complete_declared_fields(
31
35
  """
32
36
  declared = declared_fields(node_type)
33
37
  for field, kind in declared.items():
34
- if kind == CHILD and field not in result:
38
+ if kind in (CHILD, LIST) and field not in result:
35
39
  length = lengths.get(field)
36
- result[field] = None if length is None else [None] * length
40
+ if length is not None:
41
+ result[field] = [None] * length
42
+ else:
43
+ result[field] = [] if kind == LIST else None
37
44
  ordered = {key: result[key] for key in _LEADING_KEYS}
38
45
  ordered.update((field, result[field]) for field in declared if field in result)
39
46
  ordered.update(result)