fallow-types 3.43.2

Shared types and serde paths for fallow codebase intelligence
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
//! Persisted call evidence for plain functions: the parameter contract of each
//! module-scope function binding, the direct calls of admitted callees, and
//! the references that let a local function escape.
//!
//! A rule reads these facts to report a parameter that gets the same value at
//! each call, or an optional parameter that no caller passes. The facts are
//! syntactic. The analysis resolves each call target through the module graph
//! and abstains when a caller can be invisible.

/// Call evidence of one module.
#[derive(Debug, Clone, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct FunctionContractFacts {
    /// One contract for each function that a module-scope binding holds.
    pub declarations: Vec<FunctionContract>,
    /// Direct calls whose callee is an admitted import binding or a local
    /// function binding, one entry per callee, ordered by the first site.
    pub calls: Vec<FunctionCalls>,
    /// References to a local function binding that are not a direct callee,
    /// in source order.
    pub escapes: Vec<LocalFunctionEscape>,
    /// `true` for a Vue, Svelte, Astro, Glimmer or MDX host. A template, an
    /// inline script, or another script block of the file can call a binding,
    /// and the facts do not hold those calls. A consumer must treat each
    /// contract of the file, and each import that the file calls, as open.
    pub template_callers: bool,
    /// `true` when the module calls `eval` directly, at any depth. A direct
    /// `eval` can call each binding in scope with any value, so a consumer
    /// must treat each contract of the module, and each import that the
    /// module calls, as open. A contract whose own body or default values
    /// call `eval` also has [`ContractIncomplete::DirectEval`].
    pub direct_eval: bool,
    /// The uses of each `import()` or `require` call whose source gives no
    /// file and no pattern, such as `import(name)`. Such a call can load each
    /// module of the project.
    pub opaque_loads: OpaqueLoads,
    /// The local names of the exported module-scope `const` bindings whose
    /// initializer is a literal, in source order. A call argument that names
    /// one of these bindings through an import has a known identity.
    pub literal_consts: Vec<Box<str>>,
}

impl FunctionContractFacts {
    /// Each call site with its callee, ordered by callee and then by site.
    pub fn call_sites(&self) -> impl Iterator<Item = (CallTarget, &str, &CallSite)> {
        self.calls.iter().flat_map(|calls| {
            calls
                .sites
                .iter()
                .map(|site| (calls.target, &*calls.member_path, site))
        })
    }

    /// `true` when the module has no call evidence to store.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.declarations.is_empty()
            && self.calls.is_empty()
            && self.escapes.is_empty()
            && !self.template_callers
            && !self.direct_eval
            && self.opaque_loads.is_empty()
            && self.literal_consts.is_empty()
    }
}

/// How the code of one module uses the values of its loads with an unknown
/// source. A consumer must treat each exported contract of the project with
/// one of `names` as its export name as open. When `escapes` is `true`, the
/// consumer must treat each exported contract of the project as open. For
/// each of `loaders`, the consumer reads the results of the calls of that
/// function with the same rules.
#[derive(Debug, Clone, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct OpaqueLoads {
    /// The export names that the code reads on a loaded value, sorted and
    /// without repeats. `default` names the default export.
    pub names: Vec<String>,
    /// `true` when a loaded value goes to code that the facts do not follow,
    /// for example an alias, a call argument, a spread, or a return from a
    /// function that has no contract.
    pub escapes: bool,
    /// The functions of the module that return a loaded value, sorted and
    /// without repeats. Each caller of such a function gets the loaded value.
    pub loaders: Vec<LoaderReturn>,
}

