nargo-compiler 0.0.0

Nargo compiler core
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
#![warn(missing_docs)]

use nargo_ir::IRModule;
use nargo_optimizer::Optimizer;
use nargo_parser::{Parser, ParserRegistry};
use nargo_transformer::Transformer;
pub use nargo_types as types;
pub use nargo_types::{CompileMode, CompileOptions, Result};
use std::{
    collections::HashMap,
    hash::Hash,
    sync::{Arc, Mutex, OnceLock},
    thread,
    time::Instant,
};

/// 线程池配置
pub struct ThreadPoolConfig {
    /// 线程数
    pub thread_count: usize,
}

impl Default for ThreadPoolConfig {
    fn default() -> Self {
        Self { thread_count: num_cpus::get() }
    }
}

impl Clone for ThreadPoolConfig {
    fn clone(&self) -> Self {
        Self { thread_count: self.thread_count }
    }
}

/// 编译缓存键
#[derive(Hash, PartialEq, Eq, Clone)]
pub struct CompileCacheKey {
    /// 文件名
    pub name: String,
    /// 源代码哈希
    pub source_hash: u64,
    /// 编译选项哈希
    pub options_hash: u64,
}

/// 编译缓存值
#[derive(Clone)]
pub struct CompileCacheValue {
    /// 编译结果
    pub result: CompileResult,
    /// 编译时间
    pub timestamp: Instant,
}

/// Nargo 框架的便捷编译函数
///
/// 这个函数封装了 Compiler 的实例化和默认配置,适合简单的单文件编译场景。
pub fn compile(name: &str, source: &str) -> Result<CompileResult> {
    // 获取或创建编译器缓存
    let compiler_cache = COMPILER_CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    // 从缓存中获取编译器实例,如果没有则创建新的
    let mut cache = compiler_cache.lock().unwrap();
    let compiler = cache.entry(name.to_string()).or_insert_with(|| Compiler::new());

    // 使用编译器实例
    compiler.compile(name, source)
}

/// 编译 Vmz 格式的文件
///
/// # Arguments
///
/// * `name` - 文件名
/// * `source` - Vmz 源文件内容
///
/// # Returns
///
/// 编译结果,包含生成的代码、CSS、HTML 和 WASM
pub fn compile_vmz(name: &str, source: &str) -> Result<CompileResult> {
    // 获取或创建编译器缓存
    let compiler_cache = COMPILER_CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    // 从缓存中获取编译器实例,如果没有则创建新的
    let mut cache = compiler_cache.lock().unwrap();
    let compiler = cache.entry(name.to_string()).or_insert_with(|| Compiler::new());

    // 使用编译器实例
    compiler.compile(name, source)
}

/// 使用自定义选项编译 Nargo 源代码
pub fn compile_with_options(name: &str, source: &str, options: CompileOptions) -> Result<CompileResult> {
    // 获取或创建编译器缓存
    let compiler_cache = COMPILER_CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    // 从缓存中获取编译器实例,如果没有则创建新的
    let mut cache = compiler_cache.lock().unwrap();
    let compiler = cache.entry(name.to_string()).or_insert_with(|| Compiler::new());

    // 使用编译器实例
    compiler.compile_with_options(name, source, options)
}

/// Nargo 核心 API 的统一导出
pub mod prelude {
    pub use crate::{compile, compile_vmz, compile_with_options, CompileMode, CompileOptions, CompileResult, Compiler};
    pub use nargo_types::{Error, ErrorKind, Position, Result, Span};
}

use serde::Serialize;

pub mod adapter;
pub mod codegen;

/// 编译结果
#[derive(Serialize, Clone)]
pub struct CompileResult {
    /// 生成的 JavaScript 代码
    pub code: String,
    /// 生成的 CSS 代码
    pub css: String,
    /// 生成的 HTML 代码
    pub html: String,
    /// 生成的 WASM 代码(WAT 格式,用于 playground)
    pub wasm: String,
    /// 编译时间(毫秒)
    pub compile_time_ms: u64,
}

/// 编译阶段
#[derive(Debug, Clone, Serialize, Eq, Hash, PartialEq)]
pub enum CompileStage {
    /// 解析阶段
    Parse,
    /// 转换阶段
    Transform,
    /// 优化阶段
    Optimize,
    /// 代码生成阶段
    CodeGen,
}

/// 编译统计信息
#[derive(Debug, Clone, Serialize)]
pub struct CompileStats {
    /// 各阶段耗时(毫秒)
    pub stage_times: std::collections::HashMap<CompileStage, u64>,
    /// 总编译时间(毫秒)
    pub total_time: u64,
    /// 源代码大小(字节)
    pub source_size: usize,
    /// 生成代码大小(字节)
    pub output_size: usize,
}

