php-parser-py 1.2.6__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 +8 -2
- php_parser_py/_bookkeeping.py +150 -0
- php_parser_py/_graph/_ast.py +117 -26
- php_parser_py/_graph/_modifier.py +15 -8
- php_parser_py/_graph/_node.py +32 -10
- php_parser_py/_mapping/__init__.py +5 -4
- php_parser_py/_mapping/_build.py +85 -21
- php_parser_py/_mapping/_contract.py +35 -28
- php_parser_py/_mapping/_declared.py +41 -0
- php_parser_py/_mapping/_serialize.py +100 -41
- php_parser_py/_node_fields.py +207 -0
- php_parser_py/_parser.py +65 -27
- php_parser_py/_printer.py +74 -24
- php_parser_py/_resources/ExtendedPrinter.php +96 -27
- php_parser_py/_resources/parse.php +44 -5
- php_parser_py/_resources/print.php +21 -10
- php_parser_py/_resources/transport.php +19 -1
- php_parser_py/_runtime/_runner.py +28 -12
- php_parser_py/_types.py +45 -8
- php_parser_py/_version.py +44 -0
- php_parser_py-2.1.0.dist-info/METADATA +73 -0
- php_parser_py-2.1.0.dist-info/RECORD +38 -0
- php_parser_py/_resources/php +0 -0
- php_parser_py-1.2.6.dist-info/METADATA +0 -104
- php_parser_py-1.2.6.dist-info/RECORD +0 -35
- {php_parser_py-1.2.6.dist-info → php_parser_py-2.1.0.dist-info}/WHEEL +0 -0
- {php_parser_py-1.2.6.dist-info → php_parser_py-2.1.0.dist-info}/licenses/LICENSE +0 -0
- {php_parser_py-1.2.6.dist-info → php_parser_py-2.1.0.dist-info}/licenses/PHP-LICENSE +0 -0
- {php_parser_py-1.2.6.dist-info → php_parser_py-2.1.0.dist-info}/licenses/PHP-Parser-LICENSE +0 -0
- {php_parser_py-1.2.6.dist-info → php_parser_py-2.1.0.dist-info}/licenses/Zend-Engine-LICENSE +0 -0
php_parser_py/__init__.py
CHANGED
|
@@ -6,13 +6,18 @@ and manipulation of PHP code.
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
from importlib.metadata import version as _distribution_version
|
|
10
|
+
|
|
11
|
+
__version__ = _distribution_version("php-parser-py")
|
|
10
12
|
__all__ = [
|
|
11
13
|
"AST",
|
|
12
14
|
"Edge",
|
|
13
15
|
"Modifier",
|
|
14
16
|
"Node",
|
|
15
17
|
"Parser",
|
|
18
|
+
"PHPVersion",
|
|
19
|
+
"ParseProvenance",
|
|
20
|
+
"SkippedFile",
|
|
16
21
|
"Printer",
|
|
17
22
|
"StandardPrinter",
|
|
18
23
|
"ExtendedPrinter",
|
|
@@ -30,4 +35,5 @@ from ._exceptions import NodeNotInFileError, ParseError, RunnerError
|
|
|
30
35
|
from ._graph import AST, Edge, Modifier, Node
|
|
31
36
|
from ._parser import Parser, parse_code, parse_file, parse_project
|
|
32
37
|
from ._printer import ExtendedPrinter, Printer, StandardPrinter
|
|
33
|
-
from ._types import PrintMode, PrintRequest
|
|
38
|
+
from ._types import ParseProvenance, PrintMode, PrintRequest, SkippedFile
|
|
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
|
+
)
|
php_parser_py/_graph/_ast.py
CHANGED
|
@@ -3,11 +3,13 @@
|
|
|
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
|
|
12
|
+
from .._version import PHPVersion
|
|
11
13
|
from ._edge import Edge
|
|
12
14
|
from ._node import Node
|
|
13
15
|
from ._node_id import NodeId
|
|
@@ -18,30 +20,40 @@ class AST(AbcGraphQuerier[Node, Edge]):
|
|
|
18
20
|
|
|
19
21
|
Extends cpg2py's AbcGraphQuerier with Node and Edge type parameters.
|
|
20
22
|
Query-only: traversal, node/edge lookup, and file resolution. JSON
|
|
21
|
-
reconstruction lives in ``
|
|
23
|
+
reconstruction lives in the mapping package's ``serialize``.
|
|
22
24
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
- 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.
|
|
27
28
|
|
|
28
29
|
Uses the cpg2py graph API (nodes, edges, succ, prev, ancestors,
|
|
29
30
|
descendants); storage is only used for node/edge existence and Node/Edge
|
|
30
31
|
construction.
|
|
31
32
|
|
|
32
33
|
Attributes:
|
|
33
|
-
_root_node_id: ID of the root
|
|
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.
|
|
34
38
|
"""
|
|
35
39
|
|
|
36
|
-
def __init__(
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
storage: Storage,
|
|
43
|
+
root_node_id: str = PROJECT_ROOT_ID,
|
|
44
|
+
provenance: ParseProvenance | None = None,
|
|
45
|
+
) -> None:
|
|
37
46
|
"""Initialize AST with populated storage.
|
|
38
47
|
|
|
39
48
|
Args:
|
|
40
49
|
storage: cpg2py Storage containing AST nodes and edges.
|
|
41
50
|
root_node_id: ID of the root node. Defaults to "project".
|
|
51
|
+
provenance: Parse provenance of the graph. Default None marks
|
|
52
|
+
the provenance unknown.
|
|
42
53
|
"""
|
|
43
54
|
super().__init__(storage)
|
|
44
55
|
self._root_node_id = root_node_id
|
|
56
|
+
self._provenance = provenance
|
|
45
57
|
|
|
46
58
|
@property
|
|
47
59
|
def storage(self) -> Storage:
|
|
@@ -68,33 +80,112 @@ class AST(AbcGraphQuerier[Node, Edge]):
|
|
|
68
80
|
"""Return the root node ID of this AST."""
|
|
69
81
|
return self._root_node_id
|
|
70
82
|
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
@property
|
|
84
|
+
def target_php(self) -> PHPVersion | None:
|
|
85
|
+
"""Return the target PHP version the source was parsed under.
|
|
86
|
+
|
|
87
|
+
Parse provenance, not a PHP node field: serialization and printing
|
|
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).
|
|
91
|
+
"""
|
|
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.
|
|
99
|
+
|
|
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
|
|
73
107
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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.
|
|
110
|
+
|
|
111
|
+
Node IDs, edges, and all node/edge properties are duplicated
|
|
112
|
+
verbatim, preserving the ``{file_hash}_{counter}`` ID namespace, the
|
|
113
|
+
root node ID and the parse provenance. The returned AST shares no
|
|
114
|
+
mutable state with this one: mutating either graph leaves the other
|
|
115
|
+
unchanged.
|
|
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.
|
|
78
124
|
|
|
79
125
|
Returns:
|
|
80
|
-
A new AST whose storage is an independent copy
|
|
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.
|
|
81
131
|
"""
|
|
82
132
|
storage = Storage()
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
+
)
|
|
149
|
+
return AST(
|
|
150
|
+
storage, root_node_id=self._root_node_id, provenance=self._provenance
|
|
151
|
+
)
|
|
86
152
|
|
|
87
|
-
def
|
|
88
|
-
"""
|
|
89
|
-
|
|
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:
|
|
90
179
|
storage.add_node(node_id)
|
|
91
180
|
props = self._graph.get_node_props(node_id)
|
|
92
181
|
if props:
|
|
93
182
|
storage.set_node_props(node_id, copy.deepcopy(props))
|
|
94
183
|
|
|
95
|
-
def _copy_edges_into(
|
|
96
|
-
|
|
97
|
-
|
|
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:
|
|
98
189
|
storage.add_edge(edge_id)
|
|
99
190
|
props = self._graph.get_edge_props(edge_id)
|
|
100
191
|
if props:
|
|
@@ -171,8 +262,8 @@ class AST(AbcGraphQuerier[Node, Edge]):
|
|
|
171
262
|
def get_file_node(self, node_id: str) -> Node:
|
|
172
263
|
"""Get the file node that contains the given node.
|
|
173
264
|
|
|
174
|
-
Uses the AST ID convention: file node ID is the file hash (
|
|
175
|
-
nodes inside that file have ID ``file_hash + "_" +
|
|
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``.
|
|
176
267
|
Resolves by structure first, then falls back to ancestors() traversal.
|
|
177
268
|
|
|
178
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
|
|
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,
|
|
20
|
-
The source AST is never modified.
|
|
21
|
-
property, which exposes the
|
|
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.
|
php_parser_py/_graph/_node.py
CHANGED
|
@@ -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
|
|
16
|
-
|
|
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
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
|
72
|
+
Includes scalar fields, flattened attributes and bookkeeping
|
|
73
|
+
properties; child nodes live behind edges.
|
|
74
74
|
|
|
75
75
|
Returns:
|
|
76
|
-
Dictionary
|
|
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
|
|
5
|
-
|
|
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"]
|