fallow-extract 3.35.0

AST extraction engine for fallow codebase intelligence (parser, complexity, SFC / Astro / MDX / CSS)
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
//! Caller facts from the shared quote-aware markup scanner.

use super::scanners::{is_html_tag_start, scan_curly_section, scan_html_tag};
use super::shared::{ParsedAttr, kebab_to_camel_case, parse_tag_attrs};
use fallow_types::extract::{
    ComponentContractFacts, ComponentFramework, ComponentInvocation, ComponentReference, ImportInfo,
};

pub fn collect(
    source: &str,
    imports: &[ImportInfo],
    framework: ComponentFramework,
    offset: u32,
    bindings: &[fallow_types::extract::ComponentSpreadBinding],
    aliases: &[fallow_types::extract::ComponentAliasBinding],
) -> ComponentContractFacts {
    let mut facts = ComponentContractFacts::default();
    let interpolation = interpolation_brace_len(framework);
    let mut cursor = 0;
    while cursor < source.len() {
        let Some(relative) = source[cursor..]
            .find(|character| character == '<' || (character == '{' && interpolation.is_some()))
        else {
            break;
        };
        let start = cursor + relative;
        if let Some(next) = skip_non_tag(source, start, interpolation, framework) {
            cursor = next;
            continue;
        }
        let Some((tag, end)) = scan_html_tag(source, start) else {
            facts.incomplete_frameworks.push(framework);
            break;
        };
        cursor = end;
        if tag.starts_with("</") || tag.starts_with("<!") {
            continue;
        }
        let parsed = parse_tag_attrs(tag, true);
        let name = parsed.name.as_str();
        if matches!(name, "script" | "style") {
            let closing = format!("</{name}");
            cursor = source[cursor..]
                .find(&closing)
                .map_or(source.len(), |end| cursor + end + closing.len());
            continue;
        }
        collect_attribute_escapes(&parsed.attrs, imports, aliases, framework, &mut facts);
        let dynamic = matches!(name, "component" | "svelte:component" | "svelte:element")
            || parsed.attrs.iter().any(|attr| {
                matches!(
                    attr.name.as_str(),
                    "[ngComponentOutlet]" | "*ngComponentOutlet" | "is" | ":is" | "v-bind:is"
                )
            });
        if dynamic {
            facts.incomplete_frameworks.push(framework);
        }
        let imported = imports.iter().find(|import| {
            !import.local_name.is_empty()
                && (import.local_name == name
                    || (framework == ComponentFramework::Vue
                        && kebab_to_camel_case(name).eq_ignore_ascii_case(&import.local_name)))
        });
        let Some(target) = target_for_tag(name, imported, framework, start as u32 + offset) else {
            continue;
        };
        let mut supplied = Vec::new();
        let mut supplied_properties = Vec::new();
        let mut unknown_props = dynamic;
        for attr in &parsed.attrs {
            if framework == ComponentFramework::Lit && attr.name.starts_with('.') {
                supplied_properties.push(attr.name[1..].to_string());
                continue;
            }
            unknown_props |= attribute_supply(attr, framework, &mut supplied, bindings, source);
        }
        // Template scope and dynamic aliases require the framework's compiler.
        // Retaining caller uncertainty prevents a shadowed tag from proving absence.
        if imported.is_some()
            && template_binding_may_shadow(source, imported.map_or("", |import| &import.local_name))
        {
            unknown_props = true;
        }
        if framework == ComponentFramework::Svelte && !parsed.self_closing {
            let closing = format!("</{}>", parsed.name);
            if let Some(end) = source[cursor..].find(&closing) {
                if !source[cursor..cursor + end].trim().is_empty() {
                    supplied.push("children".to_string());
                }
            } else {
                unknown_props = true;
            }
        }
        supplied.sort_unstable();
        supplied.dedup();
        facts.invocations.push(ComponentInvocation {
            target,
            span_start: start as u32 + offset,
            supplied,
            supplied_properties,
            unknown_props,
            framework,
        });
    }
    facts
}

/// The cursor after the text at `start` when it is not a tag to read: a text
/// expression, a comment, or a `<` that HTML reads as text. A text expression
/// is skipped as a unit, so a `<` inside it (`{{ a<b }}`, `{a<b}`) cannot hide
/// a later tag.
fn skip_non_tag(
    source: &str,
    start: usize,
    interpolation: Option<usize>,
    framework: ComponentFramework,
) -> Option<usize> {
    if source.as_bytes()[start] == b'{' {
        let len = interpolation?;
        // A Handlebars comment is prose, so the expression scanner must not
        // read an apostrophe or `//` in it as code.
        for (open, close) in [("{{!--", "--}}"), ("{{!", "}}")] {
            if len == 2 && source[start..].starts_with(open) {
                return Some(
                    source[start + open.len()..]
                        .find(close)
                        .map_or(start + 1, |end| start + open.len() + end + close.len()),
                );
            }
        }
        return Some(
            source[start..]
                .starts_with(&"{{"[..len])
                .then(|| scan_curly_section(source, start, len, len))
                .flatten()
                .map_or(start + 1, |(_, end)| end),
        );
    }
    if source[start..].starts_with("<!--") {
        return Some(
            source[start + 4..]
                .find("-->")
                .map_or(source.len(), |end| start + 4 + end + 3),
        );
    }
    // Glimmer also opens tags with `<@arg>` and named blocks with `<:name>`.
    let glimmer_tag = framework == ComponentFramework::Ember
        && matches!(source.as_bytes().get(start + 1), Some(b'@' | b':'));
    (!glimmer_tag && !is_html_tag_start(source, start)).then_some(start + 1)
}