impl OpaqueLoads {
    /// `true` when no load reads a name, no loaded value escapes, and no
    /// function returns a loaded value.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.names.is_empty() && !self.escapes && self.loaders.is_empty()
    }

    /// Add the names, the escape and the loaders of `other`.
    pub fn merge(&mut self, other: Self) {
        self.names.extend(other.names);
        self.names.sort_unstable();
        self.names.dedup();
        self.escapes |= other.escapes;
        self.loaders.extend(other.loaders);
        self.loaders.sort_unstable();
        self.loaders.dedup();
    }

    /// Move each loader index past `base`, for the facts of a later script
    /// block of one host file.
    pub fn shift_loaders(&mut self, base: u32) {
        for loader in &mut self.loaders {
            loader.contract = loader.contract.saturating_add(base);
        }
    }
}

/// A function contract that returns the value of a load with an unknown
/// source, such as `const load = (path) => import(path)`.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, bitcode::Encode, bitcode::Decode,
)]
pub struct LoaderReturn {
    /// Index into [`FunctionContractFacts::declarations`].
    pub contract: u32,
    /// `true` when a call of the function gives a promise of the loaded
    /// value: the function is `async`, or it returns the promise of an
    /// `import()`.
    pub promise: bool,
}

/// How the code uses the results of the calls of one callee, read with the
/// rules of [`OpaqueLoads`]. The extractor does not know what the callee
/// returns, so it reads the results in two ways. When the callee is a
/// loader ([`OpaqueLoads::loaders`]), a consumer reads the way that matches
/// the loader.
#[derive(Debug, Clone, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct CallResultReads {
    /// The uses when each call gives the loaded value.
    pub value: OpaqueLoads,
    /// The uses when each call gives a promise of the loaded value.
    pub promise: OpaqueLoads,
}

impl CallResultReads {
    /// Add the uses of `other`.
    pub fn merge(&mut self, other: Self) {
        self.value.merge(other.value);
        self.promise.merge(other.promise);
    }

    /// Move each loader index past `base`.
    pub fn shift_loaders(&mut self, base: u32) {
        self.value.shift_loaders(base);
        self.promise.shift_loaders(base);
    }
}

/// The parameter contract of a function that a module-scope binding holds:
/// `function f() {}`, or `const f = () => {}` and `const f = function () {}`.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct FunctionContract {
    /// The module-scope binding name.
    pub binding_name: Box<str>,
    /// Start byte of the binding identifier.
    pub span_start: u32,
    /// One fact for each formal parameter, in order. A TypeScript `this`
    /// parameter is not a formal parameter.
    pub params: Vec<ParamFact>,
    /// `true` when a `return` of the function has an expression, or the arrow
    /// function has an expression body.
    pub returns_value: bool,
    /// `true` for an `async` function declaration, function expression or
    /// arrow function. A call of an async function always gives a promise.
    pub is_async: bool,
    /// The first reason found that the extractor cannot see each use of the
    /// parameters. `None` for a closed contract.
    pub incomplete: Option<ContractIncomplete>,
}

/// One formal parameter of a [`FunctionContract`].
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct ParamFact {
    /// The parameter name. `None` for an object or array pattern.
    pub name: Option<Box<str>>,
    /// Start byte of the parameter: the `...` of a rest parameter, else the
    /// binding or pattern.
    pub span_start: u32,
    /// The binding shape of the parameter.
    pub kind: ParamKind,
    /// `true` for a TypeScript `?` marker.
    pub optional: bool,
    /// `true` when the parameter has a default value.
    pub has_default: bool,
    /// `true` for a rest parameter.
    pub is_rest: bool,
    /// The count of conditions whose test is the parameter or its negation:
    /// the test of an `if`, a `?:`, a loop, or `p`, `!p` and `!!p` there.
    pub condition_reads: u32,
    /// `true` when the module writes the parameter binding: in the body, in
    /// a default value, or in a nested function or arrow, for example
    /// `p = !p`, `p ??= x`, `[p] = xs` or `p++`. For an object or array
    /// pattern, `true` when the module writes any binding of the pattern. A
    /// `var` or function declaration in the body that redeclares the
    /// parameter also counts as a write. A written parameter can hold a
    /// value that no caller passes.
    pub written: bool,
    /// The option keys of an object pattern, in source order. Empty for
    /// each other parameter kind, and for an object pattern whose default is
    /// not absent or an empty object literal, because such a default can
    /// set a key that no caller passes.
    pub keys: Vec<OptionKeyFact>,
}

