tachyonfx 0.25.0

A ratatui library for creating shader-like effects in TUIs.
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
use alloc::collections::BTreeMap;

use super::types::{tok, CompletionContext, TokenCursor};
use crate::dsl::tokenizer::{Token, TokenKind};

pub(super) fn analyze_last_tokens(
    tokens: &[Token],
    cursor: &TokenCursor,
    effect_fns: &BTreeMap<&str, &str>,
) -> CompletionContext {
    // Find the token at or before the cursor
    let cursor_token_idx = cursor.token_index().unwrap_or(tokens.len());

    // Pattern match on the last few tokens
    match &tokens[..cursor_token_idx] {
        // Pattern: identifier.  (e.g., "foo.")
        [.., tok!(Identifier => obj), tok!(Dot)] => {
            CompletionContext::DotAccess { receiver_type: obj.to_string() }
        },

        // Pattern: identifier.identifier  (e.g., "foo.bar")
        [.., tok!(Identifier => obj), tok!(Dot), tok!(Identifier)] => {
            CompletionContext::DotAccess { receiver_type: obj.to_string() }
        },

        // Pattern: ).  (method chain after function call, cursor after dot)
        [.., tok!(RightParen), tok!(Dot)] => {
            // The closing paren is at cursor_token_idx - 2 (before the dot)
            let closing_paren_idx = cursor_token_idx - 2;
            let paren_idx = find_matching_opening_paren(tokens, closing_paren_idx).unwrap_or(0);

            CompletionContext::DotAccess {
                receiver_type: infer_return_type(tokens, paren_idx, effect_fns),
            }
        },

        // Pattern: ).identifier  (method chain after function call, cursor in identifier)
        [.., tok!(RightParen), tok!(Dot), tok!(Identifier)] => {
            // The closing paren is at cursor_token_idx - 3 (before the dot and identifier)
            let closing_paren_idx = cursor_token_idx - 3;
            let paren_idx = find_matching_opening_paren(tokens, closing_paren_idx).unwrap_or(0);

            CompletionContext::DotAccess {
                receiver_type: infer_return_type(tokens, paren_idx, effect_fns),
            }
        },

        // Pattern: Namespace::  (e.g., "fx::" or "Color::")
        [.., tok!(Identifier => ns), tok!(DoubleColon)] => {
            CompletionContext::DoubleColon { namespace: ns.to_string() }
        },

        // Pattern: Namespace::partial  (e.g., "Color::Red" or "Interpolation::Quad")
        [.., tok!(Identifier => ns), tok!(DoubleColon), tok!(Identifier)] => {
            CompletionContext::DoubleColon { namespace: ns.to_string() }
        },

        // Pattern: Namespace::function_name(  (e.g., "WaveLayer::new(")
        [.., tok!(Identifier => ns), tok!(DoubleColon), tok!(Identifier => fn_name), tok!(LeftParen)] => {
            CompletionContext::FnCall {
                fn_name: fn_name.to_string(),
                namespace: Some(ns.to_string()),
                arg_index: 0,
            }
        },

        // Pattern: function_name(  (e.g., "fade_to(")
        [.., tok!(Identifier => fn_name), tok!(LeftParen)] => CompletionContext::FnCall {
            fn_name: fn_name.to_string(),
            namespace: None,
            arg_index: 0,
        },

        // Pattern: function_name(arg1, arg2,  (count commas for arg index)
        _tokens_slice => {
            // Find the last unclosed opening paren by walking backwards and tracking depth
            let mut paren_idx: Option<usize> = None;
            let mut depth = 0;

            for (idx, token) in tokens[..cursor_token_idx]
                .iter()
                .enumerate()
                .rev()
            {
                match token.kind {
                    TokenKind::RightParen => depth += 1,
                    TokenKind::LeftParen => {
                        if depth == 0 {
                            // Found an unclosed opening paren
                            paren_idx = Some(idx);
                            break;
                        }
                        depth -= 1;
                    },
                    _ => {},
                }
            }

            // If we found an unclosed paren, treat it as a function call
            if let Some(paren_idx) = paren_idx {
                // Count commas after the paren to determine argument index
                // Only count commas at depth 1 (direct arguments, not nested in brackets/parens)
                let mut comma_count = 0;
                let mut depth = 1;
                for token in &tokens[paren_idx + 1..cursor_token_idx] {
                    match token.kind {
                        TokenKind::LeftParen | TokenKind::LeftBracket => depth += 1,
                        TokenKind::RightParen | TokenKind::RightBracket => depth -= 1,
                        TokenKind::Comma if depth == 1 => comma_count += 1,
                        _ => {},
                    }
                }

                // Try to find the function name (and optional namespace) before the paren
                if paren_idx > 0 {
                    if let Some(tok!(Identifier => fn_name)) = tokens.get(paren_idx - 1) {
                        let namespace = if paren_idx >= 3 {
                            match (&tokens[paren_idx - 3], &tokens[paren_idx - 2]) {
                                (tok!(Identifier => ns), tok!(DoubleColon)) => Some(ns.to_string()),
                                _ => None,
                            }
                        } else {
                            None
                        };

                        return CompletionContext::FnCall {
                            fn_name: fn_name.to_string(),
                            namespace,
                            arg_index: comma_count,
                        };
                    }
                }
            }

            // Check if we're inside a struct initialization
            if let Some(brace_idx) = tokens[..cursor_token_idx]
                .iter()
                .rposition(|t| t.kind == TokenKind::LeftBrace)
            {
                // Check if this brace is closed - count brace depth from the opening brace
                let mut depth = 1;
                for token in &tokens[brace_idx + 1..cursor_token_idx] {
                    match token.kind {
                        TokenKind::LeftBrace => depth += 1,
                        TokenKind::RightBrace => {
                            depth -= 1;
                            if depth == 0 {
                                // This opening brace is closed, not inside struct init
                                break;
                            }
                        },
                        _ => {},
                    }
                }

                // Only treat as struct init if brace is still open (depth > 0)
                if depth > 0 {
                    // Look for the struct name before the brace
                    if brace_idx > 0 {
                        if let Some(tok!(Identifier => struct_name)) = tokens.get(brace_idx - 1) {
                            // Collect already filled fields (identifiers before colons after the
                            // brace)
                            let filled_fields = tokens[brace_idx..cursor_token_idx]
                                .windows(2)
                                .filter_map(|w| match w {
                                    [tok!(Identifier => field), tok!(Colon)] => {
                                        Some(field.to_string())
                                    },
                                    _ => None,
                                })
                                .collect();

                            return CompletionContext::StructInit {
                                struct_name: struct_name.to_string(),
                                filled_fields,
                            };
                        }
                    }
                }
            }

            // Default to top level context
            CompletionContext::TopLevel
        },
    }
}

