php-parser-py 2.0.3__py3-none-win_amd64.whl → 3.0.1__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 (33) hide show
  1. php_parser_py/__init__.py +4 -8
  2. php_parser_py/_bookkeeping.py +107 -0
  3. php_parser_py/_graph/_ast.py +115 -73
  4. php_parser_py/_graph/_containment.py +36 -0
  5. php_parser_py/_graph/_edge.py +12 -6
  6. php_parser_py/_graph/_modifier.py +15 -8
  7. php_parser_py/_graph/_node.py +56 -51
  8. php_parser_py/_graph/_node_id.py +2 -25
  9. php_parser_py/_mapping/__init__.py +5 -4
  10. php_parser_py/_mapping/_build.py +99 -40
  11. php_parser_py/_mapping/_contract.py +35 -28
  12. php_parser_py/_mapping/_declared.py +48 -0
  13. php_parser_py/_mapping/_serialize.py +90 -49
  14. php_parser_py/_node_fields.py +209 -0
  15. php_parser_py/_parser.py +25 -113
  16. php_parser_py/_printer.py +60 -27
  17. php_parser_py/_resources/ExtendedPrinter.php +96 -27
  18. php_parser_py/_resources/parse.php +45 -9
  19. php_parser_py/_resources/print.php +13 -10
  20. php_parser_py/_runtime/_binary.py +3 -1
  21. php_parser_py/_runtime/_bundle.py +96 -18
  22. php_parser_py/_runtime/_runner.py +53 -58
  23. php_parser_py/_types.py +58 -8
  24. php_parser_py/_version.py +9 -16
  25. php_parser_py-3.0.1.dist-info/METADATA +91 -0
  26. php_parser_py-3.0.1.dist-info/RECORD +39 -0
  27. php_parser_py-2.0.3.dist-info/METADATA +0 -106
  28. php_parser_py-2.0.3.dist-info/RECORD +0 -35
  29. {php_parser_py-2.0.3.dist-info → php_parser_py-3.0.1.dist-info}/WHEEL +0 -0
  30. {php_parser_py-2.0.3.dist-info → php_parser_py-3.0.1.dist-info}/licenses/LICENSE +0 -0
  31. {php_parser_py-2.0.3.dist-info → php_parser_py-3.0.1.dist-info}/licenses/PHP-LICENSE +0 -0
  32. {php_parser_py-2.0.3.dist-info → php_parser_py-3.0.1.dist-info}/licenses/PHP-Parser-LICENSE +0 -0
  33. {php_parser_py-2.0.3.dist-info → php_parser_py-3.0.1.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",
@@ -16,6 +13,8 @@ __all__ = [
16
13
  "Node",
17
14
  "Parser",
18
15
  "PHPVersion",
16
+ "ParseProvenance",
17
+ "SkippedFile",
19
18
  "Printer",
20
19
  "StandardPrinter",
21
20
  "ExtendedPrinter",
@@ -24,14 +23,11 @@ __all__ = [
24
23
  "ParseError",
25
24
  "RunnerError",
26
25
  "NodeNotInFileError",
27
- "parse_code",
28
- "parse_file",
29
- "parse_project",
30
26
  ]
31
27
 
32
28
  from ._exceptions import NodeNotInFileError, ParseError, RunnerError
33
29
  from ._graph import AST, Edge, Modifier, Node
34
- from ._parser import Parser, parse_code, parse_file, parse_project
30
+ from ._parser import Parser
35
31
  from ._printer import ExtendedPrinter, Printer, StandardPrinter
36
- from ._types import PrintMode, PrintRequest
32
+ from ._types import ParseProvenance, PrintMode, PrintRequest, SkippedFile
37
33
  from ._version import PHPVersion
@@ -0,0 +1,107 @@
1
+ """Stored-property rules shared by the graph and mapping layers.
2
+
3
+ Names of the bookkeeping properties build writes and serialize consumes,
4
+ the printer-set format marker, the declaration default serialize
5
+ supplies, and the attribute-name rule that reads the declared field kinds
6
+ of ``_node_fields``; ``Node`` and the mapping package apply one definition
7
+ of each.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping
13
+ from typing import Any
14
+
15
+ from ._node_fields import EITHER, NODE_FIELDS, SCALAR
16
+
17
+ # Graph property recording the key list of a node's flattened attributes
18
+ # bundle. build absorbs attributes into plain properties; serialize needs
19
+ # the recorded keys to re-file exactly those properties back into the
20
+ # attributes dict — a fixed whitelist would misfile any attribute
21
+ # PHP-Parser adds (docLabel, rawValue, ...) as a top-level node field.
22
+ # Written by build and ``Node.set_attribute``, consumed and omitted by
23
+ # serialize.
24
+ ATTRIBUTE_KEYS_PROPERTY = "pppyAttributeKeys"
25
+
26
+ # Graph property recording {field name: full list length} for child list
27
+ # fields ending in null (e.g. list($a, ,) destructuring skips). Trailing
28
+ # nulls carry no child edge, so serialize needs the recorded length to
29
+ # rebuild them. Written by build, consumed and omitted by serialize.
30
+ LIST_LENGTHS_PROPERTY = "pppyListLengths"
31
+
32
+ # Property names the mapping writes for its own records; no JSON key and
33
+ # no caller attribute may use them.
34
+ BOOKKEEPING_PROPERTIES = frozenset({ATTRIBUTE_KEYS_PROPERTY, LIST_LENGTHS_PROPERTY})
35
+
36
+ # Format marker the printer overrides set during the PHP walk; callers do
37
+ # not supply it.
38
+ FORMAT_WRAP_PARENS = "__format_wrap_parens"
39
+
40
+
41
+ def declared_fields(node_type: object) -> Mapping[str, str]:
42
+ """The fields a node type declares in the bundled PHP-Parser, with kinds.
43
+
44
+ Args:
45
+ node_type: A node's JSON ``nodeType``.
46
+
47
+ Returns:
48
+ Field name to ``CHILD``, ``LIST``, ``SCALAR`` or ``EITHER`` in
49
+ declaration order; empty for a type the bundled PHP-Parser does not declare.
50
+ """
51
+ return NODE_FIELDS.get(node_type, {}) if isinstance(node_type, str) else {}
52
+
53
+
54
+ def _is_scalar_field(props: Mapping[str, Any], key: str, recorded: list[str]) -> bool:
55
+ """Whether ``key`` names a scalar field of the node, by its declared kind.
56
+
57
+ The declared kind comes from the bundled PHP-Parser node class of the
58
+ node's type. A field declared as a node, a nullable node or a node list
59
+ is a child field whatever it holds: its empty form is an absent edge
60
+ and a recorded list length, never a stored property. A field declared as
61
+ either a scalar or a node is a scalar field only while a scalar is
62
+ stored under its name. A name the type does not declare is no field.
63
+
64
+ Args:
65
+ props: The node's stored properties.
66
+ key: Attribute name.
67
+ recorded: The node's attribute-key record.
68
+
69
+ Returns:
70
+ True when writing an attribute under ``key`` would replace a scalar
71
+ field.
72
+ """
73
+ kind = declared_fields(props.get("nodeType")).get(key)
74
+ if kind == EITHER:
75
+ return key in props and key not in recorded
76
+ return kind == SCALAR
77
+
78
+
79
+ def attribute_update(props: Mapping[str, Any], key: str, value: Any) -> dict[str, Any]:
80
+ """Properties to write so ``key`` becomes an attribute of a stored node.
81
+
82
+ Args:
83
+ props: The node's stored properties.
84
+ key: Attribute name.
85
+ value: Attribute value.
86
+
87
+ Returns:
88
+ The value under ``key`` and, when ``key`` is new, the extended
89
+ attribute-key record.
90
+
91
+ Raises:
92
+ ValueError: If ``key`` is ``nodeType``, a bookkeeping name, the
93
+ printer-set wrap-parens marker, or a field of the node's type
94
+ declared as a scalar. A child field's name is a valid
95
+ attribute name.
96
+ """
97
+ recorded: list[str] = list(props.get(ATTRIBUTE_KEYS_PROPERTY, []))
98
+ if key == "nodeType" or key in BOOKKEEPING_PROPERTIES:
99
+ raise ValueError(f"{key!r} is not an attribute name.")
100
+ if key == FORMAT_WRAP_PARENS:
101
+ raise ValueError(f"{key!r} is set by the printer; callers do not supply it.")
102
+ if _is_scalar_field(props, key, recorded):
103
+ raise ValueError(f"{key!r} is already a scalar field of the node.")
104
+ update: dict[str, Any] = {key: value}
105
+ if key not in recorded:
106
+ update[ATTRIBUTE_KEYS_PROPERTY] = [*recorded, key]
107
+ return update
@@ -3,15 +3,16 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import copy
6
+ from collections.abc import Collection, Iterable
6
7
 
7
8
  from cpg2py import AbcGraphQuerier, Storage
8
9
 
9
10
  from .._exceptions import NodeNotInFileError
10
- from .._types import PARENT_OF_EDGE, PROJECT_ROOT_ID
11
+ from .._types import PARENT_OF_EDGE, PROJECT_ROOT_ID, ParseProvenance, SkippedFile
11
12
  from .._version import PHPVersion
13
+ from ._containment import containing_file_id
12
14
  from ._edge import Edge
13
15
  from ._node import Node
14
- from ._node_id import NodeId
15
16
 
16
17
 
17
18
  class AST(AbcGraphQuerier[Node, Edge]):
@@ -19,40 +20,49 @@ class AST(AbcGraphQuerier[Node, Edge]):
19
20
 
20
21
  Extends cpg2py's AbcGraphQuerier with Node and Edge type parameters.
21
22
  Query-only: traversal, node/edge lookup, and file resolution. JSON
22
- reconstruction lives in ``Mapping.serialize``.
23
+ reconstruction lives in the mapping package's ``serialize``.
23
24
 
24
- The AST structure follows a hierarchy:
25
- - Project node (ID: "project") - root of the AST
26
- - File nodes (ID: hex hash) - children of project
27
- - Statement nodes (ID: {hex}_{counter}) - children of files
25
+ A file or project parse is organized as Project -> File -> statement
26
+ nodes; the internal code-only graph roots its statements at a synthetic
27
+ code root instead. Node IDs follow the graph model's identity rules.
28
28
 
29
29
  Uses the cpg2py graph API (nodes, edges, succ, prev, ancestors,
30
30
  descendants); storage is only used for node/edge existence and Node/Edge
31
31
  construction.
32
32
 
33
33
  Attributes:
34
- _root_node_id: ID of the root project node (always "project").
35
- _target_php: Target PHP version the parser parsed the source under;
36
- None when no parser produced this graph.
34
+ _root_node_id: ID of the root node: "project", or the code root ID
35
+ of a code-only graph.
36
+ _provenance: Target and skipped files of the parse that produced
37
+ the graph; None when the provenance is unknown.
37
38
  """
38
39
 
39
40
  def __init__(
40
41
  self,
41
42
  storage: Storage,
42
43
  root_node_id: str = PROJECT_ROOT_ID,
43
- target_php: PHPVersion | None = None,
44
+ provenance: ParseProvenance | None = None,
44
45
  ) -> None:
45
46
  """Initialize AST with populated storage.
46
47
 
47
48
  Args:
48
49
  storage: cpg2py Storage containing AST nodes and edges.
49
50
  root_node_id: ID of the root node. Defaults to "project".
50
- target_php: Target PHP version of the parse that produced the
51
- graph. Default None marks the provenance unknown.
51
+ provenance: Parse provenance of the graph. Default None marks
52
+ the provenance unknown.
53
+
54
+ Raises:
55
+ TypeError: If ``provenance`` is neither None nor a
56
+ ``ParseProvenance``.
52
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
+ )
53
63
  super().__init__(storage)
54
64
  self._root_node_id = root_node_id
55
- self._target_php = target_php
65
+ self._provenance = provenance
56
66
 
57
67
  @property
58
68
  def storage(self) -> Storage:
@@ -84,41 +94,107 @@ class AST(AbcGraphQuerier[Node, Edge]):
84
94
  """Return the target PHP version the source was parsed under.
85
95
 
86
96
  Parse provenance, not a PHP node field: serialization and printing
87
- never emit it as part of the PHP-Parser JSON. Always known on a graph
88
- a parser produced; None on a graph built without a parse.
97
+ never emit it as part of the PHP-Parser JSON. Known on a graph that a
98
+ parser or mapping build produced; a manually constructed graph may
99
+ supply a target or leave it None (unknown).
100
+ """
101
+ if self._provenance is None:
102
+ return None
103
+ return self._provenance.target_php
104
+
105
+ @property
106
+ def skipped_files(self) -> tuple[SkippedFile, ...]:
107
+ """Return the project files the parse left out, in path order.
108
+
109
+ Parse provenance, like ``target_php``: each file a project parse
110
+ could not read, decode or parse, with its failure message. Empty
111
+ for a file or code parse and for unknown provenance.
89
112
  """
90
- return self._target_php
113
+ if self._provenance is None:
114
+ return ()
115
+ return self._provenance.skipped_files
91
116
 
92
- def copy(self) -> AST:
93
- """Return a new AST backed by a deep copy of this graph.
117
+ def copy(self, files: Collection[str] | None = None) -> AST:
118
+ """Return a new AST backed by a deep copy of this graph or of some files.
94
119
 
95
- Node IDs, the edge set, and all node/edge properties are duplicated
120
+ Node IDs, edges, and all node/edge properties are duplicated
96
121
  verbatim, preserving the ``{file_hash}_{counter}`` ID namespace, the
97
- root node ID and the target PHP version. The returned AST shares no
122
+ root node ID and the parse provenance. The returned AST shares no
98
123
  mutable state with this one: mutating either graph leaves the other
99
124
  unchanged.
100
125
 
126
+ With ``files``, the copy holds only the root node, the named File
127
+ nodes and every node they reach through ``PARENT_OF`` edges, with the
128
+ edges whose both endpoints it holds. Each held node keeps the order
129
+ of its outgoing edges.
130
+
131
+ Args:
132
+ files: File node IDs to copy, or None to copy the whole graph.
133
+
101
134
  Returns:
102
- A new AST whose storage is an independent copy of this graph.
135
+ A new AST whose storage is an independent copy.
136
+
137
+ Raises:
138
+ KeyError: If an ID in ``files`` names no node.
139
+ ValueError: If an ID in ``files`` names a node that is not a File.
103
140
  """
104
141
  storage = Storage()
105
- self._copy_nodes_into(storage)
106
- self._copy_edges_into(storage)
142
+ if files is None:
143
+ self._copy_nodes_into(storage, self._graph.get_nodes())
144
+ self._copy_edges_into(storage, self._graph.get_edges())
145
+ else:
146
+ held = self._file_closure(files)
147
+ node_ids = [nid for nid in self._graph.get_nodes() if nid in held]
148
+ self._copy_nodes_into(storage, node_ids)
149
+ self._copy_edges_into(
150
+ storage,
151
+ (
152
+ edge_id
153
+ for nid in node_ids
154
+ for edge_id in self._graph.out_edges(nid)
155
+ if edge_id[1] in held
156
+ ),
157
+ )
107
158
  return AST(
108
- storage, root_node_id=self._root_node_id, target_php=self._target_php
159
+ storage, root_node_id=self._root_node_id, provenance=self._provenance
109
160
  )
110
161
 
111
- def _copy_nodes_into(self, storage: Storage) -> None:
112
- """Duplicate every node and its properties into ``storage``."""
113
- for node_id in self._graph.get_nodes():
162
+ def _file_closure(self, files: Collection[str]) -> set[str]:
163
+ """Return the root ID, the File IDs and their PARENT_OF descendants."""
164
+ held = {self._root_node_id}
165
+ pending: list[str] = []
166
+ for file_id in files:
167
+ if not self._graph.contains_node(file_id):
168
+ raise KeyError(f"Node not found: {file_id!r}")
169
+ node_type = (self._graph.get_node_props(file_id) or {}).get("nodeType")
170
+ if node_type != "File":
171
+ raise ValueError(f"Not a File node: {file_id!r} is {node_type!r}")
172
+ pending.append(file_id)
173
+ while pending:
174
+ node_id = pending.pop()
175
+ if node_id in held:
176
+ continue
177
+ held.add(node_id)
178
+ pending.extend(
179
+ edge_id[1]
180
+ for edge_id in self._graph.out_edges(node_id)
181
+ if edge_id[2] == PARENT_OF_EDGE
182
+ )
183
+ return held
184
+
185
+ def _copy_nodes_into(self, storage: Storage, node_ids: Iterable[str]) -> None:
186
+ """Duplicate the given nodes and their properties into ``storage``."""
187
+ for node_id in node_ids:
114
188
  storage.add_node(node_id)
115
189
  props = self._graph.get_node_props(node_id)
116
190
  if props:
117
191
  storage.set_node_props(node_id, copy.deepcopy(props))
118
192
 
119
- def _copy_edges_into(self, storage: Storage) -> None:
120
- """Duplicate every edge and its properties into ``storage``."""
121
- for edge_id in self._graph.get_edges():
193
+ def _copy_edges_into(
194
+ self, storage: Storage, edge_ids: Iterable[tuple[str, str, str]]
195
+ ) -> None:
196
+ """Duplicate the given edges and their properties into ``storage``."""
197
+ for edge_id in edge_ids:
122
198
  storage.add_edge(edge_id)
123
199
  props = self._graph.get_edge_props(edge_id)
124
200
  if props:
@@ -163,7 +239,7 @@ class AST(AbcGraphQuerier[Node, Edge]):
163
239
  """Return the project node (root of the AST).
164
240
 
165
241
  The project node has ID "project" and is always present when the AST
166
- was created by parse_file or parse_project.
242
+ was created by ``Parser.parse_file`` or ``Parser.parse_project``.
167
243
 
168
244
  Returns:
169
245
  Project Node instance.
@@ -195,15 +271,14 @@ class AST(AbcGraphQuerier[Node, Edge]):
195
271
  def get_file_node(self, node_id: str) -> Node:
196
272
  """Get the file node that contains the given node.
197
273
 
198
- Uses the AST ID convention: file node ID is the file hash (e.g. 8-char hex);
199
- nodes inside that file have ID ``file_hash + "_" + increment`` (e.g. ``a1b2c3d4_1``).
200
- Resolves by structure first, then falls back to ancestors() traversal.
274
+ Follows PARENT_OF edges upward to the nearest File node.
201
275
 
202
276
  Args:
203
277
  node_id: ID of any node in the AST.
204
278
 
205
279
  Returns:
206
- 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.
207
282
 
208
283
  Raises:
209
284
  KeyError: If the node ID is not in the graph.
@@ -212,40 +287,7 @@ class AST(AbcGraphQuerier[Node, Edge]):
212
287
  node = self.node(node_id)
213
288
  if node.node_type == "File":
214
289
  return node
215
-
216
- if node_id == self._root_node_id:
217
- raise NodeNotInFileError(node_id, "Project node has no containing file.")
218
-
219
- result = self._try_file_by_id_prefix(node_id)
220
- if result is not None:
221
- return result
222
-
223
- return self._find_file_ancestor(node)
224
-
225
- def _try_file_by_id_prefix(self, node_id: str) -> Node | None:
226
- """Try to find the file node via the ``NodeId`` prefix convention.
227
-
228
- Returns None when the ID does not match the convention or the file is
229
- not present.
230
- """
231
- parsed = NodeId.parse(node_id)
232
- if parsed is None or not parsed.file_hash:
233
- return None
234
-
235
- try:
236
- candidate = self.node(parsed.file_hash)
237
- except KeyError:
238
- return None
239
- return candidate if candidate.node_type == "File" else None
240
-
241
- def _find_file_ancestor(self, node: Node) -> Node:
242
- """Find first File ancestor of a node via traversal.
243
-
244
- Raises NodeNotInFileError if no File ancestor exists.
245
- """
246
- for ancestor in self.ancestors(node):
247
- if ancestor.node_type == "File":
248
- result: Node = ancestor
249
- return result
250
-
251
- 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)
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from collections.abc import Collection
6
+
5
7
  from .._types import PARENT_OF_EDGE
6
8
  from ._ast import AST
7
9
  from ._edge import Edge
@@ -9,29 +11,32 @@ from ._node import Node
9
11
 
10
12
 
11
13
  class Modifier:
12
- """Encapsulates all graph mutation operations for an AST.
14
+ """Encapsulates the structural graph mutation operations for an AST.
13
15
 
14
16
  The only approved way to add, remove, or structurally modify nodes and
15
17
  edges in the AST graph. Callers must never use Storage directly.
16
18
 
17
19
  AST (AbcGraphQuerier) is a query interface; graph mutation is a separate
18
20
  concern handled by this class. Mutation is copy-on-write: the constructor
19
- deep-copies the source AST, and every operation writes through the copy.
20
- The source AST is never modified. Callers read mutations via the ``ast``
21
- property, which exposes the modified copy.
21
+ deep-copies the source AST, or only the files it names, and every
22
+ operation writes through the copy. The source AST is never modified.
23
+ Callers read mutations via the ``ast`` property, which exposes the
24
+ modified copy.
22
25
 
23
26
  Attributes:
24
27
  _ast: The modified-copy AST, independent of the source.
25
28
  _storage: The copy's internal Storage that operations write through.
26
29
  """
27
30
 
28
- def __init__(self, ast: AST) -> None:
31
+ def __init__(self, ast: AST, *, files: Collection[str] | None = None) -> None:
29
32
  """Deep-copy an AST so that mutation leaves the source unchanged.
30
33
 
31
34
  Args:
32
35
  ast: Source AST to copy. The instance is never modified.
36
+ files: File node IDs to copy, as ``AST.copy`` takes them; None
37
+ copies the whole AST.
33
38
  """
34
- self._ast = ast.copy()
39
+ self._ast = ast.copy(files=files)
35
40
  self._storage = self._ast._graph
36
41
 
37
42
  @property
@@ -41,13 +46,15 @@ class Modifier:
41
46
 
42
47
  # -- Node Operations --
43
48
 
44
- def add_node(self, node_id: str, node_type: str, **props: object) -> Node:
49
+ def add_node(self, node_id: str, node_type: str, /, **props: object) -> Node:
45
50
  """Create a new node in the graph with the given type and properties.
46
51
 
47
52
  Args:
48
53
  node_id: Unique node ID string.
49
54
  node_type: PHP-Parser node type (e.g. "Stmt_Break").
50
- **props: Additional node properties to set.
55
+ **props: Additional node properties to set. The first two
56
+ parameters are positional-only, so a property may be named
57
+ ``node_id`` or ``node_type``.
51
58
 
52
59
  Returns:
53
60
  Node instance for the newly created node.