/// One key of an object-pattern [`ParamFact`]: `retries` in
/// `{ retries = 3, signal: abort }`.
///
/// Only a static key whose value is a plain binding, with or without a
/// default, is recorded. A computed or numeric key, a nested pattern, and a
/// key that `Object.prototype` holds, such as `toString`, are not recorded.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct OptionKeyFact {
    /// The property key.
    pub key: Box<str>,
    /// The local binding name: `abort` for `signal: abort`.
    pub binding: Box<str>,
    /// Start byte of the binding identifier.
    pub span_start: u32,
    /// `true` when the key has a default value.
    pub has_default: bool,
    /// The count of conditions whose test is the binding or its negation,
    /// as [`ParamFact::condition_reads`] counts them.
    pub condition_reads: u32,
    /// `true` when the module writes the binding.
    pub written: bool,
}

/// The binding shape of a [`ParamFact`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub enum ParamKind {
    /// A plain identifier.
    Identifier,
    /// An object destructuring pattern.
    Object,
    /// An array destructuring pattern.
    Array,
}

/// Why a [`FunctionContract`] is open.
#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub enum ContractIncomplete {
    /// The function has TypeScript overload signatures.
    Overload,
    /// The body or a default value reads `arguments`, also in a decorator,
    /// a method parameter decorator, an `extends` clause or a computed key
    /// of a class inside the function.
    ArgumentsRead,
    /// The function calls `eval` directly.
    DirectEval,
    /// A `let` or `var` declaration holds the function.
    MutableBinding,
    /// The module assigns the binding again.
    Reassigned,
    /// A parameter has a decorator.
    Decorator,
    /// The function is a generator.
    Generator,
    /// A second declaration has the same name.
    DuplicateDeclaration,
}

/// The direct calls of one callee: an admitted import binding with a member
/// path, or a local function binding.
///
/// The extractor groups the sites per callee, so the target and the path are
/// stored once. Optional calls, computed callees and calls through bindings
/// that are not admitted are not stored.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct FunctionCalls {
    /// The binding that the callee names.
    pub target: CallTarget,
    /// Dot-separated static member suffix after an import binding, empty for
    /// a bare call. Always empty for a local target.
    ///
    /// For a namespace import, the first segment is the export name. For a
    /// named or default import of a function, a non-empty path, for example
    /// `call`, `apply` or `bind`, is not a plain call of the function, so a
    /// consumer must treat the function as open for that site.
    pub member_path: Box<str>,
    /// Each call of this callee, in source order. Never empty.
    pub sites: Vec<CallSite>,
    /// The uses of the results of the sites whose result the code uses.
    pub results: CallResultReads,
}

/// One direct call of a [`FunctionCalls`] callee.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct CallSite {
    /// The count of arguments, spread arguments included.
    pub arg_count: u32,
    /// One fact for each argument before the first spread, to a fixed
    /// maximum. A string literal longer than a fixed maximum is
    /// [`ArgFact::Unknown`]. A spread moves each later argument to an
    /// unknown parameter, so no fact is kept from the spread on. Empty when
    /// each kept argument is [`ArgFact::Unknown`], so `arg_count` then holds
    /// the shape.
    ///
    /// Do not index this list directly. Use [`CallSite::arg_at`], which
    /// gives one of three outcomes for a parameter position: a known fact,
    /// an unknown value, or an omitted argument.
    pub args: Vec<ArgFact>,
    /// The index of the first spread argument.
    pub spread_from: Option<u32>,
    /// `false` when the call, with or without `await` or `void`, is a whole
    /// expression statement.
    pub result_used: bool,
    /// Start byte of the call expression.
    pub span_start: u32,
}

