macroforge_ts 0.1.80

TypeScript macro expansion engine - write compile-time macros in Rust
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
#[cfg(feature = "swc")]
use swc_core::common::{GLOBALS, Globals};

use crate::api_types::{
    ExpandOptions, ExpandResult, ImportSourceResult, LoadConfigResult, MacroDiagnostic,
    ScanOptions, ScanResult, SyntaxCheckResult, TransformResult,
};
use crate::expand_core::{expand_inner, transform_inner};

pub trait MacroforgeApi {
    type Error;

    fn check_syntax(code: String, filepath: String) -> Result<SyntaxCheckResult, Self::Error>;
    fn parse_import_sources(
        code: String,
        filepath: String,
    ) -> Result<Vec<ImportSourceResult>, Self::Error>;
    fn load_config(content: String, filepath: String) -> Result<LoadConfigResult, Self::Error>;
    fn clear_config_cache();
    fn transform_sync(code: String, filepath: String) -> Result<TransformResult, Self::Error>;
    fn expand_sync(
        code: String,
        filepath: String,
        options: Option<ExpandOptions>,
    ) -> Result<ExpandResult, Self::Error>;
    fn scan_project_sync(
        root_dir: String,
        options: Option<ScanOptions>,
    ) -> Result<ScanResult, Self::Error>;
}

// ---------------------------------------------------------------------------
// Singleton scanner (Phase 17)
// ---------------------------------------------------------------------------
//
// The Vite plugin and long-lived hosts want to reuse a single scanner
// across calls so the per-file scan cache persists between HMR events.
// We keep a process-global `Mutex<Option<CachedScanner>>` keyed on the
// `root_dir`; on `scan_project_sync` we consult it, reusing the
// existing scanner when the root matches and rebuilding from scratch
// otherwise. Native-only — WASM has no filesystem access.

#[cfg(not(target_arch = "wasm32"))]
struct CachedScanner {
    root_dir: std::path::PathBuf,
    scanner: crate::host::scanner::ProjectScanner,
}

#[cfg(not(target_arch = "wasm32"))]
static SINGLETON_SCANNER: std::sync::OnceLock<std::sync::Mutex<Option<CachedScanner>>> =
    std::sync::OnceLock::new();

#[cfg(not(target_arch = "wasm32"))]
fn singleton() -> &'static std::sync::Mutex<Option<CachedScanner>> {
    SINGLETON_SCANNER.get_or_init(|| std::sync::Mutex::new(None))
}

pub struct CoreEngine;

impl CoreEngine {
    pub fn check_syntax(code: &str, filepath: &str) -> Result<SyntaxCheckResult, String> {
        #[cfg(feature = "swc")]
        {
            match crate::expand_core::parse_program(code, filepath) {
                Ok(_) => Ok(SyntaxCheckResult {
                    ok: true,
                    error: None,
                }),
                Err(err) => Ok(SyntaxCheckResult {
                    ok: false,
                    error: Some(err.to_string()),
                }),
            }
        }

        #[cfg(all(not(feature = "swc"), feature = "oxc"))]
        {
            use oxc::allocator::Allocator;
            use oxc::parser::Parser;
            use oxc::span::SourceType;

            let allocator = Allocator::default();
            let source_type = SourceType::ts().with_jsx(filepath.ends_with(".tsx"));
            let parsed = Parser::new(&allocator, code, source_type).parse();

            if parsed.errors.is_empty() {
                Ok(SyntaxCheckResult {
                    ok: true,
                    error: None,
                })
            } else {
                Ok(SyntaxCheckResult {
                    ok: false,
                    error: Some(
                        parsed
                            .errors
                            .into_iter()
                            .map(|diagnostic| diagnostic.to_string())
                            .collect::<Vec<_>>()
                            .join("; "),
                    ),
                })
            }
        }
    }