/// The brace count that opens a text expression in this framework's markup.
/// Astro is absent because its `{ }` expressions can hold markup.
fn interpolation_brace_len(framework: ComponentFramework) -> Option<usize> {
    match framework {
        ComponentFramework::Vue | ComponentFramework::Angular | ComponentFramework::Ember => {
            Some(2)
        }
        ComponentFramework::Svelte => Some(1),
        _ => None,
    }
}

fn collect_attribute_escapes(
    attrs: &[ParsedAttr],
    imports: &[ImportInfo],
    aliases: &[fallow_types::extract::ComponentAliasBinding],
    framework: ComponentFramework,
    facts: &mut ComponentContractFacts,
) {
    for attr in attrs {
        let value = attr.value.as_deref().unwrap_or(&attr.name);
        let expression = value.contains('{')
            || (framework == ComponentFramework::Angular && attr.name.starts_with(['[', '(', '*']))
            || (framework == ComponentFramework::Vue
                && (attr.name.starts_with([':', '@']) || attr.name.starts_with("v-")));
        if !expression {
            continue;
        }
        let words: Vec<_> = value
            .split(|character: char| {
                !character.is_ascii_alphanumeric() && character != '_' && character != '$'
            })
            .collect();
        for alias in aliases {
            if words.contains(&alias.local.as_str()) {
                facts.escapes.push(alias.target.clone());
            }
        }
        for import in imports {
            if !import.local_name.is_empty() && words.contains(&import.local_name.as_str()) {
                facts.escapes.push(ComponentReference::Import {
                    local: import.local_name.clone(),
                    span_start: import.span.start,
                });
            }
        }
    }
}

fn template_binding_may_shadow(source: &str, local: &str) -> bool {
    if local.is_empty() {
        return false;
    }
    source.contains("=>")
        || source.contains("function")
        || source.contains(" as ")
        || source.contains('|')
        || source.contains("{#snippet")
        || source.contains("v-for=")
        || source.contains("v-slot")
        || source.contains("#each")
        || source.contains("#await")
        || source.contains("let:")
}

fn literal_keys(source: &str) -> Option<Vec<String>> {
    use oxc_ast::ast::{Expression, Statement};
    let source = format!("({source});");
    let allocator = oxc_allocator::Allocator::default();
    let parsed = oxc_parser::Parser::new(&allocator, &source, oxc_span::SourceType::ts()).parse();
    if parsed.fatal_error || !parsed.diagnostics.is_empty() {
        return None;
    }
    let Statement::ExpressionStatement(statement) = parsed.program.body.first()? else {
        return None;
    };
    let Expression::ObjectExpression(object) = statement.expression.without_parentheses() else {
        return None;
    };
    literal_object_keys(object)
}

fn literal_object_keys(object: &oxc_ast::ast::ObjectExpression<'_>) -> Option<Vec<String>> {
    use oxc_ast::ast::{Expression, ObjectPropertyKind, PropertyKey, PropertyKind};
    let mut keys = Vec::new();
    for property in &object.properties {
        match property {
            ObjectPropertyKind::SpreadProperty(spread) => {
                let Expression::ObjectExpression(object) = spread.argument.without_parentheses()
                else {
                    return None;
                };
                keys.extend(literal_object_keys(object)?);
            }
            ObjectPropertyKind::ObjectProperty(property) => {
                if property.computed || property.method || property.kind != PropertyKind::Init {
                    return None;
                }
                match &property.key {
                    PropertyKey::StaticIdentifier(name) => keys.push(name.name.to_string()),
                    PropertyKey::StringLiteral(name) => keys.push(name.value.to_string()),
                    _ => return None,
                }
            }
        }
    }
    Some(keys)
}

fn spread_keys(
    expression: &str,
    bindings: &[fallow_types::extract::ComponentSpreadBinding],
    source: &str,
) -> Option<Vec<String>> {
    if let Some(keys) = literal_keys(expression) {
        return Some(keys);
    }
    let local = expression.trim();
    let binding = bindings.iter().find(|binding| binding.local == local)?;
    if source.contains("v-for=")
        || source.contains("v-slot")
        || source.contains("#each")
        || source.contains("#await")
        || source.contains("{#snippet")
    {
        return None;
    }
    // Template expressions can mutate an otherwise unescaped script object.
    // Only bare spread uses are inspected; any other textual reference abstains.
    for (start, _) in source.match_indices(local) {
        let prefix = &source[..start];
        let suffix = &source[start + local.len()..];
        let bare_vue = prefix.ends_with("v-bind=\"") && suffix.starts_with('"')
            || prefix.ends_with("v-bind='") && suffix.starts_with('\'');
        let bare_brace = prefix.ends_with("{...") && suffix.starts_with('}');
        if !bare_vue && !bare_brace {
            return None;
        }
    }
    Some(binding.keys.clone())
}

