nsh-js 0.1.0

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! The TypeScript declarations of what apps import (`.nsh/types`), made
//! from what serves it: the declaration ([`Ts`]) next to each export of
//! nsh's modules (`modules.rs` and the tables it lists), the modules' own
//! types, the specs of the registries' components and modules
//! (`nsh_core::ui::declarations`), and the core's tables (styles, host
//! props and events, easings, canvas operations: `nsh_core::js`). Nothing
//! is written twice: a test loads every module and checks that what it
//! exports is what its declarations say.
//!
//! Each file declares its own names; the `import type` lines between the
//! files are worked out from the names each one uses.

use std::{collections::BTreeMap, fmt::Write as _};

use nsh_core::ui::Registry;

use crate::modules::{Item, MODULES, NativeModule, Ts};

/// The banner of every file.
const BANNER: &str = "// Generated by nsh from its Rust sources: do not edit.\n\n";

/// The element and JSX types (`types.d.ts`, all exported by `nsh`) that do
/// not come from a table: how the tables' interfaces make up the props of
/// each element.
const ELEMENT_TYPES: &str = r#"/** A list of styles, possibly nested: `[base, props.style]` where
 * `props.style` is itself a list. */
export type RecursiveArray<T> = readonly (T | RecursiveArray<T>)[];

/** A style, or a list of styles (nested lists included) merged left to
 * right; falsy entries are skipped. */
export type StyleProp<T> = T | RecursiveArray<T | false | null | undefined> | false | null | undefined;

/** Props every host element accepts. */
export interface CommonProps extends TouchProps, HostProps {
  ref?: YNode | ((node: YNode) => void);
  children?: JSX.Element;
  /** iOS-only props (ignored elsewhere). */
  ios?: IOSProps;
  /** Android-only props (ignored elsewhere). */
  android?: AndroidProps;
  /** Desktop-only props (macOS, Windows, Linux; ignored on mobile). */
  desktop?: DesktopProps;
}

/** iOS-only props of every element (`ios={{…}}`); elements add their own. */
export interface IOSProps {}

/** Desktop-only props of every element (`desktop={{…}}`); elements add their own. */
export interface DesktopProps {}

/** Android-only props of every element (`android={{…}}`). */
export interface AndroidProps extends AndroidHostProps {}

/** `<View>` */
export interface ViewProps extends CommonProps {
  style?: StyleProp<ViewStyle>;
}

/** `<Text>`: nested `<Text>` elements are spans of the same paragraph. */
export interface TextProps extends CommonProps, TextHostProps {
  style?: StyleProp<TextStyle>;
}

/** An image asset (`import logo from "./logo.png"`), sized in points. */
export interface ImageAsset {
  uri: string;
  width: number;
  height: number;
}

/** `<Image>` */
export interface ImageProps extends CommonProps, ImageHostProps {
  style?: StyleProp<ImageStyle>;
}

/** `<Scroll>` */
export interface ScrollProps extends CommonProps, ScrollingHostProps, ScrollHostProps {
  style?: StyleProp<ViewStyle>;
  /** The style of a view around the content (React Native's content
   * container): it scrolls with the content, `flexGrow: 1` makes it at
   * least as tall as the viewport (a centered empty state). Without it or
   * `contentContainerClass`, the children are the scroll view's own. */
  contentContainerStyle?: StyleProp<ViewStyle>;
  /** The classes of the content container (`contentContainerStyle`), e.g.
   * `"grow justify-center p-4"`. */
  contentContainerClass?: string;
}

/** `<Input>` */
export interface InputProps extends CommonProps, InputHostProps {
  style?: StyleProp<TextStyle>;
  ios?: IOSInputProps;
}

/** iOS-only props of `<Input>`. */
export interface IOSInputProps extends IOSProps, IOSInputHostProps {}

/** What JS sets on a Rust component's host itself: the app's classes
 * (appended to the component's own), its inline style, its test id, layout
 * events and the ref (`ref.command(name, args)`). */
export type ComponentHostProps = Pick<ViewProps, "class" | "classList" | "style" | "testID" | "onLayout" | "ref">;

export interface Insets {
  top: number;
  right: number;
  bottom: number;
  left: number;
}

/** An operating system (`Platform.OS`). */
export type OS = "ios" | "android" | "macos" | "windows" | "linux";

