fallow-engine 3.48.0

Typed analysis engine facade for fallow consumers
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
//! `@keyframes` reference hints that the Sass/Less lowering cannot keep.
//!
//! The lowering replaces a preprocessor variable with a placeholder, drops
//! each `@include`, and drops a rule that CSS cannot parse, such as a
//! `%placeholder` rule. So `animation: $name 1s`, `@include animate(spin)` and
//! `%pulse { animation-name: pulsate; }` give no keyframes reference in the
//! virtual CSS. Without these hints, a keyframes block that the project uses
//! in such a place shows up as an unreferenced-keyframes candidate.

/// What a Sass/Less source says about keyframes references that the lowered
/// CSS does not contain.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct KeyframeHints {
    /// An `animation` or `animation-name` value holds an interpolation, so the
    /// referenced name is not known before compilation.
    pub(super) opaque_reference: bool,
    /// Bare identifiers in an `animation` or `animation-name` value and in the
    /// arguments of an `@include` or a Less mixin call. A caller counts one as
    /// a reference only when a `@keyframes` block defines that name.
    pub(super) possible_names: Vec<String>,
    /// Variables (`$name`, `@name`) in an `animation` or `animation-name`
    /// value that are no parameter of the enclosing mixin. Each one is opaque
    /// unless a literal assignment gives its value.
    pub(super) animation_variables: Vec<String>,
    /// Variables in mixin call arguments. The assigned names of each one are
    /// possible names. An unknown one is not opaque, because most mixin
    /// arguments have no relation to an animation.
    pub(super) argument_variables: Vec<String>,
    /// Variable assignments (`$fade: fade-in;`, `@fade: fade-in;`). The value
    /// is the identifier list of a literal value, or `None` when the value
    /// holds a variable or an interpolation.
    pub(super) assignments: Vec<(String, Option<Vec<String>>)>,
}

/// Scan a Sass/Less source for keyframes references that the lowering loses.
pub(super) fn preprocessor_keyframe_hints(source: &str) -> KeyframeHints {
    let mut hints = KeyframeHints::default();
    // One entry per open `{` block: the parameters of a mixin definition, or
    // an empty list for any other block.
    let mut scopes: Vec<Vec<String>> = Vec::new();
    let source = blank_comments(source, BlockComments::Blank);
    for (statement, terminator) in statements(&source) {
        let statement = statement.trim();
        match terminator {
            b'{' => scopes.push(mixin_parameters(statement, &mut hints)),
            b'}' => {
                scan_declaration(statement, &scopes, &mut hints);
                scopes.pop();
            }
            _ => scan_declaration(statement, &scopes, &mut hints),
        }
    }
    hints.possible_names.sort_unstable();
    hints.possible_names.dedup();
    hints
}

/// Scan one statement that ends at `;` or `}`.
fn scan_declaration(statement: &str, scopes: &[Vec<String>], hints: &mut KeyframeHints) {
    if let Some(rest) = statement.strip_prefix("@include") {
        push_call_arguments(rest, hints);
    } else if is_less_mixin_call(statement) {
        push_call_arguments(statement, hints);
    } else if let Some((name, value)) = variable_assignment(statement) {
        // A function call such as `unique-id()` gives a value that the scan
        // cannot know.
        let names = (!is_dynamic_value(value) && !value.contains('(')).then(|| {
            let mut names = Vec::new();
            push_identifiers(value, &mut names);
            names
        });
        hints.assignments.push((name.to_owned(), names));
    } else if let Some(value) = animation_value(statement) {
        if value.contains("#{") || value.contains("@{") {
            hints.opaque_reference = true;
            return;
        }
        push_identifiers(value, &mut hints.possible_names);
        for variable in variables(value) {
            if !scopes.iter().flatten().any(|param| *param == variable) {
                hints.animation_variables.push(variable.to_owned());
            }
        }
    }
}

/// What [`blank_comments`] does with a `/* */` block comment.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum BlockComments {
    Blank,
    Keep,
}

