fncc-core 0.4.0

Parser and codegen for the fncc native UI framework — compiles .fui files to GPUI Rust code
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
pub mod codegen;
pub mod config;
pub mod parser;
pub mod semantic;

pub use parser::parse;

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::Path;

/// Recursively collect all .fui files under `dir`.
fn collect_fui_files(dir: &Path) -> Result<Vec<std::path::PathBuf>> {
    let mut files = Vec::new();
    if !dir.is_dir() {
        return Ok(files);
    }
    for entry in std::fs::read_dir(dir).context("failed to read ui dir")? {
        let entry = entry.context("failed to read entry")?;
        let path = entry.path();
        if path.is_dir() {
            files.extend(collect_fui_files(&path)?);
        } else if path.extension().is_some_and(|ext| ext == "fui") {
            files.push(path);
        }
    }
    Ok(files)
}

/// Structured parsed file for two-pass processing.
struct ParsedFile {
    path: std::path::PathBuf,
    /// Path relative to ui_dir, forward-slash-separated, without extension.
    /// e.g. "components/Header"
    relative_stem: String,
    ast: parser::Document,
}

/// Configuration for the fncc compilation pipeline.
/// Use `GenerateOptions::new(ui_dir, out_file)` for default (legacy) behavior,
/// or set `src_dir` to enable semantic analysis (state inference, command validation).
pub struct GenerateOptions<'a> {
    pub ui_dir: &'a Path,
    pub out_file: &'a Path,
    /// If `Some`, enables semantic analysis (scans `.rs` files for `#[fncc::command]`).
    /// Expected to point to the Rust source directory (e.g. `"src/"`).
    pub src_dir: Option<&'a Path>,
}

impl<'a> GenerateOptions<'a> {
    pub fn new(ui_dir: &'a Path, out_file: &'a Path) -> Self {
        GenerateOptions {
            ui_dir,
            out_file,
            src_dir: None,
        }
    }
}

/// Legacy entry point: parse all .fui files under `ui_dir` and write
/// generated Rust code into `out_file`. No semantic analysis.
pub fn generate_all(ui_dir: &Path, out_file: &Path) -> Result<()> {
    generate_all_with_options(GenerateOptions::new(ui_dir, out_file))
}