export declare namespace JSX {
  /** What components return and children accept. */
  type Element = YNode | ArrayElement | (() => Element) | string | number | boolean | null | undefined;
  interface ArrayElement extends Array<Element> {}
  interface ElementChildrenAttribute {
    children: {};
  }
  /** None: every tag is a component in scope (`View` from "nsh", ...), or
   * the global `If` / `Each`. */
  interface IntrinsicElements {}
}
"#;

/// `/** doc */` for `doc` (plain text, possibly several lines).
fn doc_comment(out: &mut String, doc: &str, indent: &str) {
    if doc.is_empty() {
        return;
    }
    let lines: Vec<&str> = doc.lines().collect();
    if lines.len() == 1 {
        let _ = writeln!(out, "{indent}/** {doc} */");
        return;
    }
    let _ = writeln!(out, "{indent}/**");
    for line in lines {
        if line.is_empty() {
            let _ = writeln!(out, "{indent} *");
        } else {
            let _ = writeln!(out, "{indent} * {line}");
        }
    }
    let _ = writeln!(out, "{indent} */");
}

/// The declaration of export `name`.
fn export(out: &mut String, name: &str, ts: Ts) {
    match ts {
        Ts::Function(doc, signatures) => {
            doc_comment(out, doc, "");
            for signature in signatures {
                let _ = writeln!(out, "export declare function {name}{signature};");
            }
        }
        Ts::Const(doc, ty) => {
            doc_comment(out, doc, "");
            let _ = writeln!(out, "export declare const {name}: {ty};");
        }
        Ts::Class(doc, body) => {
            doc_comment(out, doc, "");
            let _ = writeln!(out, "export declare class {name}{body}");
        }
        Ts::Internal => return,
    }
    out.push('\n');
}

fn exports(out: &mut String, items: &[Item]) {
    for &(name, _, ts) in items {
        export(out, name, ts);
    }
}

/// `types.d.ts`: the styles, the elements' props and events, the node and
/// JSX types.
fn element_types() -> String {
    let mut out = String::from(ELEMENT_TYPES);
    out.push('\n');
    out.push_str(&nsh_core::js::style::declarations());
    out.push('\n');
    out.push_str(&nsh_core::js::host::declarations());
    out.push('\n');
    out.push_str(crate::touch::TOUCH_TYPES);
    out.push_str("\n/** Raw touches and the gesture responder system (React Native semantics). */\nexport interface TouchProps {\n");
    for (name, handler, doc) in crate::touch::TOUCH_PROPS {
        doc_comment(&mut out, doc, "  ");
        let _ = writeln!(out, "  {name}?: {handler};");
    }
    out.push_str("}\n\n/** A native node: what `ref` receives. Its methods send commands to its\n * view, in order with the changes before them. */\nexport interface YNode {\n");
    for (name, _, signature, doc) in crate::dom::NODE_METHODS {
        doc_comment(&mut out, doc, "  ");
        let _ = writeln!(out, "  {name}{signature};");
    }
    out.push_str("}\n");
    out
}

/// The file of module `specifier` (`nsh/ui/mobile` -> `nsh/ui/mobile.d.ts`).
fn path_of(specifier: &str) -> String {
    match specifier {
        "nsh" => "nsh/index.d.ts".to_owned(),
        s => format!("{s}.d.ts"),
    }
}

/// What the core's tables add to one of nsh's modules.
fn generated(module: &str) -> String {
    match module {
        "nsh/animated" => nsh_core::js::animation::declarations(),
        "nsh/canvas" => nsh_core::js::canvas::declarations(),
        _ => String::new(),
    }
}

/// The declarations of a registry's exports, leaving out those `own`
/// declares.
fn registry_part(out: &mut String, registry: &Registry, own: &[Item]) {
    let omit: Vec<&str> = own.iter().map(|(n, ..)| *n).collect();
    out.push_str(&nsh_core::ui::declarations(registry, &omit));
    let (values, types) = registry.reexports();
    let natives = registry.native_value_names();
    let made = crate::env::REEXPORTS
        .iter()
        .chain(crate::navigation::EXPORTS);
    let mut navigation = false;
    for item in made {
        if values.contains(&item.0) || natives.contains(&item.0) {
            navigation |= crate::navigation::EXPORTS.iter().any(|n| n.0 == item.0);
            export(out, item.0, item.2);
        }
    }
    if navigation {
        out.push_str(crate::navigation::TYPES);
        out.push('\n');
    }
    if !types.is_empty() {
        let _ = writeln!(out, "export type {{ {} }};", types.join(", "));
    }
}