impl CallSite {
    /// The argument that this call passes at parameter position `index`.
    ///
    /// - From the first spread on, each position is [`ArgAt::Unknown`],
    ///   because a spread can fill any later position.
    /// - A position at or past `arg_count` is [`ArgAt::Omitted`].
    /// - A position with a stored fact other than [`ArgFact::Unknown`] is
    ///   [`ArgAt::Fact`].
    /// - Each other position is [`ArgAt::Unknown`]: a stored unknown fact,
    ///   a position past the kept facts, or a call with an empty `args`.
    #[must_use]
    pub fn arg_at(&self, index: u32) -> ArgAt<'_> {
        if self.spread_from.is_some_and(|spread| index >= spread) {
            return ArgAt::Unknown;
        }
        if index >= self.arg_count {
            return ArgAt::Omitted;
        }
        match usize::try_from(index).ok().and_then(|at| self.args.get(at)) {
            Some(ArgFact::Unknown) | None => ArgAt::Unknown,
            Some(fact) => ArgAt::Fact(fact),
        }
    }
}

/// The argument of a [`CallSite`] at one parameter position. This type is
/// not stored in the cache.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArgAt<'a> {
    /// A known argument fact. Never [`ArgFact::Unknown`].
    Fact(&'a ArgFact),
    /// The call passes a value that the facts do not know.
    Unknown,
    /// The call passes no argument at this position.
    Omitted,
}

/// The binding that a [`FunctionCalls`] callee names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, bitcode::Encode, bitcode::Decode)]
pub enum CallTarget {
    /// Index into `ModuleInfo.imports` of an admitted runtime ESM import.
    Import(u32),
    /// Index into [`FunctionContractFacts::declarations`].
    Local(u32),
}

/// The syntactic value of one call argument.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub enum ArgFact {
    /// A literal value.
    Literal(LiteralValue),
    /// The value of the parameter at this index of the called function. Only
    /// a self-call has this fact: a call of a local function inside the
    /// body or a default value of that same function. The argument is the
    /// unchanged identifier of a formal identifier parameter that the module
    /// never writes, so the call passes the value that the outer call got. A
    /// rest parameter never gets this fact, because the callee gets `[r]`
    /// for `f(r)`.
    Param(u32),
    /// An immutable binding: a module-scope `const` with a literal
    /// initializer, or an enum member.
    Binding(BindingArg),
    /// An object literal with no spread, no computed key, no numeric key,
    /// and no `__proto__` key. Each key appears once, with the value of its
    /// last property.
    Object(Vec<KeyArg>),
    /// Each other expression. `args` never holds a spread argument, because
    /// the list stops before the first spread.
    Unknown,
}

/// An argument that names an immutable binding.
///
/// The extractor checks a local binding. For an import, the analysis
/// resolves the origin export and checks that it is a `const` with a literal
/// initializer ([`FunctionContractFacts::literal_consts`]), or an enum with
/// the member.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct BindingArg {
    /// Where the root identifier of the argument comes from.
    pub root: BindingRoot,
    /// The dot-separated static path.
    ///
    /// - For [`BindingRoot::Local`]: the binding name, then the enum member
    ///   for an enum (`Mode.Grid`).
    /// - For [`BindingRoot::Import`] of a named or default import: empty for
    ///   a constant, else the enum member.
    /// - For [`BindingRoot::Import`] of a namespace import: the export name,
    ///   then the enum member.
    pub path: Box<str>,
}

/// The root of a [`BindingArg`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub enum BindingRoot {
    /// A module-scope `const` with a literal initializer, or a module-scope
    /// enum with the member, of the module that holds the call.
    Local,
    /// Index into `ModuleInfo.imports` of an admitted runtime ESM import.
    Import(u32),
}