// 静态缓存ParserRegistry实例,避免每次创建编译器时重复注册解析器
static REGISTRY_CACHE: OnceLock<Arc<ParserRegistry>> = OnceLock::new();

// 静态缓存编译器实例,避免重复创建
type CompilerCache = Mutex<HashMap<String, Compiler>>;
static COMPILER_CACHE: OnceLock<CompilerCache> = OnceLock::new();

/// Nargo 编译器
///
/// 负责协调各个编译阶段,集成 nargo-parser、nargo-transformer 等组件,并提供编译配置和优化选项。
pub struct Compiler {
    /// 解析器注册表
    pub registry: Arc<ParserRegistry>,
    /// 上次生成的 CSS
    pub last_css: String,
    /// 转换器
    pub transformer: Transformer,
    /// 编译统计信息
    pub stats: Option<CompileStats>,
    /// 线程池配置
    pub thread_pool_config: ThreadPoolConfig,
    /// 编译缓存
    pub compile_cache: HashMap<CompileCacheKey, CompileCacheValue>,
    /// 缓存大小限制(默认 1000)
    pub cache_size_limit: usize,
    /// 热编译路径快速缓存
    pub hot_cache: Option<(CompileCacheKey, CompileResult)>,
}

impl Default for Compiler {
    fn default() -> Self {
        Self::new()
    }
}

impl Clone for Compiler {
    fn clone(&self) -> Self {
        Self { registry: self.registry.clone(), last_css: self.last_css.clone(), transformer: self.transformer.clone(), stats: self.stats.clone(), thread_pool_config: self.thread_pool_config.clone(), compile_cache: self.compile_cache.clone(), cache_size_limit: self.cache_size_limit, hot_cache: self.hot_cache.clone() }
    }
}

impl Compiler {
    /// 创建新的编译器实例
    pub fn new() -> Self {
        // 获取或创建缓存的ParserRegistry实例
        let registry = REGISTRY_CACHE.get_or_init(|| {
            let registry = ParserRegistry::new();

            // Register default parsers
            // 简化实现,实际需要根据 nargo_parser 的 API 进行调整
            // 由于 ParserRegistry 期望特定类型的解析器,我们暂时不注册任何解析器
            // 实际使用时需要根据 nargo_parser 的 API 提供正确的解析器实现

            Arc::new(registry)
        });

        Self { registry: registry.clone(), last_css: String::new(), transformer: Transformer::new(), stats: None, thread_pool_config: ThreadPoolConfig::default(), compile_cache: HashMap::with_capacity(100), cache_size_limit: 1000, hot_cache: None }
    }

    /// 设置缓存大小限制
    ///
    /// # Arguments
    ///
    /// * `limit` - 缓存大小限制
    ///
    /// # Returns
    ///
    /// 返回编译器实例,便于链式调用
    pub fn with_cache_size_limit(mut self, limit: usize) -> Self {
        self.cache_size_limit = limit;
        self
    }

    /// 设置线程池配置
    ///
    /// # Arguments
    ///
    /// * `config` - 线程池配置
    ///
    /// # Returns
    ///
    /// 返回编译器实例,便于链式调用
    pub fn with_thread_pool_config(mut self, config: ThreadPoolConfig) -> Self {
        self.thread_pool_config = config;
        self
    }

    /// 编译 Nargo 源代码
    ///
    /// # Arguments
    ///
    /// * `name` - 组件名称
    /// * `source` - Nargo 源代码
    ///
    /// # Returns
    ///
    /// 编译结果
    pub fn compile(&mut self, name: &str, source: &str) -> Result<CompileResult> {
        self.compile_with_options(name, source, CompileOptions::default())
    }

