php-parser-py 2.0.3__py3-none-win_amd64.whl → 2.1.0__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.
php_parser_py/__init__.py CHANGED
@@ -16,6 +16,8 @@ __all__ = [
16
16
  "Node",
17
17
  "Parser",
18
18
  "PHPVersion",
19
+ "ParseProvenance",
20
+ "SkippedFile",
19
21
  "Printer",
20
22
  "StandardPrinter",
21
23
  "ExtendedPrinter",
@@ -33,5 +35,5 @@ from ._exceptions import NodeNotInFileError, ParseError, RunnerError
33
35
  from ._graph import AST, Edge, Modifier, Node
34
36
  from ._parser import Parser, parse_code, parse_file, parse_project
35
37
  from ._printer import ExtendedPrinter, Printer, StandardPrinter
36
- from ._types import PrintMode, PrintRequest
38
+ from ._types import ParseProvenance, PrintMode, PrintRequest, SkippedFile
37
39
  from ._version import PHPVersion
@@ -0,0 +1,150 @@
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
+ # Name of the child list PHP-Parser's printer requires on declarations.
33
+ ATTR_GROUPS = "attrGroups"
34
+
35
+ # Property names the mapping writes for its own records; no JSON key and
36
+ # no caller attribute may use them.
37
+ BOOKKEEPING_PROPERTIES = frozenset({ATTRIBUTE_KEYS_PROPERTY, LIST_LENGTHS_PROPERTY})
38
+
39
+ # Format marker the printer overrides set during the PHP walk; callers do
40
+ # not supply it.
41
+ FORMAT_WRAP_PARENS = "__format_wrap_parens"
42
+
43
+
44
+ def declared_fields(node_type: object) -> Mapping[str, str]:
45
+ """The fields a node type declares in the bundled PHP-Parser, with kinds.
46
+
47
+ Args:
48
+ node_type: A node's JSON ``nodeType``.
49
+
50
+ Returns:
51
+ Field name to ``CHILD``, ``SCALAR`` or ``EITHER`` in declaration
52
+ order; empty for a type the bundled PHP-Parser does not declare.
53
+ """
54
+ return NODE_FIELDS.get(node_type, {}) if isinstance(node_type, str) else {}
55
+
56
+
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
+ def _is_scalar_field(props: Mapping[str, Any], key: str, recorded: list[str]) -> bool:
70
+ """Whether ``key`` names a scalar field of the node, by its declared kind.
71
+
72
+ The declared kind comes from the bundled PHP-Parser node class of the
73
+ node's type. A field declared as a node, a nullable node or a node list
74
+ is a child field whatever it holds: its empty form is an absent edge
75
+ and a recorded list length, never a stored property. A field declared as
76
+ either a scalar or a node is a scalar field only while a scalar is
77
+ stored under its name. A name the type does not declare is no field.
78
+
79
+ Args:
80
+ props: The node's stored properties.
81
+ key: Attribute name.
82
+ recorded: The node's attribute-key record.
83
+
84
+ Returns:
85
+ True when writing an attribute under ``key`` would replace a scalar
86
+ field.
87
+ """
88
+ kind = declared_fields(props.get("nodeType")).get(key)
89
+ if kind == EITHER:
90
+ return key in props and key not in recorded
91
+ return kind == SCALAR
92
+
93
+
94
+ def attribute_update(props: Mapping[str, Any], key: str, value: Any) -> dict[str, Any]:
95
+ """Properties to write so ``key`` becomes an attribute of a stored node.
96
+
97
+ Args:
98
+ props: The node's stored properties.
99
+ key: Attribute name.
100
+ value: Attribute value.
101
+
102
+ Returns:
103
+ The value under ``key`` and, when ``key`` is new, the extended
104
+ attribute-key record.
105
+
106
+ Raises:
107
+ ValueError: If ``key`` is ``nodeType``, a bookkeeping name, the
108
+ printer-set wrap-parens marker, or a field of the node's type
109
+ declared as a scalar. A child field's name is a valid
110
+ attribute name.
111
+ """
112
+ recorded: list[str] = list(props.get(ATTRIBUTE_KEYS_PROPERTY, []))
113
+ if key == "nodeType" or key in BOOKKEEPING_PROPERTIES:
114
+ raise ValueError(f"{key!r} is not an attribute name.")
115
+ if key == FORMAT_WRAP_PARENS:
116
+ raise ValueError(f"{key!r} is set by the printer; callers do not supply it.")
117
+ if _is_scalar_field(props, key, recorded):
118
+ raise ValueError(f"{key!r} is already a scalar field of the node.")
119
+ update: dict[str, Any] = {key: value}
120
+ if key not in recorded:
121
+ 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
+ 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
+ )
@@ -3,11 +3,12 @@
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
12
13
  from ._edge import Edge
13
14
  from ._node import Node