/// Replace each `//` line comment, and each block comment when `block` is
/// [`BlockComments::Blank`], with spaces. Offsets and newlines stay, so line
/// numbers do not change. As in Sass, a `//` inside a quoted string or an
/// unquoted `url(//host/x)` is no comment. A `//` after a `:`, as in
/// `https://`, is no comment either. A `//` inside other parentheses, such as
/// a multi-line map, is a comment. A kept block comment is still skipped, so a
/// quote inside it does not open a string.
pub(super) fn blank_comments(source: &str, block: BlockComments) -> String {
    let mut bytes = source.as_bytes().to_vec();
    let mut i = 0;
    while i < bytes.len() {
        let end = match bytes[i] {
            quote @ (b'"' | b'\'') => {
                i = skip_string(&bytes, i + 1, quote);
                continue;
            }
            b'/' if bytes.get(i + 1) == Some(&b'*') => {
                let end = skip_block_comment(&bytes, i + 2);
                if block == BlockComments::Keep {
                    i = end;
                    continue;
                }
                end
            }
            b'/' if bytes.get(i + 1) == Some(&b'/') && (i == 0 || bytes[i - 1] != b':') => {
                line_end(&bytes, i)
            }
            b'(' if opens_url(&bytes, i) => {
                i = skip_unquoted_url(&bytes, i + 1);
                continue;
            }
            _ => {
                i += 1;
                continue;
            }
        };
        for byte in &mut bytes[i..end] {
            if *byte != b'\n' {
                *byte = b' ';
            }
        }
        i = end;
    }
    // Each blanked range starts and ends at an ASCII byte, so the bytes stay
    // valid UTF-8.
    String::from_utf8(bytes).unwrap_or_else(|_| source.to_owned())
}

/// Split a comment-free source into statements that end at `;`, `{` or `}`.
/// A `#{...}` or `@{...}` interpolation, a quoted string and a `;` inside
/// parentheses (Less mixin arguments) stay inside their statement.
fn statements(source: &str) -> Vec<(&str, u8)> {
    let bytes = source.as_bytes();
    let mut out = Vec::new();
    let mut start = 0;
    let mut depth = 0usize;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'#' | b'@' if bytes.get(i + 1) == Some(&b'{') => {
                i = skip_past(bytes, i + 2, b'}');
            }
            quote @ (b'"' | b'\'') => i = skip_string(bytes, i + 1, quote),
            b'(' => {
                depth += 1;
                i += 1;
            }
            b')' => {
                depth = depth.saturating_sub(1);
                i += 1;
            }
            b';' if depth > 0 => i += 1,
            terminator @ (b';' | b'{' | b'}') => {
                out.push((&source[start..i], terminator));
                depth = 0;
                i += 1;
                start = i;
            }
            _ => i += 1,
        }
    }
    out.push((&source[start..], b';'));
    out
}

fn skip_past(bytes: &[u8], from: usize, end: u8) -> usize {
    bytes[from.min(bytes.len())..]
        .iter()
        .position(|&b| b == end)
        .map_or(bytes.len(), |offset| from + offset + 1)
}

/// Skip a quoted string that starts at `i`, just after the opening quote. As
/// in CSS, an unescaped newline ends an unclosed string, so a stray quote does
/// not swallow the rest of the file.
fn skip_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => i += 2,
            b'\n' => return i,
            b if b == quote => return i + 1,
            _ => i += 1,
        }
    }
    bytes.len()
}

fn line_end(bytes: &[u8], from: usize) -> usize {
    bytes[from..]
        .iter()
        .position(|&b| b == b'\n')
        .map_or(bytes.len(), |offset| from + offset)
}

/// Whether the `(` at `paren` ends a `url` function name.
fn opens_url(bytes: &[u8], paren: usize) -> bool {
    paren >= 3
        && bytes[paren - 3..paren].eq_ignore_ascii_case(b"url")
        && (paren == 3
            || !matches!(bytes[paren - 4], b'-' | b'_' | b'$' | b'@')
                && !bytes[paren - 4].is_ascii_alphanumeric())
}