fn attribute_supply(
    attr: &ParsedAttr,
    framework: ComponentFramework,
    supplied: &mut Vec<String>,
    bindings: &[fallow_types::extract::ComponentSpreadBinding],
    source: &str,
) -> bool {
    let mut unknown_props = false;

    let name = attr.name.as_str();
    if name.starts_with('{') {
        let inner = name
            .strip_prefix('{')
            .and_then(|name| name.strip_suffix('}'))
            .unwrap_or(name);
        if let Some(spread) = inner.strip_prefix("...") {
            if let Some(keys) = spread_keys(spread, bindings, source) {
                supplied.extend(keys);
            } else {
                unknown_props = true;
            }
        } else if !inner.is_empty()
            && inner
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'$'))
        {
            supplied.push(inner.to_string());
        } else {
            unknown_props = true;
        }
        return unknown_props;
    }
    if name.contains('[') && framework != ComponentFramework::Angular {
        unknown_props = true;
        return unknown_props;
    }
    if framework == ComponentFramework::Vue && name == "v-bind" {
        if let Some(keys) = attr
            .value
            .as_deref()
            .and_then(|value| spread_keys(value, bindings, source))
        {
            supplied.extend(keys);
            return false;
        }
        return true;
    }
    named_attribute_supply(attr, framework, supplied)
}

fn named_attribute_supply(
    attr: &ParsedAttr,
    framework: ComponentFramework,
    supplied: &mut Vec<String>,
) -> bool {
    let name = attr.name.as_str();
    let mut unknown_props = false;
    match framework {
        ComponentFramework::Vue => {
            if name == "v-model" || name.starts_with("v-model.") {
                supplied.push("modelValue".to_string());
            } else if let Some(name) = name.strip_prefix("v-model:") {
                supplied.push(kebab_to_camel_case(name.split('.').next().unwrap_or(name)));
            } else if let Some(name) = name
                .strip_prefix(':')
                .or_else(|| name.strip_prefix("v-bind:"))
            {
                supplied.push(kebab_to_camel_case(name.split('.').next().unwrap_or(name)));
            } else if !name.starts_with(['@', '#']) && !name.starts_with("v-") {
                supplied.push(kebab_to_camel_case(name));
            }
        }
        ComponentFramework::Svelte => {
            if let Some(name) = name.strip_prefix("bind:") {
                supplied.push(name.to_string());
            } else if !name.contains(':') {
                supplied.push(name.to_string());
            }
        }
        ComponentFramework::Astro => {
            if !name.contains(':') {
                supplied.push(name.to_string());
            }
        }
        ComponentFramework::Angular => {
            if name.starts_with("[(") && name.ends_with(")]") {
                supplied.push(name[2..name.len() - 2].to_string());
            } else if name.starts_with('[') && name.ends_with(']') {
                supplied.push(name[1..name.len() - 1].to_string());
            } else if !name.starts_with(['(', '*', '#']) {
                supplied.push(name.to_string());
            }
        }
        ComponentFramework::Lit => {
            supplied.push(name.trim_start_matches('?').to_ascii_lowercase());
        }
        ComponentFramework::Ember => {
            if let Some(name) = name.strip_prefix('@') {
                supplied.push(name.to_string());
            } else if name == "...attributes" {
                unknown_props = true;
            }
        }
        _ => {
            supplied.push(name.to_string());
        }
    }
    unknown_props
}

fn target_for_tag(
    name: &str,
    imported: Option<&ImportInfo>,
    framework: ComponentFramework,
    anchor: u32,
) -> Option<ComponentReference> {
    Some(if let Some(import) = imported {
        ComponentReference::Import {
            local: import.local_name.clone(),
            span_start: import.span.start,
        }
    } else if framework == ComponentFramework::Angular
        || (framework == ComponentFramework::Lit && name.contains('-'))
    {
        ComponentReference::Selector(if framework == ComponentFramework::Lit {
            name.to_ascii_lowercase()
        } else {
            name.to_string()
        })
    } else if framework == ComponentFramework::Vue
        && (name.contains('-') || name.as_bytes().first().is_some_and(u8::is_ascii_uppercase))
    {
        // Nuxt's synthetic import lane joins this name in the graph.
        ComponentReference::Import {
            local: name.to_string(),
            span_start: anchor,
        }
    } else if framework == ComponentFramework::Ember
        && name.as_bytes().first().is_some_and(u8::is_ascii_uppercase)
    {
        ComponentReference::Import {
            local: name.to_string(),
            span_start: anchor,
        }
    } else if name.contains('-') {
        ComponentReference::Selector(name.to_ascii_lowercase())
    } else {
        return None;
    })
}