meta-language 1.0.0

A self-describing links-network core for lossless language representation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
//! Project-aware JavaScript semantics: package.json dialect, name and import
//! map; ECMAScript module requests resolved to project files; named,
//! namespace and default imports, JSON modules with their import attributes,
//! tagged templates expanded into the call they denote, and project
//! references checked by `node:assert` assertions (runtime-checked
//! propositions: JavaScript has no proof terms). The JavaScript runtime
//! implements the same analysis in js/src/program-project-javascript.js.

use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;

use super::ProjectContext;
use super::tree::{NodeId, SyntaxTree, Target, declaration, dirname, join_path, json_string};

const ASSERT_MODULES: [&str; 4] = [
    "node:assert",
    "node:assert/strict",
    "assert",
    "assert/strict",
];

type Exports = Rc<BTreeMap<String, Target>>;

struct Local {
    path: String,
    name: String,
    exports: Exports,
}

#[derive(Default)]
struct Manifest {
    imports: BTreeMap<String, String>,
}

pub(super) fn analyze(context: &mut ProjectContext<'_>) {
    let manifest = read_package_manifest(context);
    let entry = Rc::clone(&context.entry);
    let tree = &entry.tree;
    let mut locals: BTreeMap<String, Local> = BTreeMap::new();
    let mut assertions: BTreeSet<String> = BTreeSet::new();
    let statements = tree
        .roots
        .iter()
        .flat_map(|root| tree.children_of(*root, &["import_statement"]))
        .collect::<Vec<_>>();
    for statement in statements {
        let Some(fragment) = tree
            .first_child(statement, &["string"])
            .and_then(|specifier| tree.first_child(specifier, &["string_fragment"]))
        else {
            continue;
        };
        let request = tree.text(fragment);
        let clause = tree.first_child(statement, &["import_clause"]);
        if ASSERT_MODULES.contains(&request) {
            for name in imported_locals(tree, clause) {
                assertions.insert(tree.text(name).to_string());
            }
            continue;
        }
        let Some(path) = resolve_request(request, &entry.path, &manifest) else {
            continue;
        };
        if !context.has(&path) {
            continue;
        }
        let range = tree.span(statement);
        context.module(request, &path, &path, range);
        let exports = Rc::new(module_exports(context, &path));
        let attribute = tree.first_child(statement, &["import_attribute"]);
        let kind = attribute.and_then(|attribute| import_attribute_type(tree, attribute));
        let json = is_json(&path);
        if json && kind != Some("json") {
            context.diagnose("missing-import-attribute", request.to_string(), range);
        }
        if kind == Some("json") && !json {
            context.diagnose("import-attribute-mismatch", request.to_string(), range);
        }
        if let (Some(attribute), Some("json"), true) = (attribute, kind, json)
            && let Some(target) = exports.get("default")
        {
            context.reference("attribute", "type: json", tree.span(attribute), target);
        }
        let Some(clause) = clause else {
            continue;
        };
        for child in tree.children(clause).to_vec() {
            match tree.term(child) {
                "identifier" => {
                    let local = tree.text(child);
                    import_name(
                        context,
                        &exports,
                        "default",
                        child,
                        local,
                        &mut locals,
                        &path,
                    );
                }
                "namespace_import" => {
                    let namespace = Target {
                        symbol: format!("{path}#*"),
                        kind: "namespace".to_string(),
                        traits: Vec::new(),
                        file: path.clone(),
                        start: 0,
                        end: context.text(&path).map_or(0, str::len),
                    };
                    context.reference("import", "*", tree.span(child), &namespace);
                    if let Some(local) = tree.first_child(child, &["identifier"]) {
                        locals.insert(
                            tree.text(local).to_string(),
                            Local {
                                path: path.clone(),
                                name: "*".to_string(),
                                exports: Rc::clone(&exports),
                            },
                        );
                    }
                }
                "named_imports" => {
                    for item in tree.children_of(child, &["import_specifier"]) {
                        let names = tree.children_of(item, &["identifier"]);
                        let (Some(first), Some(last)) = (names.first(), names.last()) else {
                            continue;
                        };
                        let (name, local) = (tree.text(*first), tree.text(*last));
                        import_name(context, &exports, name, item, local, &mut locals, &path);
                    }
                }
                _ => {}
            }
        }
    }
    let bindings = context.bindings;
    for binding in bindings.iter().filter(|binding| binding.kind == "import") {
        let Some(local) = locals.get(&binding.name) else {
            continue;
        };
        for range in &binding.references {
            if let Some(leaf) = tree.leaf_at(range.start(), range.end()) {
                let role = if inside_assertion(tree, leaf, &assertions) {
                    "assertion"
                } else {
                    "reference"
                };
                reference_use(context, tree, local, leaf, role);
            }
        }
    }
}

