use crate::bytecode::CompiledScript;
use crate::clientscript::{self, format::Format};
use crate::compiler::Compiler;
use crate::diagnostics::DiagnosticsCollector;
use crate::lexer::Lexer;
#[cfg(feature = "memprof")]
use crate::memprof;
use crate::parallel::{
parallel_chunks, parallel_chunks_capped, parallel_map, parallel_map_balanced,
};
use crate::parser::{Parser, ScriptFile};
use crate::project::{Options, Project, SourceText, Target};
use crate::sources::Scope;
use crate::symbol::SymbolRegistry;
use crate::typechecker::TypeChecker;
use crate::writer::ScriptWriter;
use crate::{diagnostics, error, lints, sources, symloader, trigger_table, types};
use std::collections::HashMap;
use std::error::Error;
use std::fmt::Write;
use std::fs;
use std::panic;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::thread;
use tracing::{info, warn};
pub fn editor_project(
source: &Path,
pack: Option<&Path>,
client: bool,
) -> Result<Project, Box<dyn Error>> {
let scope = if client { Scope::Client } else { Scope::Rune };
let dir = sources::target_dir(source, scope);
let pack = resolve_pack_dir(&dir, pack);
let mut registry = if client {
clientscript::registry(
&dir,
pack.as_deref()
.ok_or("Client opcode definitions require --pack")?,
)?
} else {
build_symbol_registry(&dir, pack.as_deref())
};
let target = if client {
registry.preloaded_script_ids.clear();
for (key, id) in clientscript::script_ids(pack.as_deref().unwrap())? {
let (trigger, name) = key
.trim_start_matches('[')
.trim_end_matches(']')
.split_once(',')
.ok_or("Invalid client ID")?;
registry.set_script_id(trigger, name, id);
}
Target::Client(Format::load(
&pack.as_ref().unwrap().join("cs2_command.pack"),
)?)
} else {
if let Some(pack) = &pack {
symloader::load_script_ids(&mut registry, pack);
}
Target::Rune
};
let mut project = Project::new(
target,
registry,
Options {
include_tests: true,
skip_shared_lints: client
&& dir
.parent()
.is_some_and(|parent| parent.join("runescript").is_dir()),
..Options::default()
},
);
let paths = sources::script_files(&dir, if client { "cs2" } else { "rs2" })?;
let files = read_sources(&paths, |path| {
if path.extension().is_some_and(|ext| ext == "gs2") {
Scope::Global
} else {
scope
}
})?;
for id in project.open_all(files) {
if client {
let ids = project
.document(id)
.and_then(|doc| doc.syntax())
.into_iter()
.flat_map(|file| &file.scripts)
.filter_map(|script| {
script
.name
.strip_prefix("clientscript_")
.and_then(|id| id.parse::<i32>().ok())
.map(|id| (script.trigger.clone(), script.name.clone(), id))
})
.collect::<Vec<_>>();
for (trigger, name, id) in ids {
project.registry.set_script_id(&trigger, &name, id);
}
}
}
if !client {
let client_dir = if dir.file_name().is_some_and(|name| name == "runescript") {
dir.with_file_name("clientscript")
} else {
dir.join("clientscript")
};
if client_dir.is_dir() {
let paths = sources::script_files(&client_dir, "cs2")?
.into_iter()
.filter(|path| {
path.extension().is_some_and(|ext| ext == "cs2")
&& path.file_name().is_some_and(|name| name != "engine.cs2")
})
.collect::<Vec<_>>();
project.open_all(read_sources(&paths, |_| Scope::Client)?);
}
}
let mut files = sources::config_files(&dir);
if let Some(pack) = &pack {
symloader::collect_all_files(pack, &mut files);
if let Some(content) = pack.parent() {
for (folder, extension) in [("interfaces", "if3"), ("defaults", "defaults")] {
let Ok(entries) = fs::read_dir(content.join(folder)) else {
continue;
};
files.extend(
entries
.flatten()
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == extension)),
);
}
}
}
files.sort();
files.dedup();
files.retain(|path| config_kind(path).is_some());
let configs = read_sources(&files, |path| {
if path
.components()
.any(|part| part.as_os_str() == "globalscript")
{
Scope::Global
} else {
scope
}
})?;
for ((uri, config_scope, version, text), path) in configs.into_iter().zip(&files) {
project.open_config(uri, config_scope, version, text, config_kind(path).unwrap());
}
Ok(project)
}
fn read_sources(
paths: &[PathBuf],
scope: impl Fn(&Path) -> Scope + Sync,
) -> Result<Vec<SourceText>, Box<dyn Error>> {
parallel_map_balanced(paths, |path| {
let text = fs::read_to_string(path).map_err(|error| error.to_string())?;
let uri = file_uri(path).map_err(|error| error.to_string())?;
Ok((uri, scope(path), 0, text))
})
.into_iter()
.collect::<Result<Vec<_>, String>>()
.map_err(Into::into)
}
pub(crate) fn config_kind(path: &Path) -> Option<String> {
let extension = path.extension()?.to_str()?;
if matches!(extension, "pack" | "order" | "hashes") {
return Some(format!("pack:{}", path.file_stem()?.to_str()?));
}
(matches!(extension, "constant" | "if" | "if3" | "defaults" | "anim")
|| types::Type::from_name(extension).is_some()
|| extension
.strip_prefix("config")
.is_some_and(|number| number.parse::<u32>().is_ok()))
.then(|| extension.to_string())
}
pub(crate) fn file_uri(path: &Path) -> Result<String, Box<dyn Error>> {
let absolute = fs::canonicalize(path)?
.to_string_lossy()
.trim_start_matches("\\\\?\\")
.replace('\\', "/");
let mut uri = String::from(if absolute.starts_with('/') {
"file://"
} else {
"file:///"
});
for byte in absolute.bytes() {
if byte.is_ascii_alphanumeric() || b"/-._~:".contains(&byte) {
uri.push(byte as char);
} else {
write!(uri, "%{byte:02X}")?;
}
}
Ok(uri)
}
#[derive(Clone, Copy)]
pub enum SourceProvider<'a> {
Eager(&'a HashMap<String, Arc<String>>),
Lazy(&'a HashMap<String, PathBuf>),
}
impl SourceProvider<'_> {
pub fn get(&self, key: &str) -> Option<Arc<String>> {
match self {
SourceProvider::Eager(m) => m.get(key).cloned(),
SourceProvider::Lazy(m) => fs::read_to_string(m.get(key)?).ok().map(Arc::new),
}
}
}
#[cfg(feature = "memprof")]
fn mem_mark(label: &str) {
info!(
"[mem] {:<22} live {:>7.1} MB | peak {:>7.1} MB | allocs {}",
label,
memprof::current_bytes() as f64 / 1_048_576.0,
memprof::peak_bytes() as f64 / 1_048_576.0,
memprof::alloc_count(),
);
}
#[cfg(not(feature = "memprof"))]
#[inline]
fn mem_mark(_label: &str) {}
#[cfg(feature = "memprof")]
fn mem_stats_registry(reg: &crate::symbol::SymbolRegistry) {
use crate::symbol::{Symbol, SymbolKind};
use crate::types::Type;
use std::collections::{HashMap, HashSet};
let t = std::mem::size_of::<Type>();
let mb = |b: usize| b as f64 / 1_048_576.0;
fn tbl<K, V>(m: &HashMap<K, V>) -> usize {
if m.capacity() == 0 {
return 0;
}
let buckets = (m.capacity() * 8 / 7).next_power_of_two();
buckets * (std::mem::size_of::<(K, V)>() + 1)
}
fn keys_cap<V>(m: &HashMap<String, V>) -> usize {
m.keys().map(|k| k.capacity()).sum()
}
let sym_heap = |s: &Symbol| -> usize {
s.name.capacity()
+ match &s.kind {
SymbolKind::Script {
trigger,
param_types,
return_types,
..
} => trigger.capacity() + (param_types.capacity() + return_types.capacity()) * t,
SymbolKind::Command {
param_types,
return_types,
..
} => (param_types.capacity() + return_types.capacity()) * t,
SymbolKind::GameVar { category, .. } => category.capacity(),
SymbolKind::Constant { string_value, .. } => {
string_value.as_ref().map_or(0, |s| s.capacity())
}
_ => 0,
}
};
let sym_map = |m: &HashMap<String, Symbol>| -> usize {
tbl(m) + keys_cap(m) + m.values().map(&sym_heap).sum::<usize>()
};
let i32_map = |m: &HashMap<String, i32>| -> usize { tbl(m) + keys_cap(m) };
let mut rows: Vec<(&str, usize, usize)> = vec![
(
"scripts",
reg.scripts.len(),
tbl(®.scripts) + keys_cap(®.scripts),
),
("commands", reg.commands.len(), sym_map(®.commands)),
("game_vars", reg.game_vars.len(), sym_map(®.game_vars)),
("constants", reg.constants.len(), sym_map(®.constants)),
(
"entity_ids",
reg.entity_ids.len(),
tbl(®.entity_ids)
+ keys_cap(®.entity_ids)
+ reg
.entity_ids
.values()
.map(|e| e.variants.capacity() * std::mem::size_of::<(Type, i32)>())
.sum::<usize>(),
),
(
"scripts_by_trigger",
reg.scripts_by_trigger.len(),
tbl(®.scripts_by_trigger)
+ keys_cap(®.scripts_by_trigger)
+ reg
.scripts_by_trigger
.values()
.map(|s| 16 + sym_heap(s.as_ref()))
.sum::<usize>(),
),
(
"command_param_types",
reg.command_param_types.len(),
tbl(®.command_param_types)
+ keys_cap(®.command_param_types)
+ reg
.command_param_types
.values()
.map(|v| v.capacity() * t)
.sum::<usize>(),
),
("script_ids", reg.script_ids.len(), i32_map(®.script_ids)),
(
"proc_script_ids",
reg.proc_script_ids.len(),
i32_map(®.proc_script_ids),
),
(
"label_script_ids",
reg.label_script_ids.len(),
i32_map(®.label_script_ids),
),
(
"trigger_script_ids",
reg.trigger_script_ids.len(),
i32_map(®.trigger_script_ids),
),
(
"preloaded_script_ids",
reg.preloaded_script_ids.len(),
i32_map(®.preloaded_script_ids),
),
("components", reg.components.len(), i32_map(®.components)),
(
"interface_ids",
reg.interface_ids.len(),
i32_map(®.interface_ids),
),
("type_chars", reg.type_chars.len(), i32_map(®.type_chars)),
(
"dbcolumn_types",
reg.dbcolumn_types.len(),
tbl(®.dbcolumn_types) + keys_cap(®.dbcolumn_types),
),
];
let ts_tbl = {
let s: &HashSet<String> = ®.test_scripts;
if s.capacity() == 0 {
0
} else {
(s.capacity() * 8 / 7).next_power_of_two() * (std::mem::size_of::<String>() + 1)
+ s.iter().map(|k| k.capacity()).sum::<usize>()
}
};
rows.push(("test_scripts", reg.test_scripts.len(), ts_tbl));
rows.sort_by_key(|row| std::cmp::Reverse(row.2));
let total: usize = rows.iter().map(|r| r.2).sum();
info!(
"[mem] registry ~{:.2} MB (sizeof Symbol={}B, SymbolKind={}B, Type={}B):",
mb(total),
std::mem::size_of::<Symbol>(),
std::mem::size_of::<SymbolKind>(),
t,
);
for (name, n, bytes) in &rows {
info!(
"[mem] {:<20} {:>6} entries {:>7.3} MB",
name,
n,
mb(*bytes)
);
}
}
#[cfg(feature = "memprof")]
fn mem_stats_compiled(scripts: &[CompiledScript]) {
use crate::bytecode::{Instruction, Opcode, Operand};
let (mut n_instr, mut n_str, mut str_bytes) = (0usize, 0usize, 0usize);
let (mut n_switch, mut switch_entries) = (0usize, 0usize);
let (mut source_path_bytes, mut name_bytes) = (0usize, 0usize);
for s in scripts {
n_instr += s.instructions.len();
source_path_bytes += s.source_path.capacity();
name_bytes += s.name.capacity() + s.trigger.capacity();
for st in &s.strings {
n_str += 1;
str_bytes += st.len();
}
for sw in &s.switch_tables {
n_switch += 1;
switch_entries += sw.len();
}
}
let sz = std::mem::size_of::<Instruction>();
let mb = |b: usize| b as f64 / 1_048_576.0;
info!(
"[mem] sizeof Instruction={}B Operand={}B Opcode={}B CompiledScript={}B",
sz,
std::mem::size_of::<Operand>(),
std::mem::size_of::<Opcode>(),
std::mem::size_of::<CompiledScript>(),
);
info!(
"[mem] compiled: {} scripts, {} instrs => {:.2} MB instr structs",
scripts.len(),
n_instr,
mb(n_instr * sz)
);
info!(
"[mem] Str operands: {} ({:.2} MB content + {:.2} MB Box<str> headers)",
n_str,
mb(str_bytes),
mb(n_str * 16)
);
info!(
"[mem] SwitchTable operands: {} ({} entries => {:.2} MB)",
n_switch,
switch_entries,
mb(switch_entries * 16)
);
info!(
"[mem] source_path {:.2} MB, names+triggers {:.2} MB",
mb(source_path_bytes),
mb(name_bytes)
);
}
struct ParsedFile {
path: PathBuf,
file: ScriptFile,
testscript_line: Option<usize>,
source_path: String,
}
struct FileParseResult {
path: PathBuf,
read: Result<ParsedSource, std::io::Error>,
}
struct ParsedSource {
cache_key: String,
raw_source: String,
outcome: ParseOutcome,
}
enum ParseOutcome {
Parsed {
file: ScriptFile,
testscript_line: Option<usize>,
},
Error {
line: usize,
position: usize,
message: String,
phase: diagnostics::Phase,
},
}
fn parse_one_file(path: &Path, include_tests: bool) -> FileParseResult {
let raw_source = match fs::read_to_string(path) {
Ok(s) => s,
Err(e) => {
return FileParseResult {
path: path.to_path_buf(),
read: Err(e),
};
}
};
let testscript_line = find_testscript_line(&raw_source);
let source_code = if !include_tests {
if let Some(line_no) = testscript_line {
truncate_at_line(&raw_source, line_no)
} else {
raw_source.clone()
}
} else {
strip_testscript_annotation(&raw_source)
};
let canonical = fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
let mut cache_key = canonical.to_string_lossy().into_owned();
if cache_key.starts_with("\\\\?\\") {
cache_key = cache_key[4..].to_string();
}
cache_key = cache_key.replace("\\Content\\", "\\content\\");
let path_buf = path.to_path_buf();
let outcome = match Lexer::new(&source_code, &path_buf).tokenize() {
Err(e) => ParseOutcome::Error {
line: e.line,
position: e.position,
message: e.message,
phase: diagnostics::Phase::Lexing,
},
Ok(tokens) => match Parser::new(tokens, &path_buf).parse() {
Ok(file) => ParseOutcome::Parsed {
file,
testscript_line: if include_tests { testscript_line } else { None },
},
Err(e) => ParseOutcome::Error {
line: e.line,
position: e.position,
message: e.message,
phase: diagnostics::Phase::Parsing,
},
},
};
FileParseResult {
path: path_buf,
read: Ok(ParsedSource {
cache_key,
raw_source,
outcome,
}),
}
}
pub fn compile_memory(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn Error>> {
compile_memory_with_options(scripts_dir, pack_dir, lint, false, false)
}
pub fn compile_memory_with_tests(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
include_tests: bool,
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn Error>> {
compile_memory_with_options(scripts_dir, pack_dir, lint, include_tests, false)
}
pub fn compile_memory_with_options(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
include_tests: bool,
low_mem: bool,
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn Error>> {
if low_mem || std::env::var("RUNEC_RECOMPILE").is_ok_and(|v| !v.is_empty()) {
info!("[recompile] low-memory recompile pipeline enabled");
return compile_recompile_memory(scripts_dir, pack_dir, lint, include_tests);
}
let (compiled_scripts, diagnostics) = run_pipeline(scripts_dir, pack_dir, lint, include_tests)?;
info!("Writing compiled output to memory...");
let writer = ScriptWriter::new("".into());
diagnostics.print_all();
info!("Compilation complete!");
Ok(writer.build_all(&compiled_scripts)?)
}
pub fn compile(
scripts_dir: &Path,
pack_dir: Option<&Path>,
output_dir: &Path,
lint: bool,
) -> Result<(), Box<dyn Error>> {
compile_with_options(scripts_dir, pack_dir, output_dir, lint, false)
}
pub fn compile_with_options(
scripts_dir: &Path,
pack_dir: Option<&Path>,
output_dir: &Path,
lint: bool,
low_mem: bool,
) -> Result<(), Box<dyn Error>> {
if low_mem || std::env::var("RUNEC_RECOMPILE").is_ok_and(|v| !v.is_empty()) {
info!("[recompile] low-memory recompile pipeline enabled");
return compile_recompile(scripts_dir, pack_dir, output_dir, lint);
}
let (compiled_scripts, diagnostics) = run_pipeline(scripts_dir, pack_dir, lint, false)?;
let output = output_dir.display().to_string();
info!("Writing output to {}...", output.replace('\\', "/"));
let writer = ScriptWriter::new(output);
writer.write_all(&compiled_scripts)?;
diagnostics.print_all();
info!("Compilation complete!");
Ok(())
}
pub fn lint(scripts_dir: &Path, pack_dir: Option<&Path>) -> Result<(), Box<dyn Error>> {
let (_, diagnostics) = run_pipeline(scripts_dir, pack_dir, true, false)?;
diagnostics.print_all();
info!("Compilation complete!");
Ok(())
}
fn run_pipeline(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
include_tests: bool,
) -> Result<(Vec<CompiledScript>, DiagnosticsCollector), Box<dyn Error>> {
let source_dir = sources::target_dir(scripts_dir, sources::Scope::Rune);
let scripts_dir = source_dir.as_path();
if !scripts_dir.exists() || !scripts_dir.is_dir() {
return Err(Box::new(error::CompilerError::FileNotFound(
scripts_dir.display().to_string(),
)));
}
if std::env::var("RUNEC_STREAM").is_ok_and(|v| !v.is_empty()) {
info!("[stream] streaming pipeline enabled (RUNEC_STREAM)");
return run_pipeline_streaming(scripts_dir, pack_dir, lint, include_tests);
}
let mut rs2_files: Vec<PathBuf> = get_rs2_files(scripts_dir, "rs2")?;
rs2_files.sort();
info!("Found {} script files", rs2_files.len());
mem_mark("startup");
let mut diagnostics = DiagnosticsCollector::new();
info!("Parsing script files into syntax trees...");
let parse_results = parallel_map(&rs2_files, |path| parse_one_file(path, include_tests));
let mut all_files: Vec<ParsedFile> = Vec::new();
let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
let mut raw_by_path: HashMap<PathBuf, Arc<String>> = HashMap::new();
for result in parse_results {
let parsed = match result.read {
Ok(p) => p,
Err(e) => return Err(Box::new(e)),
};
let rc = Arc::new(parsed.raw_source);
let source_path = parsed.cache_key.clone();
source_cache.insert(parsed.cache_key, rc.clone());
raw_by_path.insert(result.path.clone(), rc);
match parsed.outcome {
ParseOutcome::Parsed {
file,
testscript_line,
} => all_files.push(ParsedFile {
path: result.path,
file,
testscript_line,
source_path,
}),
ParseOutcome::Error {
line,
position,
message,
phase,
} => diagnostics.error(result.path, line, position, message, phase),
}
}
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::TypeError(
"Parsing failed".to_string(),
)));
}
mem_mark("after parse");
info!("Registering scripts and building the symbol registry...");
let resolved_pack_dir = resolve_pack_dir(scripts_dir, pack_dir);
let mut registry = build_symbol_registry(scripts_dir, resolved_pack_dir.as_deref());
register_scripts(
&mut registry,
scripts_dir,
resolved_pack_dir.as_deref(),
&mut diagnostics,
&all_files,
&raw_by_path,
);
info!(" Registered {} scripts", registry.scripts.len());
drop(raw_by_path);
registry.drop_registration_scratch();
for pf in &all_files {
for script in &pf.file.scripts {
if let Some(msg) =
Compiler::validate_trigger_subject(&script.trigger, &script.name, ®istry)
{
diagnostics.warning(
pf.path.clone(),
script.line,
0,
msg,
diagnostics::Phase::SymbolRegistration,
);
}
}
}
mem_mark("after register");
#[cfg(feature = "memprof")]
mem_stats_registry(®istry);
info!("Type checking {} files...", all_files.len());
run_type_checker(&mut diagnostics, &all_files, ®istry);
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::TypeError(
"Type checking failed".to_string(),
)));
}
mem_mark("after typecheck");
info!("Generating bytecode from type-checked scripts...");
let mut compiled_scripts = codegen(&all_files, ®istry, &mut diagnostics);
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::CodeGenError(
"Code generation failed".into(),
)));
}
info!(" Generated {} compiled scripts", compiled_scripts.len());
compiled_scripts.sort_by_key(|s| s.id);
compiled_scripts.shrink_to_fit();
mem_mark("after codegen");
#[cfg(feature = "memprof")]
mem_stats_compiled(&compiled_scripts);
drop(all_files);
mem_mark("after drop asts");
info!("Checking pointers in generated code...");
check_pointers(
lint,
&mut diagnostics,
SourceProvider::Eager(&source_cache),
®istry,
&compiled_scripts,
);
mem_mark("after pointercheck");
Ok((compiled_scripts, diagnostics))
}
struct ScriptSig {
name: String,
trigger: String,
param_types: Vec<types::Type>,
return_types: Vec<types::Type>,
line: usize,
}
struct FileSigs {
path: PathBuf,
testscript_line: Option<usize>,
sigs: Vec<ScriptSig>,
}
enum SigOutcome {
Parsed {
sigs: Vec<ScriptSig>,
testscript_line: Option<usize>,
},
Error {
line: usize,
position: usize,
message: String,
phase: diagnostics::Phase,
},
}
struct FileSigsResult {
path: PathBuf,
read: Result<(String, String, SigOutcome), std::io::Error>,
}
fn parse_one_file_sigs(path: &Path, include_tests: bool) -> FileSigsResult {
let r = parse_one_file(path, include_tests);
let read = r.read.map(|ps| {
let outcome = match ps.outcome {
ParseOutcome::Parsed {
file,
testscript_line,
} => {
let sigs = file
.scripts
.iter()
.map(|d| ScriptSig {
name: d.name.clone(),
trigger: d.trigger.clone(),
param_types: d.params.iter().map(|p| p.param_type).collect(),
return_types: d.return_types.clone(),
line: d.line,
})
.collect();
SigOutcome::Parsed {
sigs,
testscript_line,
}
}
ParseOutcome::Error {
line,
position,
message,
phase,
} => SigOutcome::Error {
line,
position,
message,
phase,
},
};
(ps.cache_key, ps.raw_source, outcome)
});
FileSigsResult { path: r.path, read }
}
fn run_pipeline_streaming(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
include_tests: bool,
) -> Result<(Vec<CompiledScript>, DiagnosticsCollector), Box<dyn Error>> {
let mut rs2_files: Vec<PathBuf> = get_rs2_files(scripts_dir, "rs2")?;
rs2_files.sort();
info!("Found {} script files", rs2_files.len());
mem_mark("startup");
let mut diagnostics = DiagnosticsCollector::new();
info!("[stream] Pass 1: parsing for signatures...");
let sig_results = parallel_map(&rs2_files, |path| parse_one_file_sigs(path, include_tests));
let mut source_paths: HashMap<String, PathBuf> = HashMap::new();
let mut raw_by_path: HashMap<PathBuf, Arc<String>> = HashMap::new();
let mut file_sigs: Vec<FileSigs> = Vec::new();
for r in sig_results {
let (cache_key, raw_source, outcome) = match r.read {
Ok(t) => t,
Err(e) => return Err(Box::new(e)),
};
source_paths.insert(cache_key, r.path.clone());
raw_by_path.insert(r.path.clone(), Arc::new(raw_source));
match outcome {
SigOutcome::Parsed {
sigs,
testscript_line,
} => file_sigs.push(FileSigs {
path: r.path,
testscript_line,
sigs,
}),
SigOutcome::Error {
line,
position,
message,
phase,
} => diagnostics.error(r.path, line, position, message, phase),
}
}
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::TypeError(
"Parsing failed".to_string(),
)));
}
mem_mark("after parse");
info!("[stream] Registering scripts and building the symbol registry...");
let resolved_pack_dir = resolve_pack_dir(scripts_dir, pack_dir);
let mut registry = build_symbol_registry(scripts_dir, resolved_pack_dir.as_deref());
register_scripts_from_sigs(
&mut registry,
scripts_dir,
resolved_pack_dir.as_deref(),
&mut diagnostics,
&file_sigs,
&raw_by_path,
);
info!(" Registered {} scripts", registry.scripts.len());
drop(raw_by_path);
registry.drop_registration_scratch();
for fs in &file_sigs {
for sig in &fs.sigs {
if let Some(msg) =
Compiler::validate_trigger_subject(&sig.trigger, &sig.name, ®istry)
{
diagnostics.warning(
fs.path.clone(),
sig.line,
0,
msg,
diagnostics::Phase::SymbolRegistration,
);
}
}
}
drop(file_sigs);
mem_mark("after register");
#[cfg(feature = "memprof")]
mem_stats_registry(®istry);
info!("[stream] Pass 2: type-check + codegen (streaming)...");
let per_file = parallel_map(&rs2_files, |path| {
let parsed = match parse_one_file(path, include_tests).read {
Ok(p) => p,
Err(_) => return (Vec::new(), DiagnosticsCollector::new()),
};
let (file, testscript_line) = match parsed.outcome {
ParseOutcome::Parsed {
file,
testscript_line,
} => (file, testscript_line),
ParseOutcome::Error { .. } => return (Vec::new(), DiagnosticsCollector::new()),
};
let mut type_checker = TypeChecker::new(®istry);
type_checker.check_file_with_test_boundary(&file, path, testscript_line);
let mut compiled = Vec::new();
if !type_checker.diagnostics.has_errors() {
let mut compiler = Compiler::new(®istry);
for script in &file.scripts {
if script.trigger == "command" {
continue;
}
let Some(mut c) =
compiler.compile_checked(script, path, &mut type_checker.diagnostics)
else {
continue;
};
c.source_path = parsed.cache_key.clone();
c.shrink_to_fit();
compiled.push(c);
}
}
(compiled, type_checker.diagnostics)
});
let mut compiled_scripts: Vec<CompiledScript> = Vec::new();
for (compiled, diags) in per_file {
compiled_scripts.extend(compiled);
diagnostics.merge(diags);
}
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::TypeError(
"Type checking failed".to_string(),
)));
}
compiled_scripts.sort_by_key(|s| s.id);
compiled_scripts.shrink_to_fit();
info!(" Generated {} compiled scripts", compiled_scripts.len());
mem_mark("after codegen");
#[cfg(feature = "memprof")]
mem_stats_compiled(&compiled_scripts);
check_pointers(
lint,
&mut diagnostics,
SourceProvider::Lazy(&source_paths),
®istry,
&compiled_scripts,
);
mem_mark("after pointercheck");
Ok((compiled_scripts, diagnostics))
}
fn register_scripts_from_sigs(
registry: &mut SymbolRegistry,
scripts_dir: &Path,
resolved_pack_dir: Option<&Path>,
diagnostics: &mut DiagnosticsCollector,
file_sigs: &[FileSigs],
raw_by_path: &HashMap<PathBuf, Arc<String>>,
) {
if let Some(pd) = resolved_pack_dir {
symloader::generate_script_pack(scripts_dir, pd, raw_by_path);
symloader::load_script_ids(registry, pd);
}
use crate::diagnostic_messages as msg;
let mut registered_scripts: std::collections::HashSet<String> =
std::collections::HashSet::new();
for fs in file_sigs.iter() {
for sig in &fs.sigs {
Arc::make_mut(&mut registry.visibility).declare_script(
&fs.path,
&sig.trigger,
&sig.name,
);
if sig.trigger == "command" {
continue;
}
if !trigger_table::is_valid_trigger(&sig.trigger) {
diagnostics.warning(
fs.path.clone(),
sig.line,
0,
msg::fmt(msg::SCRIPT_TRIGGER_INVALID, &[&sig.trigger]),
crate::diagnostics::Phase::SymbolRegistration,
);
}
let key = format!("{}:{}", sig.trigger, sig.name);
if !registered_scripts.insert(key) {
diagnostics.warning(
fs.path.clone(),
sig.line,
0,
msg::fmt(msg::SCRIPT_REDECLARATION, &[&sig.trigger, &sig.name]),
crate::diagnostics::Phase::SymbolRegistration,
);
}
if !sig.return_types.is_empty() && !trigger_table::allows_returns(&sig.trigger) {
diagnostics.warning(
fs.path.clone(),
sig.line,
0,
msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[&sig.trigger]),
diagnostics::Phase::SymbolRegistration,
);
}
registry.register_script(
sig.name.clone(),
sig.trigger.clone(),
sig.param_types.clone(),
sig.return_types.clone(),
);
if let Some(ts_line) = fs.testscript_line
&& sig.line >= ts_line
{
registry.mark_test_script(&sig.trigger, &sig.name);
}
}
}
}
fn check_pointers(
lint: bool,
diagnostics: &mut DiagnosticsCollector,
source: SourceProvider,
registry: &SymbolRegistry,
compiled_scripts: &[CompiledScript],
) {
{
use crate::pointer_checker::{PointerChecker, ScriptSource};
let shared = PointerChecker::build_shared(compiled_scripts, registry, false);
let names: Vec<String> = compiled_scripts.iter().map(|s| s.name.clone()).collect();
let max_chunks = std::env::var("RUNEC_PTR_CHUNKS")
.ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|&n| n > 0)
.unwrap_or(usize::MAX);
let chunk_diags = parallel_chunks_capped(&names, max_chunks, |chunk| {
let mut checker = PointerChecker::with_shared(
ScriptSource::Resident(compiled_scripts),
registry,
shared.clone(),
);
checker.set_source_cache(source);
checker.validate_names(chunk)
});
let mut pointer_diags = DiagnosticsCollector::new();
for d in chunk_diags {
pointer_diags.merge(d);
}
let ptr_warnings = pointer_diags.warning_count();
if ptr_warnings > 0 {
info!(" Pointer check: {} warning(s)", ptr_warnings);
}
diagnostics.merge(pointer_diags);
}
#[cfg(feature = "memprof")]
crate::pointer_checker::cfg_trace_report();
if lint {
info!("Running lint passes (unused locals, unreachable code)...");
let lint_diags = lints::run_lints(compiled_scripts, Some(source));
let lint_warnings = lint_diags.warning_count();
if lint_warnings > 0 {
info!(" Lints: {} warning(s)", lint_warnings);
}
diagnostics.merge(lint_diags);
}
}
fn codegen(
all_files: &[ParsedFile],
registry: &SymbolRegistry,
diagnostics: &mut DiagnosticsCollector,
) -> Vec<CompiledScript> {
let mut compiled = Vec::new();
for (scripts, errors) in parallel_map(all_files, |pf| compile_file(pf, registry)) {
compiled.extend(scripts);
diagnostics.merge(errors);
}
compiled
}
fn compile_file(
pf: &ParsedFile,
registry: &SymbolRegistry,
) -> (Vec<CompiledScript>, DiagnosticsCollector) {
let mut diagnostics = DiagnosticsCollector::new();
let mut scripts =
crate::compiler::compile_file(&pf.file, &pf.path, registry, false, &mut diagnostics);
for script in &mut scripts {
script.source_path = pf.source_path.clone();
script.shrink_to_fit();
}
(scripts, diagnostics)
}
fn run_type_checker(
diagnostics: &mut DiagnosticsCollector,
all_files: &[ParsedFile],
registry: &SymbolRegistry,
) {
let chunk_diags = parallel_chunks(all_files, |chunk| {
let mut type_checker = TypeChecker::new(registry);
for pf in chunk {
type_checker.check_file_with_test_boundary(&pf.file, &pf.path, pf.testscript_line);
}
type_checker.diagnostics
});
for d in chunk_diags {
diagnostics.merge(d);
}
}
fn resolve_pack_dir(scripts_dir: &Path, pack_dir: Option<&Path>) -> Option<PathBuf> {
pack_dir
.map(PathBuf::from)
.filter(|p| p.exists())
.or_else(|| {
scripts_dir.ancestors().find_map(|dir| {
let pack = dir.join("pack");
pack.is_dir().then_some(pack)
})
})
.or_else(|| {
scripts_dir
.ancestors()
.nth(3)
.map(|p| p.join("content/pack"))
.filter(|p| p.exists())
})
}
fn build_symbol_registry(scripts_dir: &Path, resolved_pack_dir: Option<&Path>) -> SymbolRegistry {
let visibility = {
let dir = scripts_dir.to_path_buf();
thread::spawn(move || sources::Visibility::scan(&dir))
};
let mut registry = SymbolRegistry::new();
if let Some(pd) = resolved_pack_dir {
info!(" Loading packs from {}", pd.display());
symloader::load_packs(&mut registry, pd);
info!(
" Loaded {} commands, {} game vars",
registry.commands.len(),
registry.game_vars.len(),
);
} else {
info!(" No pack directory found - symbol resolution will be limited");
}
let mut config_files: Vec<PathBuf> = Vec::new();
config_files.extend(sources::config_files(scripts_dir));
symloader::load_constant_files(&mut registry, &config_files);
info!(
" Loaded {} constants from .constant files",
registry.constants.len()
);
symloader::load_game_var_types(&mut registry, &config_files);
if let Some(pd) = resolved_pack_dir
&& let Err(error) = clientscript::load_clan_settings(&mut registry, &config_files, pd)
{
warn!(" Clan settings not loaded: {error}");
}
if let Some(pd) = resolved_pack_dir {
let dbtable_ids = symloader::load_dbtable_pack(&pd.join("dbtable.pack"));
if !dbtable_ids.is_empty() {
symloader::load_dbtable_configs(&mut registry, &config_files, &dbtable_ids);
info!(
" Registered {} dbcolumn compound IDs",
registry.dbcolumn_types.len()
);
}
}
let engine_rs2 = scripts_dir.join("engine.rs2");
if engine_rs2.exists() {
symloader::load_engine_command_params(&mut registry, &engine_rs2);
} else {
if let Ok(entries) = std::fs::read_dir(scripts_dir) {
for entry in entries.flatten() {
let candidate = entry.path().join("engine.rs2");
if candidate.exists() {
crate::symloader::load_engine_command_params(&mut registry, &candidate);
break;
}
}
}
}
let client_dir = if scripts_dir
.file_name()
.is_some_and(|name| name == "runescript")
{
scripts_dir.with_file_name("clientscript")
} else {
scripts_dir.join("clientscript")
};
if client_dir.is_dir() {
if let Some(pack) = resolved_pack_dir {
symloader::load_clientscript_pack(&mut registry, &pack.join("clientscript.pack"));
}
symloader::load_clientscript_signatures(&mut registry, &client_dir);
}
symloader::patch_command_return_types(&mut registry);
let mut visibility = visibility
.join()
.unwrap_or_else(|panic| panic::resume_unwind(panic));
visibility.index_registry(®istry);
registry.visibility = Arc::new(visibility);
registry
}
fn register_scripts(
registry: &mut SymbolRegistry,
scripts_dir: &Path,
resolved_pack_dir: Option<&Path>,
diagnostics: &mut DiagnosticsCollector,
all_files: &[ParsedFile],
raw_by_path: &HashMap<PathBuf, Arc<String>>,
) {
if let Some(pd) = resolved_pack_dir {
symloader::generate_script_pack(scripts_dir, pd, raw_by_path);
symloader::load_script_ids(registry, pd);
}
{
use crate::diagnostic_messages as msg;
let mut registered_scripts: std::collections::HashSet<String> =
std::collections::HashSet::new();
for pf in all_files.iter() {
Arc::make_mut(&mut registry.visibility).declare_source(&pf.path, &pf.file);
for script in &pf.file.scripts {
if script.trigger == "command" {
continue;
}
if !trigger_table::is_valid_trigger(&script.trigger) {
diagnostics.warning(
pf.path.clone(),
script.line,
0,
msg::fmt(msg::SCRIPT_TRIGGER_INVALID, &[&script.trigger]),
crate::diagnostics::Phase::SymbolRegistration,
);
}
let key = format!("{}:{}", script.trigger, script.name);
if !registered_scripts.insert(key.clone()) {
diagnostics.warning(
pf.path.clone(),
script.line,
0,
msg::fmt(msg::SCRIPT_REDECLARATION, &[&script.trigger, &script.name]),
crate::diagnostics::Phase::SymbolRegistration,
);
}
if !script.return_types.is_empty()
&& !trigger_table::allows_returns(&script.trigger)
{
diagnostics.warning(
pf.path.clone(),
script.line,
0,
msg::fmt(msg::SCRIPT_TRIGGER_NO_RETURNS, &[&script.trigger]),
diagnostics::Phase::SymbolRegistration,
);
}
let param_types: Vec<types::Type> =
script.params.iter().map(|p| p.param_type).collect();
registry.register_script(
script.name.clone(),
script.trigger.clone(),
param_types,
script.return_types.clone(),
);
if let Some(ts_line) = pf.testscript_line
&& script.line >= ts_line
{
registry.mark_test_script(&script.trigger, &script.name);
}
}
}
}
}
struct RecompileStore<'a> {
idx_to_path: Vec<PathBuf>,
file_to_idxs: HashMap<PathBuf, Vec<usize>>,
registry: &'a SymbolRegistry,
include_tests: bool,
cache: HashMap<usize, std::rc::Rc<CompiledScript>>,
order: std::collections::VecDeque<usize>,
cap: usize,
}
impl RecompileStore<'_> {
fn get(&mut self, idx: usize) -> std::rc::Rc<CompiledScript> {
if let Some(rc) = self.cache.get(&idx) {
return std::rc::Rc::clone(rc);
}
let path = self.idx_to_path[idx].clone();
let parsed = parse_one_file(&path, self.include_tests);
if let Ok(ps) = parsed.read
&& let ParseOutcome::Parsed { file, .. } = ps.outcome
{
let idxs = self.file_to_idxs.get(&path).cloned().unwrap_or_default();
let mut compiler = Compiler::new(self.registry);
let mut j = 0usize;
for script in &file.scripts {
if script.trigger == "command" {
continue;
}
if let Some(&i) = idxs.get(j) {
let mut c = compiler.compile_script(script);
c.source_path = ps.cache_key.clone();
self.insert(i, std::rc::Rc::new(c));
}
j += 1;
}
}
std::rc::Rc::clone(
self.cache
.get(&idx)
.expect("recompile store: script not produced by its file"),
)
}
fn insert(&mut self, idx: usize, rc: std::rc::Rc<CompiledScript>) {
if self.cache.insert(idx, rc).is_none() {
self.order.push_back(idx);
while self.order.len() > self.cap {
if let Some(old) = self.order.pop_front()
&& old != idx
{
self.cache.remove(&old);
}
}
}
}
}
type RecompiledOutput = (Vec<Vec<u8>>, DiagnosticsCollector);
fn recompile_to_encoded(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
include_tests: bool,
) -> Result<RecompiledOutput, Box<dyn Error>> {
let source_dir = sources::target_dir(scripts_dir, sources::Scope::Rune);
let scripts_dir = source_dir.as_path();
use crate::pointer_checker::{PointerChecker, ScriptSource};
let mut rs2_files: Vec<PathBuf> = get_rs2_files(scripts_dir, "rs2")?;
rs2_files.sort();
info!("Found {} script files", rs2_files.len());
mem_mark("startup");
let mut diagnostics = DiagnosticsCollector::new();
info!("[recompile] Pass 1: parsing for signatures...");
let sig_results = parallel_map(&rs2_files, |path| parse_one_file_sigs(path, include_tests));
let mut source_paths: HashMap<String, PathBuf> = HashMap::new();
let mut raw_by_path: HashMap<PathBuf, Arc<String>> = HashMap::new();
let mut file_sigs: Vec<FileSigs> = Vec::new();
for r in sig_results {
let (cache_key, raw_source, outcome) = match r.read {
Ok(t) => t,
Err(e) => return Err(Box::new(e)),
};
source_paths.insert(cache_key, r.path.clone());
raw_by_path.insert(r.path.clone(), Arc::new(raw_source));
match outcome {
SigOutcome::Parsed {
sigs,
testscript_line,
} => file_sigs.push(FileSigs {
path: r.path,
testscript_line,
sigs,
}),
SigOutcome::Error {
line,
position,
message,
phase,
} => diagnostics.error(r.path, line, position, message, phase),
}
}
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::TypeError(
"Parsing failed".to_string(),
)));
}
mem_mark("after parse");
info!("[recompile] Registering scripts and building the symbol registry...");
let resolved_pack_dir = resolve_pack_dir(scripts_dir, pack_dir);
let mut registry = build_symbol_registry(scripts_dir, resolved_pack_dir.as_deref());
register_scripts_from_sigs(
&mut registry,
scripts_dir,
resolved_pack_dir.as_deref(),
&mut diagnostics,
&file_sigs,
&raw_by_path,
);
info!(" Registered {} scripts", registry.scripts.len());
drop(raw_by_path);
registry.drop_registration_scratch();
for fs in &file_sigs {
for sig in &fs.sigs {
if let Some(msg) =
Compiler::validate_trigger_subject(&sig.trigger, &sig.name, ®istry)
{
diagnostics.warning(
fs.path.clone(),
sig.line,
0,
msg,
diagnostics::Phase::SymbolRegistration,
);
}
}
}
mem_mark("after register");
info!("[recompile] Pass 2: type-check (streaming, no bytecode held)...");
let tc_diags = parallel_map(&rs2_files, |path| {
let parsed = match parse_one_file(path, include_tests).read {
Ok(p) => p,
Err(_) => return DiagnosticsCollector::new(),
};
let (file, testscript_line) = match parsed.outcome {
ParseOutcome::Parsed {
file,
testscript_line,
} => (file, testscript_line),
ParseOutcome::Error { .. } => return DiagnosticsCollector::new(),
};
let mut type_checker = TypeChecker::new(®istry);
type_checker.check_file_with_test_boundary(&file, path, testscript_line);
if !type_checker.diagnostics.has_errors() {
let mut compiler = Compiler::new(®istry);
for script in &file.scripts {
if script.trigger != "command" {
compiler.compile_checked(script, path, &mut type_checker.diagnostics);
}
}
}
type_checker.diagnostics
});
for d in tc_diags {
diagnostics.merge(d);
}
if diagnostics.has_errors() {
diagnostics.print_all();
return Err(Box::new(error::CompilerError::TypeError(
"Type checking failed".to_string(),
)));
}
mem_mark("after typecheck");
let mut pre: Vec<(i32, String, PathBuf)> = Vec::new();
for fs in &file_sigs {
for sig in &fs.sigs {
if sig.trigger == "command" {
continue;
}
let id = registry
.script_id_for_trigger(&sig.trigger, &sig.name)
.or_else(|| registry.script_id(&sig.name))
.unwrap_or(-1);
pre.push((
id,
format!("[{},{}]", sig.trigger, sig.name),
fs.path.clone(),
));
}
}
let n = pre.len();
let mut order: Vec<usize> = (0..n).collect();
order.sort_by_key(|&p| pre[p].0);
let idents: Vec<(i32, String)> = order
.iter()
.map(|&p| (pre[p].0, pre[p].1.clone()))
.collect();
let idx_to_path: Vec<PathBuf> = order.iter().map(|&p| pre[p].2.clone()).collect();
let mut inv = vec![0usize; n];
for (idx, &p) in order.iter().enumerate() {
inv[p] = idx;
}
let mut file_to_idxs: HashMap<PathBuf, Vec<usize>> = HashMap::new();
for (p, m) in pre.iter().enumerate() {
file_to_idxs.entry(m.2.clone()).or_default().push(inv[p]);
}
let max_id = pre.iter().map(|m| m.0).max().unwrap_or(-1);
let slot_count = if max_id < 0 { 0 } else { (max_id + 1) as usize };
let len = n;
drop(pre);
info!("[recompile] Pointer check (re-compile on demand)...");
let shared = PointerChecker::build_shared_idents(&idents, ®istry);
{
let cap = file_to_idxs
.values()
.map(|v| v.len())
.max()
.unwrap_or(0)
.max(128);
let mut store = RecompileStore {
idx_to_path,
file_to_idxs,
registry: ®istry,
include_tests,
cache: HashMap::new(),
order: std::collections::VecDeque::new(),
cap,
};
let getter: Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript>> =
Box::new(move |idx| store.get(idx));
let scripts = ScriptSource::Recompile {
len,
get: std::cell::RefCell::new(getter),
};
let mut checker = PointerChecker::with_shared(scripts, ®istry, shared);
checker.set_source_cache(SourceProvider::Lazy(&source_paths));
let names: Vec<String> = idents.iter().map(|(_, n)| n.clone()).collect();
let ptr_diags = checker.validate_names(&names);
let w = ptr_diags.warning_count();
if w > 0 {
info!(" Pointer check: {} warning(s)", w);
}
diagnostics.merge(ptr_diags);
}
mem_mark("after pointercheck");
info!("[recompile] Re-compiling + encoding output...");
let mut encoded: Vec<Vec<u8>> = vec![Vec::new(); slot_count];
for path in &rs2_files {
let parsed = match parse_one_file(path, include_tests).read {
Ok(p) => p,
Err(_) => continue,
};
let file = match parsed.outcome {
ParseOutcome::Parsed { file, .. } => file,
ParseOutcome::Error { .. } => continue,
};
let mut compiler = Compiler::new(®istry);
let mut file_scripts: Vec<CompiledScript> = Vec::new();
for script in &file.scripts {
if script.trigger == "command" {
continue;
}
let Some(mut c) = compiler.compile_checked(script, path, &mut diagnostics) else {
continue;
};
c.source_path = parsed.cache_key.clone();
file_scripts.push(c);
}
for c in &file_scripts {
if c.id >= 0 && (c.id as usize) < slot_count {
encoded[c.id as usize] = crate::writer::encode_script(c);
}
}
if lint {
diagnostics.merge(lints::run_lints(
&file_scripts,
Some(SourceProvider::Lazy(&source_paths)),
));
}
}
mem_mark("after codegen");
Ok((encoded, diagnostics))
}
fn compile_recompile(
scripts_dir: &Path,
pack_dir: Option<&Path>,
output_dir: &Path,
lint: bool,
) -> Result<(), Box<dyn Error>> {
let (encoded, diagnostics) = recompile_to_encoded(scripts_dir, pack_dir, lint, false)?;
info!(
"Writing output to {}...",
output_dir.display().to_string().replace('\\', "/")
);
ScriptWriter::new(output_dir.display().to_string()).write_encoded(&encoded)?;
diagnostics.print_all();
info!("Compilation complete!");
Ok(())
}
fn compile_recompile_memory(
scripts_dir: &Path,
pack_dir: Option<&Path>,
lint: bool,
include_tests: bool,
) -> Result<(Vec<u8>, Vec<u8>), Box<dyn Error>> {
let (encoded, diagnostics) = recompile_to_encoded(scripts_dir, pack_dir, lint, include_tests)?;
info!("Writing compiled output to memory...");
let out = ScriptWriter::new("".into()).build_encoded(&encoded);
diagnostics.print_all();
info!("Compilation complete!");
Ok(out)
}
pub(crate) fn find_testscript_line(source: &str) -> Option<usize> {
for (i, line) in source.lines().enumerate() {
if line.trim() == "#testscript" {
return Some(i + 1);
}
}
None
}
fn truncate_at_line(source: &str, line_no: usize) -> String {
source
.lines()
.take(line_no - 1)
.collect::<Vec<_>>()
.join("\n")
}
fn strip_testscript_annotation(source: &str) -> String {
source
.lines()
.map(|line| {
if line.trim() == "#testscript" {
""
} else {
line
}
})
.collect::<Vec<_>>()
.join("\n")
}
fn get_rs2_files(dir: &Path, ext: &str) -> Result<Vec<PathBuf>, Box<dyn Error>> {
Ok(sources::script_files(dir, ext)?)
}