    pub fn parse_import_sources(
        code: &str,
        filepath: &str,
    ) -> Result<Vec<ImportSourceResult>, String> {
        #[cfg(feature = "swc")]
        {
            use swc_core::ecma::ast::Program;

            let (program, _cm) =
                crate::expand_core::parse_program(code, filepath).map_err(|e| e.to_string())?;
            let module = match program {
                Program::Module(module) => module,
                Program::Script(_) => return Ok(vec![]),
            };

            let import_result = crate::host::collect_import_sources(&module, code);
            let mut imports = Vec::with_capacity(import_result.sources.len());
            for (local, module) in import_result.sources {
                imports.push(ImportSourceResult { local, module });
            }
            Ok(imports)
        }

        #[cfg(all(not(feature = "swc"), feature = "oxc"))]
        {
            use oxc::allocator::Allocator;
            use oxc::parser::Parser;
            use oxc::span::SourceType;

            let allocator = Allocator::default();
            let source_type = SourceType::ts().with_jsx(filepath.ends_with(".tsx"));
            let parsed = Parser::new(&allocator, code, source_type).parse();
            if !parsed.errors.is_empty() {
                return Err(parsed
                    .errors
                    .into_iter()
                    .map(|diagnostic| diagnostic.to_string())
                    .collect::<Vec<_>>()
                    .join("; "));
            }

            let registry = crate::ts_syn::ImportRegistry::from_oxc_program(&parsed.program, code);
            Ok(registry
                .source_modules()
                .into_iter()
                .map(|(local, module)| ImportSourceResult { local, module })
                .collect())
        }
    }

    pub fn load_config(content: &str, filepath: &str) -> Result<LoadConfigResult, String> {
        use crate::host::MacroforgeConfigLoader;
        eprintln!("[macroforge:api] load_config called for {}", filepath);

        let config = MacroforgeConfigLoader::load_and_cache(content, filepath).map_err(|e| {
            eprintln!("[macroforge:api] load_config failed: {}", e);
            format!("Failed to parse config: {}", e)
        })?;

        let has_foreign_types = !config.foreign_types.is_empty();
        let foreign_type_count = config.foreign_types.len() as u32;

        eprintln!(
            "[macroforge:api] load_config success: keep_decorators={}, foreign_types={}",
            config.keep_decorators, foreign_type_count
        );

        Ok(LoadConfigResult {
            keep_decorators: config.keep_decorators,
            generate_convenience_const: config.generate_convenience_const,
            has_foreign_types,
            foreign_type_count,
        })
    }

    pub fn clear_config_cache() {
        eprintln!("[macroforge:api] clear_config_cache called");
        crate::host::clear_config_cache();
    }