fn import_name(
    context: &mut ProjectContext<'_>,
    exports: &Exports,
    name: &str,
    node: NodeId,
    local: &str,
    locals: &mut BTreeMap<String, Local>,
    path: &str,
) {
    let range = context.entry.tree.span(node);
    let Some(target) = exports.get(name) else {
        context.diagnose("missing-project-symbol", format!("{path}#{name}"), range);
        return;
    };
    context.reference("import", name, range, target);
    locals.insert(
        local.to_string(),
        Local {
            path: path.to_string(),
            name: name.to_string(),
            exports: Rc::clone(exports),
        },
    );
}

/// One use of an imported local: a namespace or JSON member access, a tagged
/// template, or a plain reference.
fn reference_use(
    context: &mut ProjectContext<'_>,
    tree: &SyntaxTree,
    local: &Local,
    leaf: NodeId,
    role: &'static str,
) {
    let parent = tree.parent(leaf);
    let first = tree.is_first_child(leaf);
    let member = parent
        .filter(|parent| first && tree.term(*parent) == "member_expression")
        .and_then(|parent| tree.first_child(parent, &["property_identifier"]));
    if let (Some(member), Some(parent), true) =
        (member, parent, local.name == "*" || local.name == "default")
    {
        let name = if local.name == "*" {
            tree.text(member).to_string()
        } else {
            format!("default.{}", tree.text(member))
        };
        match local.exports.get(&name) {
            Some(target) => context.reference(role, &name, tree.span(parent), target),
            None => context.diagnose(
                "missing-project-symbol",
                format!("{}#{name}", local.path),
                tree.span(parent),
            ),
        }
        return;
    }
    let Some(target) = local.exports.get(&local.name) else {
        return;
    };
    let template = parent
        .filter(|parent| first && tree.term(*parent) == "call_expression")
        .and_then(|parent| tree.first_child(parent, &["template_string"]));
    if let (Some(template), Some(parent)) = (template, parent) {
        context.reference("template-tag", &local.name, tree.span(parent), target);
        if let Some(expansion) = template_call(tree, leaf, template) {
            context.expansion(
                &local.name,
                "tagged-template",
                tree.span(parent),
                expansion,
                &target.symbol,
            );
        }
        return;
    }
    context.reference(role, &local.name, tree.span(leaf), target);
}

/// The local identifiers an import clause binds.
fn imported_locals(tree: &SyntaxTree, clause: Option<NodeId>) -> Vec<NodeId> {
    let Some(clause) = clause else {
        return Vec::new();
    };
    tree.children(clause)
        .iter()
        .flat_map(|child| match tree.term(*child) {
            "identifier" => vec![*child],
            "namespace_import" => tree.children_of(*child, &["identifier"]),
            "named_imports" => tree
                .children_of(*child, &["import_specifier"])
                .into_iter()
                .filter_map(|item| tree.children_of(item, &["identifier"]).last().copied())
                .collect(),
            _ => Vec::new(),
        })
        .collect()
}

/// Whether a node is an argument of `assert(...)`, `assert.method(...)` for an
/// imported assertion module, or `console.assert(...)`.
fn inside_assertion(tree: &SyntaxTree, node: NodeId, assertions: &BTreeSet<String>) -> bool {
    let mut current = node;
    while let Some(call) = tree.parent(current) {
        if tree.term(call) == "call_expression" && tree.term(current) == "arguments" {
            let callee = tree.child(call, 0);
            let object = callee.and_then(|callee| {
                if tree.term(callee) == "member_expression" {
                    tree.child(callee, 0)
                } else {
                    Some(callee)
                }
            });
            if object.is_some_and(|object| {
                tree.term(object) == "identifier" && assertions.contains(tree.text(object))
            }) {
                return true;
            }
            if callee.is_some_and(|callee| {
                tree.term(callee) == "member_expression" && tree.text(callee) == "console.assert"
            }) {
                return true;
            }
        }
        current = call;
    }
    false
}

