neuroplex 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/brain/build.js +6 -4
  2. package/dist/brain/build.js.map +1 -1
  3. package/dist/brain/obsidian.js +4 -0
  4. package/dist/brain/obsidian.js.map +1 -1
  5. package/dist/cli/index.js +7 -3
  6. package/dist/cli/index.js.map +1 -1
  7. package/dist/config/config.d.ts +9 -0
  8. package/dist/config/config.js +19 -0
  9. package/dist/config/config.js.map +1 -1
  10. package/dist/enrich/tasks.js +2 -0
  11. package/dist/enrich/tasks.js.map +1 -1
  12. package/dist/enrich/write.js +2 -2
  13. package/dist/enrich/write.js.map +1 -1
  14. package/dist/graph/schema.d.ts +1 -0
  15. package/dist/graph/schema.js +2 -0
  16. package/dist/graph/schema.js.map +1 -1
  17. package/dist/mcp/http.js +2 -1
  18. package/dist/mcp/http.js.map +1 -1
  19. package/dist/mcp/server.d.ts +1 -1
  20. package/dist/mcp/server.js +24 -2
  21. package/dist/mcp/server.js.map +1 -1
  22. package/dist/query/cli.d.ts +1 -0
  23. package/dist/query/cli.js +16 -2
  24. package/dist/query/cli.js.map +1 -1
  25. package/dist/query/queries.d.ts +4 -0
  26. package/dist/query/queries.js +2 -0
  27. package/dist/query/queries.js.map +1 -1
  28. package/dist/query/search.js +1 -1
  29. package/dist/query/search.js.map +1 -1
  30. package/dist/query/source.d.ts +36 -0
  31. package/dist/query/source.js +94 -0
  32. package/dist/query/source.js.map +1 -0
  33. package/dist/scan/assemble.js +29 -103
  34. package/dist/scan/assemble.js.map +1 -1
  35. package/dist/scan/discover.js +12 -0
  36. package/dist/scan/discover.js.map +1 -1
  37. package/dist/scan/docs.d.ts +20 -0
  38. package/dist/scan/docs.js +217 -0
  39. package/dist/scan/docs.js.map +1 -0
  40. package/dist/scan/extract.d.ts +1 -1
  41. package/dist/scan/extract.js +18 -3
  42. package/dist/scan/extract.js.map +1 -1
  43. package/dist/scan/extractors/csharp.js +39 -0
  44. package/dist/scan/extractors/csharp.js.map +1 -1
  45. package/dist/scan/extractors/go.d.ts +4 -0
  46. package/dist/scan/extractors/go.js +743 -0
  47. package/dist/scan/extractors/go.js.map +1 -0
  48. package/dist/scan/extractors/java.d.ts +4 -0
  49. package/dist/scan/extractors/java.js +571 -0
  50. package/dist/scan/extractors/java.js.map +1 -0
  51. package/dist/scan/extractors/php.d.ts +4 -0
  52. package/dist/scan/extractors/php.js +775 -0
  53. package/dist/scan/extractors/php.js.map +1 -0
  54. package/dist/scan/extractors/rust.d.ts +4 -0
  55. package/dist/scan/extractors/rust.js +681 -0
  56. package/dist/scan/extractors/rust.js.map +1 -0
  57. package/dist/scan/parser.js +4 -0
  58. package/dist/scan/parser.js.map +1 -1
  59. package/dist/scan/resolve-named.d.ts +39 -0
  60. package/dist/scan/resolve-named.js +198 -0
  61. package/dist/scan/resolve-named.js.map +1 -0
  62. package/dist/scan/types.d.ts +5 -1
  63. package/dist/scan/types.js +1 -1
  64. package/dist/scan/types.js.map +1 -1
  65. package/package.json +1 -1