/// The modules' files, before imports: (path, body).
fn bodies(ui_sets: &[Registry]) -> Vec<(String, String)> {
    let mut files = vec![("nsh/types.d.ts".to_owned(), element_types())];
    let registries: Vec<&Registry> = nsh_core::runtime::registries()
        .iter()
        .chain(ui_sets)
        .collect();
    let declared = |m: &&NativeModule| m.exports.iter().any(|e| !matches!(e.2, Ts::Internal));
    for m in MODULES.iter().filter(declared) {
        let mut body = String::from(m.types);
        if !body.is_empty() {
            body.push('\n');
        }
        body.push_str(&generated(m.name));
        for registry in registries.iter().filter(|r| r.specifier() == Some(m.name)) {
            registry_part(&mut body, registry, m.exports);
        }
        exports(&mut body, m.exports);
        files.push((path_of(m.name), body));
    }
    // The registries that are modules of their own (`nsh/ui/mobile`, `nsh/image`).
    for registry in &registries {
        let Some(specifier) = registry.specifier() else {
            continue;
        };
        if MODULES.iter().any(|m| m.name == specifier) {
            continue;
        }
        let mut body = String::new();
        registry_part(&mut body, registry, &[]);
        files.push((path_of(specifier), body));
    }
    files
}

/// Removes comments and string literals (their words are not references).
fn code_only(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < bytes.len() {
        let rest = &text[i..];
        if rest.starts_with("/*") {
            i += rest.find("*/").map_or(rest.len(), |e| e + 2);
            out.push(' ');
        } else if rest.starts_with("//") {
            i += rest.find('\n').unwrap_or(rest.len());
        } else if bytes[i] == b'"' || bytes[i] == b'`' {
            let quote = bytes[i];
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                if bytes[i] == b'\\' {
                    i += 1;
                }
                i += 1;
            }
            i += 1;
            out.push_str("\"\"");
        } else {
            let c = rest.chars().next().unwrap_or(' ');
            out.push(c);
            i += c.len_utf8();
        }
    }
    out
}

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_' || c == '$'
}

fn is_ident(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '$'
}

/// The identifiers of `code`, with what precedes each (to tell member
/// names and declarations from references).
fn words(code: &str) -> Vec<(&str, &str)> {
    let mut out = Vec::new();
    let mut start = None;
    for (i, c) in code.char_indices() {
        match start {
            None if is_ident_start(c) => start = Some(i),
            Some(s) if !is_ident(c) => {
                out.push((&code[..s], &code[s..i]));
                start = None;
            }
            _ => {}
        }
    }
    if let Some(s) = start {
        out.push((&code[..s], &code[s..]));
    }
    out
}

/// The keywords that declare a name.
const DECLARING: &[&str] = &[
    "interface",
    "type",
    "class",
    "const",
    "function",
    "enum",
    "namespace",
    "let",
    "var",
];

/// The names `body` declares at its top level and exports (`export
/// [declare] interface X` ...).
pub(crate) fn exported_names(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in code_only(body).lines() {
        let Some(rest) = line.strip_prefix("export ") else {
            continue;
        };
        let rest = rest.trim_start_matches("declare ");
        let rest = rest.trim_start_matches("abstract ");
        let mut parts = rest.split_whitespace();
        let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        if DECLARING.contains(&keyword) {
            let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
            if !name.is_empty() {
                out.push(name);
            }
        }
    }
    out
}

/// The values `body` declares as exports (what a module's namespace must
/// hold).
#[cfg(test)]
pub(crate) fn exported_values(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in code_only(body).lines() {
        let Some(rest) = line.strip_prefix("export declare ") else {
            continue;
        };
        let rest = rest.trim_start_matches("abstract ");
        let mut parts = rest.split_whitespace();
        let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        if matches!(keyword, "const" | "function" | "class" | "let" | "var") {
            let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
            if !out.contains(&name) {
                out.push(name);
            }
        }
    }
    out
}

