Skip to main content

runec/
lib.rs

1pub mod bytecode;
2pub mod compiler;
3pub mod diagnostic_messages;
4pub mod diagnostics;
5pub mod error;
6pub mod lexer;
7pub mod lints;
8pub mod parser;
9pub mod pointer;
10pub mod pointer_checker;
11pub mod symbol;
12pub mod symloader;
13pub mod token;
14pub mod trigger_table;
15pub mod typechecker;
16pub mod types;
17pub mod writer;
18
19use crate::bytecode::CompiledScript;
20use crate::compiler::Compiler;
21use crate::diagnostics::DiagnosticsCollector;
22use crate::lexer::Lexer;
23use crate::parser::{Parser, ScriptFile};
24use crate::symbol::SymbolRegistry;
25use crate::typechecker::TypeChecker;
26use crate::writer::ScriptWriter;
27use std::collections::HashMap;
28use std::error::Error;
29use std::fs;
30use std::path::{Path, PathBuf};
31use std::rc::Rc;
32use tracing::info;
33
34/// Compile scripts and write output. When `lint` is true, also run lint passes
35/// (unused locals, unreachable code) after code generation.
36pub fn compile_memory(
37    scripts_dir: &Path,
38    pack_dir: Option<&Path>,
39    lint: bool,
40) -> Result<(Vec<u8>, Vec<u8>), Box<dyn Error>> {
41    let (compiled_scripts, diagnostics) = run_pipeline(scripts_dir, pack_dir, lint)?;
42
43    info!("Phase 5: Writing output to memory...");
44    let writer = ScriptWriter::new("".into());
45
46    diagnostics.print_all();
47    info!("Compilation complete!");
48
49    Ok(writer.build_all(&compiled_scripts)?)
50}
51
52/// Compile scripts and write output. When `lint` is true, also run lint passes
53/// (unused locals, unreachable code) after code generation.
54pub fn compile(
55    scripts_dir: &Path,
56    pack_dir: Option<&Path>,
57    output_dir: &Path,
58    lint: bool,
59) -> Result<(), Box<dyn Error>> {
60    let (compiled_scripts, diagnostics) = run_pipeline(scripts_dir, pack_dir, lint)?;
61
62    let output = output_dir.display().to_string();
63    info!("Phase 5: Writing output to {}...", output);
64    let writer = ScriptWriter::new(output);
65    writer.write_all(&compiled_scripts)?;
66
67    diagnostics.print_all();
68    info!("Compilation complete!");
69
70    Ok(())
71}
72
73/// Run all analysis passes (parse, type-check, codegen, pointer-check, lints)
74/// without writing output. Useful for editor tooling and CI lint gates.
75pub fn lint(scripts_dir: &Path, pack_dir: Option<&Path>) -> Result<(), Box<dyn Error>> {
76    let (_, diagnostics) = run_pipeline(scripts_dir, pack_dir, true)?;
77
78    diagnostics.print_all();
79    info!("Compilation complete!");
80
81    Ok(())
82}
83
84/// Runs the full compilation pipeline (parse, register, type-check, codegen,
85/// pointer-check, and optional lint passes), returning the compiled scripts
86/// and accumulated diagnostics for the caller to handle output.
87fn run_pipeline(
88    scripts_dir: &Path,
89    pack_dir: Option<&Path>,
90    lint: bool,
91) -> Result<(Vec<CompiledScript>, DiagnosticsCollector), Box<dyn Error>> {
92    if !scripts_dir.exists() || !scripts_dir.is_dir() {
93        return Err(Box::new(error::CompilerError::FileNotFound(
94            scripts_dir.display().to_string(),
95        )));
96    }
97
98    let mut rs2_files: Vec<PathBuf> = Vec::new();
99    collect_files(scripts_dir, "rs2", &mut rs2_files)?;
100    rs2_files.sort();
101    info!("Found {} script files", rs2_files.len());
102
103    let mut diagnostics = DiagnosticsCollector::new();
104
105    // Phase 1: Parse all files
106    info!("Phase 1: Parsing...");
107    let mut all_files = Vec::new();
108    let mut source_cache: HashMap<String, Rc<String>> = HashMap::new();
109    for path in &rs2_files {
110        let source_code = fs::read_to_string(path)?;
111        let canonical = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
112        let mut key = canonical.to_string_lossy().into_owned();
113        if key.starts_with("\\\\?\\") {
114            key = key[4..].to_string();
115        }
116        key = key.replace("\\Content\\", "\\content\\");
117        source_cache.insert(key, Rc::new(source_code.clone()));
118
119        let tokens = match Lexer::new(&source_code, path).tokenize() {
120            Ok(t) => t,
121            Err(e) => {
122                diagnostics.error(
123                    path.clone(),
124                    e.line,
125                    e.position,
126                    e.message.clone(),
127                    crate::diagnostics::Phase::Lexing,
128                );
129                continue;
130            }
131        };
132        let mut parser = Parser::new(tokens, path);
133        match parser.parse() {
134            Ok(file) => all_files.push((path.clone(), file)),
135            Err(e) => {
136                diagnostics.error(
137                    path.clone(),
138                    e.line,
139                    e.position,
140                    e.message.clone(),
141                    crate::diagnostics::Phase::Parsing,
142                );
143            }
144        }
145    }
146
147    if diagnostics.has_errors() {
148        diagnostics.print_all();
149        return Err(Box::new(error::CompilerError::TypeError(
150            "Parsing failed".to_string(),
151        )));
152    }
153
154    // Phase 2: Register all scripts
155    info!("Phase 2: Registering scripts...");
156    let registry = register_scripts(scripts_dir, pack_dir, &mut diagnostics, &mut all_files);
157    info!("  Registered {} scripts", registry.scripts.len());
158
159    for (path, file) in &all_files {
160        for script in &file.scripts {
161            if let Some(msg) =
162                Compiler::validate_trigger_subject(&script.trigger, &script.name, &registry)
163            {
164                diagnostics.warning(
165                    path.clone(),
166                    script.line,
167                    0,
168                    msg,
169                    crate::diagnostics::Phase::SymbolRegistration,
170                );
171            }
172        }
173    }
174
175    // Phase 3: Type checking
176    info!("Phase 3: Type checking {} files...", all_files.len());
177    run_type_checker(&mut diagnostics, &mut all_files, &registry);
178
179    if diagnostics.has_errors() {
180        diagnostics.print_all();
181        return Err(Box::new(error::CompilerError::TypeError(
182            "Type checking failed".to_string(),
183        )));
184    }
185
186    // Phase 4: Code generation
187    info!("Phase 4: Code generation...");
188    let (codegen, mut compiled_scripts) = codegen(&mut all_files, registry);
189    info!("  Generated {} compiled scripts", compiled_scripts.len());
190    compiled_scripts.sort_by_key(|s| s.id);
191
192    // Phase 4.5: Pointer checking & lints
193    info!("Phase 4.5: Pointer checking...");
194    check_pointers(
195        lint,
196        &mut diagnostics,
197        &mut source_cache,
198        &codegen,
199        &compiled_scripts,
200    );
201
202    Ok((compiled_scripts, diagnostics))
203}
204
205fn check_pointers(
206    lint: bool,
207    diagnostics: &mut DiagnosticsCollector,
208    source_cache: &mut HashMap<String, Rc<String>>,
209    codegen: &Compiler,
210    compiled_scripts: &[CompiledScript],
211) {
212    {
213        use crate::pointer_checker::PointerChecker;
214        let mut checker = PointerChecker::new(compiled_scripts, &codegen.registry);
215        checker.set_source_cache(source_cache);
216        let pointer_diags = checker.run();
217        let ptr_warnings = pointer_diags.warning_count();
218        if ptr_warnings > 0 {
219            info!("  Pointer check: {} warning(s)", ptr_warnings);
220        }
221        diagnostics.merge(pointer_diags);
222    }
223
224    // Phase 4.6: Lint passes (optional)
225    if lint {
226        info!("Phase 4.6: Lint checks...");
227        let lint_diags = lints::run_lints(compiled_scripts, Some(source_cache));
228        let lint_warnings = lint_diags.warning_count();
229        if lint_warnings > 0 {
230            info!("  Lints: {} warning(s)", lint_warnings);
231        }
232        diagnostics.merge(lint_diags);
233    }
234}
235
236fn codegen(
237    all_files: &mut [(PathBuf, ScriptFile)],
238    registry: SymbolRegistry,
239) -> (Compiler, Vec<CompiledScript>) {
240    let mut codegen = Compiler::new(registry);
241    let mut compiled_scripts = Vec::new();
242    for (path, file) in all_files {
243        for script in &file.scripts {
244            if script.trigger == "command" {
245                continue;
246            }
247            let mut compiled = codegen.compile_script(script);
248            let canonical = fs::canonicalize(path.clone()).unwrap_or_else(|_| path.to_path_buf());
249            let mut source_path = canonical.to_string_lossy().into_owned();
250            if source_path.starts_with("\\\\?\\") {
251                source_path = source_path[4..].to_string();
252            }
253            source_path = source_path.replace("\\Content\\", "\\content\\");
254            compiled.source_path = source_path;
255            compiled_scripts.push(compiled);
256        }
257    }
258    (codegen, compiled_scripts)
259}
260
261fn run_type_checker(
262    diagnostics: &mut DiagnosticsCollector,
263    all_files: &mut [(PathBuf, ScriptFile)],
264    registry: &SymbolRegistry,
265) {
266    let mut type_checker = TypeChecker::new(registry);
267    for (path, file) in all_files.iter() {
268        type_checker.check_file(file, path);
269    }
270    diagnostics.merge(type_checker.diagnostics);
271}
272
273fn register_scripts(
274    scripts_dir: &Path,
275    pack_dir: Option<&Path>,
276    diagnostics: &mut DiagnosticsCollector,
277    all_files: &mut Vec<(PathBuf, ScriptFile)>,
278) -> SymbolRegistry {
279    let mut registry = SymbolRegistry::new();
280
281    let resolved_pack_dir = pack_dir
282        .map(PathBuf::from)
283        .filter(|p| p.exists())
284        .or_else(|| {
285            scripts_dir
286                .parent()
287                .map(|p| p.join("pack"))
288                .filter(|p| p.exists())
289        })
290        .or_else(|| {
291            scripts_dir
292                .ancestors()
293                .nth(3)
294                .map(|p| p.join("content/pack"))
295                .filter(|p| p.exists())
296        });
297
298    if let Some(ref pd) = resolved_pack_dir {
299        symloader::generate_script_pack(scripts_dir, pd);
300        info!("  Loading packs from {}", pd.display());
301        symloader::load_packs(&mut registry, pd);
302        info!(
303            "  Loaded {} commands, {} game vars",
304            registry.commands.len(),
305            registry.game_vars.len(),
306        );
307    } else {
308        info!("  No pack directory found - symbol resolution will be limited");
309    }
310
311    symloader::load_constant_files(&mut registry, scripts_dir);
312
313    info!(
314        "  Loaded {} constants from .constant files",
315        registry.constants.len()
316    );
317
318    symloader::load_game_var_types(&mut registry, scripts_dir);
319
320    if let Some(ref pd) = resolved_pack_dir {
321        let dbtable_ids = symloader::load_dbtable_pack(&pd.join("dbtable.pack"));
322        if !dbtable_ids.is_empty() {
323            symloader::load_dbtable_configs(&mut registry, scripts_dir, &dbtable_ids);
324            info!(
325                "  Registered {} dbcolumn compound IDs",
326                registry.dbcolumn_types.len()
327            );
328        }
329    }
330
331    let engine_rs2 = scripts_dir.join("engine.rs2");
332
333    if engine_rs2.exists() {
334        crate::symloader::load_engine_command_params(&mut registry, &engine_rs2);
335    } else {
336        if let Ok(entries) = std::fs::read_dir(scripts_dir) {
337            for entry in entries.flatten() {
338                let candidate = entry.path().join("engine.rs2");
339                if candidate.exists() {
340                    crate::symloader::load_engine_command_params(&mut registry, &candidate);
341                    break;
342                }
343            }
344        }
345    }
346
347    crate::symloader::patch_command_return_types(&mut registry);
348
349    {
350        use crate::diagnostic_messages as msg;
351
352        let mut registered_scripts: std::collections::HashSet<String> =
353            std::collections::HashSet::new();
354
355        for (path, file) in all_files {
356            for script in &file.scripts {
357                if script.trigger == "command" {
358                    continue;
359                }
360
361                if !trigger_table::is_valid_trigger(&script.trigger) {
362                    diagnostics.warning(
363                        path.clone(),
364                        script.line,
365                        0,
366                        msg::fmt(msg::SCRIPT_TRIGGER_INVALID, &[&script.trigger]),
367                        crate::diagnostics::Phase::SymbolRegistration,
368                    );
369                }
370
371                let key = format!("{}:{}", script.trigger, script.name);
372                if !registered_scripts.insert(key.clone()) {
373                    diagnostics.warning(
374                        path.clone(),
375                        script.line,
376                        0,
377                        msg::fmt(msg::SCRIPT_REDECLARATION, &[&script.trigger, &script.name]),
378                        crate::diagnostics::Phase::SymbolRegistration,
379                    );
380                }
381
382                if !script.return_types.is_empty()
383                    && !trigger_table::allows_returns(&script.trigger)
384                {
385                    diagnostics.warning(
386                        path.clone(),
387                        script.line,
388                        0,
389                        msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[&script.trigger]),
390                        crate::diagnostics::Phase::SymbolRegistration,
391                    );
392                }
393
394                let param_types: Vec<crate::types::Type> =
395                    script.params.iter().map(|p| p.param_type).collect();
396                registry.register_script(
397                    script.name.clone(),
398                    script.trigger.clone(),
399                    param_types,
400                    script.return_types.clone(),
401                );
402            }
403        }
404    }
405    registry
406}
407
408fn collect_files(dir: &Path, ext: &str, out: &mut Vec<PathBuf>) -> Result<(), Box<dyn Error>> {
409    for entry in std::fs::read_dir(dir)? {
410        let entry = entry?;
411        let path = entry.path();
412        if path.is_dir() {
413            collect_files(&path, ext, out)?;
414        } else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
415            out.push(path);
416        }
417    }
418    Ok(())
419}