/// Find the matching opening paren for a closing paren at the given index.
/// Scans backwards from closing_paren_idx tracking paren depth.
fn find_matching_opening_paren(tokens: &[Token], closing_paren_idx: usize) -> Option<usize> {
    let mut depth = 1;

    for (idx, token) in tokens[..closing_paren_idx]
        .iter()
        .enumerate()
        .rev()
    {
        match token.kind {
            TokenKind::RightParen => depth += 1,
            TokenKind::LeftParen => {
                depth -= 1;
                if depth == 0 {
                    return Some(idx);
                }
            },
            _ => {},
        }
    }

    None
}

/// Try to infer the return type from a function call by looking at the namespace
/// e.g., Color::from_u32(...) returns Color, fx::dissolve(...) returns Effect
fn infer_return_type(
    tokens: &[Token],
    paren_idx: usize,
    effect_fns: &BTreeMap<&str, &str>,
) -> String {
    // Check the 3 tokens immediately before the opening paren for Namespace::function pattern
    if paren_idx >= 3 {
        if let [tok!(Identifier => namespace), tok!(DoubleColon), tok!(Identifier)] =
            &tokens[paren_idx - 3..paren_idx]
        {
            // Map common namespaces to their types
            return match *namespace {
                "fx" => "Effect",
                other => other, // Color, Layout, Style, etc. use their namespace as type
            }
            .to_string();
        }
    }

    // If not a qualified call, check if it's a method chain (pattern: ).method()
    // Walk backwards through the method chain to find the original qualified call
    if paren_idx >= 2 {
        if let [tok!(Dot), tok!(Identifier)] = &tokens[paren_idx - 2..paren_idx] {
            // This is a method call - find the closing paren before the dot
            if paren_idx >= 3 {
                if let tok!(RightParen) = tokens[paren_idx - 3] {
                    // Find the matching opening paren and recurse
                    if let Some(matching_paren) = find_matching_opening_paren(tokens, paren_idx - 3)
                    {
                        return infer_return_type(tokens, matching_paren, effect_fns);
                    }
                }
            }
        }
    }

    // Check for unqualified function call (pattern: function_name()
    if paren_idx >= 1 {
        if let tok!(Identifier => fn_name) = &tokens[paren_idx - 1] {
            return effect_fns
                .get(fn_name)
                .copied()
                .unwrap_or("<Unknown>")
                .to_string();
        }
    }

    "<Unknown>".to_string()
}

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

    use super::*;
    use crate::dsl::tokenizer::{sanitize_tokens, tokenize};

    fn assert_context_eq(input: &str, expected: &CompletionContext) {
        fn analyze(input: &str) -> CompletionContext {
            let tokens = tokenize(input).map(sanitize_tokens).unwrap();
            let cursor = TokenCursor::from_tokens(&tokens, input.len() as _);

            // Common effect functions for testing
            let effect_fns: BTreeMap<&str, &str> = BTreeMap::from([
                ("fade_from_fg", "Effect"),
                ("fade_to", "Effect"),
                ("dissolve", "Effect"),
                ("sweep_in", "Effect"),
                ("sweep_out", "Effect"),
                ("slide_in", "Effect"),
                ("slide_out", "Effect"),
                ("coalesce", "Effect"),
                ("paint", "Effect"),
                ("saturate", "Effect"),
                ("lighten", "Effect"),
                ("darken", "Effect"),
                ("hsl_shift", "Effect"),
            ])
            .into_iter()
            .collect();

            analyze_last_tokens(&tokens, &cursor, &effect_fns)
        }

        let cursor_index = input
            .char_indices()
            .position(|(_, c)| c == '^')
            .unwrap_or(input.len());

        let ctx = analyze(&input[..cursor_index]);
        assert_eq!(&ctx, expected, "For input: {input}");
    }

    #[test]
    fn test_top_level_context() {
        assert_context_eq("", &CompletionContext::TopLevel);
        assert_context_eq("fx", &CompletionContext::TopLevel);

        // cursor is after semicolon, hence top-level
        assert_context_eq(
            "let c = Color::from_u32(0x1d2021);",
            &CompletionContext::TopLevel,
        );
    }

    #[test]
    fn test_dot_access() {
        assert_context_eq("a.", &CompletionContext::DotAccess {
            receiver_type: "a".to_string(),
        });
        assert_context_eq("effect.", &CompletionContext::DotAccess {
            receiver_type: "effect".to_string(),
        });
        assert_context_eq("a.clon", &CompletionContext::DotAccess {
            receiver_type: "a".to_string(),
        });
        assert_context_eq("effect.with_cell", &CompletionContext::DotAccess {
            receiver_type: "effect".to_string(),
        });

        assert_context_eq(
            "Color::from_u32(0x1d2021).",
            &CompletionContext::DotAccess { receiver_type: "Color".to_string() },
        );

        assert_context_eq(
            indoc! {"
                fx::fade_from(bg, bg, 1000). ^ // chevron is cursor pos
                    .with_color_space(ColorSpace::Rgb)
            "},
            &CompletionContext::DotAccess { receiver_type: "Effect".to_string() },
        );
    }

    #[test]
    fn test_double_colon() {
        assert_context_eq("fx::", &CompletionContext::DoubleColon {
            namespace: "fx".to_string(),
        });

        assert_context_eq("Color::", &CompletionContext::DoubleColon {
            namespace: "Color".to_string(),
        });

        assert_context_eq(
            indoc! {"
                fx::^
                fx::fade_from(Black, Black, 1000)
            "},
            &CompletionContext::DoubleColon { namespace: "fx".to_string() },
        );
    }

    #[test]
    fn test_function_call_no_args() {
        assert_context_eq("fade_to(", &CompletionContext::FnCall {
            fn_name: "fade_to".to_string(),
            namespace: None,
            arg_index: 0,
        });
    }

    #[test]
    fn test_function_call_with_args() {
        assert_context_eq("fade_to(Color::Red,", &CompletionContext::FnCall {
            fn_name: "fade_to".to_string(),
            namespace: None,
            arg_index: 1,
        });

        assert_context_eq("dissolve(500, CircOut,", &CompletionContext::FnCall {
            fn_name: "dissolve".to_string(),
            namespace: None,
            arg_index: 2,
        });
    }

    #[test]
    fn test_struct_init() {
        assert_context_eq("Rect {", &CompletionContext::StructInit {
            struct_name: "Rect".to_string(),
            filled_fields: vec![],
        });

        assert_context_eq("Rect { x: 0,", &CompletionContext::StructInit {
            struct_name: "Rect".to_string(),
            filled_fields: vec!["x".to_string()],
        });

        assert_context_eq("Rect { x: 0, y: 5,", &CompletionContext::StructInit {
            struct_name: "Rect".to_string(),
            filled_fields: vec!["x".to_string(), "y".to_string()],
        });

        assert_context_eq("Yolo { foo: 0, ba", &CompletionContext::StructInit {
            struct_name: "Yolo".to_string(),
            filled_fields: vec!["foo".to_string()],
        });
    }

    #[test]
    fn test_nested_function_calls() {
        // When cursor is inside nested call, should detect the innermost context
        assert_context_eq("outer(inner(", &CompletionContext::FnCall {
            fn_name: "inner".to_string(),
            namespace: None,
            arg_index: 0,
        });
    }

    #[test]
    fn test_method_chain() {
        // Method chains infer return type from the namespace

        // fx:: functions return Effect
        assert_context_eq("fx::dissolve(500).with_", &CompletionContext::DotAccess {
            receiver_type: "Effect".to_string(),
        });

        // Color:: functions return Color
        assert_context_eq(
            "Color::from_u32(0xff0000).",
            &CompletionContext::DotAccess { receiver_type: "Color".to_string() },
        );

        // Layout:: functions return Layout
        assert_context_eq("Layout::horizontal([]).", &CompletionContext::DotAccess {
            receiver_type: "Layout".to_string(),
        });

        // Style:: functions return Style
        assert_context_eq("Style::new().", &CompletionContext::DotAccess {
            receiver_type: "Style".to_string(),
        });

        // Non-qualified function calls default to "Chained"
        assert_context_eq("some_function().", &CompletionContext::DotAccess {
            receiver_type: "<Unknown>".to_string(),
        });

        let src = indoc! {"
            fx::fade_from_fg(Black, 1000)
                .with_filter(CellFilter::All)
                .with_pattern(DissolvePattern::default())
                .with_color_space(ColorSpace::Rgb)
                .re
        "};

        assert_context_eq(src, &CompletionContext::DotAccess {
            receiver_type: "Effect".to_string(),
        });

        let src = indoc! {"
            fade_from_fg(Black, 1000)
                .with_filter(CellFilter::All)
                .with_pattern(DissolvePattern::default())
                .with_color_space(ColorSpace::Rgb)
                .re
        "};

        assert_context_eq(src, &CompletionContext::DotAccess {
            receiver_type: "Effect".to_string(),
        });
    }

    #[test]
    fn test_qualified_function_call() {
        assert_context_eq("Color::from_u32(", &CompletionContext::FnCall {
            fn_name: "from_u32".to_string(),
            namespace: Some("Color".to_string()),
            arg_index: 0,
        });
    }

    #[test]
    fn test_nested_function_calls_infer_type() {
        // Nested function calls - should infer from the outer call, not the inner
        assert_context_eq(
            "fx::sequence(&[fx::dissolve(500)]).",
            &CompletionContext::DotAccess { receiver_type: "Effect".to_string() },
        );

        // Multiple levels of nesting
        assert_context_eq(
            "fx::parallel(&[fx::sequence(&[fx::dissolve(500)])]).",
            &CompletionContext::DotAccess { receiver_type: "Effect".to_string() },
        );
    }

    #[test]
    fn test_nested_effects_inside_slice() {
        assert_context_eq("fx::sequence(&[", &CompletionContext::FnCall {
            fn_name: "sequence".to_string(),
            namespace: Some("fx".to_string()),
            arg_index: 0,
        });

        assert_context_eq(
            "fx::sequence(&[fx::dissolve(500), ",
            &CompletionContext::FnCall {
                fn_name: "sequence".to_string(),
                namespace: Some("fx".to_string()),
                arg_index: 0,
            },
        );

        assert_context_eq(
            "fx::sequence(&[fx::dissolve(500), fx::",
            &CompletionContext::DoubleColon { namespace: "fx".to_string() },
        );

        assert_context_eq(
            "fx::sequence(&[fx::dissolve(500), fx::consume_tick()]).",
            &CompletionContext::DotAccess { receiver_type: "Effect".to_string() },
        );
    }

    #[test]
    fn test_extract_partial_token() {
        let tokens = tokenize("Motion::Left").unwrap();
        let tokens = sanitize_tokens(tokens);

        // Cursor at end of "Left"
        let cursor_pos = tokens.last().unwrap().span.1;
        let cursor = TokenCursor::from_tokens(&tokens, cursor_pos);
        let partial = cursor.extract_partial_token(&tokens);
        assert_eq!(partial, "Left");

        // Cursor in middle of "Left" (after "Le")
        let cursor_pos = tokens.last().unwrap().span.0 + 2;
        let cursor = TokenCursor::from_tokens(&tokens, cursor_pos);
        let partial = cursor.extract_partial_token(&tokens);
        assert_eq!(partial, "Le");
    }
}