    /// 使用自定义选项编译 Nargo 源代码
    ///
    /// # Arguments
    ///
    /// * `name` - 组件名称
    /// * `source` - Nargo 源代码
    /// * `options` - 编译选项
    ///
    /// # Returns
    ///
    /// 编译结果
    pub fn compile_with_options(&mut self, name: &str, source: &str, mut options: CompileOptions) -> Result<CompileResult> {
        // 快速路径:使用更快的哈希计算
        let source_hash = fast_hash(source);
        let options_hash = fast_hash_options(&options);
        let cache_key = CompileCacheKey { name: name.to_string(), source_hash, options_hash };

        // 热缓存快速检查(用于增量构建)
        if let Some((ref hot_key, ref hot_result)) = self.hot_cache {
            if hot_key == &cache_key {
                // 热缓存命中,极快返回
                self.stats = Some(CompileStats { stage_times: HashMap::new(), total_time: 0, source_size: source.len(), output_size: hot_result.code.len() + hot_result.css.len() });
                return Ok(hot_result.clone());
            }
        }

        // 检查主缓存
        if let Some(cache_value) = self.compile_cache.get(&cache_key) {
            // 缓存命中,更新热缓存
            self.hot_cache = Some((cache_key.clone(), cache_value.result.clone()));
            self.stats = Some(CompileStats { stage_times: HashMap::new(), total_time: 0, source_size: source.len(), output_size: cache_value.result.code.len() + cache_value.result.css.len() });
            return Ok(cache_value.result.clone());
        }

        // 缓存未命中,执行编译
        let start_time = Instant::now();

        // 预分配空间,减少内存分配
        let mut stage_times = std::collections::HashMap::with_capacity(4);

        // 1. 解析源代码到 IR
        let parse_start = Instant::now();
        let _ir = self.compile_to_ir(name, source, &mut options)?;
        stage_times.insert(CompileStage::Parse, parse_start.elapsed().as_millis() as u64);

        // 2. 代码生成
        let codegen_start = Instant::now();
        let code = String::new(); // 简单的 JavaScript 代码生成,实际的代码生成已迁移到 nargo-bundler

        // 生成其他目标代码(用于 playground/检查)
        let html = String::new(); // HtmlBackend 已迁移到 nargo-bundler
        let wasm = String::new(); // WasmBackend 已移除
        stage_times.insert(CompileStage::CodeGen, codegen_start.elapsed().as_millis() as u64);

        // 计算总编译时间
        let total_time = start_time.elapsed().as_millis() as u64;

        // 生成编译统计信息
        self.stats = Some(CompileStats { stage_times, total_time, source_size: source.len(), output_size: code.len() + self.last_css.len() });

        // 创建编译结果
        let result = CompileResult { code, css: std::mem::take(&mut self.last_css), html, wasm, compile_time_ms: total_time };

        // 将结果存入热缓存和主缓存
        self.hot_cache = Some((cache_key.clone(), result.clone()));
        self.compile_cache.insert(cache_key, CompileCacheValue { result: result.clone(), timestamp: Instant::now() });

        // 延迟缓存清理,减少性能开销
        if self.compile_cache.len() > self.cache_size_limit * 2 {
            self.cleanup_cache();
        }

        Ok(result)
    }

    /// 编译源代码到 IR 模块
    ///
    /// # Arguments
    ///
    /// * `name` - 组件名称
    /// * `source` - Nargo 源代码
    /// * `options` - 编译选项
    ///
    /// # Returns
    ///
    /// IR 模块
    pub fn compile_to_ir(&mut self, name: &str, source: &str, options: &mut CompileOptions) -> Result<IRModule> {
        // 1. 解析源代码到 IR
        let mut parser = Parser::new(name.to_string(), source, self.registry.clone());
        let mut ir = parser.parse_all()?;

        // 2. 转换脚本(VOC TypeScript 适配器)
        let ts_adapter = adapter::TsAdapter::new();
        ts_adapter.transform(&mut ir)?;

        // 3. 重新分析脚本以更新转换后的元数据
        let analyzer = nargo_script_analyzer::ScriptAnalyzer::new();
        if let Some(script) = &ir.script {
            if let Ok(meta) = analyzer.analyze(script) {
                ir.script_meta = Some(meta.to_nargo_value());
            }
        }

        // 4. 优化和转换 IR
        let mut optimizer = Optimizer::new();

        // 处理作用域 ID
        let has_scoped_style = ir.styles.iter().any(|s| s.scoped);
        if has_scoped_style && options.scope_id.is_none() {
            options.scope_id = Some(optimizer.generate_scope_id(name));
        }

        // 通过优化器应用所有转换
        optimizer.optimize(&mut ir, options.i18n_locale.as_deref(), options.is_prod);

        // 应用 scoped CSS 转换(如果需要)
        if let Some(scope_id) = &options.scope_id {
            optimizer.apply_scope_id(&mut ir, scope_id);
        }

        // 处理样式(Tailwind/实用 CSS)
        optimizer.process_styles(&ir)?;

        // 直接获取CSS,避免不必要的克隆
        self.last_css = optimizer.get_css();

        Ok(ir)
    }