/// Skip the body of an unquoted `url(...)` that starts at `from`. A quoted
/// body is left to the string scan. The body ends at `)`, at the line end, or
/// at a quote, which the string scan then reads.
fn skip_unquoted_url(bytes: &[u8], from: usize) -> usize {
    let body = from
        + bytes[from..]
            .iter()
            .take_while(|b| matches!(b, b' ' | b'\t'))
            .count();
    if matches!(bytes.get(body), Some(b'"' | b'\'')) {
        return body;
    }
    bytes[body..]
        .iter()
        .position(|&b| matches!(b, b')' | b'\n' | b'"' | b'\''))
        .map_or(bytes.len(), |offset| body + offset)
}

fn skip_block_comment(bytes: &[u8], from: usize) -> usize {
    bytes[from.min(bytes.len())..]
        .windows(2)
        .position(|pair| pair == b"*/")
        .map_or(bytes.len(), |offset| from + offset + 2)
}

/// The parameters of a `@mixin name($a, $b)` or a Less `.name(@a; @b)`
/// definition. Any other block gives an empty list. A Less mixin also gets
/// the implicit `@arguments` parameter. A default value (`$a: spin`) counts
/// like a call argument, because a call without that argument uses it.
fn mixin_parameters(prelude: &str, hints: &mut KeyframeHints) -> Vec<String> {
    let less = is_less_mixin_head(prelude);
    if !less && !prelude.starts_with("@mixin") {
        return Vec::new();
    }
    let Some(open) = prelude.find('(') else {
        return Vec::new();
    };
    let list = prelude[open + 1..]
        .rfind(')')
        .map_or(&prelude[open + 1..], |close| {
            &prelude[open + 1..open + 1 + close]
        });
    let mut parameters = Vec::new();
    for parameter in list.split([',', ';']) {
        let (name, default) = parameter.split_once(':').unwrap_or((parameter, ""));
        parameters.extend(variables(name).map(str::to_owned));
        push_arguments(default, hints);
    }
    if less {
        parameters.push("@arguments".to_owned());
    }
    parameters
}

/// `.mixin(args);` or `#namespace.mixin(args);`: a Less mixin call. Only the
/// part before `(` must hold no `:`, so a named argument such as
/// `.m(@b: spin);` matches. A selector such as `.a:not(.b) {` never gets here,
/// because the caller passes only statements that end at `;` or `}`.
fn is_less_mixin_call(statement: &str) -> bool {
    is_less_mixin_head(statement)
}

/// A statement that starts with a Less mixin name and holds `(`, with no `:`
/// before the `(`.
fn is_less_mixin_head(statement: &str) -> bool {
    let mut chars = statement.chars();
    let starts_as_mixin = matches!(chars.next(), Some('.' | '#'))
        && chars
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '_' | '-'));
    starts_as_mixin
        && statement
            .split_once('(')
            .is_some_and(|(head, _)| !head.contains(':'))
}

/// `$name: value` or Less `@name: value`, also with `!default`.
fn variable_assignment(statement: &str) -> Option<(&str, &str)> {
    let (name, value) = statement.split_once(':')?;
    let name = name.trim();
    let sigil = name.bytes().next()?;
    let ident = &name[1..];
    let is_variable =
        matches!(sigil, b'$' | b'@') && !ident.is_empty() && ident.bytes().all(is_ident_continue);
    is_variable.then_some((name, value))
}

/// The value of an `animation` or `animation-name` declaration, also with a
/// vendor prefix.
fn animation_value(statement: &str) -> Option<&str> {
    let (property, value) = statement.split_once(':')?;
    let property = property.trim().to_ascii_lowercase();
    let property = ["-webkit-", "-moz-", "-o-", "-ms-"]
        .iter()
        .find_map(|prefix| property.strip_prefix(prefix))
        .unwrap_or(&property);
    matches!(property, "animation" | "animation-name").then_some(value)
}

/// A value that holds a Sass or Less variable or an interpolation.
fn is_dynamic_value(value: &str) -> bool {
    value.contains("#{") || value.contains("@{") || variables(value).next().is_some()
}