@@ -19,40 +20,40 @@ 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.
52
53
  """
53
54
  super().__init__(storage)
54
55
  self._root_node_id = root_node_id
55
- self._target_php = target_php
56
+ self._provenance = provenance
56
57
 
57
58
  @property
58
59
  def storage(self) -> Storage:
@@ -84,41 +85,107 @@ class AST(AbcGraphQuerier[Node, Edge]):
84
85
  """Return the target PHP version the source was parsed under.
85
86
 
86
87
  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.
88
+ never emit it as part of the PHP-Parser JSON. Known on a graph that a
89
+ parser or mapping build produced; a manually constructed graph may
90
+ supply a target or leave it None (unknown).
89
91
  """
90
- return self._target_php
92
+ if self._provenance is None:
93
+ return None
94
+ return self._provenance.target_php
95
+
96
+ @property
97
+ def skipped_files(self) -> tuple[SkippedFile, ...]:
98
+ """Return the project files the parse left out, in path order.
91
99
 
92
- def copy(self) -> AST:
93
- """Return a new AST backed by a deep copy of this graph.
100
+ Parse provenance, like ``target_php``: each file a project parse
101
+ could not read, decode or parse, with its failure message. Empty
102
+ for a file or code parse and for unknown provenance.
103
+ """
104
+ if self._provenance is None:
105
+ return ()
106
+ return self._provenance.skipped_files
107
+
108
+ def copy(self, files: Collection[str] | None = None) -> AST:
109
+ """Return a new AST backed by a deep copy of this graph or of some files.
94
110
 
95
- Node IDs, the edge set, and all node/edge properties are duplicated
111
+ Node IDs, edges, and all node/edge properties are duplicated
96
112
  verbatim, preserving the ``{file_hash}_{counter}`` ID namespace, the
97
- root node ID and the target PHP version. The returned AST shares no
113
+ root node ID and the parse provenance. The returned AST shares no
98
114
  mutable state with this one: mutating either graph leaves the other
99
115
  unchanged.
100
116
 
117
+ With ``files``, the copy holds only the root node, the named File
118
+ nodes and every node they reach through ``PARENT_OF`` edges, with the
119
+ edges whose both endpoints it holds. Each held node keeps the order
120
+ of its outgoing edges.
121
+
122
+ Args:
123
+ files: File node IDs to copy, or None to copy the whole graph.
124
+
101
125
  Returns:
102
- A new AST whose storage is an independent copy of this graph.
126
+ A new AST whose storage is an independent copy.
127
+
128
+ Raises:
129
+ KeyError: If an ID in ``files`` names no node.
130
+ ValueError: If an ID in ``files`` names a node that is not a File.
103
131
  """
104
132
  storage = Storage()
105
- self._copy_nodes_into(storage)
106
- self._copy_edges_into(storage)
133
+ if files is None:
134
+ self._copy_nodes_into(storage, self._graph.get_nodes())
135
+ self._copy_edges_into(storage, self._graph.get_edges())
136
+ else:
137
+ held = self._file_closure(files)
138
+ node_ids = [nid for nid in self._graph.get_nodes() if nid in held]
139
+ self._copy_nodes_into(storage, node_ids)
140
+ self._copy_edges_into(
141
+ storage,
142
+ (
143
+ edge_id
144
+ for nid in node_ids
145
+ for edge_id in self._graph.out_edges(nid)
146
+ if edge_id[1] in held
147
+ ),
148
+ )
107
149
  return AST(
108
- storage, root_node_id=self._root_node_id, target_php=self._target_php
150
+ storage, root_node_id=self._root_node_id, provenance=self._provenance
109
151
  )
110
152
 
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():
153
+ def _file_closure(self, files: Collection[str]) -> set[str]:
154
+ """Return the root ID, the File IDs and their PARENT_OF descendants."""
155
+ held = {self._root_node_id}
156
+ pending: list[str] = []
157
+ for file_id in files:
158
+ if not self._graph.contains_node(file_id):
159
+ raise KeyError(f"Node not found: {file_id!r}")
160
+ node_type = (self._graph.get_node_props(file_id) or {}).get("nodeType")
161
+ if node_type != "File":
162
+ raise ValueError(f"Not a File node: {file_id!r} is {node_type!r}")
163
+ pending.append(file_id)
164
+ while pending:
165
+ node_id = pending.pop()
166
+ if node_id in held:
167
+ continue
168
+ held.add(node_id)
169
+ pending.extend(
170
+ edge_id[1]
171
+ for edge_id in self._graph.out_edges(node_id)
172
+ if edge_id[2] == PARENT_OF_EDGE
173
+ )
174
+ return held
175
+
176
+ def _copy_nodes_into(self, storage: Storage, node_ids: Iterable[str]) -> None:
177
+ """Duplicate the given nodes and their properties into ``storage``."""
178
+ for node_id in node_ids:
114
179
  storage.add_node(node_id)
115
180
  props = self._graph.get_node_props(node_id)
116
181
  if props:
117
182
  storage.set_node_props(node_id, copy.deepcopy(props))