    /// 获取上次生成的 CSS
    ///
    /// # Returns
    ///
    /// CSS 代码
    pub fn get_css(&self) -> String {
        self.last_css.clone()
    }

    /// 获取编译统计信息
    ///
    /// # Returns
    ///
    /// 编译统计信息
    pub fn get_stats(&self) -> Option<&CompileStats> {
        self.stats.as_ref()
    }

    /// 重置编译器状态
    pub fn reset(&mut self) {
        self.last_css.clear();
        self.transformer.clear_logs();
        self.stats = None;
        self.thread_pool_config = ThreadPoolConfig::default();
        self.compile_cache.clear();
        self.cache_size_limit = 1000;
        self.hot_cache = None;
    }

    /// 计算字符串的哈希值(保留向后兼容性)
    fn hash_string(&self, s: &str) -> u64 {
        fast_hash(s)
    }

    /// 计算编译选项的哈希值(保留向后兼容性)
    fn hash_options(&self, options: &CompileOptions) -> u64 {
        fast_hash_options(options)
    }

    /// 清理缓存,保持缓存大小在限制范围内
    fn cleanup_cache(&mut self) {
        if self.compile_cache.len() > self.cache_size_limit {
            // 按时间戳排序,移除最旧的缓存项
            let mut entries: Vec<(CompileCacheKey, CompileCacheValue)> = self.compile_cache.drain().collect();
            entries.sort_by(|a, b| a.1.timestamp.cmp(&b.1.timestamp));
            let keep_count = self.cache_size_limit;
            let to_keep = entries.into_iter().take(keep_count).collect();
            self.compile_cache = to_keep;
        }
    }

    /// 并行编译多个 Nargo 源代码文件
    ///
    /// # Arguments
    ///
    /// * `files` - 文件名和源代码的映射
    /// * `options` - 编译选项
    ///
    /// # Returns
    ///
    /// 编译结果的映射,键为文件名,值为编译结果
    pub fn compile_parallel(&self, files: &HashMap<String, String>, options: CompileOptions) -> Result<HashMap<String, CompileResult>> {
        let thread_count = self.thread_pool_config.thread_count;
        let files: Vec<(String, String)> = files.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
        let chunk_size = (files.len() + thread_count - 1) / thread_count;

        // 预分配足够的空间,避免运行时扩容
        let mut handles = Vec::with_capacity(thread_count);

        for chunk in files.chunks(chunk_size) {
            // 只克隆当前块的数据,避免克隆整个文件列表
            let chunk_clone: Vec<(String, String)> = chunk.to_vec();
            let options_clone = options.clone();
            let compiler_clone = self.clone();

            let handle = thread::spawn(move || {
                // 预分配结果空间
                let mut results = HashMap::with_capacity(chunk_clone.len());
                for (name, source) in chunk_clone {
                    let mut compiler = compiler_clone.clone();
                    match compiler.compile_with_options(&name, &source, options_clone.clone()) {
                        Ok(result) => {
                            results.insert(name, result);
                        }
                        Err(e) => {
                            // 处理错误
                            eprintln!("编译文件 {} 时出错: {:?}", name, e);
                        }
                    }
                }
                results
            });

            handles.push(handle);
        }

        // 预分配结果空间
        let mut all_results = HashMap::with_capacity(files.len());
        for handle in handles {
            if let Ok(results) = handle.join() {
                all_results.extend(results);
            }
        }

        Ok(all_results)
    }
}

/// 快速字符串哈希函数
#[inline(always)]
fn fast_hash(s: &str) -> u64 {
    // 使用更高效的哈希算法
    let mut hash = 0xcbf29ce484222325u64;
    let prime = 0x100000001b3u64;

    for byte in s.bytes() {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(prime);
    }

    hash
}

/// 快速编译选项哈希函数
#[inline(always)]
fn fast_hash_options(options: &CompileOptions) -> u64 {
    let mut hash = 0xcbf29ce484222325u64;
    let prime = 0x100000001b3u64;

    // 哈希 mode
    hash ^= options.mode as u64;
    hash = hash.wrapping_mul(prime);

    // 哈希 is_prod
    hash ^= options.is_prod as u64;
    hash = hash.wrapping_mul(prime);

    // 哈希 scope_id
    if let Some(scope_id) = &options.scope_id {
        for byte in scope_id.bytes() {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(prime);
        }
    }

    // 哈希 i18n_locale
    if let Some(locale) = &options.i18n_locale {
        for byte in locale.bytes() {
            hash ^= byte as u64;
            hash = hash.wrapping_mul(prime);
        }
    }

    hash
}