/// `` tag`a${x}b` `` calls tag with the frozen strings array (carrying its raw
/// strings) followed by the substituted values.
fn template_call(tree: &SyntaxTree, tag: NodeId, template: NodeId) -> Option<String> {
    let mut strings = Vec::new();
    let mut values = Vec::new();
    let mut current = String::new();
    for child in tree.children(template) {
        match tree.term(*child) {
            "string_fragment" => current.push_str(tree.text(*child)),
            "escape_sequence" => return None,
            "template_substitution" => {
                strings.push(std::mem::take(&mut current));
                let [_, inner, _] = tree.children(*child) else {
                    return None;
                };
                values.push(tree.text(*inner).to_string());
            }
            _ => {}
        }
    }
    strings.push(current);
    let array = format!(
        "[{}]",
        strings
            .iter()
            .map(|value| json_string(value))
            .collect::<Vec<_>>()
            .join(", ")
    );
    let argument =
        format!("Object.freeze(Object.assign({array}, {{ raw: Object.freeze({array}) }}))");
    let arguments = std::iter::once(argument)
        .chain(values)
        .collect::<Vec<_>>()
        .join(", ");
    Some(format!("{}({arguments})", tree.text(tag)))
}

fn import_attribute_type(tree: &SyntaxTree, attribute: NodeId) -> Option<&str> {
    for pair in tree.descendants(attribute, &["pair"]) {
        let key = tree.child(pair, 0);
        let fragment = tree
            .child(pair, 2)
            .filter(|value| tree.term(*value) == "string")
            .and_then(|value| tree.first_child(value, &["string_fragment"]));
        let name =
            key.map(|key| tree.text(tree.first_child(key, &["string_fragment"]).unwrap_or(key)));
        if let (Some(fragment), Some("type")) = (fragment, name) {
            return Some(tree.text(fragment));
        }
    }
    None
}

fn resolve_request(request: &str, entry: &str, manifest: &Manifest) -> Option<String> {
    if request.starts_with("./") || request.starts_with("../") {
        return Some(join_path(dirname(entry), request));
    }
    if request.starts_with('#') {
        return manifest
            .imports
            .get(request)
            .map(|target| join_path("", target));
    }
    None
}

/// package.json: the package name, its module dialect ("type"), the
/// package-internal import map and the declared dependencies.
fn read_package_manifest(context: &mut ProjectContext<'_>) -> Manifest {
    let mut manifest = Manifest::default();
    let Some(file) = context.load_as("package.json", "JSON") else {
        return manifest;
    };
    let tree = &file.tree;
    context.fact(
        "project-manifest",
        "package.json",
        "package.json",
        (0, file.source.len()),
    );
    let members = json_root(tree)
        .map(|root| json_members(tree, root))
        .unwrap_or_default();
    let text =
        |node: NodeId| tree.text(tree.first_child(node, &["string_content"]).unwrap_or(node));
    if let Some(name) = find(&members, "name").filter(|name| tree.term(*name) == "string") {
        context.fact(
            "project-package",
            text(name),
            "package.json",
            content_range(tree, name),
        );
    }
    let kind = find(&members, "type");
    let dialect = kind
        .filter(|kind| tree.term(*kind) == "string")
        .map_or("commonjs", text);
    let range = kind.map_or((0, 0), |kind| content_range(tree, kind));
    context.fact("project-dialect", dialect, "package.json", range);
    if let Some(imports) =
        find(&members, "imports").filter(|imports| tree.term(*imports) == "object")
    {
        for (key, value) in json_members(tree, imports) {
            if tree.term(value) != "string" {
                continue;
            }
            manifest
                .imports
                .insert(key.clone(), text(value).to_string());
            context.fact(
                "project-import-map",
                &key,
                "package.json",
                content_range(tree, value),
            );
        }
    }
    for section in ["dependencies", "devDependencies", "peerDependencies"] {
        let Some(dependencies) =
            find(&members, section).filter(|dependencies| tree.term(*dependencies) == "object")
        else {
            continue;
        };
        for (key, value) in json_members(tree, dependencies) {
            context.fact("project-dependency", &key, "package.json", tree.span(value));
        }
    }
    manifest
}

fn find(members: &[(String, NodeId)], key: &str) -> Option<NodeId> {
    // A later member with the same key replaces an earlier one.
    members
        .iter()
        .rev()
        .find(|(name, _)| name == key)
        .map(|(_, value)| *value)
}

fn content_range(tree: &SyntaxTree, node: NodeId) -> (usize, usize) {
    tree.first_child(node, &["string_content"]).map_or_else(
        || {
            let (start, end) = tree.span(node);
            (start + 1, end.saturating_sub(1))
        },
        |content| tree.span(content),
    )
}

