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