graphe-code 0.1.0__py3-none-any.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.
- graphe/__init__.py +0 -0
- graphe/cli.py +991 -0
- graphe/core.py +461 -0
- graphe/generic.py +662 -0
- graphe/godot.py +386 -0
- graphe/js.py +564 -0
- graphe/python.py +917 -0
- graphe/root.py +82 -0
- graphe_code-0.1.0.dist-info/METADATA +24 -0
- graphe_code-0.1.0.dist-info/RECORD +14 -0
- graphe_code-0.1.0.dist-info/WHEEL +5 -0
- graphe_code-0.1.0.dist-info/entry_points.txt +2 -0
- graphe_code-0.1.0.dist-info/licenses/LICENSE +21 -0
- graphe_code-0.1.0.dist-info/top_level.txt +1 -0
graphe/generic.py
ADDED
|
@@ -0,0 +1,662 @@
|
|
|
1
|
+
"""The generic reader (T-0030, ADR 0003): the languages without a dedicated reader, read the same way by tree-sitter.
|
|
2
|
+
A language is data only (`Language`): its grammars by suffix, a query of ours per grammar, the method names
|
|
3
|
+
never linked by name, and, for C/C++'s macros and C#'s `#if`, whether a file with errors is read and what is
|
|
4
|
+
blanked first. The reading, the owner of a call, the `Class.method` naming and the linking are written once.
|
|
5
|
+
|
|
6
|
+
The queries follow one capture convention (docs/readers.md): `@function`, `@method`, `@class`, each with its
|
|
7
|
+
`@name`; `@call` for `f()`, `@send` for `x.m()`; `@reference` for `new C()`, `extends C`; `@receiver` for a method's
|
|
8
|
+
type when it is declared outside it (Go); `@action` for an entry point's action outside any function (PHP's
|
|
9
|
+
`case 'x':`), its body's uses its own, one without a body leading to the next (`dispatches`, sure). A use belongs to
|
|
10
|
+
the innermost definition that contains it; a function in
|
|
11
|
+
a `@class` is its method; a method's class is its `@receiver`, or else the innermost `@class` that contains it; a
|
|
12
|
+
`@class` in a `@class` is `Outer.Inner` (T-0043), its methods `Outer.Inner.m`.
|
|
13
|
+
|
|
14
|
+
- a node per file, function, method (`Class.method`), class and action; the definitions of one kind and name in a file are one
|
|
15
|
+
(Rust's `struct T` and its `impl T`, Java's overloads); the ids carry the extension (`a_t_go`);
|
|
16
|
+
- every link a call, a send or a reference makes is by the name alone (INFERRED), and only when the name has a single definition in the
|
|
17
|
+
language (or family: C/C++, Java/Kotlin): a call or a send to a function or a method (an `apart` language, PHP: a
|
|
18
|
+
call to a function, a send to a method), a reference to a class. A send never links a common name.
|
|
19
|
+
Each call or send is a site: `ours?`, `ambiguous`, `common` or `external` (no definition of that name);
|
|
20
|
+
- a file that does not parse is skipped and named on stderr, unless the language is `tolerant` (C's macros, C#'s
|
|
21
|
+
`#if`, Swift's and Go's newer syntax, Rust's `dyn 'a + Trait`).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import functools
|
|
27
|
+
import re
|
|
28
|
+
import sys
|
|
29
|
+
from collections import defaultdict
|
|
30
|
+
from typing import NamedTuple
|
|
31
|
+
|
|
32
|
+
import tree_sitter
|
|
33
|
+
import tree_sitter_c
|
|
34
|
+
import tree_sitter_c_sharp
|
|
35
|
+
import tree_sitter_cpp
|
|
36
|
+
import tree_sitter_go
|
|
37
|
+
import tree_sitter_java
|
|
38
|
+
import tree_sitter_kotlin
|
|
39
|
+
import tree_sitter_php
|
|
40
|
+
import tree_sitter_ruby
|
|
41
|
+
import tree_sitter_rust
|
|
42
|
+
import tree_sitter_swift
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Language(NamedTuple):
|
|
46
|
+
name: str
|
|
47
|
+
grammars: dict[str, tuple[tree_sitter.Language, str]] # suffix -> (grammar, query)
|
|
48
|
+
common: frozenset[str] # method names never linked from a send
|
|
49
|
+
tolerant: bool = False # a file that does not parse is read, not skipped (C's macros, C#, Swift, Go, Rust)
|
|
50
|
+
erased: re.Pattern[bytes] | None = None # what it matches is blanked before parsing (one line, columns kept)
|
|
51
|
+
apart: bool = False # a call is linked to a function only, a send to a method only (PHP)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Definition(NamedTuple):
|
|
55
|
+
kind: str # function, method, class, action
|
|
56
|
+
name: str # `f`, `T.m`, `T`, `liste`
|
|
57
|
+
line: int
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class Use(NamedTuple):
|
|
61
|
+
kind: str # call, send, reference; dispatches: from an action without a body (owner) to the next one (name)
|
|
62
|
+
name: str # the bare name used
|
|
63
|
+
line: int
|
|
64
|
+
owner: Definition | None # None: the file
|
|
65
|
+
text: str # what is used, up to its name (`x.y.m`)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
DEFINITIONS = ("function", "method", "class", "action")
|
|
69
|
+
USES = ("call", "send", "reference")
|
|
70
|
+
|
|
71
|
+
GO_QUERY = """
|
|
72
|
+
(function_declaration name: (identifier) @name) @function
|
|
73
|
+
(method_declaration
|
|
74
|
+
receiver: (parameter_list (parameter_declaration type: [
|
|
75
|
+
(type_identifier) @receiver
|
|
76
|
+
(generic_type type: (type_identifier) @receiver)
|
|
77
|
+
(pointer_type (type_identifier) @receiver)
|
|
78
|
+
(pointer_type (generic_type type: (type_identifier) @receiver))]))
|
|
79
|
+
name: (field_identifier) @name) @method
|
|
80
|
+
(type_spec name: (type_identifier) @name) @class
|
|
81
|
+
(call_expression function: (identifier) @name) @call
|
|
82
|
+
(call_expression function: (selector_expression field: (field_identifier) @name)) @send
|
|
83
|
+
(type_conversion_expression type: (generic_type type: (type_identifier) @name)) @call
|
|
84
|
+
(composite_literal type: [
|
|
85
|
+
(type_identifier) @name
|
|
86
|
+
(generic_type type: (type_identifier) @name)
|
|
87
|
+
(qualified_type name: (type_identifier) @name)]) @reference
|
|
88
|
+
(field_declaration !name type: [
|
|
89
|
+
(type_identifier) @name
|
|
90
|
+
(qualified_type name: (type_identifier) @name)
|
|
91
|
+
(pointer_type (type_identifier) @name)
|
|
92
|
+
(pointer_type (qualified_type name: (type_identifier) @name))]) @reference
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
# The common names: the standard library's (and xorm's `And`, `Exec`) that one function of gitea would collect from
|
|
96
|
+
# every `filepath.Join`, `strings.NewReader`, `cond.And` (T-0031, `check`'s most frequent sends linked by name), and
|
|
97
|
+
# the methods of Go's common interfaces. shortcut: a hand-kept list; to extend when `check` shows a standard name
|
|
98
|
+
# among the most frequent sends linked by name (`ours?`) on a host.
|
|
99
|
+
GO = Language("go", {".go": (tree_sitter.Language(tree_sitter_go.language()), GO_QUERY)}, frozenset({
|
|
100
|
+
"String", "Error", "Close", "Len", "Less", "Swap", "Read", "Write", "Get", "Set", "Add", "Delete", "Load",
|
|
101
|
+
"Store", "Lock", "Unlock", "Wait", "Done", "Run", "Do", "Next", "Reset", "Flush", "Sort", "Join", "Split",
|
|
102
|
+
"NewReader", "HasPrefix", "HasSuffix", "TrimPrefix", "TrimSuffix", "Cut", "Contains", "Replace", "ToUpper",
|
|
103
|
+
"ToLower", "Count", "Bytes", "Strings", "Fatal", "Printf", "Errorf", "MustCompile", "Compile", "QuoteMeta",
|
|
104
|
+
"Getenv", "ReadFile", "WriteFile", "MkdirAll", "Open", "OpenFile", "Create", "Remove", "Stat", "Symlink", "Base",
|
|
105
|
+
"Clean", "Parse", "ParseBool", "Format", "Marshal", "Unmarshal", "MarshalIndent", "WithTimeout", "WithCancel",
|
|
106
|
+
"WithContext", "Must", "Equal", "Skip", "Stack", "Exec", "And", "Or", "Where", "Find", "Insert", "Update"}),
|
|
107
|
+
# Grammar 0.25.0 knows neither Go 1.26's `new(expr)` nor generic methods: 47 of gitea's 3199 files, read all the
|
|
108
|
+
# same (T-0039). shortcut: a generic method is lost in its error node, its calls its file's; to upgrade the
|
|
109
|
+
# grammar when one knows them. shortcut: a Go file that does not parse is not named on stderr; to name it if a
|
|
110
|
+
# host's garbage shows.
|
|
111
|
+
tolerant=True)
|
|
112
|
+
|
|
113
|
+
# The functions of a trait without a body (`fn sides(&self);`) are not captured: they would make each name ambiguous.
|
|
114
|
+
RUST_QUERY = """
|
|
115
|
+
(function_item name: (identifier) @name) @function
|
|
116
|
+
[(struct_item name: (type_identifier) @name)
|
|
117
|
+
(enum_item name: (type_identifier) @name)
|
|
118
|
+
(union_item name: (type_identifier) @name)
|
|
119
|
+
(trait_item name: (type_identifier) @name)] @class
|
|
120
|
+
(impl_item type: [
|
|
121
|
+
(type_identifier) @name
|
|
122
|
+
(generic_type type: (type_identifier) @name)
|
|
123
|
+
(scoped_type_identifier name: (type_identifier) @name)
|
|
124
|
+
(reference_type type: [
|
|
125
|
+
(type_identifier) @name
|
|
126
|
+
(generic_type type: (type_identifier) @name)
|
|
127
|
+
(scoped_type_identifier name: (type_identifier) @name)])]) @class
|
|
128
|
+
(call_expression function: (identifier) @name) @call
|
|
129
|
+
(call_expression function: (field_expression field: (field_identifier) @name)) @send
|
|
130
|
+
(call_expression function: (scoped_identifier name: (identifier) @name)) @send
|
|
131
|
+
(struct_expression name: [
|
|
132
|
+
(type_identifier) @name
|
|
133
|
+
(scoped_type_identifier name: (type_identifier) @name)]) @reference
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
# The common names: the standard library's and the usual crates' (tokio, futures, http) that one function of
|
|
137
|
+
# libsignal would collect from every `Vec::with_capacity`, `std::future::ready`, `f.debug_struct(..).field` (T-0032,
|
|
138
|
+
# `check`'s most frequent sends linked by name, from `field` to `builder` below); the others, from `take` on, are
|
|
139
|
+
# guessed: the std traits' and iterators' methods. shortcut: a hand-kept list; to extend when `check` shows a
|
|
140
|
+
# standard name among the most frequent sends linked by name (`ours?`) on a host.
|
|
141
|
+
RUST = Language("rust", {".rs": (tree_sitter.Language(tree_sitter_rust.language()), RUST_QUERY)}, frozenset({
|
|
142
|
+
"new", "default", "clone", "len", "is_empty", "push", "pop", "get", "get_mut", "insert", "remove", "contains",
|
|
143
|
+
"iter", "iter_mut", "into_iter", "map", "and_then", "ok_or", "unwrap", "expect", "to_string", "to_owned", "from",
|
|
144
|
+
"into", "as_ref", "as_str", "fmt", "eq", "cmp", "hash", "next", "collect", "write", "read", "extend", "clear",
|
|
145
|
+
"field", "as_slice", "ok", "err", "decode", "transpose", "with_capacity", "ready", "recv", "channel", "is_none",
|
|
146
|
+
"then", "concat", "null", "timeout", "current", "as_secs", "as_millis", "status", "any", "sort", "as_mut",
|
|
147
|
+
"as_pin_mut", "builder", "take", "encode", "send", "is_some", "spawn", "block_on", "lock", "join", "to_vec",
|
|
148
|
+
"try_from", "try_into", "parse", "split", "chain", "filter", "fold", "find", "zip", "copied", "cloned", "flatten",
|
|
149
|
+
"unwrap_or", "unwrap_or_default", "unwrap_or_else", "map_err", "context", "with_context", "run", "call", "poll"}),
|
|
150
|
+
# Grammar 0.24.2 rejects a lifetime first in a trait object (`dyn 's + FnOnce(..)`): 1 of libsignal's 612 files,
|
|
151
|
+
# read all the same (T-0040). shortcut: a Rust file that does not parse is not named on stderr; to name it if a
|
|
152
|
+
# host's garbage shows.
|
|
153
|
+
tolerant=True)
|
|
154
|
+
|
|
155
|
+
# An abstract method (no body) is not captured, as Rust's trait signatures; a constructor is the method `C.C`.
|
|
156
|
+
JAVA_QUERY = """
|
|
157
|
+
[(class_declaration name: (identifier) @name)
|
|
158
|
+
(interface_declaration name: (identifier) @name)
|
|
159
|
+
(enum_declaration name: (identifier) @name)
|
|
160
|
+
(record_declaration name: (identifier) @name)] @class
|
|
161
|
+
(method_declaration name: (identifier) @name body: (block)) @method
|
|
162
|
+
(constructor_declaration name: (identifier) @name) @method
|
|
163
|
+
(method_invocation !object name: (identifier) @name) @call
|
|
164
|
+
(method_invocation object: (_) name: (identifier) @name) @send
|
|
165
|
+
(object_creation_expression type: [
|
|
166
|
+
(type_identifier) @name
|
|
167
|
+
(scoped_type_identifier (type_identifier) @name .)
|
|
168
|
+
(generic_type [(type_identifier) @name (scoped_type_identifier (type_identifier) @name .)])]) @reference
|
|
169
|
+
(superclass [
|
|
170
|
+
(type_identifier) @name
|
|
171
|
+
(scoped_type_identifier (type_identifier) @name .)
|
|
172
|
+
(generic_type [(type_identifier) @name (scoped_type_identifier (type_identifier) @name .)])]) @reference
|
|
173
|
+
(super_interfaces (type_list [
|
|
174
|
+
(type_identifier) @name
|
|
175
|
+
(scoped_type_identifier (type_identifier) @name .)
|
|
176
|
+
(generic_type [(type_identifier) @name (scoped_type_identifier (type_identifier) @name .)])])) @reference
|
|
177
|
+
(extends_interfaces (type_list [
|
|
178
|
+
(type_identifier) @name
|
|
179
|
+
(scoped_type_identifier (type_identifier) @name .)
|
|
180
|
+
(generic_type [(type_identifier) @name (scoped_type_identifier (type_identifier) @name .)])])) @reference
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
# The common names: the JDK's (and JRuby's `newString`) that one method of protobuf would collect from every
|
|
184
|
+
# `s.getBytes`, `clazz.getMethod`, `buffer.flip`, `map.keySet` (T-0033, `check`'s most frequent sends linked by name,
|
|
185
|
+
# from `getBytes` to `getPackage` below); the others are guessed: the methods of the collections, `Object`,
|
|
186
|
+
# `String`, `Optional`, the streams, the threads, the boxed numbers and `Arrays`. shortcut: a hand-kept list; to
|
|
187
|
+
# extend when `check` shows a standard name among the most frequent sends linked by name (`ours?`) on a host.
|
|
188
|
+
JAVA = Language("java", {".java": (tree_sitter.Language(tree_sitter_java.language()), JAVA_QUERY)}, frozenset({
|
|
189
|
+
"get", "set", "add", "put", "remove", "size", "isEmpty", "contains", "equals", "hashCode", "toString", "length",
|
|
190
|
+
"append", "close", "build", "of", "valueOf", "apply", "accept", "run", "call", "next", "hasNext", "stream",
|
|
191
|
+
"map", "filter", "collect", "forEach", "getName", "getValue", "getKey", "clear", "addAll", "format",
|
|
192
|
+
"getBytes", "getMethod", "keySet", "flip", "remaining", "startsWith", "endsWith", "newString", "array",
|
|
193
|
+
"hasArray", "arrayOffset", "slice", "replace", "push", "emptySet", "empty", "loadClass", "getPackage",
|
|
194
|
+
"entrySet", "values", "iterator", "charAt", "substring", "indexOf", "trim", "split", "compareTo", "getClass",
|
|
195
|
+
"isPresent", "orElse", "ifPresent", "println", "print", "write", "read", "flush", "start", "join", "getMessage",
|
|
196
|
+
"intValue", "longValue", "parseInt", "asList", "sort", "copyOf", "max", "min"}))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
# C# (T-0035): the upstream `tags.scm` captures only `x.M()`, the bare `F()` is ours. A type is named by its last name,
|
|
200
|
+
# bare, generic, qualified or behind the `pb::` alias of generated code. As Java's, a method without a body (abstract,
|
|
201
|
+
# an interface's) is not captured and a constructor is the method `C.C`. A property is the method `C.P` (T-0041), so the
|
|
202
|
+
# calls of its `get`, `set` and `=> expr` are its own; read without a call, it has no caller but as a delegate invoked
|
|
203
|
+
# (`codec.ValueWriter(..)`, 14 on protobuf), and an auto-property (`{ get; set; }`) is a node all the same. An
|
|
204
|
+
# interface's or abstract property is written alike but has no body, as a signature: not captured (8 on protobuf).
|
|
205
|
+
# shortcut: an indexer, an event's accessors, a local function, an operator and a destructor are no definitions, their
|
|
206
|
+
# calls belong to the class (or the method); to capture them if a host's `explain` needs them. shortcut: a property's
|
|
207
|
+
# name counts among the definitions of that name, so a method so named is ambiguous (`JsonToken.Name`,
|
|
208
|
+
# `SegmentedBufferHelper.IsAtEnd`: 31 sites on protobuf) and a library's send of that name is linked to it (NUnit's
|
|
209
|
+
# `Assert.False`, then a common name); to keep properties out of a call's targets, the delegates' calls lost, if a
|
|
210
|
+
# host's methods suffer.
|
|
211
|
+
_CS_NAME = "[(identifier) @name (generic_name (identifier) @name)]"
|
|
212
|
+
_CS_TYPE = (f"[(identifier) @name (generic_name (identifier) @name) (qualified_name name: {_CS_NAME}) "
|
|
213
|
+
f"(alias_qualified_name name: {_CS_NAME})]")
|
|
214
|
+
CSHARP_QUERY = f"""
|
|
215
|
+
[(class_declaration name: (identifier) @name)
|
|
216
|
+
(interface_declaration name: (identifier) @name)
|
|
217
|
+
(struct_declaration name: (identifier) @name)
|
|
218
|
+
(enum_declaration name: (identifier) @name)
|
|
219
|
+
(record_declaration name: (identifier) @name)] @class
|
|
220
|
+
(method_declaration name: (identifier) @name body: (_)) @method
|
|
221
|
+
(constructor_declaration name: (identifier) @name) @method
|
|
222
|
+
([(class_declaration body: (declaration_list (property_declaration name: (identifier) @name) @method))
|
|
223
|
+
(struct_declaration body: (declaration_list (property_declaration name: (identifier) @name) @method))
|
|
224
|
+
(record_declaration body: (declaration_list (property_declaration name: (identifier) @name) @method))]
|
|
225
|
+
(#not-match? @method "^([^{{=]* )?abstract "))
|
|
226
|
+
(invocation_expression function: {_CS_NAME}) @call
|
|
227
|
+
(invocation_expression function: (member_access_expression name: {_CS_NAME})) @send
|
|
228
|
+
(invocation_expression function: (conditional_access_expression (member_binding_expression name: {_CS_NAME}))) @send
|
|
229
|
+
(object_creation_expression type: {_CS_TYPE}) @reference
|
|
230
|
+
(base_list {_CS_TYPE}) @reference
|
|
231
|
+
(primary_constructor_base_type type: {_CS_TYPE}) @reference
|
|
232
|
+
"""
|
|
233
|
+
|
|
234
|
+
CSHARP = Language("csharp", {".cs": (tree_sitter.Language(tree_sitter_c_sharp.language()), CSHARP_QUERY)},
|
|
235
|
+
# The common names: the BCL's that one method of protobuf would collect from every
|
|
236
|
+
# `builder.Append` (a StringBuilder), `enumerator.MoveNext`, `typeof(T).GetProperty` (T-0035,
|
|
237
|
+
# `check`'s most frequent sends linked by name, the first three); the others are guessed: the
|
|
238
|
+
# methods of `object`, the strings, the collections, LINQ, the streams and reflection. NUnit's
|
|
239
|
+
# `Assert.False`, `True`, `Null`, `IsEmpty` (72, 38, 27, 1 on protobuf) were `external` until a
|
|
240
|
+
# property is a method (T-0041): then linked to `JsonToken.False`, `ByteString.IsEmpty`...
|
|
241
|
+
# shortcut: a hand-kept list; to extend when `check` shows a standard name among the most frequent
|
|
242
|
+
# sends linked by name (`ours?`) on a host.
|
|
243
|
+
frozenset({
|
|
244
|
+
"Append", "MoveNext", "GetProperty", "AppendLine", "AppendFormat", "ToString", "Equals",
|
|
245
|
+
"GetHashCode", "GetType", "CompareTo", "Add", "AddRange", "Remove", "RemoveAt", "Contains",
|
|
246
|
+
"ContainsKey", "TryGetValue", "Clear", "CopyTo", "ToArray", "ToList", "ToDictionary", "Select",
|
|
247
|
+
"Where", "Any", "All", "First", "FirstOrDefault", "Single", "Count", "Sum", "OrderBy",
|
|
248
|
+
"SequenceEqual", "GetEnumerator", "Dispose", "Split", "Join", "Substring", "IndexOf",
|
|
249
|
+
"StartsWith", "EndsWith", "Trim", "Replace", "ToUpper", "ToLower", "ToUpperInvariant",
|
|
250
|
+
"ToLowerInvariant", "Write", "WriteLine", "ReadLine", "ReadToEnd", "Flush", "Close", "Invoke",
|
|
251
|
+
"GetValue", "SetValue", "GetMethod", "GetField", "GetCustomAttributes", "IsAssignableFrom",
|
|
252
|
+
"False", "True", "Null", "IsEmpty"}),
|
|
253
|
+
# protobuf's generated code cuts its base list with `#if` (`: pb::IMessage<T>` `#if ..` `, ..`
|
|
254
|
+
# `#endif`): the grammar does not parse it, 44 of 224 files skipped. The directives erased, 2 left
|
|
255
|
+
# (`f() = x;`, and an expression whose two branches then follow each other), read all the same: no
|
|
256
|
+
# method lost its class. shortcut: both branches are read (their calls counted twice, their
|
|
257
|
+
# definitions one); to keep one branch if a host's definitions differ between them. shortcut: a C#
|
|
258
|
+
# file that does not parse is no longer named on stderr; to name it if a host's garbage shows.
|
|
259
|
+
tolerant=True, erased=re.compile(rb"(?m)^[ \t]*#[ \t]*(?:if|elif|else|endif)\b.*$"))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
# Ruby (T-0036): the upstream `tags.scm` takes a bare identifier for a call, which may be a local variable: ours
|
|
263
|
+
# captures the explicit calls only, `b()`, `c arg`, `x.c`. A module is a class, as it holds its `def self.m`; a
|
|
264
|
+
# `class << self` is none, its methods its class's. `C.new` is a reference to `C`. shortcut: a bare `b` is no call (it
|
|
265
|
+
# may be a variable); to tell a variable from a call (the grammar's `locals.scm`) if a host's `explain` misses them.
|
|
266
|
+
# A module being a class, a class in a module is `Module.Class` (T-0043): `Google.Protobuf.Descriptor`. shortcut: a
|
|
267
|
+
# scoped module is named by its last name, so one class is `Protobuf.X` under `module Google::Protobuf` and
|
|
268
|
+
# `Google.Protobuf.X` under `module Google` `module Protobuf`; to name a module by its whole path if a host's `explain`
|
|
269
|
+
# needs them together. shortcut: an `attr_reader`, an `alias` or a `define_method` is no definition, and a setter call `x.y = v` is a send
|
|
270
|
+
# `y`, not `y=`; to capture them if a host's hand-written accessors need callers.
|
|
271
|
+
_RB_CONSTANT = "[(constant) @name (scope_resolution name: (constant) @name)]"
|
|
272
|
+
RUBY_QUERY = f"""
|
|
273
|
+
[(class name: {_RB_CONSTANT}) (module name: {_RB_CONSTANT})] @class
|
|
274
|
+
(call receiver: {_RB_CONSTANT} method: (identifier) @_eval block: (_) (#eq? @_eval "class_eval")) @class
|
|
275
|
+
[(method name: (_) @name) (singleton_method name: (_) @name)] @method
|
|
276
|
+
(call !receiver method: [(identifier) (constant)] @name) @call
|
|
277
|
+
(call receiver: (_) method: [(identifier) (constant)] @name) @send
|
|
278
|
+
(superclass {_RB_CONSTANT}) @reference
|
|
279
|
+
(call receiver: {_RB_CONSTANT} method: (identifier) @_new (#eq? @_new "new")) @reference
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
# The common names: `new` (892 sends `C.new`, 9 `def self.new` in protobuf), `each` (38) and `pack` (6 of its 9 sends
|
|
283
|
+
# `Array#pack`, linked to `Any.pack`), measured on protobuf (T-0036, `check`); the others are guessed: the methods of
|
|
284
|
+
# `Object`, the conversions, `Enumerable`, `Array`, `Hash`, `String` and `IO`. A name whose sends are mostly protobuf's
|
|
285
|
+
# is left out: `push`, `pop`, `first`, `delete`, `keys` (its `RepeatedField` and `Map` mirror `Array` and `Hash`),
|
|
286
|
+
# `eql?` (its messages'). shortcut: a
|
|
287
|
+
# hand-kept list; to extend when `check` shows a standard name among the most frequent sends linked by name (`ours?`)
|
|
288
|
+
# on a host.
|
|
289
|
+
RUBY = Language("ruby", {".rb": (tree_sitter.Language(tree_sitter_ruby.language()), RUBY_QUERY)}, frozenset({
|
|
290
|
+
"new", "each", "pack", "to_s", "inspect", "hash", "dup", "clone", "freeze", "frozen?", "is_a?", "kind_of?",
|
|
291
|
+
"respond_to?", "send", "public_send", "nil?", "class", "tap", "then", "to_i", "to_f", "to_sym", "to_str",
|
|
292
|
+
"to_proc", "map", "select", "reject", "each_with_index", "each_with_object", "each_pair", "include?", "any?",
|
|
293
|
+
"all?", "find", "count", "sum", "min", "max", "sort", "sort_by", "reduce", "inject", "flat_map", "flatten",
|
|
294
|
+
"compact", "uniq", "zip", "join", "key?", "fetch", "merge", "dig", "empty?", "size", "split", "strip",
|
|
295
|
+
"gsub", "sub", "start_with?", "end_with?", "upcase", "downcase", "read", "write", "puts", "print", "close",
|
|
296
|
+
"call"}))
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# PHP (T-0044), the `php` reader in place of the PHP reader by patterns since T-0045. The grammar with its HTML
|
|
300
|
+
# (`language_php`), so a page's text holds no call. A class, an interface, a trait
|
|
301
|
+
# and an enum are a class, a namespace none; as Java's, a method without a body (an interface's, abstract) is not
|
|
302
|
+
# captured. `x->m()`, `x?->m()` and `X::m()` (`self::`, `parent::`) are sends; `new C`, `extends`, `implements`, a
|
|
303
|
+
# trait's `use` and a caught type (`catch (A | B $e)`) references by the last name. shortcut: PHP's function and method names are case-insensitive, the
|
|
304
|
+
# links by the exact name; to fold the case if a host calls `Foo()` for `foo()`. shortcut: a call through a variable
|
|
305
|
+
# (`$f()`, `$x->$m()`) is none, and an anonymous class at a file's top is no class, its methods functions; to capture
|
|
306
|
+
# them if a host's `explain` needs them. A `case 'x':` outside any function is an action (an entry point's
|
|
307
|
+
# `switch ($action)`: Grid Zero's 8), on one line or not. shortcut: only a single-quoted word is, as the PHP reader's
|
|
308
|
+
# (`case "x":`, a constant, `default:` are none); to take them if a host's router uses them.
|
|
309
|
+
_PHP_NAME = "[(name) @name (qualified_name (name) @name .)]"
|
|
310
|
+
PHP_QUERY = f"""
|
|
311
|
+
[(class_declaration name: (name) @name) (interface_declaration name: (name) @name)
|
|
312
|
+
(trait_declaration name: (name) @name) (enum_declaration name: (name) @name)] @class
|
|
313
|
+
(function_definition name: (name) @name) @function
|
|
314
|
+
(method_declaration name: (name) @name body: (compound_statement)) @method
|
|
315
|
+
(function_call_expression function: {_PHP_NAME}) @call
|
|
316
|
+
[(member_call_expression name: (name) @name) (nullsafe_member_call_expression name: (name) @name)
|
|
317
|
+
(scoped_call_expression name: (name) @name)] @send
|
|
318
|
+
[(object_creation_expression {_PHP_NAME}) (base_clause {_PHP_NAME}) (class_interface_clause {_PHP_NAME})
|
|
319
|
+
(use_declaration {_PHP_NAME}) (catch_clause type: (type_list (named_type {_PHP_NAME})))] @reference
|
|
320
|
+
(case_statement value: (string (string_content) @name) (#match? @name "^\\\\w+$")) @action
|
|
321
|
+
"""
|
|
322
|
+
|
|
323
|
+
# `apart`: on protobuf, 219 bare calls to PHP's built-ins (`count()` 185, `substr()` 19, `pack()`) went to its
|
|
324
|
+
# methods of that name. No common name: every send linked by a standard name on protobuf is to one of its own methods
|
|
325
|
+
# (`$any->pack`, `getFile`), PHP's library being functions (T-0044, `check`).
|
|
326
|
+
PHP = Language("php", {".php": (tree_sitter.Language(tree_sitter_php.language_php()), PHP_QUERY)}, frozenset(),
|
|
327
|
+
apart=True)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# Swift (T-0037): the upstream `tags.scm` captures no call. A class, a struct, an enum and an actor are one
|
|
331
|
+
# `class_declaration`, a class; a protocol is one too. An `extension C` is no class: its methods are `C`'s by
|
|
332
|
+
# `@receiver` (as Go's), so that a type extended in several files stays one class and its references are linked. A
|
|
333
|
+
# method is captured as a direct child of its body, the only way to tell a type's from an extension's; `init` is
|
|
334
|
+
# `C.init`, a computed property `var p: T { .. }` the method `C.p` (577 on libsignal, whose 670 calls would be their
|
|
335
|
+
# class's; reading `x.p` is no call, so it has no caller). A type is named by its last name, generic or not.
|
|
336
|
+
# shortcut: a nested function, an operator (`static func ==`) and a subscript are no definitions, and a stored
|
|
337
|
+
# property's initial value or observers (`didSet`) call from the class; to capture them if a host's `explain` needs
|
|
338
|
+
# them. shortcut: a call to a capitalised name (`C(..)`, `Foo.Bar(..)`) is a reference to that type, a lower-case one
|
|
339
|
+
# a call, Swift's naming convention; to tell them apart by their definitions if a host breaks it. shortcut: the grammar
|
|
340
|
+
# reads `defer { }` as a call `defer`, and the standard `withUnsafePointer(to:)` and `withUnsafeMutablePointer(to:)`
|
|
341
|
+
# are linked to a host's method of that name (libsignal's, 24 bare calls all the standard's): no calls, so a host's
|
|
342
|
+
# own bare function so named gets no caller; to drop them by their `to:` label if a host defines one.
|
|
343
|
+
_SW_LAST = ("[(user_type (type_identifier) @{c} .) "
|
|
344
|
+
"(user_type (type_identifier) @{c} . (type_arguments) .)]")
|
|
345
|
+
_SW_EXTENDED = _SW_LAST.format(c="receiver")
|
|
346
|
+
_SW_TYPE = _SW_LAST.format(c="name")
|
|
347
|
+
_SW_FUNCTION = ("[(function_declaration name: (simple_identifier) @name body: (_)) "
|
|
348
|
+
"(init_declaration \"init\" @name body: (_)) "
|
|
349
|
+
"(property_declaration name: (pattern bound_identifier: (simple_identifier) @name) "
|
|
350
|
+
"computed_value: (_))]")
|
|
351
|
+
SWIFT_QUERY = f"""
|
|
352
|
+
[(class_declaration name: (type_identifier) @name) (protocol_declaration name: (type_identifier) @name)] @class
|
|
353
|
+
(source_file (function_declaration name: (simple_identifier) @name body: (_)) @function)
|
|
354
|
+
(class_declaration name: (type_identifier) body: [(class_body {_SW_FUNCTION} @function)
|
|
355
|
+
(enum_class_body {_SW_FUNCTION} @function)])
|
|
356
|
+
(class_declaration name: {_SW_EXTENDED} body: (class_body {_SW_FUNCTION} @method))
|
|
357
|
+
(call_expression (simple_identifier) @name
|
|
358
|
+
(#not-match? @name "^([A-Z]|(defer|withUnsafePointer|withUnsafeMutablePointer)$)")) @call
|
|
359
|
+
(call_expression (simple_identifier) @name (#match? @name "^[A-Z]")) @reference
|
|
360
|
+
(call_expression (navigation_expression suffix: (navigation_suffix suffix: (simple_identifier) @name))
|
|
361
|
+
(#not-match? @name "^[A-Z]")) @send
|
|
362
|
+
(call_expression (navigation_expression suffix: (navigation_suffix suffix: (simple_identifier) @name))
|
|
363
|
+
(#match? @name "^[A-Z]")) @reference
|
|
364
|
+
(call_expression (prefix_expression target: (simple_identifier) @name)) @send
|
|
365
|
+
(constructor_expression constructed_type: {_SW_TYPE}) @reference
|
|
366
|
+
(inheritance_specifier inherits_from: {_SW_TYPE}) @reference
|
|
367
|
+
"""
|
|
368
|
+
|
|
369
|
+
# The common names: `init` (611 sends `self.init`, `.init`, `super.init`), `append` (71, `Data`'s), `combine` (3 of
|
|
370
|
+
# its 4 sends `Hasher.combine`, linked to `GroupSendEndorsement.combine`) and `withCString` (`String`'s, which libsignal
|
|
371
|
+
# wraps on `Optional`), measured on libsignal (T-0037, `check`); the others are guessed: the standard library's
|
|
372
|
+
# collections, sequences, `Codable`, `Hashable` and unsafe pointers. `remove` is left out: its one send is
|
|
373
|
+
# libsignal's `svrB.remove()`. shortcut: a hand-kept list; to extend when `check` shows a standard name among the most
|
|
374
|
+
# frequent sends linked by name (`ours?`) on a host.
|
|
375
|
+
SWIFT = Language("swift", {".swift": (tree_sitter.Language(tree_sitter_swift.language()), SWIFT_QUERY)}, frozenset({
|
|
376
|
+
"init", "append", "combine", "withCString", "map", "filter", "reduce", "forEach", "compactMap", "flatMap",
|
|
377
|
+
"contains", "first", "last", "insert", "removeAll", "sorted", "sort", "joined", "split", "description", "hash",
|
|
378
|
+
"encode", "decode", "withUnsafeBytes", "withUnsafeBufferPointer", "withUnsafeMutableBufferPointer",
|
|
379
|
+
"withUnsafeMutableBytes", "index", "firstIndex", "count", "isEmpty", "prefix", "suffix", "dropFirst", "dropLast",
|
|
380
|
+
"enumerated", "zip", "makeIterator", "next", "get", "set", "value", "copyBytes"}),
|
|
381
|
+
# The grammar does not parse 10 of libsignal's 218 files (parameter packs `repeat (each T)`, `case .self`,
|
|
382
|
+
# `catch E.c(_:)`, `() = try x`); read all the same, they lose no definition. shortcut: a Swift file that does
|
|
383
|
+
# not parse is not named on stderr; to name it if a host's garbage shows.
|
|
384
|
+
tolerant=True)
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
# Kotlin (T-0038): the grammar ships no `tags.scm`, the query is ours. A class, an interface, an enum and an `object`
|
|
388
|
+
# are classes; a companion object is none, its functions its class's. A function is captured as a direct child of a
|
|
389
|
+
# file or of a type's body, so an anonymous object's (`object : Runnable { override fun run() }`) and a local one are
|
|
390
|
+
# none, their calls their enclosing function's; an abstract one (no body) is none, as Java's. An extension function
|
|
391
|
+
# `fun Foo.Bar.f()` is the method `Bar.f` by `@receiver` (as Go's): libsignal's 73, its `toFfiArgType` of each type
|
|
392
|
+
# apart. A secondary constructor is the method `C.constructor`. A type is named by its last name, generic or not.
|
|
393
|
+
# shortcut: a property's getter or setter (32 on libsignal) and an `init { }` block are no definitions, their calls
|
|
394
|
+
# their class's; to capture them as Swift's computed properties if a host's `explain` needs them. shortcut: the grammar
|
|
395
|
+
# reads no class body on one line (`class C { fun f() {} }`) and takes `Array<Int>(1)` without a trailing lambda for
|
|
396
|
+
# comparisons; to take a newer grammar if a host loses code to them. shortcut: a call to
|
|
397
|
+
# a capitalised name (`C(..)`, `Foo.Bar(..)`) is a reference to that type, a lower-case one a call, Kotlin's naming
|
|
398
|
+
# convention; to tell them apart by their definitions if a host breaks it.
|
|
399
|
+
_KT_LAST = ("[(user_type (identifier) @{c} .) "
|
|
400
|
+
"(user_type (identifier) @{c} . (type_arguments) .)]")
|
|
401
|
+
_KT_TYPE = _KT_LAST.format(c="name")
|
|
402
|
+
_KT_RECEIVER = _KT_LAST.format(c="receiver")
|
|
403
|
+
# The name right after the modifiers, the type parameters or nothing: a receiver between them is an extension.
|
|
404
|
+
_KT_FUNCTION = ("[(function_declaration . name: (identifier) @name (function_body)) "
|
|
405
|
+
"(function_declaration (modifiers) . name: (identifier) @name (function_body)) "
|
|
406
|
+
"(function_declaration (type_parameters) . name: (identifier) @name (function_body)) "
|
|
407
|
+
"(secondary_constructor \"constructor\" @name)]")
|
|
408
|
+
KOTLIN_QUERY = f"""
|
|
409
|
+
[(class_declaration name: (identifier) @name) (object_declaration name: (identifier) @name)] @class
|
|
410
|
+
(source_file {_KT_FUNCTION} @function)
|
|
411
|
+
(class_declaration [(class_body {_KT_FUNCTION} @function) (enum_class_body {_KT_FUNCTION} @function)])
|
|
412
|
+
[(object_declaration (class_body {_KT_FUNCTION} @function)) (companion_object (class_body {_KT_FUNCTION} @function))]
|
|
413
|
+
(function_declaration {_KT_RECEIVER} . name: (identifier) @name (function_body)) @function
|
|
414
|
+
(function_declaration (nullable_type {_KT_RECEIVER}) . name: (identifier) @name (function_body)) @function
|
|
415
|
+
(call_expression (identifier) @name (#not-match? @name "^[A-Z]")) @call
|
|
416
|
+
(call_expression (identifier) @name (#match? @name "^[A-Z]")) @reference
|
|
417
|
+
(call_expression (navigation_expression (identifier) @name .) (#not-match? @name "^[A-Z]")) @send
|
|
418
|
+
(call_expression (navigation_expression (identifier) @name .) (#match? @name "^[A-Z]")) @reference
|
|
419
|
+
(delegation_specifier {_KT_TYPE}) @reference
|
|
420
|
+
(delegation_specifier (constructor_invocation {_KT_TYPE})) @reference
|
|
421
|
+
(delegation_specifier (explicit_delegation {_KT_TYPE})) @reference
|
|
422
|
+
"""
|
|
423
|
+
|
|
424
|
+
# The common names: `get` (78 sends, `CompletableFuture.get`, linked to `TestingIntBox.get`), `toString` (32), `map`
|
|
425
|
+
# (31, mostly a collection's, linked to `RequestResult.map`) and `hashCode`, measured on libsignal (T-0038, `check`);
|
|
426
|
+
# the others are guessed: `Any`'s, the scope functions, the collections', the arrays' and `Result`'s. Left out, their
|
|
427
|
+
# sends mostly libsignal's: `await` (its `CompletableFuture.await`), `start`, `of`, and `remove` and `invoke`, whose one
|
|
428
|
+
# send each is libsignal's (`svrB.remove()`, `SetProfileHelpers.invoke`); `start`, `of` and `remove` are Java's (`JVM`). Out since Java is read with it (T-0042):
|
|
429
|
+
# `thenApply`, `thenCompose`, `complete`, `completeExceptionally`, the methods of libsignal's own Java
|
|
430
|
+
# `CompletableFuture` (56 of its Java sends were linked to them), and `toByteArray`, protobuf's (306 Java sends).
|
|
431
|
+
# shortcut: a hand-kept list; to extend when `check` shows a standard name among the most frequent sends linked by name
|
|
432
|
+
# (`ours?`) on a host.
|
|
433
|
+
KOTLIN = Language("kotlin", {".kt": (tree_sitter.Language(tree_sitter_kotlin.language()), KOTLIN_QUERY)}, frozenset({
|
|
434
|
+
"get", "toString", "map", "hashCode", "equals", "compareTo", "let", "apply", "also", "run", "use", "takeIf",
|
|
435
|
+
"filter", "forEach", "flatMap", "mapNotNull", "first", "firstOrNull", "last", "single", "toList", "toSet", "toMap",
|
|
436
|
+
"toTypedArray", "joinToString", "contains", "isEmpty", "isNotEmpty", "set", "add", "addAll", "put",
|
|
437
|
+
"clear", "copyOf", "copyOfRange", "contentEquals", "contentHashCode", "close", "split",
|
|
438
|
+
"getOrNull", "getOrThrow", "getOrElse",
|
|
439
|
+
"onSuccess", "onFailure", "fold", "iterator", "next", "hasNext"}))
|
|
440
|
+
|
|
441
|
+
# Java and Kotlin are one family (T-0042), as C and C++: a Kotlin call to its host's Java is linked, and the reverse.
|
|
442
|
+
# Each file keeps its grammar and query; the common names are both lists. Not `tolerant`, as each was. shortcut: Java's
|
|
443
|
+
# `start`, `of` and `remove` silence 16 of libsignal's Kotlin sends to its own; out, Java's `List.of` would be linked to
|
|
444
|
+
# Kotlin's `BadgeVisibility.of` (35 sends) and 501 of protobuf's sends made ambiguous; to give each grammar its own list
|
|
445
|
+
# if a host's Kotlin loses more. shortcut: Kotlin's `ByteArray(n)`, the standard library's, is a reference to a Java
|
|
446
|
+
# class so named (libsignal's `zkgroup.internal.ByteArray`, 24 links), and a Java send to a library is linked to a
|
|
447
|
+
# Kotlin definition so named (protobuf's generated `Any.unpack(X.class)` to its Kotlin `ProtoAny.unpack`, 3 links, 8
|
|
448
|
+
# sites; Kotlin's `"s".toByteArray()` would be to a host's single Java `toByteArray`); to never reference Kotlin's
|
|
449
|
+
# standard types, or to link a call to the other language's definitions only (BACKLOG.md), if a host's `callers` suffer.
|
|
450
|
+
JVM = Language("java", {**JAVA.grammars, **KOTLIN.grammars}, JAVA.common | KOTLIN.common)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
# C and C++ (T-0034): the upstream `tags.scm` capture no call. A query pattern sees direct children only, so the
|
|
454
|
+
# forms a name takes are spelled out: wrapped in pointers or a reference (`char** f()`, `T& C::m()`), qualified up
|
|
455
|
+
# to three scopes (`ns::C::m`), the class the innermost scope (`C<T>::m` too). A prototype (`int f(int);`, a method
|
|
456
|
+
# declared in its class) and a declaration without a body (`class C;`, `= default`) are not captured: each would make
|
|
457
|
+
# a name ambiguous between the `.h` and the file that defines it. shortcut: a scope is taken for a class, so
|
|
458
|
+
# `void internal::Helper() {}` is the method `internal.Helper`; to tell a namespace from a class if a host needs it.
|
|
459
|
+
_C_DECLARATOR = ("[{f} (pointer_declarator declarator: {f}) (pointer_declarator declarator: (pointer_declarator "
|
|
460
|
+
"declarator: {f})){ref}]")
|
|
461
|
+
_C_DEFINITIONS = """
|
|
462
|
+
(function_definition declarator: {declarator} body: (_)) @function
|
|
463
|
+
[(struct_specifier name: {type} body: (_))
|
|
464
|
+
(union_specifier name: {type} body: (_))
|
|
465
|
+
(enum_specifier name: {type} body: (_))
|
|
466
|
+
(type_definition type: [(struct_specifier !name body: (_)) (union_specifier !name body: (_))]
|
|
467
|
+
declarator: (type_identifier) @name)] @class
|
|
468
|
+
(call_expression function: {call}) @call
|
|
469
|
+
(call_expression function: (field_expression field: {field})) @send
|
|
470
|
+
"""
|
|
471
|
+
_C_FUNCTION = "(function_declarator declarator: (identifier) @name)"
|
|
472
|
+
C_QUERY = _C_DEFINITIONS.format(declarator=_C_DECLARATOR.format(f=_C_FUNCTION, ref=""), type="(type_identifier) @name",
|
|
473
|
+
call="(identifier) @name", field="(field_identifier) @name")
|
|
474
|
+
# The forms are listed flat: py-tree-sitter 0.26.1 drops a match whose alternation holds a captured alternation
|
|
475
|
+
# (`[[(identifier) (field_identifier)] @name (qualified_identifier)]` misses `int a() {}` in a class).
|
|
476
|
+
_CPP_QUALIFIED = ("{n} (qualified_identifier name: [{n}]) "
|
|
477
|
+
"(qualified_identifier name: (qualified_identifier name: [{n}]))")
|
|
478
|
+
_CPP_SCOPED = ("(qualified_identifier scope: [(namespace_identifier) @receiver (template_type name: (type_identifier) "
|
|
479
|
+
"@receiver)] name: [(identifier) @name (destructor_name) @name (operator_name) @name])")
|
|
480
|
+
_CPP_FUNCTION = ("(function_declarator declarator: [(identifier) @name (field_identifier) @name "
|
|
481
|
+
f"(destructor_name) @name (operator_name) @name {_CPP_QUALIFIED.format(n=_CPP_SCOPED)}])")
|
|
482
|
+
_CPP_TYPE = "(type_identifier) @name (template_type name: (type_identifier) @name)"
|
|
483
|
+
_CPP_CALL = "(identifier) @name (template_function name: (identifier) @name)"
|
|
484
|
+
CPP_QUERY = _C_DEFINITIONS.format(
|
|
485
|
+
declarator=_C_DECLARATOR.format(f=_CPP_FUNCTION, ref=f" (reference_declarator {_CPP_FUNCTION})"),
|
|
486
|
+
type=f"[{_CPP_TYPE}]", call=f"[{_CPP_CALL}]",
|
|
487
|
+
field="[(field_identifier) @name (template_method name: (field_identifier) @name)]") + f"""
|
|
488
|
+
(class_specifier name: [{_CPP_TYPE}] body: (_)) @class
|
|
489
|
+
(call_expression function: (qualified_identifier name: [{_CPP_QUALIFIED.format(n=_CPP_CALL)}])) @send
|
|
490
|
+
(new_expression type: [{_CPP_QUALIFIED.format(n=_CPP_TYPE)}]) @reference
|
|
491
|
+
(base_class_clause [{_CPP_QUALIFIED.format(n=_CPP_TYPE)}]) @reference
|
|
492
|
+
"""
|
|
493
|
+
|
|
494
|
+
_C = tree_sitter.Language(tree_sitter_c.language())
|
|
495
|
+
_CPP = tree_sitter.Language(tree_sitter_cpp.language())
|
|
496
|
+
# C and C++ are one family (T-0034): a C++ call to a C function is linked. A `.h` is read as C++, which reads C.
|
|
497
|
+
C = Language("c", {".c": (_C, C_QUERY), **dict.fromkeys((".h", ".cpp", ".cc", ".cxx", ".hpp"), (_CPP, CPP_QUERY))},
|
|
498
|
+
# The common names: the standard library's (and absl's `Status::message`) that one function of
|
|
499
|
+
# protobuf would collect from every `std::string(..)`, `v.emplace_back`, `s.append`, `v.reserve`
|
|
500
|
+
# (T-0034, `check`'s most frequent sends linked by name, from `string` to `count` below); the others are
|
|
501
|
+
# guessed: the methods of the containers, the strings, the smart pointers, `optional` and `std::`'s
|
|
502
|
+
# functions. shortcut: a hand-kept list; to extend when `check` shows a standard name among the most
|
|
503
|
+
# frequent sends linked by name (`ours?`) on a host.
|
|
504
|
+
frozenset({
|
|
505
|
+
"string", "append", "emplace_back", "pop_back", "reserve", "message", "str", "release", "count",
|
|
506
|
+
"size", "empty", "begin", "end", "cbegin", "cend", "push_back", "data", "get", "reset", "find",
|
|
507
|
+
"insert", "erase", "clear", "at", "front", "back", "c_str", "substr", "length", "emplace", "resize",
|
|
508
|
+
"swap", "value", "has_value", "value_or", "ok", "status", "move", "forward", "make_unique",
|
|
509
|
+
"make_shared", "min", "max", "assign", "compare", "contains", "load", "store", "lock", "unlock",
|
|
510
|
+
"join", "push", "pop", "top", "rfind", "find_first_of", "starts_with", "ends_with", "what"}),
|
|
511
|
+
# The macros the grammar cannot read, upper case with an underscore and no arguments:
|
|
512
|
+
# `class PROTOBUF_EXPORT Foo` reads as a function `Foo`, `f() const ABSL_ATTRIBUTE_LIFETIME_BOUND {` (834
|
|
513
|
+
# on protobuf) as no function, `UPB_INLINE void f()` and `T* PROTOBUF_NONNULL C::f()` as garbage. Erased
|
|
514
|
+
# on protobuf: 2542 classes and 26202 functions and methods against 2208 and 23811, no name made of a
|
|
515
|
+
# macro left. shortcut: a constant (`INT_MAX`) or a class (`struct MY_POINT {`) so named is erased too,
|
|
516
|
+
# and a macro with arguments (`PROTOBUF_ALIGNAS(8)`) is not; to tell them apart if a host loses code.
|
|
517
|
+
tolerant=True, erased=re.compile(rb"\b[A-Z][A-Z0-9]*_[A-Z0-9_]*[A-Z0-9]\b(?!\s*\()"))
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
@functools.cache
|
|
521
|
+
def _query(grammar: tree_sitter.Language, text: str) -> tree_sitter.Query:
|
|
522
|
+
return tree_sitter.Query(grammar, text)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def _grammar(language: Language, file: str) -> tuple[tree_sitter.Language, str]:
|
|
526
|
+
return next(g for suffix, g in language.grammars.items() if file.endswith(suffix))
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def read(language: Language, file: str, source: bytes) -> tuple[list[Definition], list[Use]]:
|
|
530
|
+
"""A file's definitions and uses, each use with its owner. Raises SyntaxError if the file does not parse and the
|
|
531
|
+
language is not `tolerant`."""
|
|
532
|
+
grammar, text = _grammar(language, file)
|
|
533
|
+
if language.erased:
|
|
534
|
+
source = language.erased.sub(lambda m: b" " * len(m[0]), source)
|
|
535
|
+
root = tree_sitter.Parser(grammar).parse(source).root_node
|
|
536
|
+
# shortcut: unless the language is `tolerant`, one error node skips the whole file (protobuf: 5 Kotlin files,
|
|
537
|
+
# BACKLOG.md); to make it `tolerant` once measured on its host, or a newer grammar, when one is published.
|
|
538
|
+
if root.has_error and not language.tolerant:
|
|
539
|
+
raise SyntaxError(file)
|
|
540
|
+
found = [] # (start, end, role, name node, receiver, node)
|
|
541
|
+
for _, captures in tree_sitter.QueryCursor(_query(grammar, text)).matches(root):
|
|
542
|
+
role = next(r for r in DEFINITIONS + USES if r in captures)
|
|
543
|
+
node, name = captures[role][0], captures["name"][0]
|
|
544
|
+
if name.is_missing: # a name the grammar inserted to recover: C++'s `enum : int {..}` (T-0034)
|
|
545
|
+
continue
|
|
546
|
+
found.append((node.start_byte, node.end_byte, role, name, captures.get("receiver", [None])[0], node))
|
|
547
|
+
definitions, uses = [], []
|
|
548
|
+
# A file's definitions of one kind and name are one: Rust's `struct T` and its `impl T`, Java's overloads.
|
|
549
|
+
# shortcut: the line (and the extent) is the first one's; to give the node every line if `explain --source`
|
|
550
|
+
# needs the others. A class in a class is `Outer.Inner` (T-0043), so `X.Builder` and `Y.Builder` stay apart.
|
|
551
|
+
# shortcut: an anonymous class is no class, its methods the enclosing class's (`A.run`); to make its body a
|
|
552
|
+
# `@class` if a host needs them apart.
|
|
553
|
+
by_kind_name: dict[tuple[str, str], Definition] = {}
|
|
554
|
+
stack: list[tuple[int, Definition]] = [] # the open definitions: (their end, them)
|
|
555
|
+
bare = None # the last action without a body, and its node: it leads to the case that follows it
|
|
556
|
+
# By position, an outer node before the inner one it starts with (`f(g())`), a definition before a use there.
|
|
557
|
+
for start, end, role, name_node, receiver, node in sorted(found, key=lambda f: (f[0], -f[1], f[2] in USES)):
|
|
558
|
+
while stack and stack[-1][0] <= start:
|
|
559
|
+
stack.pop()
|
|
560
|
+
name, line = name_node.text.decode("utf-8", "replace"), name_node.start_point[0] + 1
|
|
561
|
+
if role in USES:
|
|
562
|
+
used = source[start:name_node.end_byte].decode("utf-8", "replace")
|
|
563
|
+
uses.append(Use(role, name, line, stack[-1][1] if stack else None, re.sub(r"\s+", "", used)[:60]))
|
|
564
|
+
continue
|
|
565
|
+
if role == "action" and stack:
|
|
566
|
+
continue # a function's own `switch`, or one nested in an action: no entry point's, its calls stay there
|
|
567
|
+
kind = role
|
|
568
|
+
# shortcut: a `@receiver` is a last name, so a method declared outside its nested class (C++'s
|
|
569
|
+
# `Outer::Inner::m`, Kotlin's `fun Outer.Inner.f()`, Swift's `extension Outer.Inner`) is `Inner.m`, apart from
|
|
570
|
+
# the class's own `Outer.Inner.m`; to capture the receiver's whole path if a host's `explain` needs them together.
|
|
571
|
+
cls = receiver.text.decode("utf-8", "replace") if receiver is not None else \
|
|
572
|
+
next((d.name for _, d in reversed(stack) if d.kind == "class"), None)
|
|
573
|
+
if role == "class":
|
|
574
|
+
name = f"{cls}.{name}" if cls else name
|
|
575
|
+
elif role != "action": # an action is named as it is, in no class
|
|
576
|
+
kind, name = ("method", f"{cls}.{name}") if cls else ("function", name)
|
|
577
|
+
if (kind, name) not in by_kind_name:
|
|
578
|
+
by_kind_name[kind, name] = Definition(kind, name, line)
|
|
579
|
+
definitions.append(by_kind_name[kind, name])
|
|
580
|
+
if bare and kind == "action" and bare[0].name != name:
|
|
581
|
+
following = bare[1].next_named_sibling
|
|
582
|
+
while following is not None and following.type == "comment":
|
|
583
|
+
following = following.next_named_sibling
|
|
584
|
+
if following == node: # not past a `default:` or a case of another value, nor into another switch
|
|
585
|
+
uses.append(Use("dispatches", name, line, bare[0], name))
|
|
586
|
+
if kind == "action":
|
|
587
|
+
# without a body: nothing but punctuation after its name (`case 'liste':`)
|
|
588
|
+
empty = not re.search(rb"\w", source[name_node.end_byte:end])
|
|
589
|
+
bare = (by_kind_name[kind, name], node) if empty else None
|
|
590
|
+
stack.append((end, by_kind_name[kind, name]))
|
|
591
|
+
return definitions, uses
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
def _id(text: str) -> str:
|
|
595
|
+
return re.sub(r"\W", "_", text).lower()
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def contribute(language: Language, project) -> dict:
|
|
599
|
+
"""The contribution of one language (docs/contribution.md): only its own definitions are linked. A host without
|
|
600
|
+
its files contributes nothing, not even an empty coverage."""
|
|
601
|
+
paths = sorted({p for suffix in language.grammars for p in project.files(suffix)})
|
|
602
|
+
if not paths:
|
|
603
|
+
return {}
|
|
604
|
+
nodes, links, sites, ids = [], [], [], set()
|
|
605
|
+
|
|
606
|
+
def node(nid: str, label: str, kind: str, rel: str, line: int, name: str) -> str:
|
|
607
|
+
base, n = nid, 2 # made unique (`Get` and `get`, two `init`): an id taken would merge them
|
|
608
|
+
while nid in ids:
|
|
609
|
+
nid, n = f"{base}_{n}", n + 1
|
|
610
|
+
ids.add(nid)
|
|
611
|
+
nodes.append({"id": nid, "label": label, "kind": kind, "source_file": rel, "source_location": f"L{line}",
|
|
612
|
+
"name": name})
|
|
613
|
+
return nid
|
|
614
|
+
|
|
615
|
+
def link(source: str, target: str, relation: str, rel: str, line: int, sure: bool = True) -> None:
|
|
616
|
+
links.append({"source": source, "target": target, "relation": relation,
|
|
617
|
+
"confidence": "EXTRACTED" if sure else "INFERRED", "source_file": rel,
|
|
618
|
+
"source_location": f"L{line}", "context": ""})
|
|
619
|
+
|
|
620
|
+
files = [] # (rel, the file's id, the id of each definition, the uses)
|
|
621
|
+
callables: dict[str, list[str]] = defaultdict(list) # bare name -> function and method ids
|
|
622
|
+
classes: dict[str, list[str]] = defaultdict(list)
|
|
623
|
+
for path in paths:
|
|
624
|
+
rel = path.relative_to(project.root).as_posix()
|
|
625
|
+
try:
|
|
626
|
+
definitions, uses = read(language, rel, path.read_bytes())
|
|
627
|
+
except SyntaxError:
|
|
628
|
+
print(f"graphe: {rel} does not parse ({language.name}): skipped", file=sys.stderr)
|
|
629
|
+
continue
|
|
630
|
+
fid = node(_id(rel), rel.rsplit("/", 1)[-1], "file", rel, 1, rel)
|
|
631
|
+
held = {d: node(f"{fid}_action_{_id(d.name)}" if d.kind == "action" else f"{fid}_{_id(d.name)}",
|
|
632
|
+
d.name if d.kind in ("class", "action") else f"{d.name}()", d.kind, rel, d.line, d.name)
|
|
633
|
+
for d in definitions}
|
|
634
|
+
in_file = {d.name: held[d] for d in definitions if d.kind == "class"}
|
|
635
|
+
for d in definitions:
|
|
636
|
+
# by the bare name a use carries: `Inner` for `Outer.Inner`, `m` for `T.m`; no call reaches an action
|
|
637
|
+
if d.kind != "action":
|
|
638
|
+
(classes if d.kind == "class" else callables)[d.name.rsplit(".", 1)[-1]].append(held[d])
|
|
639
|
+
# a method's class holds it when it is defined in the same file (Go's type is often in another one)
|
|
640
|
+
cls = d.name.rsplit(".", 1)[0] if d.kind == "method" else None
|
|
641
|
+
link(in_file.get(cls, fid), held[d], "contains", rel, d.line)
|
|
642
|
+
files.append((rel, fid, held, uses))
|
|
643
|
+
functions = {n["id"] for n in nodes if n["kind"] == "function"}
|
|
644
|
+
for rel, fid, held, uses in files:
|
|
645
|
+
actions = {d.name: i for d, i in held.items() if d.kind == "action"}
|
|
646
|
+
for u in uses:
|
|
647
|
+
owner = held[u.owner] if u.owner else fid
|
|
648
|
+
if u.kind == "dispatches":
|
|
649
|
+
link(owner, actions[u.name], "dispatches", rel, u.line)
|
|
650
|
+
continue
|
|
651
|
+
ours = (classes if u.kind == "reference" else callables).get(u.name, [])
|
|
652
|
+
if u.kind != "reference":
|
|
653
|
+
if language.apart:
|
|
654
|
+
ours = [t for t in ours if (t in functions) == (u.kind == "call")]
|
|
655
|
+
verdict = "external" if not ours else "common" if u.kind == "send" and u.name in language.common \
|
|
656
|
+
else "ours?" if len(ours) == 1 else "ambiguous"
|
|
657
|
+
sites.append({"verdict": verdict, "file": rel, "line": u.line, "name": u.name, "text": u.text})
|
|
658
|
+
if verdict != "ours?":
|
|
659
|
+
continue
|
|
660
|
+
if len(ours) == 1 and ours[0] != owner:
|
|
661
|
+
link(owner, ours[0], "calls" if u.kind != "reference" else "references", rel, u.line, sure=False)
|
|
662
|
+
return {"nodes": nodes, "links": links, "sites": sites}
|