/// The names `body` uses, declares itself (at any depth, and type
/// parameters) or imports.
fn references(body: &str) -> (Vec<String>, Vec<String>) {
    let code = code_only(body);
    let mut used = Vec::new();
    let mut local = Vec::new();
    for (before, word) in words(&code) {
        let prev = before.trim_end();
        let prev_word = prev
            .rsplit(|c: char| !is_ident(c))
            .next()
            .unwrap_or_default();
        if DECLARING.contains(&prev_word) && prev.ends_with(prev_word) {
            local.push(word.to_owned());
        } else if prev.ends_with('.') {
            // A member (`JSX.Element`, `Symbol.iterator`).
        } else {
            used.push(word.to_owned());
        }
    }
    // Imported by the body itself (`nsh`'s `JSX`).
    for line in body.lines() {
        if let Some(rest) = line.strip_prefix("import type {")
            && let Some(names) = rest.split('}').next()
        {
            local.extend(names.split(',').map(|n| n.trim().to_owned()));
        }
    }
    (used, local)
}

/// `to` relative to the directory of `from` (both under `.nsh/types`),
/// without the extension: `./types`, `../types`.
fn relative(from: &str, to: &str) -> String {
    let from_dir: Vec<&str> =
        from.split('/').collect::<Vec<_>>()[..from.split('/').count() - 1].to_vec();
    let to_parts: Vec<&str> = to.split('/').collect();
    let common = from_dir
        .iter()
        .zip(&to_parts)
        .take_while(|(a, b)| a == b)
        .count();
    let mut path = String::new();
    if from_dir.len() == common {
        path.push_str("./");
    } else {
        for _ in common..from_dir.len() {
            path.push_str("../");
        }
    }
    path.push_str(&to_parts[common..].join("/"));
    path.trim_end_matches(".d.ts").to_owned()
}

/// The files of `.nsh/types` for apps whose hosts serve `ui_sets`
/// (`nsh/ui/mobile`, ...), as (path relative to it, contents): one per
/// module apps import, `nsh/types.d.ts` (the element types `nsh` exports),
/// `nsh/jsx-runtime.d.ts` (where TypeScript finds the JSX namespace:
/// `jsxImportSource: "nsh"`) and `nsh/globals.d.ts`.
pub fn type_definitions(ui_sets: &[Registry]) -> Vec<(String, String)> {
    let files = bodies(ui_sets);
    // Who declares each name.
    let mut owner: BTreeMap<String, &str> = BTreeMap::new();
    for (path, body) in &files {
        for name in exported_names(body) {
            owner.entry(name).or_insert(path);
        }
    }
    let mut out: Vec<(String, String)> = files
        .iter()
        .map(|(path, body)| {
            let (used, local) = references(body);
            let mut imports: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
            for name in &used {
                if local.contains(name) {
                    continue;
                }
                if let Some(&from) = owner.get(name)
                    && from != path
                {
                    let names = imports.entry(from).or_default();
                    if !names.contains(&name.as_str()) {
                        names.push(name);
                    }
                }
            }
            let mut text = String::from(BANNER);
            let any = !imports.is_empty();
            for (from, mut names) in imports {
                names.sort_unstable();
                let _ = writeln!(
                    text,
                    "import type {{ {} }} from \"{}\";",
                    names.join(", "),
                    relative(path, from)
                );
            }
            if any {
                text.push('\n');
            }
            text.push_str(body);
            (path.clone(), text)
        })
        .collect();
    out.push((
        "nsh/jsx-runtime.d.ts".to_owned(),
        format!("{BANNER}export type {{ JSX }} from \"./types\";\n"),
    ));
    out.push(("nsh/globals.d.ts".to_owned(), globals()));
    out
}

/// A constant's value as TypeScript (`2`, not `2.0`).
fn number(v: f64) -> String {
    if v.fract() == 0.0 && v.abs() < 1e15 {
        format!("{}", v as i64)
    } else {
        format!("{v}")
    }
}