fn json_root(tree: &SyntaxTree) -> Option<NodeId> {
    let document = tree
        .roots
        .iter()
        .copied()
        .find(|root| tree.term(*root) == "document")
        .or_else(|| tree.roots.first().copied())?;
    Some(tree.first_child(document, &["object"]).unwrap_or(document))
}

/// The members of a JSON object, keyed by their decoded-as-written key text,
/// in first-appearance order with the last value of a repeated key.
fn json_members(tree: &SyntaxTree, object: NodeId) -> Vec<(String, NodeId)> {
    let mut members: Vec<(String, NodeId)> = Vec::new();
    for pair in tree.children_of(object, &["pair"]) {
        let (Some(key), Some(value)) = (tree.child(pair, 0), tree.child(pair, 2)) else {
            continue;
        };
        let name = tree
            .first_child(key, &["string_content"])
            .map_or("", |content| tree.text(content))
            .to_string();
        if let Some(member) = members.iter_mut().find(|(existing, _)| *existing == name) {
            member.1 = value;
        } else {
            members.push((name, value));
        }
    }
    members
}

/// Whether a module path names a JSON module; as in Node.js, the extension is
/// compared case-sensitively.
#[allow(clippy::case_sensitive_file_extension_comparisons)]
fn is_json(path: &str) -> bool {
    path.ends_with(".json")
}

/// The exports of a project module: exported declarations of a JavaScript
/// module, or the default value and top-level members of a JSON module.
fn module_exports(context: &mut ProjectContext<'_>, path: &str) -> BTreeMap<String, Target> {
    let mut exports = BTreeMap::new();
    if is_json(path) {
        let Some(file) = context.load_as(path, "JSON") else {
            return exports;
        };
        let tree = &file.tree;
        let root = json_root(tree);
        let span = root.map_or((0, 0), |root| tree.span(root));
        exports.insert(
            "default".to_string(),
            declaration(path, "default", "json-value", &[], span),
        );
        if let Some(root) = root.filter(|root| tree.term(*root) == "object") {
            for pair in tree.children_of(root, &["pair"]) {
                let Some(key) = tree
                    .child(pair, 0)
                    .and_then(|key| tree.first_child(key, &["string_content"]))
                else {
                    continue;
                };
                let name = format!("default.{}", tree.text(key));
                let target = declaration(path, &name, "json-member", &[], tree.span(key));
                exports.insert(name, target);
            }
        }
        return exports;
    }
    let Some(file) = context.load(path) else {
        return exports;
    };
    let tree = &file.tree;
    let statements = tree
        .roots
        .iter()
        .flat_map(|root| tree.children_of(*root, &["export_statement"]))
        .collect::<Vec<_>>();
    for statement in statements {
        let declared = tree.first_child(
            statement,
            &[
                "function_declaration",
                "generator_function_declaration",
                "class_declaration",
                "lexical_declaration",
                "variable_declaration",
            ],
        );
        if tree.first_child(statement, &["default"]).is_some() {
            let span = tree.span(declared.unwrap_or(statement));
            exports.insert(
                "default".to_string(),
                declaration(path, "default", "default", &[], span),
            );
            continue;
        }
        let Some(declared) = declared else {
            continue;
        };
        let term = tree.term(declared);
        if term == "lexical_declaration" || term == "variable_declaration" {
            for declarator in tree.children_of(declared, &["variable_declarator"]) {
                if let Some(name) = tree.first_child(declarator, &["identifier"]) {
                    let text = tree.text(name);
                    let target = declaration(path, text, "variable", &[], tree.span(name));
                    exports.insert(text.to_string(), target);
                }
            }
            continue;
        }
        let Some(name) = tree.first_child(declared, &["identifier"]) else {
            continue;
        };
        let text = tree.text(name);
        let mut traits = Vec::new();
        if tree.first_child(declared, &["async"]).is_some() {
            traits.push("async");
        }
        if term == "generator_function_declaration" {
            traits.push("generator");
        }
        let recursive = tree
            .first_child(declared, &["statement_block", "class_body"])
            .is_some_and(|body| {
                tree.descendants(body, &["identifier"])
                    .into_iter()
                    .any(|node| tree.text(node) == text)
            });
        if recursive {
            traits.push("recursive");
        }
        let kind = if term == "class_declaration" {
            "class"
        } else {
            "function"
        };
        exports.insert(
            text.to_string(),
            declaration(path, text, kind, &traits, tree.span(name)),
        );
    }
    exports
}