118
183
 
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():
184
+ def _copy_edges_into(
185
+ self, storage: Storage, edge_ids: Iterable[tuple[str, str, str]]
186
+ ) -> None:
187
+ """Duplicate the given edges and their properties into ``storage``."""
188
+ for edge_id in edge_ids:
122
189
  storage.add_edge(edge_id)
123
190
  props = self._graph.get_edge_props(edge_id)
124
191
  if props:
@@ -195,8 +262,8 @@ class AST(AbcGraphQuerier[Node, Edge]):
195
262
  def get_file_node(self, node_id: str) -> Node:
196
263
  """Get the file node that contains the given node.
197
264
 
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``).
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``.
200
267
  Resolves by structure first, then falls back to ancestors() traversal.
201
268
 
202
269
  Args:
@@ -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.
@@ -6,21 +6,20 @@ from typing import Any
6
6
 
7
7
  from cpg2py import AbcNodeQuerier, Storage
8
8
 
9
+ from .._bookkeeping import attribute_update
9
10
  from ._node_id import NodeId
10
11
 
11
12
 
12
13
  class Node(AbcNodeQuerier):
13
14
  """Wraps a single AST node with dynamic property access to PHP-Parser JSON fields.
14
15
 
15
- Extends cpg2py's AbcNodeQuerier to provide access to PHP-Parser node data
16
- stored in cpg2py Storage. All node properties come from PHP-Parser's JSON
17
- output and are accessed dynamically without hardcoded field definitions.
16
+ Extends cpg2py's AbcNodeQuerier to provide access to the node's stored
17
+ properties without hardcoded field definitions.
18
18
 
19
- PHP-Parser nodes have two types of data:
20
- - **Subnodes**: Structural properties like name, params, stmts, byRef, etc.
21
- - **Attributes**: Metadata like startLine, endLine, comments, etc.
22
-
23
- Both are accessible through this class using dict-like syntax or properties.
19
+ The stored properties are the node's scalar fields (name, byRef, ...),
20
+ its flattened attributes (startLine, comments, ...) and the mapping's
21
+ bookkeeping properties. Child nodes (params, stmts, ...) are not
22
+ properties; they are reached through PARENT_OF edges.
24
23
 
25
24
  Attributes:
26
25
  _storage: cpg2py Storage instance containing node data.
@@ -70,13 +69,36 @@ class Node(AbcNodeQuerier):
70
69
  def all_properties(self) -> dict[str, Any]:
71
70
  """Return all stored properties for this node.
72
71
 
73
- Includes both subnodes (structural properties) and attributes (metadata).
72
+ Includes scalar fields, flattened attributes and bookkeeping
73
+ properties; child nodes live behind edges.
74
74
 
75
75
  Returns:
76
- Dictionary containing all properties from PHP-Parser JSON.
76
+ Dictionary of the node's stored properties.
77
77
  """
78
78
  return self.properties or {}
79
79
 
80
+ # Attribute writes
81
+
82
+ def set_attribute(self, key: str, value: Any) -> None:
83
+ """Store a value in this node's ``attributes`` bundle.
84
+
85
+ Records ``key`` in the node's attribute-key list, so reconstruction
86
+ files it in ``attributes`` rather than as a top-level field. This
87
+ is how a graph-based caller supplies a format marker such as
88
+ ``__format_regex``. An existing attribute is replaced. The write
89
+ goes to this node's own graph.
90
+
91
+ Args:
92
+ key: Attribute name.
93
+ value: JSON-serializable attribute value.
94
+
95
+ Raises:
96
+ ValueError: If ``key`` is ``nodeType``, a bookkeeping property
97
+ name, the printer-set ``__format_wrap_parens`` marker, or
98
+ the name of a scalar field of this node.
99
+ """
100
+ self.set_properties(attribute_update(self.all_properties, key, value))
101
+
80
102
  # Dict-like access methods
81
103
 
82
104
  def __getitem__(self, key: str) -> Any:
@@ -1,14 +1,15 @@
1
1
  """Mapping package: the single owner of the JSON<->graph contract.
2
2
 
3
3
  Exposes the inverse pair ``build`` (forward: JSON->graph) and ``serialize``
4
- (backward: graph->JSON) as module-level entry points, sharing one
5
- field-classification rule so they stay inverse.
4
+ (backward: graph->JSON) as module-level entry points. Fields are classified
5
+ once, during build; serialize consumes the stored properties, edges and
6
+ bookkeeping instead of reclassifying.
6
7
  """
7
8
 
8
9
  from __future__ import annotations
9
10
 
10
11
  from ._build import build
11
12
  from ._contract import EdgeSlot
12
- from ._serialize import serialize, statement_ids
13
+ from ._serialize import serialize, serialize_files, statement_ids
13
14
 
14
- __all__ = ["build", "serialize", "statement_ids", "EdgeSlot"]
15
+ __all__ = ["build", "serialize", "serialize_files", "statement_ids", "EdgeSlot"]