/// One key of an [`ArgFact::Object`] argument.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct KeyArg {
    /// The property key.
    pub key: Box<str>,
    /// The value of the key.
    pub value: KeyValue,
}

/// The value of one [`KeyArg`]. The same facts as [`ArgFact`], with no
/// nested object.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub enum KeyValue {
    /// A literal value.
    Literal(LiteralValue),
    /// An immutable binding.
    Binding(BindingArg),
    /// A self-call passes the unchanged binding of the same key of the same
    /// object-pattern parameter, at the same position:
    /// `walk(node, { depth })` inside `walk(node, { depth })`.
    PassThrough,
    /// Each other value, a method, a getter or a setter.
    Unknown,
}

/// A literal argument value in canonical form.
#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub enum LiteralValue {
    /// `true` or `false`.
    Boolean(bool),
    /// `null`.
    Null,
    /// The unshadowed identifier `undefined`.
    Undefined,
    /// The IEEE 754 bits of a numeric literal or its negation, so `1` and
    /// `1.0` are equal. `-0` and `0` are different values, because
    /// `Object.is` and `1 / x` tell them apart.
    Number(u64),
    /// The value of a string literal or of a template literal with no
    /// expression.
    String(Box<str>),
}

/// A reference to a local function binding that is not a direct callee, for
/// example `items.map(format)`, `const g = format`, `<Format />` or
/// `` format`x` ``.
#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
pub struct LocalFunctionEscape {
    /// Index into [`FunctionContractFacts::declarations`].
    pub contract: u32,
    /// Start byte of the reference.
    pub span_start: u32,
}

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

    fn site(arg_count: u32, args: Vec<ArgFact>, spread_from: Option<u32>) -> CallSite {
        CallSite {
            arg_count,
            args,
            spread_from,
            result_used: false,
            span_start: 0,
        }
    }

    const TRUE: ArgFact = ArgFact::Literal(LiteralValue::Boolean(true));

    #[test]
    fn a_position_from_the_spread_on_is_unknown() {
        let call = site(2, vec![TRUE], Some(1));
        assert_eq!(call.arg_at(0), ArgAt::Fact(&TRUE));
        assert_eq!(call.arg_at(1), ArgAt::Unknown);
        assert_eq!(call.arg_at(3), ArgAt::Unknown);
        assert_eq!(site(1, Vec::new(), Some(0)).arg_at(3), ArgAt::Unknown);
    }

    #[test]
    fn a_position_past_the_count_is_omitted() {
        assert_eq!(site(0, Vec::new(), None).arg_at(0), ArgAt::Omitted);
        assert_eq!(site(1, vec![TRUE], None).arg_at(1), ArgAt::Omitted);
    }

    #[test]
    fn empty_args_with_a_count_are_unknown() {
        let call = site(2, Vec::new(), None);
        assert_eq!(call.arg_at(0), ArgAt::Unknown);
        assert_eq!(call.arg_at(1), ArgAt::Unknown);
        assert_eq!(call.arg_at(2), ArgAt::Omitted);
    }

    #[test]
    fn a_stored_unknown_is_unknown_and_a_param_is_a_fact() {
        let call = site(2, vec![ArgFact::Unknown, ArgFact::Param(0)], None);
        assert_eq!(call.arg_at(0), ArgAt::Unknown);
        assert_eq!(call.arg_at(1), ArgAt::Fact(&ArgFact::Param(0)));
    }

    #[test]
    fn a_position_past_the_kept_facts_is_unknown() {
        // The extractor keeps 16 argument facts and the full count.
        let call = site(40, vec![TRUE; 16], None);
        assert_eq!(call.arg_at(15), ArgAt::Fact(&TRUE));
        assert_eq!(call.arg_at(16), ArgAt::Unknown);
        assert_eq!(call.arg_at(39), ArgAt::Unknown);
        assert_eq!(call.arg_at(40), ArgAt::Omitted);
    }
}