    pub fn transform_sync(code: String, filepath: String) -> Result<TransformResult, String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
            let handle = builder
                .spawn(
                    move || -> std::thread::Result<anyhow::Result<TransformResult>> {
                        #[cfg(feature = "swc")]
                        {
                            let globals = Globals::default();
                            GLOBALS.set(&globals, || {
                                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                    transform_inner(&code, &filepath)
                                }))
                            })
                        }

                        #[cfg(not(feature = "swc"))]
                        {
                            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                transform_inner(&code, &filepath)
                            }))
                        }
                    },
                )
                .map_err(|e| format!("Failed to spawn transform thread: {}", e))?;

            handle
                .join()
                .map_err(|_| "Transform worker crashed".to_string())?
                .map_err(|_| "Transform panicked".to_string())?
                .map_err(|e| e.to_string())
        }

        #[cfg(target_arch = "wasm32")]
        {
            #[cfg(feature = "swc")]
            {
                let globals = Globals::default();
                GLOBALS.set(&globals, || {
                    transform_inner(&code, &filepath).map_err(|e| e.to_string())
                })
            }

            #[cfg(not(feature = "swc"))]
            {
                transform_inner(&code, &filepath).map_err(|e| e.to_string())
            }
        }
    }

    pub fn expand_sync(
        code: String,
        filepath: String,
        options: Option<ExpandOptions>,
    ) -> Result<ExpandResult, String> {
        eprintln!("[macroforge:api] expand_sync called for {}", filepath);
        if let Some(ref opts) = options {
            eprintln!(
                "[macroforge:api] options: config_path={:?}, external_decorator_modules={:?}, has_type_registry={}",
                opts.config_path,
                opts.external_decorator_modules,
                opts.type_registry_json.is_some()
            );
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
            let handle = builder
                .spawn(
                    move || -> std::thread::Result<anyhow::Result<ExpandResult>> {
                        #[cfg(feature = "swc")]
                        {
                            let globals = Globals::default();
                            GLOBALS.set(&globals, || {
                                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                    expand_inner(&code, &filepath, options)
                                }))
                            })
                        }

                        #[cfg(not(feature = "swc"))]
                        {
                            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                                expand_inner(&code, &filepath, options)
                            }))
                        }
                    },
                )
                .map_err(|e| format!("Failed to spawn expand thread: {}", e))?;

            handle
                .join()
                .map_err(|_| "Expand worker crashed".to_string())?
                .map_err(|_| "Expand panicked".to_string())?
                .map_err(|e| e.to_string())
        }

        #[cfg(target_arch = "wasm32")]
        {
            #[cfg(feature = "swc")]
            {
                let globals = Globals::default();
                GLOBALS.set(&globals, || {
                    expand_inner(&code, &filepath, options).map_err(|e| e.to_string())
                })
            }

            #[cfg(not(feature = "swc"))]
            {
                expand_inner(&code, &filepath, options).map_err(|e| e.to_string())
            }
        }
    }

    /// Invalidate a single file in the singleton scan cache. Called
    /// by the Vite plugin's `handleHotUpdate` hook so the next
    /// [`Self::scan_project_sync`] re-parses the changed file instead
    /// of serving stale IR. Returns `true` when an entry was actually
    /// dropped, `false` when the cache was empty or the path wasn't
    /// cached. No-op on WASM.
    pub fn invalidate_scan_cache_entry(path: &str) -> bool {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let guard = singleton().lock().ok();
            if let Some(guard) = guard
                && let Some(cs) = guard.as_ref()
            {
                return cs
                    .scanner
                    .invalidate_cache_entry(std::path::Path::new(path));
            }
            false
        }
        #[cfg(target_arch = "wasm32")]
        {
            let _ = path;
            false
        }
    }

    /// Clear the entire singleton scan cache. Called when
    /// `macroforge.config.ts` or `tsconfig.json` changes — anything
    /// that could invalidate previously-lowered IR.
    pub fn clear_scan_cache() {
        #[cfg(not(target_arch = "wasm32"))]
        {
            if let Ok(guard) = singleton().lock()
                && let Some(cs) = guard.as_ref()
            {
                cs.scanner.clear_cache();
            }
        }
    }

    pub fn scan_project_sync(
        root_dir: String,
        options: Option<ScanOptions>,
    ) -> Result<ScanResult, String> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let builder = std::thread::Builder::new().stack_size(32 * 1024 * 1024);
            let handle = builder
                .spawn(move || Self::scan_project_inner(&root_dir, options))
                .map_err(|e| format!("Failed to spawn scan thread: {}", e))?;

            handle
                .join()
                .map_err(|_| "Scan worker panicked".to_string())?
        }
        #[cfg(target_arch = "wasm32")]
        {
            Self::scan_project_inner(&root_dir, options)
        }
    }

    fn scan_project_inner(
        root_dir: &str,
        options: Option<ScanOptions>,
    ) -> Result<ScanResult, String> {
        use crate::host::scanner::{ProjectScanner, ScanConfig};

        let mut config = ScanConfig {
            root_dir: std::path::PathBuf::from(root_dir),
            ..ScanConfig::default()
        };

        if let Some(opts) = options {
            if let Some(exts) = opts.extensions {
                config.extensions = exts;
            }
            if let Some(exported) = opts.exported_only {
                config.exported_only = exported;
            }
        }

        // Phase 17: reuse the singleton scanner when the root matches
        // so the per-file cache carries over between scans. On a root
        // mismatch we drop the old scanner and start fresh.
        #[cfg(not(target_arch = "wasm32"))]
        let output = {
            let root_path = config.root_dir.clone();
            let mut guard = singleton()
                .lock()
                .map_err(|_| "singleton scanner mutex poisoned".to_string())?;
            let needs_rebuild = match guard.as_ref() {
                Some(cs) => cs.root_dir != root_path,
                None => true,
            };
            if needs_rebuild {
                let mut scanner = ProjectScanner::new(config);
                scanner.enable_cache();
                *guard = Some(CachedScanner {
                    root_dir: root_path,
                    scanner,
                });
            }
            let cs = guard.as_ref().unwrap();
            cs.scanner
                .scan()
                .map_err(|e| format!("Project scan failed: {}", e))?
        };
        #[cfg(target_arch = "wasm32")]
        let output = {
            let scanner = ProjectScanner::new(config);
            scanner
                .scan()
                .map_err(|e| format!("Project scan failed: {}", e))?
        };

        let types_found = output.registry.len() as u32;
        let declarative_macros_found = output.declarative_registry.macro_count() as u32;
        let registry_json = serde_json::to_string(&output.registry)
            .map_err(|e| format!("Failed to serialize registry: {}", e))?;
        let declarative_registry_json = output
            .declarative_registry
            .to_json()
            .map_err(|e| format!("Failed to serialize declarative registry: {}", e))?;

        let diagnostics = output
            .warnings
            .into_iter()
            .map(|msg| MacroDiagnostic {
                level: "warning".to_string(),
                message: msg,
                start: None,
                end: None,
            })
            .collect();

        Ok(ScanResult {
            registry_json,
            declarative_registry_json,
            files_scanned: output.files_scanned,
            types_found,
            declarative_macros_found,
            diagnostics,
        })
    }
}