/// Each `$name` and `@name` token of `text`, with its sigil.
fn variables(text: &str) -> impl Iterator<Item = &str> {
    let bytes = text.as_bytes();
    bytes.iter().enumerate().filter_map(move |(i, &b)| {
        if !matches!(b, b'$' | b'@') {
            return None;
        }
        let first = *bytes.get(i + 1)?;
        if !(first.is_ascii_alphabetic() || first == b'_' || first == b'-') {
            return None;
        }
        let end = bytes[i + 1..]
            .iter()
            .position(|c| !is_ident_continue(*c))
            .map_or(bytes.len(), |offset| i + 1 + offset);
        Some(&text[i..end])
    })
}

/// Push the arguments inside the outer parentheses of a mixin call.
fn push_call_arguments(call: &str, hints: &mut KeyframeHints) {
    let Some(open) = call.find('(') else {
        return;
    };
    let arguments = call[open + 1..]
        .rfind(')')
        .map_or(&call[open + 1..], |close| &call[open + 1..open + 1 + close]);
    push_arguments(arguments, hints);
}

/// Push each bare identifier and each variable of mixin arguments. An
/// interpolation such as `#{$prefix}-spin` builds a name that the scan
/// cannot know, so it is an opaque reference.
fn push_arguments(arguments: &str, hints: &mut KeyframeHints) {
    if arguments.contains("#{") || arguments.contains("@{") {
        hints.opaque_reference = true;
    }
    push_identifiers(arguments, &mut hints.possible_names);
    hints
        .argument_variables
        .extend(variables(arguments).map(str::to_owned));
}

/// Push each bare identifier of `text`. A variable (`$x`, `@x`), a member
/// (`.x`), a flag (`!default`) or a number is not a keyframes name.
fn push_identifiers(text: &str, into: &mut Vec<String>) {
    let bytes = text.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if is_ident_continue(b) {
            let start = i;
            while i < bytes.len() && is_ident_continue(bytes[i]) {
                i += 1;
            }
            let preceded_by_sigil =
                start > 0 && matches!(bytes[start - 1], b'$' | b'@' | b'.' | b'!');
            let word = &text[start..i];
            let starts_as_ident = word
                .bytes()
                .find(|c| *c != b'-')
                .is_some_and(|c| c.is_ascii_alphabetic() || c == b'_');
            if !preceded_by_sigil && starts_as_ident {
                into.push(word.to_owned());
            }
        } else {
            i += 1;
        }
    }
}