/// `globals.d.ts`: what an app can use besides the ECMAScript library: the
/// host's globals, the web classes (from their specs) and functions.
fn globals() -> String {
    let mut out = String::from(BANNER);
    out.push_str("// The globals of nsh's JS environment besides the ECMAScript library\n// (there is no DOM).\n\n");
    out.push_str(crate::host::GLOBALS);
    for types in crate::web::TYPES {
        out.push('\n');
        out.push_str(types);
    }
    for spec in crate::web::declared_specs() {
        let ts = &spec.ts;
        out.push('\n');
        doc_comment(&mut out, ts.doc, "");
        let name = spec.name.to_str().unwrap_or_default();
        let _ = writeln!(out, "declare class {name}{} {{", ts.head);
        for (constant, value) in spec.constants {
            let constant = constant.to_str().unwrap_or_default();
            let value = number(*value);
            let _ = writeln!(out, "  static readonly {constant}: {value};");
            let _ = writeln!(out, "  readonly {constant}: {value};");
        }
        for line in ts.members.lines() {
            let _ = writeln!(out, "  {line}");
        }
        out.push_str("}\n");
    }
    for f in crate::web::functions() {
        out.push('\n');
        doc_comment(&mut out, f.doc, "");
        let name = f.name.to_str().unwrap_or_default();
        let _ = writeln!(out, "declare function {name}{};", f.signature);
    }
    out
}