/// Full entry point: parse `.fui` files and optionally run semantic analysis
/// (state inference, command validation) when `opts.src_dir` is `Some`.
pub fn generate_all_with_options(opts: GenerateOptions) -> Result<()> {
    let ui_dir = opts.ui_dir;
    let out_file = opts.out_file;
    let files = collect_fui_files(ui_dir)?;

    // Pass 1: Parse all files
    let mut parsed_files: Vec<ParsedFile> = Vec::new();
    for path in &files {
        let source = std::fs::read_to_string(path).with_context(|| format!("failed to read {:?}", path))?;
        let ast = parser::parse(&source).map_err(|e| anyhow::anyhow!("failed to parse {:?}: {e}", path))?;

        // Compute relative stem from ui_dir
        let relative_stem = match path.strip_prefix(ui_dir) {
            Ok(rel) => {
                let stem = rel.file_stem().unwrap_or_default();
                let parent = rel.parent().unwrap_or_else(|| std::path::Path::new(""));
                parent.join(stem).to_string_lossy().to_string()
            }
            Err(_) => path.file_stem().unwrap_or_default().to_string_lossy().to_string(),
        };
        let relative_stem = relative_stem.replace(std::path::MAIN_SEPARATOR_STR, "/");

        parsed_files.push(ParsedFile {
            path: path.clone(),
            relative_stem,
            ast,
        });
    }

    // Build import resolution index: "ui::path::Component" -> render function name
    let mut import_index: HashMap<String, String> = HashMap::new();
    for pf in &parsed_files {
        let ui_path = format!("ui::{}", pf.relative_stem.replace('/', "::"));
        let component_name = pf.relative_stem.split('/').next_back().unwrap_or("");
        let render_fn = format!("render_{}", codegen::to_snake_case(component_name));
        import_index.insert(ui_path, render_fn);
    }

    // Validate imports: every FuiPath import must exist in the index
    for pf in &parsed_files {
        for imp in &pf.ast.imports {
            if let parser::ImportSource::FuiPath(ref ui_path) = imp.source
                && !import_index.contains_key(ui_path)
            {
                anyhow::bail!(
                    "in '{}': import `{}` -> file not found at `{}.fui`",
                    pf.path.display(),
                    ui_path,
                    ui_path.strip_prefix("ui::").unwrap_or(ui_path)
                );
            }
        }
    }

    // Semantic analysis (optional): scan .rs files for #[fncc::command]
    let semantic_db = if let Some(src_dir) = opts.src_dir {
        let db = semantic::analyze_rs_files(src_dir)?;
        // Extraction-level diagnostics (e.g. duplicate commands) are hard errors
        if let Some(diag) = db.diagnostics.first() {
            anyhow::bail!("{}", diag);
        }
        Some(db)
    } else {
        None
    };

    // Per-file state type resolution: @state or inferred from commands
    let mut state_types: HashMap<usize, Option<String>> = HashMap::new();
    if let Some(ref db) = semantic_db {
        for (file_id, pf) in parsed_files.iter().enumerate() {
            let command_refs = parser::collect_commands(&pf.ast.root);

            let mut inferred_types: Vec<&str> = Vec::new();
            for cmd_name in &command_refs {
                let cmd = db.commands.get(cmd_name).ok_or_else(|| {
                    anyhow::anyhow!(
                        "in '{}': onclick=\"{}\" references #[fncc::command] fn {}() which was not found in any Rust source file",
                        pf.path.display(), cmd_name, cmd_name,
                    )
                })?;
                if let Some(ref st) = cmd.state_type
                    && !inferred_types.contains(&st.as_str())
                {
                    inferred_types.push(st);
                }
            }

            let resolved = match (pf.ast.state_type.as_ref(), inferred_types.as_slice()) {
                (Some(declared), []) => Some(declared.clone()),
                (Some(declared), [inferred]) if declared.as_str() == *inferred => Some(declared.clone()),
                (Some(declared), [inferred]) => anyhow::bail!(
                    "in '{}': @state {} conflicts with inferred state type {} from command signatures — remove @state or align the types",
                    pf.path.display(),
                    declared,
                    inferred,
                ),
                (Some(d), _) => anyhow::bail!(
                    "in '{}': commands reference multiple state types ({}) but @state {} was declared",
                    pf.path.display(),
                    inferred_types.join(", "),
                    d,
                ),
                (None, []) => None,
                (None, [inferred]) => Some((*inferred).to_string()),
                (None, _) => anyhow::bail!(
                    "in '{}': commands reference multiple state types ({}) — a component can only have one",
                    pf.path.display(),
                    inferred_types.join(", "),
                ),
            };

            state_types.insert(file_id, resolved);
        }
    }

    // Pass 2: Generate code with resolved imports
    let mut output = String::new();
    output.push_str("// Generated by fncc-core. Do not edit.\n\n");

    for (file_id, pf) in parsed_files.iter().enumerate() {
        let resolved: Vec<(&str, &str)> = pf
            .ast
            .imports
            .iter()
            .map(|imp| {
                let render_fn = match &imp.source {
                    parser::ImportSource::FuiPath(ui_path) => {
                        import_index.get(ui_path).map(|s| s.as_str()).unwrap_or("")
                    }
                    parser::ImportSource::Gpui => "",
                };
                (imp.name.as_str(), render_fn)
            })
            .collect();

        let component_name = pf.relative_stem.split('/').next_back();
        let resolved_state = state_types.get(&file_id).and_then(|s| s.as_deref());
        let generated = codegen::generate_with_imports(&pf.ast, file_id, &resolved, component_name, resolved_state);
        output.push_str(&generated);
        output.push('\n');
    }

    std::fs::write(out_file, &output).context("failed to write generated file")?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static LIB_TEST_COUNTER: AtomicUsize = AtomicUsize::new(0);

    fn test_dir() -> (PathBuf, PathBuf) {
        let id = LIB_TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("fncc_lib_test_{id}"));
        let ui_dir = dir.join("ui");
        std::fs::create_dir_all(&ui_dir).unwrap();
        (dir, ui_dir)
    }

    #[test]
    fn test_generate_all_creates_output_file() {
        let (dir, ui_dir) = test_dir();
        std::fs::write(ui_dir.join("App.fui"), "<Text>hello</Text>").unwrap();
        let out_file = dir.join("out.rs");

        generate_all(&ui_dir, &out_file).unwrap();

        assert!(out_file.exists());
        let content = std::fs::read_to_string(&out_file).unwrap();
        assert!(content.contains("// Generated by fncc-core. Do not edit."));
        // Function name uses file stem ("App"), not root element name
        assert!(content.contains("pub fn render_app()"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_ignores_non_fui_files() {
        let (dir, ui_dir) = test_dir();
        std::fs::write(ui_dir.join("App.fui"), "<A></A>").unwrap();
        std::fs::write(ui_dir.join("notes.txt"), "not a fui").unwrap();
        std::fs::write(ui_dir.join("main.rs"), "fn main() {}").unwrap();
        let out_file = dir.join("out.rs");

        generate_all(&ui_dir, &out_file).unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        // Function name uses file stem ("App"), not root element name
        assert!(content.contains("pub fn render_app()"));
        assert!(!content.contains("notes"));
        assert!(!content.contains("main"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_import() {
        let (dir, ui_dir) = test_dir();

        // Header.fui — stateless component
        std::fs::write(ui_dir.join("Header.fui"), "<Text size=\"xl\">Welcome</Text>").unwrap();
        // App.fui — imports Header
        std::fs::write(
            ui_dir.join("App.fui"),
            "---\nuse ui::Header;\n---\n<Stack><Header /></Stack>",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        generate_all(&ui_dir, &out_file).unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        // Header generates its own render function
        assert!(content.contains("pub fn render_header()"));
        // App uses the imported component
        assert!(content.contains("render_header()"));
        // No ui:: import leaks into generated Rust
        assert!(!content.contains("use ui::"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_grouped_imports() {
        let (dir, ui_dir) = test_dir();

        std::fs::create_dir_all(ui_dir.join("components")).unwrap();
        std::fs::write(
            ui_dir.join("components").join("Button.fui"),
            "<Button onclick=\"handle_click\">Click</Button>",
        )
        .unwrap();
        std::fs::write(
            ui_dir.join("components").join("Card.fui"),
            "<Stack><Text>card</Text></Stack>",
        )
        .unwrap();
        std::fs::write(
            ui_dir.join("App.fui"),
            "---\nuse ui::components::{Button, Card};\n---\n<Stack><Card /><Button /></Stack>",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        generate_all(&ui_dir, &out_file).unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        assert!(content.contains("pub fn render_button()"));
        assert!(content.contains("pub fn render_card()"));
        assert!(content.contains("render_card()"));
        assert!(content.contains("render_button()"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_import_missing_file_errors() {
        let (dir, ui_dir) = test_dir();

        std::fs::write(ui_dir.join("App.fui"), "---\nuse ui::Missing;\n---\n<Stack></Stack>").unwrap();

        let out_file = dir.join("out.rs");
        let result = generate_all(&ui_dir, &out_file);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("Missing") || err.contains("not found"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_gpui_import() {
        let (dir, ui_dir) = test_dir();

        std::fs::write(
            ui_dir.join("App.fui"),
            "---\nuse gpui::TextInput;\n---\n<Stack></Stack>",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        generate_all(&ui_dir, &out_file).unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        // gpui imports are real Rust — preserved in frontmatter
        assert!(content.contains("use gpui::TextInput;"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_recursive_scan() {
        let (dir, ui_dir) = test_dir();

        // File in subdirectory
        std::fs::create_dir_all(ui_dir.join("widgets")).unwrap();
        std::fs::write(ui_dir.join("widgets").join("Footer.fui"), "<Text>footer</Text>").unwrap();
        // File in root
        std::fs::write(
            ui_dir.join("App.fui"),
            "---\nuse ui::widgets::Footer;\n---\n<Stack><Footer /></Stack>",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        generate_all(&ui_dir, &out_file).unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        assert!(
            content.contains("pub fn render_footer()"),
            "content missing render_footer fn:\n{content}"
        );
        assert!(content.contains("render_footer()"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    // --- Semantic analysis tests ---

    fn test_dir_with_src() -> (PathBuf, PathBuf, PathBuf) {
        let id = LIB_TEST_COUNTER.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!("fncc_sem_lib_test_{id}"));
        let ui_dir = dir.join("ui");
        let src_dir = dir.join("src");
        std::fs::create_dir_all(&ui_dir).unwrap();
        std::fs::create_dir_all(&src_dir).unwrap();
        (dir, ui_dir, src_dir)
    }

    #[test]
    fn test_generate_all_with_options_infers_state_from_rs() {
        let (dir, ui_dir, src_dir) = test_dir_with_src();

        // .fui file without @state
        std::fs::write(
            ui_dir.join("App.fui"),
            r#"<Stack direction="vertical" gap="12">
    <Text>Count: {state.count}</Text>
    <Button onclick="inc">+1</Button>
</Stack>"#,
        )
        .unwrap();

        // .rs file with Level 3 command
        std::fs::write(
            src_dir.join("main.rs"),
            "#[fncc::command]\nfn inc(state: &mut CounterState, cx: &mut Context<CounterState>) { state.count += 1; cx.notify(); }\n",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        generate_all_with_options(GenerateOptions {
            ui_dir: &ui_dir,
            out_file: &out_file,
            src_dir: Some(&src_dir),
        })
        .unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        // Should generate impl Render for CounterState (inferred from command)
        assert!(content.contains("impl Render for CounterState {"));
        assert!(content.contains("__fncc_cmd_inc"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_options_hard_error_on_missing_command() {
        let (dir, ui_dir, src_dir) = test_dir_with_src();

        std::fs::write(
            ui_dir.join("App.fui"),
            r#"<Button onclick="nonexistent">Click</Button>"#,
        )
        .unwrap();

        // No .rs file with #[fncc::command] nonexistent
        std::fs::write(src_dir.join("main.rs"), "fn main() {}\n").unwrap();

        let out_file = dir.join("out.rs");
        let result = generate_all_with_options(GenerateOptions {
            ui_dir: &ui_dir,
            out_file: &out_file,
            src_dir: Some(&src_dir),
        });

        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("nonexistent"), "error should mention command name: {err}");
        assert!(err.contains("not found"), "error should say not found: {err}");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_options_state_conflict_errors() {
        let (dir, ui_dir, src_dir) = test_dir_with_src();

        // .fui with @state that conflicts with command signature
        std::fs::write(
            ui_dir.join("App.fui"),
            "---\n@state OldState\n---\n<Button onclick=\"upd\">Update</Button>",
        )
        .unwrap();

        std::fs::write(
            src_dir.join("main.rs"),
            "#[fncc::command]\nfn upd(state: &mut NewState, cx: &mut Context<NewState>) {}\n",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        let result = generate_all_with_options(GenerateOptions {
            ui_dir: &ui_dir,
            out_file: &out_file,
            src_dir: Some(&src_dir),
        });

        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("@state OldState"),
            "error should mention @state declaration: {err}"
        );
        assert!(err.contains("NewState"), "error should mention inferred type: {err}");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_options_stateless_remains_stateless() {
        let (dir, ui_dir, src_dir) = test_dir_with_src();

        // Stateless component, no @state, no Level 3 commands
        std::fs::write(ui_dir.join("App.fui"), "<Text>hello</Text>").unwrap();
        std::fs::write(src_dir.join("main.rs"), "fn main() {}\n").unwrap();

        let out_file = dir.join("out.rs");
        generate_all_with_options(GenerateOptions {
            ui_dir: &ui_dir,
            out_file: &out_file,
            src_dir: Some(&src_dir),
        })
        .unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        // Should be stateless — standalone render function
        assert!(content.contains("pub fn render_app()"));
        assert!(!content.contains("impl Render for"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_with_options_state_mismatch_across_commands() {
        let (dir, ui_dir, src_dir) = test_dir_with_src();

        std::fs::write(
            ui_dir.join("App.fui"),
            r#"<Stack>
    <Button onclick="cmd_a">A</Button>
    <Button onclick="cmd_b">B</Button>
</Stack>"#,
        )
        .unwrap();

        std::fs::write(
            src_dir.join("main.rs"),
            "#[fncc::command]\nfn cmd_a(s: &mut TypeA, cx: &mut Context<TypeA>) {}\n\
             #[fncc::command]\nfn cmd_b(s: &mut TypeB, cx: &mut Context<TypeB>) {}\n",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        let result = generate_all_with_options(GenerateOptions {
            ui_dir: &ui_dir,
            out_file: &out_file,
            src_dir: Some(&src_dir),
        });

        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("multiple state types"),
            "error should mention multiple types: {err}"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn test_generate_all_legacy_still_works_without_src_dir() {
        // Verify that legacy generate_all (no src_dir) still works unchanged
        let (dir, ui_dir) = test_dir();

        std::fs::write(
            ui_dir.join("App.fui"),
            "---\n@state CounterState\n---\n<Button onclick=\"inc\">+1</Button>",
        )
        .unwrap();

        let out_file = dir.join("out.rs");
        generate_all(&ui_dir, &out_file).unwrap();

        let content = std::fs::read_to_string(&out_file).unwrap();
        assert!(content.contains("impl Render for CounterState {"));
        std::fs::remove_dir_all(&dir).unwrap();
    }
}