@@ -0,0 +1,681 @@
1
+ import { lineRange, namedChildren } from '../parser.js';
2
+ import { emptyExtraction, } from '../types.js';
3
+ const ROUTE_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options']);
4
+ const REQUEST_VERBS = new Set(['get', 'post', 'put', 'patch', 'delete', 'head']);
5
+ /** Axum / actix method routers: `get(h)`, `web::post().to(h)`, `any(h)`. */
6
+ const ROUTER_VERBS = new Set([...ROUTE_VERBS, 'any']);
7
+ /** Smart pointers and containers whose inner type is the interesting one. */
8
+ const WRAPPERS = new Set(['Arc', 'Rc', 'Box', 'Mutex', 'RwLock', 'RefCell', 'Cell', 'Weak', 'Option', 'Pin', 'Cow']);
9
+ const LITERALS = new Set([
10
+ 'integer_literal',
11
+ 'float_literal',
12
+ 'string_literal',
13
+ 'raw_string_literal',
14
+ 'char_literal',
15
+ 'boolean_literal',
16
+ 'negative_literal',
17
+ ]);
18
+ const COMMENTS = new Set(['line_comment', 'block_comment']);
19
+ const TYPE_KINDS = {
20
+ struct_item: 'class',
21
+ union_item: 'class',
22
+ enum_item: 'type',
23
+ type_item: 'type',
24
+ trait_item: 'interface',
25
+ };
26
+ /** Associated functions that build a value of their type (`let x = T::new()`). */
27
+ const CONSTRUCTOR = /^(new|default|with_\w+|from\w*|builder)$/;
28
+ const PATH_KEYWORDS = new Set(['self', 'super', 'crate']);
29
+ /** Extracts symbols, imports, calls, heritage, HTTP routes and requests from a Rust tree. */
30
+ export function extractRust(root) {
31
+ const ctx = {
32
+ out: emptyExtraction(),
33
+ names: new Set(),
34
+ callKeys: new Set(),
35
+ requestKeys: new Set(),
36
+ heritageKeys: new Set(),
37
+ scopes: new Map(),
38
+ };
39
+ collectScopes(root, ctx.scopes);
40
+ visitItems(namedChildren(root), '', ctx);
41
+ collectImports(root, ctx.out.imports);
42
+ return ctx.out;
43
+ }
44
+ // ---------------------------------------------------------------------------
45
+ // Items
46
+ /** Visits the items of a file or inline module; `prefix` is `''` or `module.`. */
47
+ function visitItems(nodes, prefix, ctx) {
48
+ const typeExports = new Map();
49
+ for (const node of nodes) {
50
+ const name = node.childForFieldName('name')?.text;
51
+ if (name && TYPE_KINDS[node.type])
52
+ typeExports.set(name, isPub(node));
53
+ }
54
+ let attrs = [];
55
+ for (const node of nodes) {
56
+ if (node.type === 'attribute_item') {
57
+ attrs.push(node);
58
+ continue;
59
+ }
60
+ if (COMMENTS.has(node.type))
61
+ continue;
62
+ const range = rangeWithAttrs(node, attrs);
63
+ const itemAttrs = attrs;
64
+ attrs = [];
65
+ if (node.type === 'ERROR')
66
+ continue;
67
+ visitItem(node, itemAttrs, range, prefix, typeExports, ctx);
68
+ }
69
+ }
70
+ function visitItem(node, attrs, range, prefix, typeExports, ctx) {
71
+ const name = node.childForFieldName('name')?.text;
72
+ const typeKind = TYPE_KINDS[node.type];
73
+ if (node.type === 'function_item' && name) {
74
+ const http = routeOf(attrs, name, ctx.scopes);
75
+ const qualified = addSymbol(`${prefix}${name}`, http ? 'route' : 'function', range, isPub(node), ctx, http);
76
+ walkFunction(node, qualified, undefined, ctx);
77
+ }
78
+ else if (typeKind && name) {
79
+ addSymbol(`${prefix}${name}`, typeKind, range, isPub(node), ctx);
80
+ if (node.type === 'trait_item')
81
+ visitTrait(node, `${prefix}${name}`, isPub(node), ctx);
82
+ }
83
+ else if (node.type === 'impl_item') {
84
+ visitImpl(node, prefix, typeExports, ctx);
85
+ }
86
+ else if ((node.type === 'const_item' || node.type === 'static_item') && name) {
87
+ const value = node.childForFieldName('value');
88
+ if (!value || !LITERALS.has(value.type))
89
+ return;
90
+ const text = value.text.length > 120 ? `${value.text.slice(0, 117)}...` : value.text;
91
+ const qualified = `${prefix}${name}`;
92
+ if (ctx.names.has(qualified))
93
+ return;
94
+ ctx.names.add(qualified);
95
+ ctx.out.symbols.push({ name: qualified, kind: 'variable', range, exported: isPub(node), doc: `= ${text}` });
96
+ }
97
+ else if (node.type === 'mod_item' && name) {
98
+ const body = node.childForFieldName('body');
99
+ if (body)
100
+ visitItems(namedChildren(body), `${prefix}${name}.`, ctx);
101
+ }
102
+ }
103
+ /** `trait A: B + C { fn x(&self); fn y() {} }`. */
104
+ function visitTrait(node, trait, exported, ctx) {
105
+ const bounds = node.childForFieldName('bounds');
106
+ for (const bound of bounds ? namedChildren(bounds) : []) {
107
+ const target = typeName(bound);
108
+ if (target)
109
+ addHeritage(trait, 'extends', target, ctx);
110
+ }
111
+ const body = node.childForFieldName('body');
112
+ if (!body)
113
+ return;
114
+ forEachMember(body, (member, range) => {
115
+ const name = member.childForFieldName('name')?.text;
116
+ if (!name || (member.type !== 'function_item' && member.type !== 'function_signature_item'))
117
+ return;
118
+ const qualified = addSymbol(`${trait}.${name}`, 'method', range, exported, ctx);
119
+ if (member.type === 'function_item')
120
+ walkFunction(member, qualified, lastSegment(trait), ctx);
121
+ });
122
+ }
123
+ /** `impl Type { .. }` and `impl Trait for Type { .. }`. */
124
+ function visitImpl(node, prefix, typeExports, ctx) {
125
+ const typeNode = node.childForFieldName('type');
126
+ const type = typeNode ? baseTypeName(typeNode) : undefined;
127
+ if (!type)
128
+ return;
129
+ const owner = `${prefix}${type}`;
130
+ const traitNode = node.childForFieldName('trait');
131
+ const trait = traitNode ? typeName(traitNode) : undefined;
132
+ if (trait)
133
+ addHeritage(owner, 'implements', trait, ctx);
134
+ const typeExported = typeExports.get(type) ?? true;
135
+ const body = node.childForFieldName('body');
136
+ if (!body)
137
+ return;
138
+ forEachMember(body, (member, range) => {
139
+ const name = member.childForFieldName('name')?.text;
140
+ if (member.type !== 'function_item' || !name)
141
+ return;
142
+ const exported = trait ? typeExported : isPub(member);
143
+ const qualified = addSymbol(`${owner}.${name}`, 'method', range, exported, ctx);
144
+ walkFunction(member, qualified, type, ctx);
145
+ });
146
+ }
147
+ /** Calls `fn` for each member of a declaration list, with its range including attributes. */
148
+ function forEachMember(body, fn) {
149
+ let attrs = [];
150
+ for (const member of namedChildren(body)) {
151
+ if (member.type === 'attribute_item') {
152
+ attrs.push(member);
153
+ continue;
154
+ }
155
+ if (COMMENTS.has(member.type))
156
+ continue;
157
+ const range = rangeWithAttrs(member, attrs);
158
+ attrs = [];
159
+ if (member.type !== 'ERROR')
160
+ fn(member, range);
161
+ }
162
+ }
163
+ /**
164
+ * Reports a symbol and returns its qualified name. A repeated name (e.g. `fmt` from two
165
+ * trait impls) keeps the first symbol, and the later body's calls are attributed to it.
166
+ */
167
+ function addSymbol(name, kind, range, exported, ctx, http) {
168
+ if (ctx.names.has(name))
169
+ return name;
170
+ ctx.names.add(name);
171
+ ctx.out.symbols.push({ name, kind, range, exported, ...(http ? { http } : {}) });
172
+ return name;
173
+ }
174
+ function addHeritage(symbol, relation, target, ctx) {
175
+ const key = `${symbol}\0${relation}\0${target}`;
176
+ if (ctx.heritageKeys.has(key))
177
+ return;
178
+ ctx.heritageKeys.add(key);
179
+ ctx.out.heritage.push({ symbol, relation, target });
180
+ }
181
+ const isPub = (node) => namedChildren(node).some((c) => c.type === 'visibility_modifier');
182
+ function rangeWithAttrs(node, attrs) {
183
+ const range = lineRange(node);
184
+ const first = attrs[0];
185
+ return first ? { start: first.startPosition.row + 1, end: range.end } : range;
186
+ }
187
+ const lastSegment = (path) => path.slice(path.lastIndexOf('.') + 1);
188
+ /** Type name as written, generics dropped, `::` as `.`: `fmt::Display<T>` → `fmt.Display`. */
189
+ function typeName(node) {
190
+ if (node.type === 'generic_type') {
191
+ const inner = node.childForFieldName('type');
192
+ return inner ? typeName(inner) : undefined;
193
+ }
194
+ if (node.type === 'type_identifier' || node.type === 'identifier')
195
+ return node.text;
196
+ if (node.type === 'scoped_type_identifier' || node.type === 'scoped_identifier') {
197
+ return node.text.replace(/\s+/g, '').replace(/::/g, '.').replace(/^\./, '');
198
+ }
199
+ return undefined;
200
+ }
201
+ /** Last segment of a type, generics and path dropped: `crate::m::S<T>` → `S`. */
202
+ function baseTypeName(node) {
203
+ const name = typeName(node);
204
+ return name ? lastSegment(name) : undefined;
205
+ }
206
+ /**
207
+ * The user type behind references and wrappers: `&mut T`, `Arc<Mutex<T>>`, `Box<dyn T>` → `T`.
208
+ * Primitives give undefined; `Self` gives `selfType`.
209
+ */
210
+ function innerType(node, selfType) {
211
+ if (!node)
212
+ return undefined;
213
+ switch (node.type) {
214
+ case 'reference_type':
215
+ case 'pointer_type':
216
+ return innerType(node.childForFieldName('type'), selfType);
217
+ case 'dynamic_type':
218
+ case 'abstract_type':
219
+ return innerType(node.childForFieldName('trait'), selfType);
220
+ case 'generic_type': {
221
+ const base = baseTypeName(node);
222
+ const typeArgs = node.childForFieldName('type_arguments');
223
+ const firstArg = (typeArgs ? namedChildren(typeArgs) : []).find((c) => c.type !== 'lifetime' && !COMMENTS.has(c.type));
224
+ if (base && WRAPPERS.has(base) && firstArg)
225
+ return innerType(firstArg, selfType);
226
+ return base;
227
+ }
228
+ case 'type_identifier':
229
+ case 'scoped_type_identifier': {
230
+ const base = baseTypeName(node);
231
+ return base === 'Self' ? selfType : base;
232
+ }
233
+ default:
234
+ return undefined;
235
+ }
236
+ }
237
+ // ---------------------------------------------------------------------------
238
+ // HTTP routes declared with attributes (actix-web, Rocket)
239
+ /** `#[get("/p")]`, `#[route("/p", method = "POST")]` → endpoint; null otherwise. */
240
+ function routeOf(attrs, fnName, scopes) {
241
+ for (const item of attrs) {
242
+ const attr = namedChildren(item).find((c) => c.type === 'attribute');
243
+ const head = attr ? namedChildren(attr)[0] : undefined;
244
+ const name = head ? lastSegment(typeName(head) ?? '') : '';
245
+ const args = attr?.childForFieldName('arguments');
246
+ if (!args || (name !== 'route' && !ROUTE_VERBS.has(name)))
247
+ continue;
248
+ const tokens = namedChildren(args);
249
+ const pathNode = tokens.find((t) => t.type === 'string_literal');
250
+ const path = pathNode ? stringContent(pathNode) : undefined;
251
+ if (path === undefined)
252
+ continue;
253
+ let method = name.toUpperCase();
254
+ if (name === 'route') {
255
+ const at = tokens.findIndex((t, i) => t.text === 'method' && tokens[i + 1]?.type === 'string_literal');
256
+ const methodNode = at >= 0 ? tokens[at + 1] : undefined;
257
+ method = methodNode ? (stringContent(methodNode) ?? 'ANY').toUpperCase() : 'ANY';
258
+ }
259
+ return { method, path: joinPath(scopes.get(fnName) ?? '', path) };
260
+ }
261
+ return undefined;
262
+ }
263
+ function joinPath(prefix, path) {
264
+ const joined = `/${prefix}/${path}`.replace(/\/{2,}/g, '/');
265
+ return joined.length > 1 && path === '' ? joined.replace(/\/$/, '') : joined;
266
+ }
267
+ /**
268
+ * actix `web::scope("/api").service(handler)` (scopes may nest through `.service(web::scope(..))`):
269
+ * records handler name → full scope prefix.
270
+ */
271
+ function collectScopes(node, scopes) {
272
+ if (node.type === 'ERROR')
273
+ return;
274
+ if (node.type === 'call_expression' && node.parent?.type !== 'field_expression') {
275
+ const links = chainLinks(node);
276
+ const root = links[0];
277
+ if (root?.name === 'scope') {
278
+ const pathArg = root.args[0];
279
+ const path = pathArg ? stringContent(pathArg) : undefined;
280
+ if (path !== undefined)
281
+ registerScope(links, path, scopes);
282
+ }
283
+ }
284
+ for (const child of namedChildren(node))
285
+ collectScopes(child, scopes);
286
+ }
287
+ function registerScope(links, prefix, scopes) {
288
+ for (const link of links) {
289
+ if (link.name !== 'service')
290
+ continue;
291
+ for (const arg of link.args) {
292
+ if (arg.type === 'identifier' || arg.type === 'scoped_identifier') {
293
+ const handler = lastSegment(typeName(arg) ?? '');
294
+ if (handler && !scopes.has(handler))
295
+ scopes.set(handler, prefix);
296
+ }
297
+ else if (arg.type === 'call_expression') {
298
+ const inner = chainLinks(arg);
299
+ const innerPath = inner[0]?.name === 'scope' && inner[0].args[0] ? stringContent(inner[0].args[0]) : undefined;
300
+ if (innerPath !== undefined)
301
+ registerScope(inner, joinPath(prefix, innerPath), scopes);
302
+ }
303
+ }
304
+ }
305
+ }
306
+ /** A call chain from its root: `a::b(x).c(y).d()` → [b(x), c(y), d()]. Empty if not a chain of calls. */
307
+ function chainLinks(call) {
308
+ const links = [];
309
+ let node = call;
310
+ while (node?.type === 'call_expression') {
311
+ const fn = node.childForFieldName('function');
312
+ const argsNode = node.childForFieldName('arguments');
313
+ const args = argsNode ? namedChildren(argsNode).filter((a) => !COMMENTS.has(a.type)) : [];
314
+ if (fn?.type === 'field_expression') {
315
+ links.unshift({ name: fn.childForFieldName('field')?.text ?? '', args, call: node });
316
+ node = fn.childForFieldName('value');
317
+ }
318
+ else {
319
+ const name = fn ? lastSegment(typeName(fn) ?? '') : '';
320
+ links.unshift({ name, args, call: node });
321
+ node = null;
322
+ }
323
+ }
324
+ return links;
325
+ }
326
+ /**
327
+ * Method routers: `get(h).post(c)` (axum), `web::get().to(h)` (actix) → [[GET, h], [POST, c]].
328
+ */
329
+ function methodHandlers(router) {
330
+ const result = [];
331
+ let pending;
332
+ for (const link of chainLinks(router)) {
333
+ const handler = link.args[0];
334
+ if (ROUTER_VERBS.has(link.name)) {
335
+ const method = link.name === 'any' ? 'ANY' : link.name.toUpperCase();
336
+ if (handler)
337
+ result.push([method, handler]);
338
+ else
339
+ pending = method;
340
+ }
341
+ else if (link.name === 'to' && pending && handler) {
342
+ result.push([pending, handler]);
343
+ pending = undefined;
344
+ }
345
+ }
346
+ return result;
347
+ }
348
+ /** `.route("/p", get(h).post(c))`: one route symbol per method, each calling its handler. */
349
+ function recordRouterRoute(call, prefix, scope, ctx) {
350
+ const fn = call.childForFieldName('function');
351
+ if (fn?.type !== 'field_expression' || fn.childForFieldName('field')?.text !== 'route')
352
+ return;
353
+ const argsNode = call.childForFieldName('arguments');
354
+ const args = argsNode ? namedChildren(argsNode).filter((a) => !COMMENTS.has(a.type)) : [];
355
+ const [pathNode, router] = args;
356
+ const path = pathNode ? stringContent(pathNode) : undefined;
357
+ if (path === undefined || router?.type !== 'call_expression' || !argsNode)
358
+ return;
359
+ const range = lineRange(argsNode);
360
+ for (const [method, handler] of methodHandlers(router)) {
361
+ const http = { method, path: joinPath(prefix, path) };
362
+ const base = `${method} ${http.path}`;
363
+ let name = base;
364
+ for (let n = 2; ctx.names.has(name); n++)
365
+ name = `${base} (${n})`;
366
+ addSymbol(name, 'route', range, false, ctx, http);
367
+ const target = callTarget(handler, { ...scope, caller: name });
368
+ if (target)
369
+ pushCall(name, target.callee, target.object, undefined, handler, ctx);
370
+ }
371
+ }
372
+ // ---------------------------------------------------------------------------
373
+ // Calls and requests
374
+ function walkFunction(fn, caller, selfType, ctx) {
375
+ const scope = { caller, vars: new Map(), selfType };
376
+ const params = fn.childForFieldName('parameters');
377
+ for (const param of params ? namedChildren(params) : []) {
378
+ if (param.type !== 'parameter')
379
+ continue;
380
+ const pattern = param.childForFieldName('pattern');
381
+ const type = innerType(param.childForFieldName('type'), selfType);
382
+ if (pattern?.type === 'identifier' && type)
383
+ scope.vars.set(pattern.text, type);
384
+ }
385
+ const body = fn.childForFieldName('body');
386
+ if (body)
387
+ walkCalls(body, scope, '', ctx);
388
+ }
389
+ /** `routePrefix` is the path prefix from enclosing axum `.nest("/p", ...)` calls. */
390
+ function walkCalls(node, scope, routePrefix, ctx) {
391
+ if (node.type === 'ERROR' || (node.type === 'macro_invocation' && !isFormat(node)))
392
+ return;
393
+ if (node.type === 'let_declaration')
394
+ recordLet(node, scope);
395
+ if (node.type === 'struct_expression')
396
+ recordStructLiteral(node, scope, ctx);
397
+ if (node.type === 'call_expression') {
398
+ recordCall(node, scope, ctx);
399
+ recordRequest(node, scope.caller, ctx);
400
+ const nested = nestPrefix(node);
401
+ if (nested) {
402
+ const fn = node.childForFieldName('function');
403
+ if (fn)
404
+ walkCalls(fn, scope, routePrefix, ctx);
405
+ walkCalls(nested.router, scope, joinPath(routePrefix, nested.path), ctx);
406
+ return;
407
+ }
408
+ }
409
+ for (const child of namedChildren(node))
410
+ walkCalls(child, scope, routePrefix, ctx);
411
+ // After the receiver chain, so a builder's routes are reported in source order.
412
+ if (node.type === 'call_expression')
413
+ recordRouterRoute(node, routePrefix, scope, ctx);
414
+ }
415
+ /** `.nest("/api", router)` → the prefix and the inline router expression. */
416
+ function nestPrefix(call) {
417
+ const fn = call.childForFieldName('function');
418
+ if (fn?.type !== 'field_expression' || fn.childForFieldName('field')?.text !== 'nest')
419
+ return undefined;
420
+ const argsNode = call.childForFieldName('arguments');
421
+ const [pathNode, router] = argsNode ? namedChildren(argsNode).filter((a) => !COMMENTS.has(a.type)) : [];
422
+ const path = pathNode ? stringContent(pathNode) : undefined;
423
+ return path !== undefined && router ? { path, router } : undefined;
424
+ }
425
+ const isFormat = (node) => node.childForFieldName('macro')?.text === 'format';
426
+ /** `let x: T = ..`, `let x = T::new(..)`, `let x = T { .. }` → x: T. */
427
+ function recordLet(node, scope) {
428
+ const pattern = node.childForFieldName('pattern');
429
+ if (pattern?.type !== 'identifier')
430
+ return;
431
+ const declared = innerType(node.childForFieldName('type'), scope.selfType);
432
+ const type = declared ?? inferredType(node.childForFieldName('value'), scope.selfType);
433
+ if (type)
434
+ scope.vars.set(pattern.text, type);
435
+ }
436
+ function inferredType(value, selfType) {
437
+ let node = value;
438
+ while (node && (node.type === 'try_expression' || node.type === 'await_expression'))
439
+ node = namedChildren(node)[0] ?? null;
440
+ if (node?.type === 'struct_expression')
441
+ return innerType(node.childForFieldName('name'), selfType);
442
+ if (node?.type !== 'call_expression')
443
+ return undefined;
444
+ const fn = node.childForFieldName('function');
445
+ if (fn?.type !== 'scoped_identifier' || !CONSTRUCTOR.test(fn.childForFieldName('name')?.text ?? ''))
446
+ return undefined;
447
+ const path = fn.childForFieldName('path');
448
+ const type = path ? baseTypeName(path) : undefined;
449
+ if (!type || !/^[A-Z]/.test(type))
450
+ return undefined;
451
+ return type === 'Self' ? selfType : type;
452
+ }
453
+ /** Callee and receiver of a call's function node (or a handler reference); undefined when complex. */
454
+ function callTarget(fn, scope) {
455
+ if (fn.type === 'generic_function') {
456
+ const inner = fn.childForFieldName('function');
457
+ return inner ? callTarget(inner, scope) : undefined;
458
+ }
459
+ if (fn.type === 'identifier')
460
+ return { callee: fn.text };
461
+ if (fn.type === 'scoped_identifier') {
462
+ const callee = fn.childForFieldName('name')?.text;
463
+ const path = fn.childForFieldName('path');
464
+ if (!callee)
465
+ return undefined;
466
+ const object = path ? baseTypeName(path) : undefined;
467
+ return object && !PATH_KEYWORDS.has(object) ? { callee, object } : { callee };
468
+ }
469
+ if (fn.type === 'field_expression') {
470
+ const receiver = fn.childForFieldName('value');
471
+ const callee = fn.childForFieldName('field')?.text;
472
+ if (!callee || (receiver?.type !== 'identifier' && receiver?.type !== 'self'))
473
+ return undefined;
474
+ return { callee, object: receiver.text };
475
+ }
476
+ return undefined;
477
+ }
478
+ function recordCall(call, scope, ctx) {
479
+ const fn = call.childForFieldName('function');
480
+ const target = fn ? callTarget(fn, scope) : undefined;
481
+ if (!target)
482
+ return;
483
+ pushCall(scope.caller, target.callee, target.object, objectTypeOf(target.object, scope), call, ctx);
484
+ }
485
+ /** `Foo { .. }` counts as a call to `Foo` (`Self { .. }` to the impl type). */
486
+ function recordStructLiteral(node, scope, ctx) {
487
+ const nameNode = node.childForFieldName('name');
488
+ const callee = nameNode ? innerType(nameNode, scope.selfType) : undefined;
489
+ if (callee)
490
+ pushCall(scope.caller, callee, undefined, undefined, node, ctx);
491
+ }
492
+ function objectTypeOf(object, scope) {
493
+ if (object === 'self' || object === 'Self')
494
+ return scope.selfType;
495
+ return object === undefined ? undefined : scope.vars.get(object);
496
+ }
497
+ function pushCall(caller, callee, object, objectType, node, ctx) {
498
+ const key = `${caller}\0${callee}\0${object ?? ''}`;
499
+ if (ctx.callKeys.has(key))
500
+ return;
501
+ ctx.callKeys.add(key);
502
+ ctx.out.calls.push({
503
+ caller,
504
+ callee,
505
+ ...(object !== undefined ? { object } : {}),
506
+ ...(object !== undefined && objectType !== undefined ? { objectType } : {}),
507
+ line: node.startPosition.row + 1,
508
+ });
509
+ }
510
+ /**
511
+ * reqwest requests: `client.get(url)` (and the other verbs), `reqwest::get(url)`,
512
+ * `client.request(Method::POST, url)`, with a literal or `format!` URL.
513
+ */
514
+ function recordRequest(call, caller, ctx) {
515
+ const fn = call.childForFieldName('function');
516
+ const argsNode = call.childForFieldName('arguments');
517
+ if (!fn || !argsNode)
518
+ return;
519
+ const args = namedChildren(argsNode).filter((a) => !COMMENTS.has(a.type));
520
+ let verb;
521
+ if (fn.type === 'field_expression') {
522
+ verb = fn.childForFieldName('field')?.text;
523
+ }
524
+ else if (fn.type === 'scoped_identifier' && fn.childForFieldName('path')?.text === 'reqwest') {
525
+ verb = fn.childForFieldName('name')?.text;
526
+ }
527
+ if (!verb)
528
+ return;
529
+ let method;
530
+ let urlNode;
531
+ if (verb === 'request') {
532
+ const methodNode = args[0];
533
+ method = methodNode ? methodName(methodNode) : undefined;
534
+ urlNode = args[1];
535
+ }
536
+ else if (REQUEST_VERBS.has(verb)) {
537
+ method = verb.toUpperCase();
538
+ urlNode = args[0];
539
+ }
540
+ const url = urlNode ? urlValue(urlNode) : undefined;
541
+ if (!method || url === undefined || !/^(\/|https?:\/\/|\{\}\/)/.test(url))
542
+ return;
543
+ const key = `${caller}\0${method}\0${url}`;
544
+ if (ctx.requestKeys.has(key))
545
+ return;
546
+ ctx.requestKeys.add(key);
547
+ ctx.out.requests.push({ caller, method, url, line: call.startPosition.row + 1 });
548
+ }
549
+ /** `Method::POST`, `reqwest::Method::GET`, `"POST"`. */
550
+ function methodName(node) {
551
+ if (node.type === 'scoped_identifier')
552
+ return node.childForFieldName('name')?.text.toUpperCase();
553
+ return stringContent(node)?.toUpperCase();
554
+ }
555
+ /** A string literal, or a `format!` with interpolations as `{}`; `&` references are unwrapped. */
556
+ function urlValue(node) {
557
+ if (node.type === 'reference_expression') {
558
+ const value = node.childForFieldName('value');
559
+ return value ? urlValue(value) : undefined;
560
+ }
561
+ if (node.type === 'macro_invocation' && isFormat(node)) {
562
+ const tree = namedChildren(node).find((c) => c.type === 'token_tree');
563
+ const template = tree ? namedChildren(tree)[0] : undefined;
564
+ const text = template ? stringContent(template) : undefined;
565
+ if (text === undefined)
566
+ return undefined;
567
+ return text
568
+ .split(/(\{\{|\}\})/)
569
+ .map((part) => (part === '{{' ? '{' : part === '}}' ? '}' : part.replace(/\{[^{}]*\}/g, '{}')))
570
+ .join('');
571
+ }
572
+ return stringContent(node);
573
+ }
574
+ /** Content of a string or raw string literal, as written (escapes kept). */
575
+ function stringContent(node) {
576
+ if (node.type === 'string_literal')
577
+ return node.text.replace(/^b?"/, '').replace(/"$/, '');
578
+ if (node.type === 'raw_string_literal')
579
+ return node.text.replace(/^b?r#*"/, '').replace(/"#*$/, '');
580
+ return undefined;
581
+ }
582
+ // ---------------------------------------------------------------------------
583
+ // Imports
584
+ function collectImports(node, imports) {
585
+ if (node.type === 'ERROR')
586
+ return;
587
+ const line = node.startPosition.row + 1;
588
+ if (node.type === 'use_declaration') {
589
+ const argument = node.childForFieldName('argument');
590
+ if (argument)
591
+ useImports(argument, '', line, imports);
592
+ return;
593
+ }
594
+ if (node.type === 'mod_item' && !node.childForFieldName('body')) {
595
+ const name = node.childForFieldName('name')?.text;
596
+ if (name)
597
+ imports.push({ specifier: `self::${name}`, bindings: [{ local: name, imported: '*' }], line });
598
+ return;
599
+ }
600
+ if (node.type === 'extern_crate_declaration') {
601
+ const name = node.childForFieldName('name')?.text;
602
+ const local = node.childForFieldName('alias')?.text ?? name;
603
+ if (name && local)
604
+ imports.push({ specifier: name, bindings: [{ local, imported: '*' }], line });
605
+ return;
606
+ }
607
+ for (const child of namedChildren(node))
608
+ collectImports(child, imports);
609
+ }
610
+ const joinUse = (base, path) => (base && path ? `${base}::${path}` : base || path);
611
+ const pathText = (node) => (node ? node.text.replace(/\s+/g, '') : '');
612
+ /** One import per imported name of a `use` tree; `base` is the path of enclosing lists. */
613
+ function useImports(node, base, line, imports) {
614
+ const add = (specifier, local, imported) => {
615
+ if (specifier && local)
616
+ imports.push({ specifier, bindings: [{ local, imported }], line });
617
+ };
618
+ switch (node.type) {
619
+ case 'identifier':
620
+ case 'crate':
621
+ case 'super':
622
+ // `use serde;` imports a whole crate; in a list (`{a, b}`) a name from `base`.
623
+ if (base)
624
+ add(base, node.text, node.text);
625
+ else
626
+ add(node.text, node.text, '*');
627
+ return;
628
+ case 'self':
629
+ add(base, base.slice(base.lastIndexOf(':') + 1), '*');
630
+ return;
631
+ case 'scoped_identifier': {
632
+ const name = node.childForFieldName('name')?.text ?? '';
633
+ const specifier = joinUse(base, pathText(node.childForFieldName('path')));
634
+ if (name === 'self')
635
+ add(specifier, specifier.slice(specifier.lastIndexOf(':') + 1), '*');
636
+ else
637
+ add(specifier, name, name);
638
+ return;
639
+ }
640
+ case 'use_as_clause': {
641
+ const path = node.childForFieldName('path');
642
+ const alias = node.childForFieldName('alias')?.text ?? '';
643
+ if (!path)
644
+ return;
645
+ if (path.type === 'scoped_identifier') {
646
+ const name = path.childForFieldName('name')?.text ?? '';
647
+ const specifier = joinUse(base, pathText(path.childForFieldName('path')));
648
+ add(specifier, alias, name === 'self' ? '*' : name);
649
+ }
650
+ else if (path.type === 'self') {
651
+ add(base, alias, '*');
652
+ }
653
+ else if (base) {
654
+ add(base, alias, path.text);
655
+ }
656
+ else {
657
+ add(path.text, alias, '*');
658
+ }
659
+ return;
660
+ }
661
+ case 'use_wildcard': {
662
+ const path = namedChildren(node)[0];
663
+ add(joinUse(base, path ? pathText(path) : ''), '*', '*');
664
+ return;
665
+ }
666
+ case 'scoped_use_list': {
667
+ const list = node.childForFieldName('list');
668
+ const specifier = joinUse(base, pathText(node.childForFieldName('path')));
669
+ if (list)
670
+ useImports(list, specifier, line, imports);
671
+ return;
672
+ }
673
+ case 'use_list':
674
+ for (const item of namedChildren(node))
675
+ useImports(item, base, line, imports);
676
+ return;
677
+ default:
678
+ return;
679
+ }
680
+ }
681
+ //# sourceMappingURL=rust.js.map