/// The names of a class body's members (`static`, accessors and symbols
/// as `[Symbol.iterator]`), one per declaration (overloads repeat).
#[cfg(test)]
fn member_names(members: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in members.lines() {
        if line.starts_with([' ', ')', '}', '/', '*']) || line.trim().is_empty() {
            continue;
        }
        let mut rest = line;
        for prefix in ["static ", "readonly ", "get ", "set "] {
            rest = rest.strip_prefix(prefix).unwrap_or(rest);
        }
        let name = if rest.starts_with('[') {
            rest[..rest.find(']').map_or(rest.len(), |e| e + 1)].to_owned()
        } else {
            rest.chars().take_while(|c| is_ident(*c)).collect()
        };
        if !name.is_empty() && name != "constructor" && !out.contains(&name) {
            out.push(name);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn paths_are_relative() {
        assert_eq!(relative("nsh/list.d.ts", "nsh/types.d.ts"), "./types");
        assert_eq!(relative("nsh/ui/mobile.d.ts", "nsh/types.d.ts"), "../types");
        assert_eq!(
            relative("nsh/types.d.ts", "nsh/ui/mobile.d.ts"),
            "./ui/mobile"
        );
    }

    #[test]
    fn references_skip_members_strings_and_declarations() {
        let (used, local) = references(
            "/** A `Foo` */\nexport interface Bar<T> { a: JSX.Element; b: \"Baz\"; c: Qux<T> }",
        );
        assert!(used.contains(&"JSX".to_owned()));
        assert!(used.contains(&"Qux".to_owned()));
        assert!(!used.contains(&"Element".to_owned()));
        assert!(!used.contains(&"Baz".to_owned()));
        assert!(!used.contains(&"Foo".to_owned()));
        assert!(local.contains(&"Bar".to_owned()));
    }

    /// A name a file imports is declared in one file only.
    #[test]
    fn imports_are_unambiguous() {
        let files = bodies(&[nsh_ui_mobile::registry()]);
        let mut owners: BTreeMap<String, Vec<&str>> = BTreeMap::new();
        for (path, body) in &files {
            for name in exported_names(body) {
                let paths = owners.entry(name).or_default();
                if !paths.contains(&path.as_str()) {
                    paths.push(path);
                }
            }
        }
        for (path, body) in &files {
            let (used, local) = references(body);
            for name in used.iter().filter(|n| !local.contains(n)) {
                if let Some(paths) = owners.get(name) {
                    let others: Vec<_> = paths.iter().filter(|p| **p != path).collect();
                    assert!(
                        others.len() <= 1 || paths.contains(&path.as_str()),
                        "{path} uses `{name}`, declared in {others:?}"
                    );
                }
            }
        }
    }

    /// Each web class declares the members its spec defines, and no others.
    #[test]
    fn web_classes_declare_their_members() {
        use crate::web::Key;
        let mut wrong = Vec::new();
        for spec in crate::web::declared_specs() {
            let name = spec.name.to_str().unwrap();
            let mut declared = member_names(spec.ts.members);
            declared.sort();
            let mut defined: Vec<String> = spec
                .methods
                .iter()
                .map(|(key, ..)| match key {
                    Key::Name(n) => n.to_str().unwrap().to_owned(),
                    Key::Iterator => "[Symbol.iterator]".to_owned(),
                    Key::AsyncIterator => "[Symbol.asyncIterator]".to_owned(),
                })
                .chain(
                    spec.accessors
                        .iter()
                        .map(|(n, ..)| n.to_str().unwrap().to_owned()),
                )
                .chain(
                    spec.statics
                        .iter()
                        .map(|(n, ..)| n.to_str().unwrap().to_owned()),
                )
                .collect();
            defined.sort();
            defined.dedup();
            let missing: Vec<_> = defined.iter().filter(|n| !declared.contains(n)).collect();
            let extra: Vec<_> = declared.iter().filter(|n| !defined.contains(n)).collect();
            if !missing.is_empty() || !extra.is_empty() {
                wrong.push(format!(
                    "{name}: undeclared {missing:?}, not defined {extra:?}"
                ));
            }
            if let Some(parent) = spec.parent {
                let parent = crate::web::declared_specs()
                    .chain(crate::web::internal_specs())
                    .find(|s| s.class == parent)
                    .map(|s| s.name.to_str().unwrap())
                    .unwrap();
                if !spec.ts.head.contains(&format!("extends {parent}")) {
                    wrong.push(format!("{name} extends {parent}"));
                }
            }
        }
        assert!(wrong.is_empty(), "{}", wrong.join("\n"));
    }

    /// The declared globals exist, and every global the host adds is declared.
    #[test]
    fn globals_match_the_host() {
        let globals = globals();
        let mut declared: Vec<String> = Vec::new();
        for line in code_only(&globals).lines() {
            let Some(rest) = line.strip_prefix("declare ") else {
                continue;
            };
            let mut parts = rest.split_whitespace();
            if let (Some("var" | "function" | "class" | "const"), Some(name)) =
                (parts.next(), parts.next())
            {
                let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
                if !declared.contains(&name) {
                    declared.push(name);
                }
            }
        }
        let names = |source: &str| -> Vec<String> {
            source
                .split(' ')
                .filter(|n| !n.is_empty())
                .map(str::to_owned)
                .collect()
        };
        let host = crate::Host::new().unwrap();
        host.eval_source(
            "import { text } from \"nsh:rt\";\ntext(Object.getOwnPropertyNames(globalThis).join(\" \"));",
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let on_host = ops
            .into_iter()
            .find_map(|op| match op {
                nsh_core::Op::CreateText { text, .. } => Some(names(&text)),
                _ => None,
            })
            .unwrap();
        let rt = rquickjs::Runtime::new().unwrap();
        let ctx = rquickjs::Context::full(&rt).unwrap();
        let bare: Vec<String> = ctx.with(|ctx| {
            let list: String = ctx
                .eval("Object.getOwnPropertyNames(globalThis).join(' ')")
                .unwrap();
            names(&list)
        });
        for name in &declared {
            assert!(
                on_host.contains(name),
                "`{name}` is declared but not a global"
            );
        }
        for name in on_host
            .iter()
            .filter(|n| !bare.contains(n) && !n.starts_with("__"))
            .filter(|n| !crate::web::ECMASCRIPT_GLOBALS.contains(&n.as_str()))
        {
            assert!(declared.contains(name), "global `{name}` is not declared");
        }
    }

    /// What each module exports at run time is what its declarations say.
    #[test]
    fn declarations_match_the_modules() {
        let ui = nsh_ui_mobile::registry();
        let host = crate::Host::with_options(crate::HostOptions {
            ui_sets: vec![ui.clone()],
            ..crate::HostOptions::default()
        })
        .unwrap();
        for (path, body) in bodies(&[ui]) {
            if path == "nsh/types.d.ts" {
                continue;
            }
            let specifier = match path.trim_end_matches(".d.ts") {
                "nsh/index" => "nsh",
                s => s,
            }
            .to_owned();
            let mut declared = exported_values(&body);
            declared.sort();
            host.eval_source(&format!(
                "import {{ text }} from \"nsh:rt\";\nimport * as m from \"{specifier}\";\ntext(Object.keys(m).sort().join(\",\"));"
            ))
            .unwrap_or_else(|e| panic!("{specifier}: {e}"));
            let mut ops = Vec::new();
            host.take_ops(&mut ops);
            let actual = ops
                .into_iter()
                .find_map(|op| match op {
                    nsh_core::Op::CreateText { text, .. } => Some(text.to_string()),
                    _ => None,
                })
                .expect("the module's names");
            assert_eq!(actual, declared.join(","), "{specifier}");
        }
    }
}