fn is_ident_continue(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
}

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

    #[test]
    fn interpolation_in_animation_value_is_opaque() {
        for source in [
            ".b { -webkit-animation-name: #{$prefix}-spin; }",
            ".b { animation-name: ~\"@{prefix}-spin\"; }",
            "@mixin m($name) { animation: #{$name}-in 1s; }",
        ] {
            assert!(
                preprocessor_keyframe_hints(source).opaque_reference,
                "{source}"
            );
        }
    }

    #[test]
    fn free_variable_in_animation_value_is_recorded() {
        let hints =
            preprocessor_keyframe_hints(".b { animation: $fade 2s; }\n.c { animation: @name 1s; }");
        assert!(!hints.opaque_reference);
        assert_eq!(hints.animation_variables, vec!["$fade", "@name"]);
    }

    #[test]
    fn mixin_parameter_in_animation_value_is_not_recorded() {
        for source in [
            "@mixin animate($name, $d: 1s) { animation: $name $d; }\n.a { @include animate(spin); }",
            ".m(@a; @b) { animation: @a 1s; }\n.x { .m(spin; 2s); }",
            ".m(@a) { animation: @arguments; }",
            "@mixin outer($n) { .x { animation: $n 1s; } }",
        ] {
            let hints = preprocessor_keyframe_hints(source);
            assert!(!hints.opaque_reference, "{source}");
            assert!(hints.animation_variables.is_empty(), "{source}: {hints:?}");
        }
    }

    #[test]
    fn mixin_parameter_does_not_leak_out_of_its_scope() {
        let source = "@mixin m($name) { animation: $name 1s; }\n.a { animation: $name 2s; }";
        let hints = preprocessor_keyframe_hints(source);
        assert_eq!(hints.animation_variables, vec!["$name"]);
    }

    #[test]
    fn literal_assignment_is_recorded() {
        let source = "$fade: fade-in !default;\n@pulse: pulse;\n$other: $fade;\n$id: unique-id();\n.a { animation: $fade 1s; }";
        let hints = preprocessor_keyframe_hints(source);
        assert_eq!(
            hints.assignments,
            vec![
                ("$fade".to_owned(), Some(vec!["fade-in".to_owned()])),
                ("@pulse".to_owned(), Some(vec!["pulse".to_owned()])),
                ("$other".to_owned(), None),
                ("$id".to_owned(), None),
            ]
        );
    }

    #[test]
    fn literal_animation_value_gives_possible_names() {
        let source =
            "%pulse { animation-name: pulsate; }\n.a { animation: spin 1s linear; color: $red; }";
        let hints = preprocessor_keyframe_hints(source);
        assert!(!hints.opaque_reference);
        assert_eq!(hints.possible_names, vec!["linear", "pulsate", "spin"]);
    }

    #[test]
    fn mixin_call_arguments_are_collected() {
        let source = ".a { @include animate(spin, $speed, 2s); }\n.b { .pulse(fade-in 1s); }\n.c:not(.d) { color: red; }\n";
        let hints = preprocessor_keyframe_hints(source);
        assert!(!hints.opaque_reference);
        assert_eq!(hints.possible_names, vec!["fade-in", "spin"]);
        assert_eq!(hints.argument_variables, vec!["$speed"]);
    }

    #[test]
    fn less_named_and_semicolon_arguments_are_collected() {
        let source = ".x { .m(@b: spin); }\n.y { .m(pulse; 2s); }\n.z { #ns.m(@a: fade); }";
        let hints = preprocessor_keyframe_hints(source);
        assert_eq!(hints.possible_names, vec!["fade", "pulse", "spin"]);
    }

    #[test]
    fn interpolation_braces_do_not_end_a_statement() {
        let source = ".a { animation: #{$name} 1s; }\n.b { @include x(spin); }";
        let hints = preprocessor_keyframe_hints(source);
        assert!(hints.opaque_reference);
        assert_eq!(hints.possible_names, vec!["spin"]);
    }

    #[test]
    fn comment_above_a_statement_does_not_hide_it() {
        for comment in ["// note", "/* note */"] {
            let source = format!(
                ".a {{\n  {comment}\n  animation: #{{$p}}-go 1s;\n}}\n\
                 .b {{\n  {comment}\n  @include an(spin);\n}}\n\
                 {comment}\n$fade: fade-in;\n"
            );
            let hints = preprocessor_keyframe_hints(&source);
            assert!(hints.opaque_reference, "{source}");
            assert_eq!(hints.possible_names, vec!["spin"], "{source}");
            assert_eq!(
                hints.assignments,
                vec![("$fade".to_owned(), Some(vec!["fade-in".to_owned()]))],
                "{source}"
            );
        }
    }

    #[test]
    fn protocol_relative_url_is_no_comment() {
        let source = ".a { background: url(//cdn.example/a.png); animation: spin 1s; }";
        let hints = preprocessor_keyframe_hints(source);
        assert_eq!(hints.possible_names, vec!["spin"]);
    }

    #[test]
    fn mixin_parameter_defaults_count_as_arguments() {
        let hints = preprocessor_keyframe_hints(
            "@mixin an($n: spin, $d: $def) { animation: $n $d; }\n.m(@a: pulse) { animation: @a; }",
        );
        assert!(hints.animation_variables.is_empty(), "{hints:?}");
        assert_eq!(hints.possible_names, vec!["pulse", "spin"]);
        assert_eq!(hints.argument_variables, vec!["$def"]);
    }

    #[test]
    fn interpolated_mixin_argument_is_opaque() {
        let hints = preprocessor_keyframe_hints(".a { @include an(#{$p}-spin); }");
        assert!(hints.opaque_reference);
    }

    #[test]
    fn comments_hide_their_content() {
        let source = "// animation: $x;\n/* @include y(spin); */\n.a { color: red; }";
        assert_eq!(
            preprocessor_keyframe_hints(source),
            KeyframeHints::default()
        );
    }
}