From 89d1fece55a13216d5ce61abe478946f97493e9c Mon Sep 17 00:00:00 2001 From: Jordan Abraham Date: Tue, 17 Nov 2026 07:25:53 -0500 Subject: [PATCH 1/2] feat: rename varpbit/writeinv/hookarg, prune unused config fields, bump 0.7.0 --- Cargo.lock | 14 ++--- Cargo.toml | 2 +- src/bytecode.rs | 12 ++--- src/clientscript.rs | 2 +- src/clientscript/decode.rs | 7 ++- src/clientscript/decompile/inference.rs | 10 ++-- src/clientscript/decompile/source.rs | 22 ++++---- src/clientscript/hooks.rs | 32 ++++++------ src/ide/config.rs | 6 +-- src/ide/fields.rs | 68 ++++--------------------- src/inspection.rs | 4 +- src/opcodes.rs | 4 +- src/pointer_checker.rs | 6 +-- src/sources.rs | 6 +-- src/symbol.rs | 4 +- src/symloader.rs | 7 +-- src/types.rs | 28 +++++----- tests/decompile_test.rs | 12 ++--- tests/editor_parity_test.rs | 8 +-- 19 files changed, 103 insertions(+), 151 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ad6f633..3808805 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -75,9 +75,9 @@ checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "clap" -version = "4.6.7" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +checksum = "ac230478587d0269d8d6998b82ae69ea51509d55df66d9e92edd1f986904cd4a" dependencies = [ "clap_builder", "clap_derive", @@ -97,9 +97,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.6.7" +version = "4.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +checksum = "895c9d8d2ac2dd8b8a29f3724a14e72aaaa6debcf8c38c82f97305c6a172767a" dependencies = [ "heck", "proc-macro2", @@ -109,9 +109,9 @@ dependencies = [ [[package]] name = "clap_lex" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" +checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79" [[package]] name = "colorchoice" @@ -228,7 +228,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "rs-runec" -version = "0.6.1" +version = "0.7.0" dependencies = [ "anyhow", "clap", diff --git a/Cargo.toml b/Cargo.toml index 7fd032d..600081d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rs-runec" -version = "0.6.1" +version = "0.7.0" edition = "2024" rust-version = "1.95.0" authors = ["Tyler Telis ", "RustCityRS "] diff --git a/src/bytecode.rs b/src/bytecode.rs index 0945e08..8c20539 100644 --- a/src/bytecode.rs +++ b/src/bytecode.rs @@ -22,8 +22,8 @@ pub enum Opcode { Gosub = opcodes::GOSUB, Jump = opcodes::JUMP, Switch = opcodes::SWITCH, - PushVarbit = opcodes::PUSH_VARBIT, - PopVarbit = opcodes::POP_VARBIT, + PushVarpBit = opcodes::PUSH_VARPBIT, + PopVarpBit = opcodes::POP_VARPBIT, BranchLessThanOrEquals = opcodes::BRANCH_LESS_THAN_OR_EQUALS, BranchGreaterThanOrEquals = opcodes::BRANCH_GREATER_THAN_OR_EQUALS, PushIntLocal = opcodes::PUSH_INT_LOCAL, @@ -129,7 +129,7 @@ impl Opcode { match category { "varn" => Self::PushVarn, "vars" => Self::PushVars, - "varpbit" => Self::PushVarbit, + "varpbit" => Self::PushVarpBit, "varc" => Self::PushVarcInt, "varcstr" => Self::PushVarcString, "varclan" => Self::PushVarClan, @@ -153,7 +153,7 @@ impl Opcode { match category { "varn" => Self::PopVarn, "vars" => Self::PopVars, - "varpbit" => Self::PopVarbit, + "varpbit" => Self::PopVarpBit, "varc" => Self::PopVarcInt, "varcstr" => Self::PopVarcString, "varclan" => Self::PopVarClan, @@ -180,8 +180,8 @@ impl Opcode { "PopVarn" => Some(Self::PopVarn), "PushVars" => Some(Self::PushVars), "PopVars" => Some(Self::PopVars), - "PushVarbit" => Some(Self::PushVarbit), - "PopVarbit" => Some(Self::PopVarbit), + "PushVarpBit" => Some(Self::PushVarpBit), + "PopVarpBit" => Some(Self::PopVarpBit), "PushVarcInt" => Some(Self::PushVarcInt), "PopVarcInt" => Some(Self::PopVarcInt), "PushVarcString" => Some(Self::PushVarcString), diff --git a/src/clientscript.rs b/src/clientscript.rs index 397cf6c..bf3b36a 100644 --- a/src/clientscript.rs +++ b/src/clientscript.rs @@ -19,7 +19,7 @@ pub mod format; pub(crate) mod hooks; pub(crate) mod triggers; use format::{Format, Width}; -pub use hooks::{HookValue, component_hook}; +pub use hooks::{HookArg, component_hook}; #[derive(Clone, Copy, PartialEq, Eq)] pub enum CommandKind { diff --git a/src/clientscript/decode.rs b/src/clientscript/decode.rs index 19efb74..e78b299 100644 --- a/src/clientscript/decode.rs +++ b/src/clientscript/decode.rs @@ -11,12 +11,11 @@ use std::io::Result; pub struct Script { pub name: String, pub local_int_count: u16, - pub local_string_count: u16, + pub local_obj_count: u16, pub local_long_count: u16, pub int_param_count: u16, pub string_param_count: u16, pub long_param_count: u16, - /// Physical opcode IDs are retained for disassembly and lossless output. pub opcodes: Vec, pub operations: Vec, pub int_operands: Vec, @@ -177,7 +176,7 @@ impl Script { let mut script = Self { name: code.string()?, local_int_count: counts[0][0], - local_string_count: counts[0][1], + local_obj_count: counts[0][1], local_long_count: counts[0][2], int_param_count: counts[1][0], string_param_count: counts[1][1], @@ -234,7 +233,7 @@ impl Script { } let local = match operation { Opcode::PushIntLocal | Opcode::PopIntLocal => Some(script.local_int_count), - Opcode::PushStringLocal | Opcode::PopStringLocal => Some(script.local_string_count), + Opcode::PushStringLocal | Opcode::PopStringLocal => Some(script.local_obj_count), Opcode::PushLongLocal | Opcode::PopLongLocal => Some(script.local_long_count), _ => None, }; diff --git a/src/clientscript/decompile/inference.rs b/src/clientscript/decompile/inference.rs index 2d176a7..a11a560 100644 --- a/src/clientscript/decompile/inference.rs +++ b/src/clientscript/decompile/inference.rs @@ -3,7 +3,7 @@ use super::source::script_name; use crate::arguments::{ command_hints, command_parameters, command_returns, expression_types, proc_hints, stack_hints, }; -use crate::clientscript::hooks::{self, HookValue}; +use crate::clientscript::hooks::{self, HookArg}; use crate::parser::{ BinOp, Expr, ScriptDeclaration, ScriptFile, Statement, StringPart, array_name, }; @@ -679,7 +679,7 @@ pub fn hook_literal( /// The scripts' types, and what each variable they use turned out to be. pub fn infer( files: &[(u32, ScriptFile)], - component_hooks: &[Vec], + component_hooks: &[Vec], registry: &SymbolRegistry, ) -> (HashMap, Vec<(String, Type)>) { let mut inference = Inference { @@ -759,7 +759,7 @@ pub fn infer( }) .collect(); for hook in component_hooks { - if let Some(HookValue::Int(script)) = hook.first() + if let Some(HookArg::Int(script)) = hook.first() && let Some(key) = keys.get(script) { let callee = inference.scopes[key].clone(); @@ -767,8 +767,8 @@ pub fn infer( .iter() .map(|value| { let ty = match value { - HookValue::String(_) => Type::String, - HookValue::Int(value) => event_name(*value, registry) + HookArg::String(_) => Type::String, + HookArg::Int(value) => event_name(*value, registry) .and_then(event_type) .unwrap_or(Type::Int), }; diff --git a/src/clientscript/decompile/source.rs b/src/clientscript/decompile/source.rs index 42c20f8..365860a 100644 --- a/src/clientscript/decompile/source.rs +++ b/src/clientscript/decompile/source.rs @@ -4,7 +4,7 @@ use super::structure; use crate::bytecode::Opcode; use crate::clientscript::decode::Script; use crate::clientscript::decode::is_branch; -use crate::clientscript::hooks::{self, HookValue}; +use crate::clientscript::hooks::{self, HookArg}; use crate::clientscript::{self, Command, CommandKind}; use crate::parser::Expr; use crate::symbol::{SymbolKind, SymbolRegistry}; @@ -21,9 +21,7 @@ pub struct Signature { pub param_types: Vec, pub return_types: Vec, pub locals: HashMap, - /// The stack of each parameter in order, when a caller shows it. pub order: Option>, - /// The stack of each return value in order, as the script's end pushes them. pub return_order: Vec, } @@ -63,7 +61,7 @@ fn stack(kind: BaseVarType) -> usize { pub fn infer_signatures( scripts: &HashMap, - component_hooks: &[Vec], + component_hooks: &[Vec], names: &dyn Names, params: &HashMap, commands: &[Command], @@ -142,13 +140,13 @@ pub fn infer_signatures( /// How an interface writes a component's hook: `script(args){transmits}`. pub fn component_hook_text( - values: &[HookValue], + values: &[HookArg], transmits: Option<(&str, &[i32])>, signatures: &HashMap, names: &dyn Names, registry: &SymbolRegistry, ) -> Result { - let Some(HookValue::Int(script)) = values.first() else { + let Some(HookArg::Int(script)) = values.first() else { bail!("A hook must start with its script"); }; let script = u32::try_from(*script).context("Hook with a negative script")?; @@ -163,13 +161,13 @@ pub fn component_hook_text( .iter() .map(|value| { Ok(match value { - HookValue::Int(value) => structure::expressions(&[inference::hook_literal( + HookArg::Int(value) => structure::expressions(&[inference::hook_literal( *value, ints.next().copied(), names, registry, )])?, - HookValue::String(value) => structure::hook_string(value), + HookArg::String(value) => structure::hook_string(value), }) }) .collect::>>()?; @@ -405,7 +403,7 @@ fn decompile_source( out.push('\n'); for (kind, count) in [ script.local_int_count, - script.local_string_count, + script.local_obj_count, script.local_long_count, ] .into_iter() @@ -692,7 +690,7 @@ impl Decompiler<'_> { Some((format!("{}L", script.long_operands[pc].unwrap()), 2)) } Opcode::PushVarp => Some((variable("varp"), 0)), - Opcode::PushVarbit => Some((variable("varpbit"), 0)), + Opcode::PushVarpBit => Some((variable("varpbit"), 0)), Opcode::PushVarcInt => Some((variable("varc"), 0)), Opcode::PushVarcString => Some((variable("varcstr"), 1)), Opcode::PushClanSettingInt => Some((variable("varclansetting"), 0)), @@ -724,7 +722,7 @@ impl Decompiler<'_> { } match opcode { Opcode::PopVarp - | Opcode::PopVarbit + | Opcode::PopVarpBit | Opcode::PopVarcInt | Opcode::PopVarcString | Opcode::PopIntLocal @@ -732,7 +730,7 @@ impl Decompiler<'_> { | Opcode::PopLongLocal => { let (target, kind) = match opcode { Opcode::PopVarp => (variable("varp"), 0), - Opcode::PopVarbit => (variable("varpbit"), 0), + Opcode::PopVarpBit => (variable("varpbit"), 0), Opcode::PopVarcInt => (variable("varc"), 0), Opcode::PopVarcString => (variable("varcstr"), 1), Opcode::PopIntLocal => (local(0), 0), diff --git a/src/clientscript/hooks.rs b/src/clientscript/hooks.rs index f829b62..6a0336e 100644 --- a/src/clientscript/hooks.rs +++ b/src/clientscript/hooks.rs @@ -7,7 +7,7 @@ use std::path::PathBuf; /// A value a component's hook hands its script. #[derive(Clone, Debug, PartialEq, Eq)] -pub enum HookValue { +pub enum HookArg { Int(i32), String(String), } @@ -16,20 +16,20 @@ fn hook_value( arg: &Expr, hint: Option, registry: &SymbolRegistry, -) -> Result { +) -> Result { let string = hint.is_some_and(|ty| ty.base_type() == BaseVarType::String); Ok(match arg { - Expr::IntLiteral(value) | Expr::CoordLiteral(value) => HookValue::Int(*value), - Expr::CharLiteral(value) => HookValue::Int(*value as i32), - Expr::BoolLiteral(value) => HookValue::Int(i32::from(*value)), - Expr::NullLiteral if string => HookValue::String("null".to_owned()), - Expr::NullLiteral => HookValue::Int(-1), + Expr::IntLiteral(value) | Expr::CoordLiteral(value) => HookArg::Int(*value), + Expr::CharLiteral(value) => HookArg::Int(*value as i32), + Expr::BoolLiteral(value) => HookArg::Int(i32::from(*value)), + Expr::NullLiteral if string => HookArg::String("null".to_owned()), + Expr::NullLiteral => HookArg::Int(-1), Expr::StringLiteral(name) => match hint .filter(|_| !string) .and_then(|ty| registry.lookup_reference(name, ty)) { - Some(id) => HookValue::Int(id), - None => HookValue::String(name.clone()), + Some(id) => HookArg::Int(id), + None => HookArg::String(name.clone()), }, Expr::JoinedString { parts } => { let mut text = String::new(); @@ -39,7 +39,7 @@ fn hook_value( }; text.push_str(part); } - HookValue::String(text) + HookArg::String(text) } Expr::Identifier(name) | Expr::ConstantVar(name, _) => { let component = name @@ -47,7 +47,7 @@ fn hook_value( .and_then(|(interface, component)| registry.lookup_component(interface, component)); let reference = hint.and_then(|ty| registry.lookup_reference(name, ty)); if let Some(id) = component.or(reference) { - return Ok(HookValue::Int(id)); + return Ok(HookArg::Int(id)); } if let Some(SymbolKind::Constant { int_value, @@ -56,14 +56,14 @@ fn hook_value( }) = registry.lookup_constant(name).map(|symbol| &symbol.kind) { if let Some(value) = int_value { - return Ok(HookValue::Int(*value)); + return Ok(HookArg::Int(*value)); } if let Some(value) = string_value { - return Ok(HookValue::String(value.clone())); + return Ok(HookArg::String(value.clone())); } } match registry.lookup_entity_id(name) { - Some(entity) => HookValue::Int(entity.id), + Some(entity) => HookArg::Int(entity.id), None => return Err(format!("Unknown hook argument '{name}'")), } } @@ -77,7 +77,7 @@ pub fn component_hook( text: &str, kind: Option<&str>, registry: &SymbolRegistry, -) -> Result<(Vec, Vec), String> { +) -> Result<(Vec, Vec), String> { let values = parse(text)?; let Expr::Tuple(args) = &values[1] else { unreachable!() @@ -102,7 +102,7 @@ pub fn component_hook( _ => unreachable!(), }; let hints = stack_hints(registry, ¶ms, args, &SymbolTable::new()); - let mut hook = vec![HookValue::Int(script)]; + let mut hook = vec![HookArg::Int(script)]; for (arg, hint) in args.iter().zip(hints) { hook.push(hook_value(arg, hint, registry)?); } diff --git a/src/ide/config.rs b/src/ide/config.rs index ca06940..0120bcb 100644 --- a/src/ide/config.rs +++ b/src/ide/config.rs @@ -21,7 +21,7 @@ pub(super) fn entity_type(kind: &str) -> Option { "mesanim" => Some(Type::MesAnim), "namedobj" => Some(Type::Obj), "sprites" => Some(Type::Graphic), - "writeinv" => Some(Type::WriteinvObj), + "writeinv" => Some(Type::WriteInv), _ => Type::from_name(kind), } } @@ -781,7 +781,7 @@ fn is_placeholder(ty: Type, name: &str) -> bool { Type::IdKit => &["idkit", "idk"], Type::Texture => &["material", "texture"], Type::Varp => &["varplayer", "varp"], - Type::Varbit => &["varplayerbit", "varpbit"], + Type::VarpBit => &["varplayerbit", "varpbit"], Type::Varn => &["varnpc", "varn"], Type::Vars => &["varworld", "vars"], Type::Varc => &["varclient", "varc"], @@ -798,7 +798,7 @@ fn is_placeholder(ty: Type, name: &str) -> bool { } fn is_var(ty: Type) -> bool { - matches!(ty, Type::Varp | Type::Varn | Type::Vars | Type::Varbit) + matches!(ty, Type::Varp | Type::Varn | Type::Vars | Type::VarpBit) } fn mismatch(names: &HashMap<&str, usize>, symbols: &[Symbol], ty: Type, name: &str) -> String { diff --git a/src/ide/fields.rs b/src/ide/fields.rs index 651ea86..a262e28 100644 --- a/src/ide/fields.rs +++ b/src/ide/fields.rs @@ -101,7 +101,7 @@ const PARAM: &[Value] = &[Config(Type::Param), OfParam]; const PARAM_INT: &[Value] = &[Config(Type::Param), Number]; const PARAM_TEXT: &[Value] = &[Config(Type::Param), Text]; const VARP_RANGE: &[Value] = &[Config(Type::Varp), Number, Number]; -const VARBIT_RANGE: &[Value] = &[Config(Type::Varbit), Number, Number]; +const VARPBIT_RANGE: &[Value] = &[Config(Type::VarpBit), Number, Number]; const TILE: &[Value] = &[Tile]; const AREA: &[Field] = &[("colour", RGB), ("trigger", FLAG)]; @@ -110,7 +110,6 @@ const BAS: &[Field] = &[ ("readyanim", SEQ), ("readyanim_l", SEQ), ("readyanim_r", SEQ), - ("readyanim_random", WEIGHTED_SEQ), ("walkanim", SEQ), ("walkanim_b", SEQ), ("walkanim_l", SEQ), @@ -123,7 +122,6 @@ const BAS: &[Field] = &[ ("crawlanim_b", SEQ), ("crawlanim_l", SEQ), ("crawlanim_r", SEQ), - ("rotate", NUMBER), ("turnspeed", NUMBER), ("turnmax", NUMBER), ("rollspeed", NUMBER), @@ -311,8 +309,6 @@ const INV: &[Field] = &[ const LIGHT: &[Field] = &[ ("amplitude", NUMBER), - ("speed", NUMBER), - ("base", NUMBER), ("function", NUMBER), ("frequency", NUMBER), ("offset", NUMBER), @@ -335,11 +331,8 @@ const LOC: &[Field] = &[ ("paramint", PARAM_INT), ("paramstr", PARAM_TEXT), ("cursor", OP_CURSOR), - ("msi_id", &[Config(Type::Msi)]), ("mapelement", &[Config(Type::MapElement)]), ("quest", QUEST), - ("ambient_sfx", NUMBER), - ("ambient_sfx_random", NUMBER), ("occlude", FLAG), ("occlude_off", FLAG), ("hillskew", FLAG), @@ -352,7 +345,6 @@ const LOC: &[Field] = &[ ("mirror", FLAG), ("shadow", FLAG), ("breakroutefinding", FLAG), - ("noblocks_npcs", FLAG), ("members_only", FLAG), ("hidden", FLAG), ("absent", FLAG), @@ -366,9 +358,7 @@ const LOC: &[Field] = &[ ("resizey", NUMBER), ("resizez", NUMBER), ("raiseobject", FLAG), - ("hillskew_t", NUMBER), ("wallwidth", NUMBER), - ("interaction_sides", NUMBER), ("offsetx", NUMBER), ("offsety", NUMBER), ("offsetz", NUMBER), @@ -408,7 +398,7 @@ const MEL: &[Field] = &[ ("opbase", TEXT), ( "showvar", - &[Config(Type::Varbit), Config(Type::Varp), Number, Number], + &[Config(Type::VarpBit), Config(Type::Varp), Number, Number], ), ("show", WORD), ("mapfunction", FLAG), @@ -425,14 +415,7 @@ const MEL: &[Field] = &[ const MESANIM: &[Field] = &[("len", SEQ)]; -const MSI: &[Field] = &[ - ("sprite", GRAPHIC), - ("nosprite", FLAG), - ("locsize", FLAG), - ("colour", RGB), - ("graphic", GRAPHIC), - ("resize", FLAG), -]; +const MSI: &[Field] = &[("colour", RGB), ("graphic", GRAPHIC), ("resize", FLAG)]; const NPC_FIELDS: &[Field] = &[ ("model", MODEL), @@ -457,14 +440,8 @@ const NPC_FIELDS: &[Field] = &[ ("blockwalk", WORD), ("vislevel", NUMBER), ("cursor", OP_CURSOR), - ("attackcursor", &[Config(Type::Cursor)]), ("alwaysontop", FLAG), ("minimap", FLAG), - ("visiblepriority", FLAG), - ("invisiblepriority", FLAG), - ("animateidle", FLAG), - ("clickable", FLAG), - ("slowwalk", FLAG), ("members", FLAG), ("vorbis", FLAG), ("givechase", FLAG), @@ -473,7 +450,6 @@ const NPC_FIELDS: &[Field] = &[ ("contrast", NUMBER), ("walkmask", NUMBER), ("size", NUMBER), - ("mainoptionindex", NUMBER), ("resizeh", NUMBER), ("resizev", NUMBER), ("hitbar", NUMBER), @@ -493,22 +469,8 @@ const NPC_FIELDS: &[Field] = &[ ("ranged", NUMBER), ("headicon", NUMBER), ("unknown", NUMBER), - ("idlesound", NUMBER), - ("crawlsound", NUMBER), - ("walksound", NUMBER), - ("runsound", NUMBER), - ("sounddistance", NUMBER), - ("soundvolume", NUMBER), - ("campaign", NUMBER), ("timer", NUMBER), - ("translate", NUMBER), - ("slayertype", NUMBER), - ("shadowcolour", NUMBER), - ("shadowmod", NUMBER), ("tint", NUMBER), - ("armyicon", NUMBER), - ("height", NUMBER), - ("mapfunction", NUMBER), ("patrol", NUMBER), ("multinpc", &[Number, Config(Type::Npc)]), ("membersop", TEXT), @@ -600,9 +562,9 @@ const QUEST_FIELDS: &[Field] = &[ ("name", TEXT), ("sortname", TEXT), ("progressvarp", VARP_RANGE), - ("progressvarbit", VARBIT_RANGE), + ("progressvarpbit", VARPBIT_RANGE), ("varprequirement", VARP_RANGE), - ("varbitrequirement", VARBIT_RANGE), + ("varpbitrequirement", VARPBIT_RANGE), ("questrequirement", QUEST), ("statrequirement", &[Config(Type::Stat), Number]), ("pointsrequirement", NUMBER), @@ -616,7 +578,7 @@ const QUEST_FIELDS: &[Field] = &[ ("icon", GRAPHIC), ("mainstartcoord", NUMBER), ("viacoord", NUMBER), - ("masterquestvarbit", VARBIT_RANGE), + ("masterquestvarpbit", VARPBIT_RANGE), ("masterquestvarp", VARP_RANGE), ("parent", QUEST), ("questpoints", NUMBER), @@ -628,16 +590,8 @@ const SEQ_FIELDS: &[Field] = &[ ("frame", WORD), ("iframe", WORD), ("delay", NUMBER), - ("synth", NUMBER), - ("op", NUMBER), - ("sound_mask", NUMBER), - ("loopoffset", NUMBER), ("priority", NUMBER), ("walkmerge", WORD), - ("looptype", NUMBER), - ("interrupt", NUMBER), - ("loopcount", NUMBER), - ("tween", FLAG), ("loops", NUMBER), ("maxloops", NUMBER), ("duplicatebehaviour", WORD), @@ -683,9 +637,9 @@ const DEFAULTS: &[Field] = &[ ("maxhitmarks", NUMBER), ("hitmarkoffset", NUMBER), ("performancemetricsmodel", MODEL), - ("unknown1", TEXTURE), - ("unknown4", &[Config(Type::Enum)]), - ("unknown5", &[Config(Type::Enum)]), + ("environmentmap", TEXTURE), + ("titles", &[Config(Type::Enum)]), + ("femaletitles", &[Config(Type::Enum)]), ("wearpostype", NUMBER), ]; @@ -806,7 +760,7 @@ const IF3: &[Field] = &[ ("onvarcstrtransmit", HOOK), ]; -const VARBIT_FIELDS: &[Field] = &[("basevar", VARP), ("startbit", NUMBER), ("endbit", NUMBER)]; +const VARPBIT_FIELDS: &[Field] = &[("basevar", VARP), ("startbit", NUMBER), ("endbit", NUMBER)]; const VARCONBIT_FIELDS: &[Field] = &[ ("basevar", &[Config(Type::VarCon)]), @@ -873,7 +827,7 @@ pub(super) fn keys(kind: &str) -> &'static [Field] { "seq" => SEQ_FIELDS, "spotanim" => SPOTANIM, "struct" => STRUCT, - "varpbit" => VARBIT_FIELDS, + "varpbit" => VARPBIT_FIELDS, "varconbit" => VARCONBIT_FIELDS, "varcon" => VARC, "controller" => CONTROLLER, diff --git a/src/inspection.rs b/src/inspection.rs index c0095dd..8f2fb8f 100644 --- a/src/inspection.rs +++ b/src/inspection.rs @@ -670,7 +670,7 @@ fn instruction_effect(instruction: &Instruction, registry: &SymbolRegistry) -> O PushVarp | PushVarn | PushVars - | PushVarbit + | PushVarpBit | PushVarcInt | PushVarcString | PushVarClan @@ -688,7 +688,7 @@ fn instruction_effect(instruction: &Instruction, registry: &SymbolRegistry) -> O | PopVarp | PopVarn | PopVars - | PopVarbit + | PopVarpBit | PopVarcInt | PopVarcString | PopVarClan diff --git a/src/opcodes.rs b/src/opcodes.rs index 92a7f35..7d80e28 100644 --- a/src/opcodes.rs +++ b/src/opcodes.rs @@ -32,8 +32,8 @@ opcodes! { GOSUB = 22 => "gosub"; JUMP = 23 => "jump"; SWITCH = 24 => "switch"; - PUSH_VARBIT = 25 => "push_varbit"; - POP_VARBIT = 27 => "pop_varbit"; + PUSH_VARPBIT = 25 => "push_varpbit"; + POP_VARPBIT = 27 => "pop_varpbit"; BRANCH_LESS_THAN_OR_EQUALS = 31 => "branch_less_than_or_equals"; BRANCH_GREATER_THAN_OR_EQUALS = 32 => "branch_greater_than_or_equals"; PUSH_INT_LOCAL = 33 => "push_int_local"; diff --git a/src/pointer_checker.rs b/src/pointer_checker.rs index 409c776..f0574f0 100644 --- a/src/pointer_checker.rs +++ b/src/pointer_checker.rs @@ -1279,7 +1279,7 @@ impl<'a> PointerChecker<'a> { // distinct opcodes (PushVar/PushVar2); we flatten that into a // single opcode + operand flag and recover it here. Opcode::PushVarp - | Opcode::PushVarbit + | Opcode::PushVarpBit | Opcode::PushVarcInt | Opcode::PushVarcString | Opcode::PushVarClan @@ -1298,7 +1298,7 @@ impl<'a> PointerChecker<'a> { } Opcode::PopVarp - | Opcode::PopVarbit + | Opcode::PopVarpBit | Opcode::PopVarcInt | Opcode::PopVarcString | Opcode::PopVarClan @@ -2574,7 +2574,7 @@ mod tests { // Test: secondary (dot-prefixed) var reads require the `*2` pointer // ----------------------------------------------------------------------- // Regression: categorize_nodes used to map every PushVarn/PopVarn (and - // PushVarp/PopVarp/PushVarbit/PopVarbit) to the primary active_npc / + // PushVarp/PopVarp/PushVarpBit/PopVarpBit) to the primary active_npc / // active_player pointer, ignoring the bit-16 "secondary" flag that // compiler.rs sets on `.%var` operands. That miscategorization caused // the 4 spurious `uninitialized active_npc` warnings at diff --git a/src/sources.rs b/src/sources.rs index b4f419c..0b50150 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -281,7 +281,7 @@ fn config_kind(ty: Type) -> Option<&'static str> { | Type::Varp | Type::Varn | Type::Vars - | Type::Varbit + | Type::VarpBit | Type::Hunt | Type::Controller | Type::Hitmark @@ -302,7 +302,7 @@ fn config_kind(ty: Type) -> Option<&'static str> { | Type::VarClanSetting | Type::VarCon | Type::VarConBit - | Type::VarNBit + | Type::VarnBit | Type::VarObj => Some(ty.name()), _ => None, } @@ -525,7 +525,7 @@ impl Visibility { ) -> Option { if let Some(kind) = config_kind(ty) { let normalized; - let name = if !matches!(ty, Type::Varp | Type::Varbit | Type::Varn | Type::Vars) { + let name = if !matches!(ty, Type::Varp | Type::VarpBit | Type::Varn | Type::Vars) { normalized = crate::symbol::normalize_entity_name(name); normalized.as_ref() } else { diff --git a/src/symbol.rs b/src/symbol.rs index 1a42b80..b276b78 100644 --- a/src/symbol.rs +++ b/src/symbol.rs @@ -144,7 +144,7 @@ pub enum SymbolKind { param_types: Vec, return_types: Vec, }, - /// A game variable (varp, varn, vars, varbit). + /// A game variable (varp, varn, vars, varpbit). GameVar { var_type: Type, var_id: i32, @@ -934,7 +934,7 @@ impl SymbolRegistry { Type::Varp | Type::Varn | Type::Vars - | Type::Varbit + | Type::VarpBit | Type::Varc | Type::VarCon | Type::VarConBit diff --git a/src/symloader.rs b/src/symloader.rs index e0b29ea..afaef40 100644 --- a/src/symloader.rs +++ b/src/symloader.rs @@ -192,7 +192,7 @@ pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) -> Result<(), ("varclan.pack", Type::VarClan), ("varcon.pack", Type::VarCon), ("varconbit.pack", Type::VarConBit), - ("varnbit.pack", Type::VarNBit), + ("varnbit.pack", Type::VarnBit), ("varobj.pack", Type::VarObj), ("category.pack", Type::Category), // UI types (override category) @@ -226,7 +226,7 @@ pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) -> Result<(), ("hunt.pack", Type::Hunt), ("npc_mode.pack", Type::NpcMode), ("enum.pack", Type::Enum), - ("writeinv.pack", Type::WriteinvObj), + ("writeinv.pack", Type::WriteInv), ("inv.pack", Type::Inv), ("loc.pack", Type::Loc), ("npc_stat.pack", Type::NpcStat), @@ -649,7 +649,7 @@ impl Comments { /// Scan the game-var configs and refine the type of each matching game-var. /// `load_game_vars` defaults everything to `Type::Int`; the real type comes /// from the `type=` line in the config block. Only varp, varn, vars -/// and varbit are registered from their file alone; the cache's tables number +/// and varpbit are registered from their file alone; the cache's tables number /// the others, through their `.pack`. pub fn load_game_var_types(registry: &mut SymbolRegistry, files: &[std::path::PathBuf]) { // Track the next auto-assigned ID per category for vars only found in config files. @@ -1018,6 +1018,7 @@ fn register_type_chars(registry: &mut SymbolRegistry) { ("npcstat", 0xFE), ("idkit", b'K' as i32), // 75 ("idk", b'K' as i32), + ("wma", b'`' as i32), ]; for (name, val) in type_chars { registry.type_chars.insert(name.to_string(), *val); diff --git a/src/types.rs b/src/types.rs index f492884..0efb570 100644 --- a/src/types.rs +++ b/src/types.rs @@ -81,13 +81,13 @@ pub enum Type { Varp, Varn, Vars, - Varbit, + VarpBit, Varc, VarClan, VarClanSetting, VarCon, VarConBit, - VarNBit, + VarnBit, VarObj, // Map types @@ -104,7 +104,7 @@ pub enum Type { MoveSpeed, EntityOverlay, StringVector, - WriteinvObj, + WriteInv, // Config tables Bas, @@ -299,13 +299,13 @@ impl Type { "varp" => Some(Type::Varp), "varn" => Some(Type::Varn), "vars" => Some(Type::Vars), - "varpbit" => Some(Type::Varbit), + "varpbit" => Some(Type::VarpBit), "varc" => Some(Type::Varc), "varclan" => Some(Type::VarClan), "varclansetting" => Some(Type::VarClanSetting), "varcon" => Some(Type::VarCon), "varconbit" => Some(Type::VarConBit), - "varnbit" => Some(Type::VarNBit), + "varnbit" => Some(Type::VarnBit), "varobj" => Some(Type::VarObj), "mapzone" => Some(Type::MapZone), "wma" | "maparea" => Some(Type::MapArea), @@ -318,7 +318,7 @@ impl Type { "movespeed" => Some(Type::MoveSpeed), "entityoverlay" => Some(Type::EntityOverlay), "stringvector" => Some(Type::StringVector), - "writeinvobj" => Some(Type::WriteinvObj), + "writeinv" | "writeinvobj" => Some(Type::WriteInv), "controller" => Some(Type::Controller), "bas" => Some(Type::Bas), "billboard" => Some(Type::Billboard), @@ -388,7 +388,7 @@ impl Type { Type::String => "string", Type::Long => "long", Type::Char => "char", - Type::Colour => "rgb", + Type::Colour => "colour", Type::ClanForumQfc => "clanforumqfc", Type::IntArray => "intarray", Type::Key => "key", @@ -441,16 +441,16 @@ impl Type { Type::Varp => "varp", Type::Varn => "varn", Type::Vars => "vars", - Type::Varbit => "varpbit", + Type::VarpBit => "varpbit", Type::Varc => "varc", Type::VarClan => "varclan", Type::VarClanSetting => "varclansetting", Type::VarCon => "varcon", Type::VarConBit => "varconbit", - Type::VarNBit => "varnbit", + Type::VarnBit => "varnbit", Type::VarObj => "varobj", Type::MapZone => "mapzone", - Type::MapArea => "wma", + Type::MapArea => "maparea", Type::MapElement => "mapelement", Type::LocShape => "loc_shape", Type::NpcMode => "npc_mode", @@ -460,7 +460,7 @@ impl Type { Type::MoveSpeed => "movespeed", Type::EntityOverlay => "entityoverlay", Type::StringVector => "stringvector", - Type::WriteinvObj => "writeinvobj", + Type::WriteInv => "writeinv", Type::Controller => "controller", Type::Bas => "bas", Type::Billboard => "billboard", @@ -566,13 +566,13 @@ impl Type { "def_movespeed", "def_entityoverlay", "def_stringvector", - "def_writeinvobj", + "def_writeinv", "def_controller", "def_regionuid", "def_bas", "def_billboard", - "def_effector", - "def_emitter", + "def_particleeffector", + "def_particleemitter", "def_cursor", "def_flo", "def_flu", diff --git a/tests/decompile_test.rs b/tests/decompile_test.rs index 6b29374..602eba9 100644 --- a/tests/decompile_test.rs +++ b/tests/decompile_test.rs @@ -1,6 +1,6 @@ use runec::bytecode::{Opcode, Operand}; use runec::clientscript::{ - self, HookValue, Source, + self, HookArg, Source, decode::Script, decompile::{self, Names}, format::Format, @@ -201,11 +201,11 @@ fn a_component_hook_reads_back_from_how_it_is_written() { registry.register_constant("event_com".into(), Type::Int, Some(i32::MIN + 3), None); registry.register_game_var("bank_open".into(), Type::Int, 90, "varp".into()); let values = vec![ - HookValue::Int(2), - HookValue::Int(i32::MIN + 3), - HookValue::Int(1), - HookValue::String("a
b".into()), - HookValue::Int(-1), + HookArg::Int(2), + HookArg::Int(i32::MIN + 3), + HookArg::Int(1), + HookArg::String("a
b".into()), + HookArg::Int(-1), ]; let signatures = HashMap::from([( 2, diff --git a/tests/editor_parity_test.rs b/tests/editor_parity_test.rs index 39ff36e..a93dc11 100644 --- a/tests/editor_parity_test.rs +++ b/tests/editor_parity_test.rs @@ -424,7 +424,7 @@ const CONFIG_TABLES: &[(&str, Type)] = &[ ("varclansetting", Type::VarClanSetting), ("varcon", Type::VarCon), ("varconbit", Type::VarConBit), - ("varnbit", Type::VarNBit), + ("varnbit", Type::VarnBit), ("varobj", Type::VarObj), ]; @@ -509,10 +509,10 @@ fn a_sprite_name_keeps_its_comma() { "3=icon,2\n", "pack:sprites", ); - let text = "[msi_0]\nsprite=icon,2\n"; + let text = "[msi_0]\ngraphic=icon,2\n"; let msi = project.open_config("mem:all.msi", Scope::Global, 1, text, "msi"); assert_eq!( - definition_after(&project, msi, text, "sprite="), + definition_after(&project, msi, text, "graphic="), Some(sprites) ); } @@ -542,7 +542,7 @@ fn a_config_value_can_be_an_id_or_a_table_placeholder() { "mem:all.msi", Scope::Global, 1, - "[msi_0]\nsprite=1804\n\n[msi_1]\nsprite=sprites_168\n\n[msi_2]\nsprite=null\n", + "[msi_0]\ngraphic=1804\n\n[msi_1]\ngraphic=sprites_168\n\n[msi_2]\ngraphic=null\n", "msi", ); project.open_config( From 9fb9da89f081df9b8cce281c08f9a7d264111140 Mon Sep 17 00:00:00 2001 From: Jordan Abraham Date: Tue, 17 Nov 2026 12:16:58 -0500 Subject: [PATCH 2/2] feat: add LobbyScript (.ls2) compile, lint and LSP support --- README.md | 51 ++- src/diagnostic_messages.rs | 3 + src/effects.rs | 14 +- src/filesystem.rs | 236 ++++++++++++-- src/ide/config.rs | 4 +- src/ide/index.rs | 8 +- src/ide/queries.rs | 16 +- src/lib.rs | 6 +- src/lsp.rs | 29 +- src/lsp/workspace.rs | 37 ++- src/lsp/workspace/tests.rs | 104 ++++++ src/main.rs | 67 +++- src/opcodes.rs | 1 - src/pointer.rs | 10 - src/project.rs | 37 ++- src/sources.rs | 40 ++- src/symloader.rs | 15 +- src/trigger_table.rs | 45 +++ src/typechecker.rs | 43 +++ tests/lobbyscript_test.rs | 631 +++++++++++++++++++++++++++++++++++++ 20 files changed, 1279 insertions(+), 118 deletions(-) create mode 100644 tests/lobbyscript_test.rs diff --git a/README.md b/README.md index 801bc23..7530869 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,9 @@ # RuneScape Compiler (runec) `runec` compiles RuneScript (`.rs2`) for the server and ClientScript (`.cs2`) -for the client. GlobalScript (`.gs2`) holds code shared by both. It also provides -an editor language server and a Rust library with ClientScript decompilation. +for the client. GlobalScript (`.gs2`) holds code shared by both. LobbyScript +(`.ls2`) is compiled on its own for a lobby server. It also provides an editor +language server and a Rust library with ClientScript decompilation. The examples assume `runec` is installed and on your `PATH`. Run commands from your project's root directory and adjust the source, pack and output paths to @@ -31,33 +32,37 @@ content/ ├── scripts/ │ ├── engine.rs2 │ ├── engine.cs2 +│ ├── engine.ls2 │ ├── interface_bank/ │ │ ├── scripts/bank.rs2 │ │ ├── client/bank.cs2 │ │ └── global/bank.gs2 │ ├── skill_combat/ +│ ├── lobby/friends.ls2 │ └── quests/ └── pack/ # script IDs, command opcodes and named assets ``` Discovery searches the whole scripts root recursively. File extensions select the target: `.rs2` runs on the server, `.cs2` on the client, and `.gs2` is compiled -for both. Folder names have no effect. Each file can contain multiple scripts. +for both. `.ls2` runs on the lobby server, which compiles only `.ls2` and never +`.gs2`. Folder names have no effect. Each file can contain multiple scripts. Keep existing feature names and nested source/config folders when adding client or shared scripts to a server project. Existing `runescript`, `clientscript` and `globalscript` folders still work; passing one of those paths resolves to its ancestor `scripts` root. Configs and constants are shared by default. To restrict a file, put -`// @scope(server)` or `// @scope(client)` in its leading comments. -`// @scope(shared)` states the default explicitly. This ownership travels with +`// @scope(server)`, `// @scope(client)` or `// @scope(lobby)` in its leading +comments. `// @scope(shared)` states the default explicitly. This ownership travels with the file when it moves. Shared scripts can only use shared definitions; each target can also use its own private definitions. Script ownership always comes -from the extension. +from the extension. LobbyScript uses shared configs and constants but no `.gs2` +procs, and other targets cannot use `.ls2` scripts. Your project supplies the engine commands, asset names and script IDs. -`engine.rs2` and `engine.cs2` declare command parameters and return types. They -can be anywhere under the root; duplicate engine files are an error. +`engine.rs2`, `engine.cs2` and `engine.ls2` declare command parameters and return +types. They can be anywhere under the root; duplicate engine files are an error. Client commands follow their declared argument order. A command whose first `component` parameter is evaluated last uses `@stack(component_last)`: @@ -84,6 +89,7 @@ The pack directory maps names to IDs: | Files | Purpose | |---|---| | `command.pack` | Server command opcodes; server script IDs are generated in memory | +| `ls2_command.pack` | Lobby command opcodes, in the `command.pack` format | | `cs2_command.pack` and `clientscript.pack` | Client opcodes and script IDs | | Other packs, such as `obj.pack` and `inv.pack` | Named assets and game data | @@ -123,6 +129,24 @@ Keep explicit ID entries when renaming scripts. For example, renaming `clientscript_1465` to `bank_refresh` requires `1465=[proc,bank_refresh]` in `clientscript.pack` to preserve that client's script ID. +## Compile lobby scripts + +```bash +runec compile-lobby --source content/scripts --pack content/pack --output data/lobby +``` + +This reads only the `.ls2` scripts and writes `script.dat` and `script.idx` in the +server format, with script IDs of their own. Lobby commands come from +`ls2_command.pack`, with signatures in `engine.ls2`; commands listed only in +`command.pack` do not resolve. Lobby scripts +accept only the `proc`, `label`, `login`, `logout`, `if_button`, `if_button1` to +`if_button10`, `if_buttond` and `if_close` triggers, and cannot use the secondary +player (`.command`, `.%var` or commands that need `.active_player`). Each is a +compile error. `compile-lobby` takes the same flags as `compile`; without +`--output`, lobby output goes to `./data/pack/lobby`. +`runec lint-lobby --source content/scripts --pack content/pack` checks lobby +scripts without writing output. + ## Check server scripts ```bash @@ -144,6 +168,7 @@ Use `--help` for all available options: runec --help runec compile --help runec compile-client --help +runec compile-lobby --help runec lsp --help ``` @@ -200,7 +225,8 @@ runec lsp --source content/scripts --pack content/pack ``` It loads separate server and client analysis contexts from the available engine -files. Shared scripts are checked against both. Use `--server` or `--client` to +files, and a lobby context when `engine.ls2` exists. Shared scripts are checked +against the server and client. Use `--server`, `--client` or `--lobby` to restrict a process to one target when needed. If the editor has separate fields for the executable and arguments, use `runec` @@ -212,13 +238,14 @@ With `--source`, only that revision's scripts tree, packs and supported cache asset folders belong to the server. Files from other revisions opened by project-wide search are ignored, so their script names cannot create duplicates. -Map all three script extensions to this server: +Map all four script extensions to this server: | File pattern | Language ID | |---|---| | `*.rs2` | `rs2` | | `*.cs2` | `cs2` | | `*.gs2` | `gs2` | +| `*.ls2` | `ls2` | The language server provides diagnostics, completion, hover, definitions, references, rename, syntax highlighting, signature help, inlay hints, formatting, @@ -344,7 +371,9 @@ Use [Project](src/project.rs) to manage source documents in memory: The host supplies a [SymbolRegistry](src/symbol.rs) and owns storage and script ID persistence. [EngineProfile](src/environment.rs) describes engine-specific -triggers and pointer rules. +triggers and pointer rules. `Target::Lobby` compiles `Scope::Lobby` documents to +server bytecode; a lobby server compiles its scripts tree with +`compile_lobby_memory_with_ids`. For ClientScript tools, use [Format](src/clientscript/format.rs) for opcode mappings, [Script::decode](src/clientscript/decode.rs) for binary decoding, and diff --git a/src/diagnostic_messages.rs b/src/diagnostic_messages.rs index d10244c..f8cd9ad 100644 --- a/src/diagnostic_messages.rs +++ b/src/diagnostic_messages.rs @@ -46,6 +46,9 @@ pub const SCRIPT_SUBJECT_ONLY_GLOBAL: &str = "Trigger '%s' only allows global su pub const SCRIPT_SUBJECT_NO_GLOBAL: &str = "Trigger '%s' does not allow global subjects."; pub const SCRIPT_SUBJECT_NO_CATEGORY: &str = "Trigger '%s' does not allow category subjects."; pub const SCRIPT_SUBJECT_NO_SPACES: &str = "Trigger '%s' does not allow spaces in subjects."; +pub const SCRIPT_TRIGGER_NOT_LOBBY: &str = "The trigger type '%s' is not available in lobbyscript."; +pub const LOBBY_SECONDARY_POINTER: &str = + "'%s' uses the secondary player pointer, which is not available in lobbyscript."; // Switch statement node specific pub const SWITCH_INVALID_TYPE: &str = "'%s' is not allowed within a switch statement."; diff --git a/src/effects.rs b/src/effects.rs index b774f27..57ff8a7 100644 --- a/src/effects.rs +++ b/src/effects.rs @@ -367,7 +367,7 @@ impl Effects { let scope = project.target_scope(); let documents = project .documents() - .filter(|document| document.scope == scope || document.scope == Scope::Global) + .filter(|document| project.includes(document.scope)) .collect::>(); let mut commands = HashMap::new(); let mut script_names = HashSet::new(); @@ -432,7 +432,7 @@ impl Effects { Visitor { registry: project.registry(), commands: &commands, - server: scope == Scope::Rune, + server: scope != Scope::Client, script_names: &script_names, callback_names: &callback_names, node: &mut nodes[next], @@ -457,10 +457,12 @@ impl Effects { vec![trigger.as_str()] }; for trigger in triggers { - for owner in [Scope::Global, node.scope] - .into_iter() - .take(if node.scope == Scope::Global { 1 } else { 2 }) - { + let owners = [Scope::Global, node.scope]; + let owners = match node.scope { + Scope::Global | Scope::Lobby => &owners[1..], + _ => &owners[..], + }; + for &owner in owners { if let Some(ids) = definitions.get(&(owner, trigger.to_owned(), name.clone())) { diff --git a/src/filesystem.rs b/src/filesystem.rs index 35b8228..3567eb4 100644 --- a/src/filesystem.rs +++ b/src/filesystem.rs @@ -33,7 +33,23 @@ pub fn editor_project( pack: Option<&Path>, client: bool, ) -> Result> { - let scope = if client { Scope::Client } else { Scope::Rune }; + editor_project_for_scope( + source, + pack, + if client { Scope::Client } else { Scope::Rune }, + ) +} + +/// [`editor_project`] for a server, client or lobby target. +pub fn editor_project_for_scope( + source: &Path, + pack: Option<&Path>, + scope: Scope, +) -> Result> { + if scope == Scope::Global { + return Err("GlobalScript belongs to the server and client targets".into()); + } + let client = scope == Scope::Client; let dir = sources::target_dir(source, scope); let pack = resolve_pack_dir(&dir, pack); let mut editor_roots = sources::roots(&dir); @@ -44,7 +60,7 @@ pub fn editor_project( .ok_or("Client opcode definitions require --pack")?, )? } else { - build_symbol_registry(&dir, pack.as_deref())? + build_symbol_registry(&dir, pack.as_deref(), scope)? }; let target = if client { registry.preloaded_script_ids.clear(); @@ -59,6 +75,8 @@ pub fn editor_project( Target::Client(Format::load( &pack.as_ref().unwrap().join("cs2_command.pack"), )?) + } else if scope == Scope::Lobby { + Target::Lobby } else { Target::Rune }; @@ -74,7 +92,7 @@ pub fn editor_project( ..Options::default() }, ); - let paths = sources::script_files(&dir, if client { "cs2" } else { "rs2" })?; + let paths = sources::script_files(&dir, scope.extension())?; let files = read_sources(&paths)?; for id in project.open_all(files) { if client { @@ -612,6 +630,7 @@ pub fn compile_memory_with_options( low_mem: bool, ) -> Result<(Vec, Vec), Box> { compile_memory_inner( + Scope::Rune, scripts_dir, pack_dir, lint, @@ -627,10 +646,56 @@ pub fn compile_memory_with_ids( pack_dir: Option<&Path>, ids: &mut ScriptIds, ) -> Result<(Vec, Vec), Box> { - compile_memory_inner(scripts_dir, pack_dir, false, false, false, ids) + compile_memory_inner(Scope::Rune, scripts_dir, pack_dir, false, false, false, ids) +} + +/// [`compile_memory`] for lobbyscript: `.ls2` sources, `ls2_command.pack` and `engine.ls2`. +pub fn compile_lobby_memory( + scripts_dir: &Path, + pack_dir: Option<&Path>, + lint: bool, +) -> Result<(Vec, Vec), Box> { + compile_lobby_memory_with_options(scripts_dir, pack_dir, lint, false, false) +} + +/// [`compile_memory_with_options`] for lobbyscript. +pub fn compile_lobby_memory_with_options( + scripts_dir: &Path, + pack_dir: Option<&Path>, + lint: bool, + include_tests: bool, + low_mem: bool, +) -> Result<(Vec, Vec), Box> { + compile_memory_inner( + Scope::Lobby, + scripts_dir, + pack_dir, + lint, + include_tests, + low_mem, + &mut ScriptIds::new(), + ) +} + +/// [`compile_memory_with_ids`] for lobbyscript. Lobby IDs are separate from the server's. +pub fn compile_lobby_memory_with_ids( + scripts_dir: &Path, + pack_dir: Option<&Path>, + ids: &mut ScriptIds, +) -> Result<(Vec, Vec), Box> { + compile_memory_inner( + Scope::Lobby, + scripts_dir, + pack_dir, + false, + false, + false, + ids, + ) } fn compile_memory_inner( + scope: Scope, scripts_dir: &Path, pack_dir: Option<&Path>, lint: bool, @@ -640,11 +705,11 @@ fn compile_memory_inner( ) -> Result<(Vec, Vec), Box> { 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, ids); + return compile_recompile_memory(scope, scripts_dir, pack_dir, lint, include_tests, ids); } let (compiled_scripts, diagnostics) = - run_pipeline(scripts_dir, pack_dir, lint, include_tests, ids)?; + run_pipeline(scope, scripts_dir, pack_dir, lint, include_tests, ids)?; info!("Writing compiled output to memory..."); let writer = ScriptWriter::new("".into()); @@ -683,17 +748,69 @@ pub fn compile_with_options( output_dir: &Path, lint: bool, low_mem: bool, +) -> Result<(), Box> { + compile_output( + Scope::Rune, + scripts_dir, + pack_dir, + output_dir, + lint, + low_mem, + ) +} + +/// [`compile`] for lobbyscript: `.ls2` sources, `ls2_command.pack` and `engine.ls2`. +pub fn compile_lobby( + scripts_dir: &Path, + pack_dir: Option<&Path>, + output_dir: &Path, + lint: bool, +) -> Result<(), Box> { + compile_lobby_with_options(scripts_dir, pack_dir, output_dir, lint, false) +} + +/// [`compile_with_options`] for lobbyscript. +pub fn compile_lobby_with_options( + scripts_dir: &Path, + pack_dir: Option<&Path>, + output_dir: &Path, + lint: bool, + low_mem: bool, +) -> Result<(), Box> { + compile_output( + Scope::Lobby, + scripts_dir, + pack_dir, + output_dir, + lint, + low_mem, + ) +} + +fn compile_output( + scope: Scope, + scripts_dir: &Path, + pack_dir: Option<&Path>, + output_dir: &Path, + lint: bool, + low_mem: bool, ) -> Result<(), Box> { // The recompile pipeline never holds all compiled scripts (it re-compiles on // demand for the pointer check + writes file-by-file). It does its own // output, so it returns here. The default path below is unchanged. 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); + return compile_recompile(scope, scripts_dir, pack_dir, output_dir, lint); } - let (compiled_scripts, diagnostics) = - run_pipeline(scripts_dir, pack_dir, lint, false, &mut ScriptIds::new())?; + let (compiled_scripts, diagnostics) = run_pipeline( + scope, + scripts_dir, + pack_dir, + lint, + false, + &mut ScriptIds::new(), + )?; let output = output_dir.display().to_string(); // Normalize separators for a clean, consistent log message (input paths may @@ -711,7 +828,27 @@ pub fn compile_with_options( /// Run all analysis passes (parse, type-check, codegen, pointer-check, lints) /// without writing output. Useful for editor tooling and CI lint gates. pub fn lint(scripts_dir: &Path, pack_dir: Option<&Path>) -> Result<(), Box> { - let (_, diagnostics) = run_pipeline(scripts_dir, pack_dir, true, false, &mut ScriptIds::new())?; + lint_scope(Scope::Rune, scripts_dir, pack_dir) +} + +/// [`lint`] for lobbyscript. +pub fn lint_lobby(scripts_dir: &Path, pack_dir: Option<&Path>) -> Result<(), Box> { + lint_scope(Scope::Lobby, scripts_dir, pack_dir) +} + +fn lint_scope( + scope: Scope, + scripts_dir: &Path, + pack_dir: Option<&Path>, +) -> Result<(), Box> { + let (_, diagnostics) = run_pipeline( + scope, + scripts_dir, + pack_dir, + true, + false, + &mut ScriptIds::new(), + )?; diagnostics.print_all(); info!("Compilation complete!"); @@ -723,13 +860,14 @@ pub fn lint(scripts_dir: &Path, pack_dir: Option<&Path>) -> Result<(), Box, lint: bool, include_tests: bool, ids: &mut ScriptIds, ) -> Result<(Vec, DiagnosticsCollector), Box> { - let source_dir = sources::target_dir(scripts_dir, sources::Scope::Rune); + let source_dir = sources::target_dir(scripts_dir, scope); let scripts_dir = source_dir.as_path(); if !scripts_dir.exists() || !scripts_dir.is_dir() { return Err(Box::new(error::CompilerError::FileNotFound( @@ -741,10 +879,10 @@ fn run_pipeline( // with RUNEC_STREAM=1. The default batch path below is unchanged. 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, ids); + return run_pipeline_streaming(scope, scripts_dir, pack_dir, lint, include_tests, ids); } - let mut rs2_files: Vec = get_rs2_files(scripts_dir, "rs2")?; + let mut rs2_files: Vec = get_rs2_files(scripts_dir, scope.extension())?; rs2_files.sort(); info!("Found {} script files", rs2_files.len()); @@ -803,8 +941,8 @@ fn run_pipeline( // Phase 2: assign IDs and register every parsed script. 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, ids, &mut diagnostics, &all_files); + let mut registry = build_symbol_registry(scripts_dir, resolved_pack_dir.as_deref(), scope)?; + register_scripts(scope, &mut registry, ids, &mut diagnostics, &all_files); info!(" Registered {} scripts", registry.scripts.len()); // Pre-assigned script ids were consumed during registration; free them // before codegen (the compile's peak-memory phase) rather than at scope end. @@ -968,13 +1106,14 @@ fn parse_one_file_sigs(path: &Path, include_tests: bool) -> FileSigsResult { } fn run_pipeline_streaming( + scope: Scope, scripts_dir: &Path, pack_dir: Option<&Path>, lint: bool, include_tests: bool, ids: &mut ScriptIds, ) -> Result<(Vec, DiagnosticsCollector), Box> { - let mut rs2_files: Vec = get_rs2_files(scripts_dir, "rs2")?; + let mut rs2_files: Vec = get_rs2_files(scripts_dir, scope.extension())?; rs2_files.sort(); info!("Found {} script files", rs2_files.len()); mem_mark("startup"); @@ -1025,8 +1164,8 @@ fn run_pipeline_streaming( // Registration (from signatures, not ASTs). 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, ids, &mut diagnostics, &file_sigs); + let mut registry = build_symbol_registry(scripts_dir, resolved_pack_dir.as_deref(), scope)?; + register_scripts_from_sigs(scope, &mut registry, ids, &mut diagnostics, &file_sigs); info!(" Registered {} scripts", registry.scripts.len()); registry.drop_registration_scratch(); @@ -1148,6 +1287,7 @@ fn assign_script_ids<'a>( /// `register_scripts` for the streaming path: identical logic, driven by the /// extracted signatures instead of the (already-dropped) ASTs. fn register_scripts_from_sigs( + scope: Scope, registry: &mut SymbolRegistry, ids: &mut ScriptIds, diagnostics: &mut DiagnosticsCollector, @@ -1174,11 +1314,20 @@ fn register_scripts_from_sigs( &sig.trigger, &sig.name, ); + if scope == Scope::Lobby && !trigger_table::is_lobby_trigger(&sig.trigger, &fs.path) { + diagnostics.error( + fs.path.clone(), + sig.line, + 0, + msg::fmt(msg::SCRIPT_TRIGGER_NOT_LOBBY, &[&sig.trigger]), + diagnostics::Phase::SymbolRegistration, + ); + } if sig.trigger == "command" { continue; } - if !trigger_table::is_valid_trigger(&sig.trigger) { + if scope != Scope::Lobby && !trigger_table::is_valid_trigger(&sig.trigger) { diagnostics.warning( fs.path.clone(), sig.line, @@ -1368,9 +1517,15 @@ fn resolve_pack_dir(scripts_dir: &Path, pack_dir: Option<&Path>) -> Option, + scope: Scope, ) -> Result> { - let config_files = sources::target_config_files(scripts_dir, Scope::Rune)?; - let engine_rs2 = sources::engine_file(scripts_dir, Scope::Rune)?; + let config_files = sources::target_config_files(scripts_dir, scope)?; + let engine_rs2 = sources::engine_file(scripts_dir, scope)?; + let commands = if scope == Scope::Lobby { + "ls2_command.pack" + } else { + "command.pack" + }; // Visibility reads every source and config, and only its indexing needs // the registry built meanwhile. let visibility = { @@ -1381,7 +1536,7 @@ fn build_symbol_registry( if let Some(pd) = resolved_pack_dir { info!(" Loading packs from {}", pd.display()); - symloader::load_packs(&mut registry, pd)?; + symloader::load_packs_with_commands(&mut registry, pd, commands)?; info!( " Loaded {} commands, {} game vars", registry.commands.len(), @@ -1438,6 +1593,7 @@ fn build_symbol_registry( /// Assign IDs and register the parsed scripts, reporting declaration errors. fn register_scripts( + scope: Scope, registry: &mut SymbolRegistry, ids: &mut ScriptIds, diagnostics: &mut DiagnosticsCollector, @@ -1463,11 +1619,22 @@ fn register_scripts( 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 scope == Scope::Lobby + && !trigger_table::is_lobby_trigger(&script.trigger, &pf.path) + { + diagnostics.error( + pf.path.clone(), + script.line, + 0, + msg::fmt(msg::SCRIPT_TRIGGER_NOT_LOBBY, &[&script.trigger]), + diagnostics::Phase::SymbolRegistration, + ); + } if script.trigger == "command" { continue; } - if !trigger_table::is_valid_trigger(&script.trigger) { + if scope != Scope::Lobby && !trigger_table::is_valid_trigger(&script.trigger) { diagnostics.warning( pf.path.clone(), script.line, @@ -1603,17 +1770,18 @@ type RecompiledOutput = (Vec>, DiagnosticsCollector); /// `compile_recompile_memory`) wrap this. On a phase error it prints diagnostics /// and returns `Err`, matching the batch path. fn recompile_to_encoded( + scope: Scope, scripts_dir: &Path, pack_dir: Option<&Path>, lint: bool, include_tests: bool, ids: &mut ScriptIds, ) -> Result> { - let source_dir = sources::target_dir(scripts_dir, sources::Scope::Rune); + let source_dir = sources::target_dir(scripts_dir, scope); let scripts_dir = source_dir.as_path(); use crate::pointer_checker::{PointerChecker, ScriptSource}; - let mut rs2_files: Vec = get_rs2_files(scripts_dir, "rs2")?; + let mut rs2_files: Vec = get_rs2_files(scripts_dir, scope.extension())?; rs2_files.sort(); info!("Found {} script files", rs2_files.len()); mem_mark("startup"); @@ -1658,8 +1826,8 @@ fn recompile_to_encoded( // Registration. 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, ids, &mut diagnostics, &file_sigs); + let mut registry = build_symbol_registry(scripts_dir, resolved_pack_dir.as_deref(), scope)?; + register_scripts_from_sigs(scope, &mut registry, ids, &mut diagnostics, &file_sigs); info!(" Registered {} scripts", registry.scripts.len()); registry.drop_registration_scratch(); for fs in &file_sigs { @@ -1845,13 +2013,20 @@ fn recompile_to_encoded( /// Full compile via the recompile (low-memory) pipeline: writes `script.dat` / /// `script.idx` to `output_dir`, then prints diagnostics. fn compile_recompile( + scope: Scope, scripts_dir: &Path, pack_dir: Option<&Path>, output_dir: &Path, lint: bool, ) -> Result<(), Box> { - let (encoded, diagnostics) = - recompile_to_encoded(scripts_dir, pack_dir, lint, false, &mut ScriptIds::new())?; + let (encoded, diagnostics) = recompile_to_encoded( + scope, + scripts_dir, + pack_dir, + lint, + false, + &mut ScriptIds::new(), + )?; info!( "Writing output to {}...", output_dir.display().to_string().replace('\\', "/") @@ -1866,6 +2041,7 @@ fn compile_recompile( /// `(script.dat, script.idx)` bytes, then prints diagnostics. Byte-identical to /// the in-memory batch path (`compile_memory*`). fn compile_recompile_memory( + scope: Scope, scripts_dir: &Path, pack_dir: Option<&Path>, lint: bool, @@ -1873,7 +2049,7 @@ fn compile_recompile_memory( ids: &mut ScriptIds, ) -> Result<(Vec, Vec), Box> { let (encoded, diagnostics) = - recompile_to_encoded(scripts_dir, pack_dir, lint, include_tests, ids)?; + recompile_to_encoded(scope, scripts_dir, pack_dir, lint, include_tests, ids)?; info!("Writing compiled output to memory..."); let out = ScriptWriter::new("".into()).build_encoded(&encoded); diagnostics.print_all(); diff --git a/src/ide/config.rs b/src/ide/config.rs index 0120bcb..65961f6 100644 --- a/src/ide/config.rs +++ b/src/ide/config.rs @@ -15,7 +15,7 @@ use std::path::Path; pub(super) fn entity_type(kind: &str) -> Option { match kind { - "command" | "cs2_command" => None, + "command" | "cs2_command" | "ls2_command" => None, "if" | "interface" | "overlayinterface" => Some(Type::Interface), "idk" => Some(Type::IdKit), "mesanim" => Some(Type::MesAnim), @@ -33,7 +33,7 @@ pub(super) fn key(kind: &str, name: &str) -> String { | "varclan" | "varobj" | "varnbit" | "varcon" | "varconbit" => { format!("gamevar:{name}") } - "command" | "cs2_command" => format!("command:{name}"), + "command" | "cs2_command" | "ls2_command" => format!("command:{name}"), _ => format!( "config:{}:{name}", entity_type(kind).map_or(kind, |ty| ty.name()) diff --git a/src/ide/index.rs b/src/ide/index.rs index cfc5190..665f8cf 100644 --- a/src/ide/index.rs +++ b/src/ide/index.rs @@ -44,9 +44,9 @@ pub(super) fn visible(symbol: &Symbol, document: &Document, offset: usize) -> bo if symbol.kind == SymbolKind::Command { return true; } - symbol - .scope - .is_none_or(|scope| scope == Scope::Global || scope == document.scope) + symbol.scope.is_none_or(|scope| { + scope == document.scope || (scope == Scope::Global && document.scope != Scope::Lobby) + }) } #[derive(Clone)] @@ -846,6 +846,7 @@ impl Index { "label" }; lookup(&key(Scope::Global, trigger, &token.value)) + .filter(|_| document.scope != Scope::Lobby) .or_else(|| lookup(&key(document.scope, trigger, &token.value))) } _ => { @@ -918,6 +919,7 @@ impl Index { .copied(); } keys.get(key(Scope::Global, trigger, &token.value).as_str()) + .filter(|_| document.scope != Scope::Lobby) .or_else(|| keys.get(key(document.scope, trigger, &token.value).as_str())) .copied() }; diff --git a/src/ide/queries.rs b/src/ide/queries.rs index 42b1306..18777b0 100644 --- a/src/ide/queries.rs +++ b/src/ide/queries.rs @@ -311,15 +311,13 @@ impl Project { let header = line.strip_prefix('[').filter(|line| !line.contains(']')); if header.is_some_and(|header| !header.contains(',')) { let names = self.registry.profile.as_ref().map_or_else( - || { - if self.target_scope() == Scope::Client { - triggers::TRIGGERS - .iter() - .map(|trigger| trigger.name) - .collect::>() - } else { - trigger_table::names().collect() - } + || match self.target_scope() { + Scope::Client => triggers::TRIGGERS + .iter() + .map(|trigger| trigger.name) + .collect::>(), + Scope::Lobby => trigger_table::lobby_names(&document.label).collect(), + _ => trigger_table::names().collect(), }, |profile| profile.triggers.keys().map(String::as_str).collect(), ); diff --git a/src/lib.rs b/src/lib.rs index b6d5344..c847294 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,8 +33,10 @@ pub mod filesystem; pub(crate) use filesystem::find_testscript_line; pub use filesystem::{ - ScriptIds, SourceProvider, compile, compile_memory, compile_memory_with_ids, - compile_memory_with_options, compile_memory_with_tests, compile_with_options, lint, + ScriptIds, SourceProvider, compile, compile_lobby, compile_lobby_memory, + compile_lobby_memory_with_ids, compile_lobby_memory_with_options, compile_lobby_with_options, + compile_memory, compile_memory_with_ids, compile_memory_with_options, + compile_memory_with_tests, compile_with_options, lint, lint_lobby, }; mod parallel; diff --git a/src/lsp.rs b/src/lsp.rs index 4a08469..b391a6c 100644 --- a/src/lsp.rs +++ b/src/lsp.rs @@ -255,7 +255,7 @@ fn uri_path(uri: &str) -> Option { fn script_only(label: &Path) -> bool { label .extension() - .is_some_and(|ext| matches!(ext.to_str(), Some("rs2" | "cs2" | "gs2"))) + .is_some_and(|ext| matches!(ext.to_str(), Some("rs2" | "cs2" | "gs2" | "ls2"))) && label .file_stem() .is_none_or(|stem| stem.to_string_lossy() != "engine") @@ -297,6 +297,7 @@ fn scope(value: &str) -> Result { "rune" | "rs2" | "runescript" => Ok(Scope::Rune), "client" | "cs2" | "clientscript" => Ok(Scope::Client), "global" | "gs2" | "globalscript" => Ok(Scope::Global), + "lobby" | "ls2" | "lobbyscript" => Ok(Scope::Lobby), _ => Err(format!("Unknown script language '{value}'")), } } @@ -340,16 +341,20 @@ pub fn project_from_json(value: &Value) -> Result { return Err(format!("Expected array '{name}'")); } } - let client = match value.get("target") { - None => false, - Some(Value::String(target)) if matches!(target.as_str(), "rune" | "rs2") => false, - Some(Value::String(target)) if matches!(target.as_str(), "client" | "cs2") => true, - _ => return Err("Expected target 'rune' or 'client'".into()), + let language = match value.get("target") { + None => Scope::Rune, + Some(Value::String(target)) if matches!(target.as_str(), "rune" | "rs2") => Scope::Rune, + Some(Value::String(target)) if matches!(target.as_str(), "client" | "cs2") => Scope::Client, + Some(Value::String(target)) if matches!(target.as_str(), "lobby" | "ls2") => Scope::Lobby, + _ => return Err("Expected target 'rune', 'client' or 'lobby'".into()), }; - let target = if client { - Target::Client(Format::parse(field(value, "opcodes")?).map_err(|error| error.to_string())?) - } else { - Target::Rune + let client = language == Scope::Client; + let target = match language { + Scope::Client => Target::Client( + Format::parse(field(value, "opcodes")?).map_err(|error| error.to_string())?, + ), + Scope::Lobby => Target::Lobby, + _ => Target::Rune, }; let mut registry = SymbolRegistry::new(); let mut visibility = Visibility::new(); @@ -924,7 +929,7 @@ impl Server { self.request_id += 1; write_message( output, - json!({"jsonrpc":"2.0","id":format!("runec/watch/{}",self.request_id),"method":"client/registerCapability","params":{"registrations":[{"id":"runec/files","method":"workspace/didChangeWatchedFiles","registerOptions":{"watchers":[{"globPattern":"**/*.{rs2,cs2,gs2,pack,constant,obj,npc,loc,inv,enum,struct,param,dbtable,dbrow,varp,varn,vars,varpbit,varc,seq,spotanim,mesanim,hunt,if,interface,idk,flo,flu,anim,mel,order,hashes,config*}","kind":7}]}}]}}), + json!({"jsonrpc":"2.0","id":format!("runec/watch/{}",self.request_id),"method":"client/registerCapability","params":{"registrations":[{"id":"runec/files","method":"workspace/didChangeWatchedFiles","registerOptions":{"watchers":[{"globPattern":"**/*.{rs2,cs2,gs2,ls2,pack,constant,obj,npc,loc,inv,enum,struct,param,dbtable,dbrow,varp,varn,vars,varpbit,varc,seq,spotanim,mesanim,hunt,if,interface,idk,flo,flu,anim,mel,order,hashes,config*}","kind":7}]}}]}}), )?; } let inspection_command = method == "workspace/executeCommand" @@ -1633,7 +1638,7 @@ impl Server { let source = self.source(params)?; if method == "textDocument/codeLens" { let document = self.project.document(source).unwrap(); - if document.scope != Scope::Global && document.scope != self.project.target_scope() { + if !self.project.includes(document.scope) { return Ok(json!([])); } let Some(syntax) = document.syntax() else { diff --git a/src/lsp/workspace.rs b/src/lsp/workspace.rs index b03e44d..1ddb144 100644 --- a/src/lsp/workspace.rs +++ b/src/lsp/workspace.rs @@ -17,7 +17,7 @@ pub fn serve_workspace_with_loaders(loaders: Vec<(Scope, ProjectLoader)>) -> io: { return Err(io::Error::new( io::ErrorKind::InvalidInput, - "A workspace requires one loader per available server/client target", + "A workspace requires one loader per available server/client/lobby target", )); } serve_host(Workspace::new( @@ -47,6 +47,7 @@ fn target_name(scope: Scope) -> &'static str { Scope::Rune => "rune", Scope::Client => "client", Scope::Global => "global", + Scope::Lobby => "lobby", } } @@ -55,6 +56,7 @@ fn target_label(scope: Scope) -> &'static str { Scope::Rune => "server", Scope::Client => "client", Scope::Global => "shared", + Scope::Lobby => "lobby", } } @@ -106,12 +108,22 @@ impl Workspace { .unwrap_or(Scope::Global) } + /// Shared configs reach every context; .gs2 sources are not lobbyscript. + fn accepts(&self, uri: &str, target: Scope) -> bool { + let scope = self.document_scope(uri); + scope == target + || (scope == Scope::Global + && (target != Scope::Lobby + || extension_scope(uri) + .or_else(|| self.languages.get(&uri_key(uri)).copied()) + .is_none())) + } + fn targets(&self, uri: Option<&str>) -> Vec { - let scope = uri.map_or(Scope::Global, |uri| self.document_scope(uri)); self.contexts .iter() .enumerate() - .filter(|(_, context)| scope == Scope::Global || context.scope == scope) + .filter(|(_, context)| uri.is_none_or(|uri| self.accepts(uri, context.scope))) .map(|(index, _)| index) .collect() } @@ -386,8 +398,7 @@ impl Workspace { continue; }; let key = uri_key(uri); - let scope = self.document_scope(uri); - if scope == Scope::Global || scope == self.contexts[index].scope { + if self.accepts(uri, self.contexts[index].scope) { self.contexts[index] .diagnostics .insert(key.clone(), message["params"].clone()); @@ -433,10 +444,9 @@ impl Workspace { continue; }; let uri = first["uri"].as_str().unwrap(); - let scope = self.document_scope(uri); let version = entries .iter() - .filter(|(index, _)| scope == Scope::Global || scope == self.contexts[*index].scope) + .filter(|(index, _)| self.accepts(uri, self.contexts[*index].scope)) .filter_map(|(_, value)| value["version"].as_i64()) .max(); let diagnostics = self.diagnostics( @@ -444,7 +454,7 @@ impl Workspace { entries .iter() .filter(|(index, value)| { - (scope == Scope::Global || scope == self.contexts[*index].scope) + self.accepts(uri, self.contexts[*index].scope) && (value["version"].as_i64().is_none() || value["version"].as_i64() == version) }) @@ -597,10 +607,13 @@ impl Host for Workspace { .is_some_and(|name| name == "engine"); targets.retain(|&index| { let target = self.contexts[index].scope; - scope == Scope::Global || scope == target - // The server's index needs current callback declarations; - // its engine commands remain independent of client commands. - || (scope == Scope::Client && target == Scope::Rune && !engine) + (scope == Scope::Global && target != Scope::Lobby) + || scope == target + // Server and lobby indexes need current callback declarations; + // their engine commands remain independent of client commands. + || (scope == Scope::Client + && matches!(target, Scope::Rune | Scope::Lobby) + && !engine) }); } if method == "workspace/executeCommand" { diff --git a/src/lsp/workspace/tests.rs b/src/lsp/workspace/tests.rs index 5fd7acb..f3a254c 100644 --- a/src/lsp/workspace/tests.rs +++ b/src/lsp/workspace/tests.rs @@ -446,3 +446,107 @@ fn interleaved_preview_replies_return_to_their_own_target() { fs::remove_file(path).unwrap(); } } + +fn lobby_workspace() -> Workspace { + let mut workspace = workspace(); + let environment = json!({ + "target":"lobby", + "commands":[ + {"name":"pulse","opcode":9000,"params":["int"],"returns":[]}, + {"name":"lobby_only","opcode":79,"params":[],"returns":[]} + ] + }); + let project = project_from_json(&environment).unwrap(); + let loader: ProjectLoader = Box::new(move || project_from_json(&environment)); + workspace.contexts.push(Context { + scope: Scope::Lobby, + server: Server::new(Some(project), Some(loader)), + diagnostics: HashMap::new(), + }); + workspace +} + +#[test] +fn lobby_sources_route_only_to_the_lobby_context() { + let mut workspace = lobby_workspace(); + let sent = initialize(&mut workspace); + let watcher = sent + .iter() + .find(|message| message["method"] == "client/registerCapability") + .unwrap(); + assert!( + watcher["params"]["registrations"][0]["registerOptions"]["watchers"][0]["globPattern"] + .as_str() + .unwrap() + .contains(",ls2,") + ); + for (index, (uri, language)) in [ + ("file:///game/scripts/bank/clientscript/lobby.ls2", "cs2"), + ("untitled:lobby", "ls2"), + ("untitled:lobbyscript", "lobbyscript"), + ] + .into_iter() + .enumerate() + { + open( + &mut workspace, + uri, + language, + &format!("[proc,entry{index}]\nlobby_only;\n"), + ); + let sent = send( + &mut workspace, + json!({"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{"textDocument":{"uri":uri}}}), + ); + assert_eq!(response(&sent, 2)["items"], json!([])); + assert_eq!(workspace.document_scope(uri), Scope::Lobby); + for context in &workspace.contexts { + let found = context.server.find(uri); + assert_eq!(found.is_some(), context.scope == Scope::Lobby, "{uri}"); + if let Some(id) = found { + assert_eq!( + context.server.project.document(id).unwrap().scope, + Scope::Lobby + ); + } + } + } + let uri = "file:///game/scripts/lobby/server.ls2"; + open( + &mut workspace, + uri, + "ls2", + "[proc,server_entry]\nserver_only;\n", + ); + let sent = send( + &mut workspace, + json!({"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{"textDocument":{"uri":uri}}}), + ); + let items = response(&sent, 3)["items"].as_array().unwrap(); + assert!( + items + .iter() + .any(|item| item["message"].as_str().unwrap().contains("server_only")), + "{items:?}" + ); + + let shared = "file:///game/scripts/bank/shared.gs2"; + open(&mut workspace, shared, "gs2", "[proc,shared]\nreturn;\n"); + let config = "file:///game/scripts/bank/limits.constant"; + open(&mut workspace, config, "rs2config", "^limit=1\n"); + let callback = "file:///game/scripts/bank/refresh.cs2"; + open( + &mut workspace, + callback, + "cs2", + "[clientscript,refresh]\nreturn;\n", + ); + for context in &workspace.contexts { + assert_eq!( + context.server.find(shared).is_some(), + context.scope != Scope::Lobby + ); + assert!(context.server.find(config).is_some()); + assert!(context.server.find(callback).is_some()); + } +} diff --git a/src/main.rs b/src/main.rs index 0ec3d93..e6d62d3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -33,6 +33,9 @@ enum Commands { /// Restrict the language server to RuneScript and GlobalScript #[arg(long, requires = "source")] server: bool, + /// Restrict the language server to LobbyScript + #[arg(long, conflicts_with_all = ["client", "server"], requires = "source")] + lobby: bool, }, /// Compile .cs2 sources to individual cache script files CompileClient { @@ -71,6 +74,34 @@ enum Commands { #[arg(long)] pack: Option, }, + /// Compile all .ls2 scripts to binary output for the lobby server + CompileLobby { + /// Source directory containing .ls2 files + #[arg(short, long)] + source: String, + /// Output directory for compiled scripts + #[arg(short, long, default_value = "./data/pack/lobby")] + output: String, + /// Pack directory (overrides auto-detection) + #[arg(long)] + pack: Option, + /// Run lint passes (unused locals, unreachable code) after compilation + #[arg(long, default_value_t = false)] + lint: bool, + /// Trade compilation time for lower peak memory by recompiling scripts + /// on demand. Output is byte-identical to normal compilation. + #[arg(long, visible_alias = "recompile", default_value_t = false)] + low_mem: bool, + }, + /// Run all analysis passes on .ls2 scripts without writing output + LintLobby { + /// Source directory containing .ls2 files + #[arg(short, long)] + source: String, + /// Pack directory (overrides auto-detection) + #[arg(long)] + pack: Option, + }, } fn main() -> Result<(), Box> { @@ -102,6 +133,7 @@ fn run() -> Result<(), Box> { pack, client, server, + lobby, } => { if let Some(source) = source { let source = sources::source_root(&source); @@ -112,10 +144,15 @@ fn run() -> Result<(), Box> { let has_server = files .iter() .any(|path| Scope::from_path(path) == Some(Scope::Rune)); + let has_lobby = files + .iter() + .any(|path| path.file_name().is_some_and(|name| name == "engine.ls2")); let targets = if client { vec![Scope::Client] } else if server { vec![Scope::Rune] + } else if lobby { + vec![Scope::Lobby] } else { let mut targets = Vec::new(); if has_server || !has_client { @@ -124,6 +161,9 @@ fn run() -> Result<(), Box> { if has_client { targets.push(Scope::Client); } + if has_lobby { + targets.push(Scope::Lobby); + } targets }; runec::lsp::serve_workspace_with_loaders( @@ -134,10 +174,10 @@ fn run() -> Result<(), Box> { let pack = pack.clone(); let loader: Box Result> = Box::new(move || { - runec::filesystem::editor_project( + runec::filesystem::editor_project_for_scope( &source, pack.as_deref(), - scope == Scope::Client, + scope, ) .map_err(|error| error.to_string()) }); @@ -183,6 +223,29 @@ fn run() -> Result<(), Box> { let pack_dir = pack.map(PathBuf::from); runec::lint(&scripts_dir, pack_dir.as_deref())?; } + Commands::CompileLobby { + source, + output, + pack, + lint, + low_mem, + } => { + let scripts_dir = PathBuf::from(source); + let pack_dir = pack.map(PathBuf::from); + let output_dir = PathBuf::from(output); + runec::compile_lobby_with_options( + &scripts_dir, + pack_dir.as_deref(), + &output_dir, + lint, + low_mem, + )?; + } + Commands::LintLobby { source, pack } => { + let scripts_dir = PathBuf::from(source); + let pack_dir = pack.map(PathBuf::from); + runec::lint_lobby(&scripts_dir, pack_dir.as_deref())?; + } } #[cfg(feature = "memprof")] diff --git a/src/opcodes.rs b/src/opcodes.rs index 7d80e28..d1ff38a 100644 --- a/src/opcodes.rs +++ b/src/opcodes.rs @@ -120,7 +120,6 @@ opcodes! { PROJANIM_HALFSQ = 1026 => "projanim_halfsq"; SOUND_VORBIS_AREA = 1027 => "sound_vorbis_area"; TEXT_COORD = 1028 => "text_coord"; - MAP_LOBBY = 1029 => "map_lobby"; // Player AFK_EVENT = 2000 => "afk_event"; diff --git a/src/pointer.rs b/src/pointer.rs index 0864a56..3e6404b 100644 --- a/src/pointer.rs +++ b/src/pointer.rs @@ -1663,16 +1663,6 @@ fn build_command_pointers() -> HashMap { &[], false, ); - add( - "map_lobby", - &[ActivePlayer], - &[], - &[], - &[ActivePlayer2], - &[], - &[], - false, - ); add( "staffmodlevel", &[ActivePlayer], diff --git a/src/project.rs b/src/project.rs index ffcde40..451014a 100644 --- a/src/project.rs +++ b/src/project.rs @@ -14,7 +14,10 @@ use crate::text::LineIndex; use crate::token::Kind; use crate::typechecker::TypeChecker; use crate::writer::encode_script; -use crate::{SourceProvider, lints, parallel_chunks, parallel_map_balanced}; +use crate::{ + SourceProvider, diagnostic_messages as msg, lints, parallel_chunks, parallel_map_balanced, + trigger_table, +}; use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, HashMap, HashSet}; use std::hash::{Hash, Hasher}; @@ -34,15 +37,17 @@ pub type SourceText = (String, Scope, i64, String); pub enum Target { Rune, Client(Format), + /// Server bytecode for lobbyscript, which compiles no .gs2. + Lobby, } impl Target { fn includes(&self, scope: Scope) -> bool { - scope == Scope::Global - || matches!( - (self, scope), - (Self::Rune, Scope::Rune) | (Self::Client(_), Scope::Client) - ) + match self { + Self::Rune => matches!(scope, Scope::Rune | Scope::Global), + Self::Client(_) => matches!(scope, Scope::Client | Scope::Global), + Self::Lobby => scope == Scope::Lobby, + } } } @@ -183,8 +188,12 @@ impl Project { match self.target { Target::Rune => Scope::Rune, Target::Client(_) => Scope::Client, + Target::Lobby => Scope::Lobby, } } + pub(crate) fn includes(&self, scope: Scope) -> bool { + self.target.includes(scope) + } pub(crate) fn analysis_cancelled(&self) -> bool { self.options.cancellation.is_cancelled() } @@ -430,6 +439,18 @@ impl Project { continue; }; for script in &source.file.scripts { + if document.scope == Scope::Lobby + && !trigger_table::is_lobby_trigger(&script.trigger, &document.label) + { + diagnostics.error( + document.label.clone(), + script.line, + 1, + msg::fmt(msg::SCRIPT_TRIGGER_NOT_LOBBY, &[&script.trigger]), + Phase::SymbolRegistration, + ); + continue; + } if script.trigger == "command" { continue; } @@ -702,7 +723,7 @@ impl Project { if check_pointers { let mut checker = match self.target { Target::Client(_) => PointerChecker::new_client(&compiled, &self.registry), - Target::Rune => PointerChecker::new(&compiled, &self.registry), + Target::Rune | Target::Lobby => PointerChecker::new(&compiled, &self.registry), }; checker.set_source_cache(source); let names = compiled @@ -726,7 +747,7 @@ impl Project { } let document = &self.documents[&id]; let bytes = match &self.target { - Target::Rune => Ok(encode_script(&script)), + Target::Rune | Target::Lobby => Ok(encode_script(&script)), Target::Client(format) => clientscript::encode(&script, format), }; match bytes { diff --git a/src/sources.rs b/src/sources.rs index 0b50150..2eafcd6 100644 --- a/src/sources.rs +++ b/src/sources.rs @@ -15,6 +15,7 @@ pub enum Scope { Rune = 1, Client = 2, Global = 4, + Lobby = 8, } impl Scope { @@ -23,6 +24,7 @@ impl Scope { Self::Rune => "runescript", Self::Client => "clientscript", Self::Global => "globalscript", + Self::Lobby => "lobbyscript", } } @@ -31,6 +33,7 @@ impl Scope { Self::Rune => "rs2", Self::Client => "cs2", Self::Global => "gs2", + Self::Lobby => "ls2", } } @@ -39,12 +42,13 @@ impl Scope { "rs2" => Some(Self::Rune), "cs2" => Some(Self::Client), "gs2" => Some(Self::Global), + "ls2" => Some(Self::Lobby), _ => None, } } /// Scripts use their extension. Configs and constants default to shared; - /// a leading `// @scope(server|client|shared)` comment can restrict them. + /// a leading `// @scope(server|client|lobby|shared)` comment can restrict them. pub fn for_file(path: &Path, text: &str) -> io::Result { if let Some(scope) = Self::from_path(path) { return Ok(scope); @@ -68,12 +72,13 @@ impl Scope { let declared = match value.map(str::trim) { Some("server") => Self::Rune, Some("client") => Self::Client, + Some("lobby") => Self::Lobby, Some("shared") => Self::Global, _ => { return Err(io::Error::new( io::ErrorKind::InvalidData, format!( - "{}: expected // @scope(server|client|shared)", + "{}: expected // @scope(server|client|lobby|shared)", path.display() ), )); @@ -158,7 +163,7 @@ pub fn script_files(dir: &Path, extension: &str) -> io::Result> { files.retain(|path| { path.extension() .and_then(|ext| ext.to_str()) - .is_some_and(|ext| ext == extension || ext == "gs2") + .is_some_and(|ext| ext == extension || (ext == "gs2" && extension != "ls2")) }); Ok(files) } @@ -199,7 +204,7 @@ fn declarations(file: &Path) -> Vec<(String, String)> { let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else { return declared; }; - let is_script = matches!(ext, "rs2" | "cs2" | "gs2"); + let is_script = matches!(ext, "rs2" | "cs2" | "gs2" | "ls2"); if !is_script && ext != "constant" && !Type::from_name(ext).is_some_and(|ty| config_kind(ty).is_some()) @@ -261,6 +266,13 @@ fn declarations(file: &Path) -> Vec<(String, String)> { declared } +/// Script declarations, as opposed to configs, constants and game vars. +fn script_kind(kind: &str) -> bool { + (crate::trigger_table::is_valid_trigger(kind) + || crate::clientscript::triggers::lookup(kind).is_some()) + && !Type::from_name(kind).is_some_and(|ty| config_kind(ty).is_some()) +} + fn config_kind(ty: Type) -> Option<&'static str> { match ty { Type::NamedObj | Type::Obj => Some("obj"), @@ -327,7 +339,7 @@ impl Visibility { self.documents.remove(label); } - fn scope(&self, label: &Path) -> Option { + pub(crate) fn scope(&self, label: &Path) -> Option { self.documents .get(label) .copied() @@ -488,9 +500,16 @@ impl Visibility { .and_then(|names| names.get(name)) .copied() .unwrap_or(0); + // Lobbyscript shares configs with every target but compiles no .gs2. + let script = scope == Scope::Lobby && script_kind(kind); + let private = match scope { + Scope::Lobby if script => 0, + Scope::Lobby => Scope::Lobby as u8, + _ => Scope::Rune as u8 | Scope::Client as u8, + }; if (kind == "constant" || kind == "proc") && owners & Scope::Global as u8 != 0 - && owners & (Scope::Rune as u8 | Scope::Client as u8) != 0 + && owners & private != 0 { return Some(format!( "{kind} '{name}' is declared in both shared and private scopes; keep one shared declaration" @@ -499,11 +518,18 @@ impl Visibility { if owners == 0 && !required { return None; } - if owners & (scope as u8 | Scope::Global as u8) != 0 { + let shared = if script { 0 } else { Scope::Global as u8 }; + if owners & (scope as u8 | shared) != 0 { return None; } let allowed = if scope == Scope::Global { "a .gs2 source or shared config".to_owned() + } else if scope == Scope::Lobby { + if script { + "a .ls2 source".to_owned() + } else { + "a .ls2 source, or a shared or @scope(lobby) config".to_owned() + } } else { format!( "a .{} or .gs2 source, or a visible config", diff --git a/src/symloader.rs b/src/symloader.rs index afaef40..c1f0c0b 100644 --- a/src/symloader.rs +++ b/src/symloader.rs @@ -135,6 +135,15 @@ pub fn patch_command_return_types(registry: &mut SymbolRegistry) { /// This matches how 2004scape's Compiler.ts loads CompilerTypeInfo from pack files. /// Fails when `command.pack` gives a command an opcode other than its own. pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) -> Result<(), String> { + load_packs_with_commands(registry, pack_dir, "command.pack") +} + +/// [`load_packs`] with another `opcode=name` command pack, such as `ls2_command.pack`. +pub(crate) fn load_packs_with_commands( + registry: &mut SymbolRegistry, + pack_dir: &Path, + commands: &str, +) -> Result<(), String> { if !pack_dir.exists() { return Ok(()); } @@ -143,7 +152,7 @@ pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) -> Result<(), // Pack files loaded below may overwrite these with content-specific values. register_engine_constants(registry); - load_commands(registry, &pack_dir.join("command.pack"))?; + load_commands(registry, &pack_dir.join(commands))?; load_clientscript_pack(registry, &pack_dir.join("clientscript.pack")); load_game_vars(registry, &pack_dir.join("varp.pack"), "varp"); @@ -1232,8 +1241,8 @@ fn register_engine_constants(registry: &mut SymbolRegistry) { ("runecraft", 20), ("hunter", 21), ("construction", 22), - ("summoning", 23), - ("dungeoneering", 24), + ("animallore", 23), + ("rand", 24), ]; for &(name, id) in stats { registry.register_entity_id(name.to_string(), Type::Stat, id); diff --git a/src/trigger_table.rs b/src/trigger_table.rs index df4e690..7628f1a 100644 --- a/src/trigger_table.rs +++ b/src/trigger_table.rs @@ -15,6 +15,7 @@ use crate::types::Type; use std::collections::HashMap; +use std::path::Path; use std::sync::OnceLock; #[derive(Debug, Clone, Copy)] @@ -385,6 +386,27 @@ const NAME_KEYED_TRIGGERS: &[&str] = &[ // yet standardized in the reference implementation. const EXTENDED_TRIGGERS: &[&str] = &["switch_window_mode"]; +// Lobbyscript accepts only these, with their server bytes. +const LOBBY_TRIGGERS: &[&str] = &[ + "proc", + "label", + "login", + "logout", + "if_button", + "if_button1", + "if_button2", + "if_button3", + "if_button4", + "if_button5", + "if_button6", + "if_button7", + "if_button8", + "if_button9", + "if_button10", + "if_buttond", + "if_close", +]; + // ── Public lookup API ──────────────────────────────────────────────── fn table() -> &'static HashMap<&'static str, TriggerInfo> { @@ -426,6 +448,22 @@ pub fn is_valid_trigger(name: &str) -> bool { || EXTENDED_TRIGGERS.contains(&name) } +// `command` declares engine signatures, so only engine.ls2 takes it. +pub fn is_lobby_trigger(name: &str, path: &Path) -> bool { + LOBBY_TRIGGERS.contains(&name) || name == "command" && is_lobby_engine(path) +} + +pub fn lobby_names(path: &Path) -> impl Iterator { + LOBBY_TRIGGERS + .iter() + .copied() + .chain(is_lobby_engine(path).then_some("command")) +} + +fn is_lobby_engine(path: &Path) -> bool { + path.file_name().is_some_and(|file| file == "engine.ls2") +} + pub fn allows_returns(name: &str) -> bool { matches!(name, "proc" | "clientscript" | "command" | "logout") } @@ -442,6 +480,13 @@ mod tests { } } + #[test] + fn lobby_triggers_are_server_triggers() { + for name in lobby_names(Path::new("engine.ls2")) { + assert!(is_valid_trigger(name), "{name} is not a server trigger"); + } + } + #[test] fn button_triggers_match_legacy_set() { // Locks in pointer_checker's old hand-maintained list. diff --git a/src/typechecker.rs b/src/typechecker.rs index 6f26bd7..16ea7a8 100644 --- a/src/typechecker.rs +++ b/src/typechecker.rs @@ -6,6 +6,8 @@ use crate::compiler::Compiler; use crate::diagnostic_messages as msg; use crate::diagnostics::{DiagnosticsCollector, Phase}; use crate::parser::*; +use crate::pointer::{PointerSet, PointerType, default_command_pointers}; +use crate::sources::Scope; use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable}; use crate::types::{BaseVarType, Type}; use std::collections::HashSet; @@ -41,6 +43,7 @@ pub struct TypeChecker<'a> { file_path: PathBuf, current_script_is_test: bool, current_script_is_proc: bool, + lobby: bool, } impl<'a> TypeChecker<'a> { @@ -52,6 +55,7 @@ impl<'a> TypeChecker<'a> { file_path: PathBuf::new(), current_script_is_test: false, current_script_is_proc: false, + lobby: false, } } @@ -66,6 +70,7 @@ impl<'a> TypeChecker<'a> { testscript_line: Option, ) { self.file_path = file_path.to_path_buf(); + self.lobby = self.registry.visibility.scope(file_path) == Some(Scope::Lobby); for script in &file.scripts { self.current_script_is_test = match testscript_line { Some(ts_line) => script.line >= ts_line, @@ -75,6 +80,35 @@ impl<'a> TypeChecker<'a> { } } + /// A dot form, or a command that needs `.active_player`. + fn secondary_pointer(&self, expr: &Expr) -> Option { + let name = match expr { + Expr::GameVar(name, _) => { + return name.strip_prefix('.').map(|name| format!(".%{name}")); + } + Expr::CommandCall { name, .. } => name, + Expr::Identifier(name) + if self + .registry + .lookup_command(name.trim_start_matches('.')) + .is_some() => + { + name + } + _ => return None, + }; + let pointers = match &self.registry.profile { + Some(profile) => profile.command_pointers.get(name.as_str()), + None => default_command_pointers().get(name.as_str()), + }; + let secondary = |set: PointerSet| { + set.contains(PointerType::ActivePlayer2) || set.contains(PointerType::PActivePlayer2) + }; + (name.starts_with('.') + || pointers.is_some_and(|holder| secondary(holder.required) || secondary(holder.set))) + .then(|| name.clone()) + } + fn is_test_command(name: &str) -> bool { TEST_COMMAND_PREFIXES .iter() @@ -878,6 +912,15 @@ impl<'a> TypeChecker<'a> { self.error(line, message); return Some(Type::Error); } + if self.lobby + && let Some(form) = self.secondary_pointer(expr) + { + let at = match expr { + Expr::GameVar(_, at) | Expr::CommandCall { call_line: at, .. } if *at > 0 => *at, + _ => line, + }; + self.error(at, msg::fmt(msg::LOBBY_SECONDARY_POINTER, &[&form])); + } match expr { Expr::IntLiteral(_) => { // Matching TS visitIntegerLiteral: if hint is a non-literal type, diff --git a/tests/lobbyscript_test.rs b/tests/lobbyscript_test.rs new file mode 100644 index 0000000..a24f90b --- /dev/null +++ b/tests/lobbyscript_test.rs @@ -0,0 +1,631 @@ +use runec::ScriptIds; +use runec::clientscript; +use runec::filesystem::{editor_project, editor_project_for_scope}; +use runec::project::{Options, Project, Target}; +use runec::sources::{self, Scope}; +use runec::symbol::SymbolRegistry; +use runec::types::Type; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const LOBBY: &str = "[proc,lobby_entry]()(int) +mes(\"welcome\"); +return(~lobby_helper); +[proc,lobby_helper]()(int) +return(^shared); +"; + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let root = Path::new(env!("CARGO_TARGET_TMPDIR")) + .join("lobbyscript") + .join(format!( + "lobbyscript-{}-{}", + process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + let fixture = Self(root); + for (path, text) in [ + ("pack/command.pack", "2062=mes\n2071=p_delay\n"), + ("pack/ls2_command.pack", "2062=mes\n"), + ("pack/obj.pack", "1=shared_obj\n"), + ("pack/varp.pack", "1=shared_var\n"), + ("pack/varc.pack", "1=shared_varc\n"), + ("pack/interface.pack", "1=lobby_panel\n1:2=button\n"), + ( + "pack/clientscript.pack", + "1=[proc,shared]\n2=[proc,client_entry]\n", + ), + ( + "pack/cs2_command.pack", + "0=PushConstantInt\n1=PushVarp\n21=Return\n40=GosubWithParams\n", + ), + ("scripts/values.constant", "^shared = 42\n"), + ("scripts/items.obj", "[shared_obj]\n"), + ("scripts/vars.varp", "[shared_var]\ntype=int\n"), + ("scripts/vars.varc", "[shared_varc]\ntype=int\n"), + ( + "scripts/engine.rs2", + "[command,mes](string $text)\n[command,p_delay](int $delay)\n", + ), + ("scripts/lobby/engine.ls2", "[command,mes](string $text)\n"), + ("scripts/client/engine.cs2", ""), + ( + "scripts/global/shared.gs2", + "[proc,shared]()(int) return(^shared);\n", + ), + ( + "scripts/server/main.rs2", + "[proc,rune_entry]()(int) return(~shared);\n", + ), + ( + "scripts/client/main.cs2", + "[proc,client_entry]()(int) return(~shared);\n", + ), + ("scripts/lobby/main.ls2", LOBBY), + ] { + fixture.write(path, text); + } + fixture + } + + fn write(&self, relative: &str, text: &str) { + let path = self.0.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + + fn scripts(&self) -> PathBuf { + self.0.join("scripts") + } + + fn pack(&self) -> PathBuf { + self.0.join("pack") + } + + fn rune(&self) -> Result<(Vec, Vec), String> { + runec::compile_memory(&self.scripts(), Some(&self.pack()), false) + .map_err(|error| error.to_string()) + } + + fn client(&self) -> Result>, String> { + clientscript::compile_directory(&self.scripts(), &self.pack()) + .map(|compiled| compiled.into_values().collect()) + .map_err(|error| error.to_string()) + } + + /// Both lobby pipelines: batch, and the low-memory one that registers from signatures. + fn lobby(&self) -> bool { + let normal = runec::compile_lobby_memory(&self.scripts(), Some(&self.pack()), false); + let low_memory = runec::compile_lobby_memory_with_options( + &self.scripts(), + Some(&self.pack()), + false, + false, + true, + ); + assert_eq!(normal.is_ok(), low_memory.is_ok()); + if let (Ok(normal), Ok(low_memory)) = (&normal, &low_memory) { + assert_eq!(normal, low_memory); + } + normal.is_ok() + } + + fn errors(&self, scope: Scope) -> Vec { + let mut project = editor_project_for_scope(&self.scripts(), Some(&self.pack()), scope) + .unwrap_or_else(|error| panic!("{scope:?} project: {error}")); + project + .check() + .diagnostics + .errors() + .into_iter() + .map(|diagnostic| diagnostic.message.clone()) + .collect() + } + + fn assert_lobby_error(&self, expected: &str) { + assert!(!self.lobby(), "lobby accepted: {expected}"); + let errors = self.errors(Scope::Lobby); + assert!( + errors.iter().any(|error| error.contains(expected)), + "{expected}: {errors:?}" + ); + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let root = self.0.canonicalize().unwrap(); + let workspace = Path::new(env!("CARGO_TARGET_TMPDIR")) + .canonicalize() + .unwrap(); + assert!(root.starts_with(&workspace) && root != workspace); + fs::remove_dir_all(root).unwrap(); + } +} + +fn idx_slots(idx: &[u8]) -> u32 { + u32::from_be_bytes(idx[..4].try_into().unwrap()) +} + +#[test] +fn lobby_scope_follows_the_ls2_extension() { + let fixture = Fixture::new(); + assert_eq!(Scope::from_path(Path::new("main.ls2")), Some(Scope::Lobby)); + assert_eq!(Scope::Lobby.extension(), "ls2"); + assert_eq!(Scope::Lobby.folder(), "lobbyscript"); + assert_eq!( + Scope::for_file(Path::new("runescript/main.ls2"), "// @scope(server)\n").unwrap(), + Scope::Lobby + ); + assert_eq!( + Scope::for_file(Path::new("lobby.constant"), "// @scope(lobby)\n").unwrap(), + Scope::Lobby + ); + let error = Scope::for_file(Path::new("bad.constant"), "// @scope(lobyb)\n") + .unwrap_err() + .to_string(); + assert!( + error.contains("@scope(server|client|lobby|shared)"), + "{error}" + ); + let scripts = fixture.scripts(); + assert_eq!( + sources::script_files(&scripts, "ls2").unwrap(), + vec![ + scripts.join("lobby/engine.ls2"), + scripts.join("lobby/main.ls2") + ] + ); + for extension in ["rs2", "cs2"] { + let files = sources::script_files(&scripts, extension).unwrap(); + assert!(files.iter().any(|path| path.ends_with("global/shared.gs2"))); + assert!( + !files + .iter() + .any(|path| path.extension().is_some_and(|ext| ext == "ls2")) + ); + } + assert_eq!( + sources::engine_file(&scripts, Scope::Lobby).unwrap(), + Some(scripts.join("lobby/engine.ls2")) + ); +} + +#[test] +fn lobby_procs_compile_to_server_bytecode() { + let fixture = Fixture::new(); + assert!(fixture.lobby()); + let (dat, idx) = + runec::compile_lobby_memory(&fixture.scripts(), Some(&fixture.pack()), false).unwrap(); + assert_eq!(idx_slots(&idx), 2); + assert_eq!(dat[..4], idx[..4]); + assert!(fixture.errors(Scope::Lobby).is_empty()); + + let output = fixture.0.join("out"); + runec::compile_lobby(&fixture.scripts(), Some(&fixture.pack()), &output, false).unwrap(); + assert_eq!(fs::read(output.join("script.dat")).unwrap(), dat); + assert_eq!(fs::read(output.join("script.idx")).unwrap(), idx); + runec::lint_lobby(&fixture.scripts(), Some(&fixture.pack())).unwrap(); + + let compile = |target: Target, scope: Scope| { + let mut registry = SymbolRegistry::new(); + registry.register_command("mes".into(), 2062, vec![Type::String], vec![]); + let mut project = Project::new(target, registry, Options::default()); + project.open("memory:main", scope, 1, LOBBY.replace("^shared", "42")); + let compilation = project.compile(); + assert!( + !compilation.analysis.diagnostics.has_errors(), + "{:?}", + compilation.analysis.diagnostics + ); + compilation + .artifacts + .into_iter() + .map(|artifact| (artifact.name, artifact.bytes)) + .collect::>() + }; + let lobby = compile(Target::Lobby, Scope::Lobby); + assert_eq!(lobby.len(), 2); + assert_eq!(lobby, compile(Target::Rune, Scope::Rune)); +} + +#[test] +fn server_and_client_builds_ignore_lobby_sources() { + let fixture = Fixture::new(); + let rune = fixture.rune().unwrap(); + let client = fixture.client().unwrap(); + fixture.write( + "scripts/lobby/main.ls2", + "[proc,lobby_entry]\nnot_a_command(;\n[opnpc1,nothing]\n", + ); + assert_eq!(fixture.rune().unwrap(), rune); + assert_eq!(fixture.client().unwrap(), client); + for scope in [Scope::Rune, Scope::Client] { + assert!(fixture.errors(scope).is_empty(), "{scope:?}"); + } + fixture.write("scripts/lobby/main.ls2", LOBBY); + + fixture.write( + "scripts/server/main.rs2", + "[proc,rune_entry]()(int) return(~lobby_entry);\n", + ); + assert!(fixture.rune().is_err()); + let errors = fixture.errors(Scope::Rune); + assert!( + errors + .iter() + .any(|error| error.contains("proc 'lobby_entry' is not visible to runescript")), + "{errors:?}" + ); + fixture.write( + "scripts/server/main.rs2", + "[proc,rune_entry]()(int) return(~shared);\n", + ); + + fixture.write( + "scripts/client/main.cs2", + "[proc,client_entry]()(int) return(~lobby_entry);\n", + ); + let error = fixture.client().unwrap_err(); + assert!( + error.contains("proc 'lobby_entry' is not visible to clientscript"), + "{error}" + ); + fixture.write( + "scripts/global/shared.gs2", + "[proc,shared]()(int) return(~lobby_entry);\n", + ); + assert!(fixture.rune().is_err()); + assert!(fixture.lobby()); +} + +#[test] +fn lobby_sees_shared_configs_but_not_other_scripts() { + let fixture = Fixture::new(); + fixture.write( + "scripts/lobby/configs.ls2", + "[proc,lobby_configs]()(int, component, obj, int, int) +return(^shared, lobby_panel:button, shared_obj, %shared_var, %shared_varc); +", + ); + assert!(fixture.lobby()); + assert!(fixture.errors(Scope::Lobby).is_empty()); + for (callee, expected) in [ + ( + "shared", + "proc 'shared' is not visible to lobbyscript; define it in a .ls2 source", + ), + ( + "rune_entry", + "proc 'rune_entry' is not visible to lobbyscript; define it in a .ls2 source", + ), + ( + "client_entry", + "proc 'client_entry' is not visible to lobbyscript; define it in a .ls2 source", + ), + ] { + fixture.write( + "scripts/lobby/configs.ls2", + &format!("[proc,lobby_call]()(int) return(~{callee});\n"), + ); + fixture.assert_lobby_error(expected); + } + fixture.write( + "scripts/server/private.constant", + "// @scope(server)\n^server_only = 1\n", + ); + fixture.write( + "scripts/lobby/configs.ls2", + "[proc,lobby_call]()(int) return(^server_only);\n", + ); + fixture.assert_lobby_error("constant 'server_only' is not visible to lobbyscript"); + fixture.write( + "scripts/lobby/private.constant", + "// @scope(lobby)\n^lobby_only = 1\n", + ); + fixture.write( + "scripts/lobby/configs.ls2", + "[proc,lobby_call]()(int) return(^lobby_only);\n", + ); + assert!(fixture.lobby()); + fixture.write( + "scripts/server/main.rs2", + "[proc,rune_entry]()(int) return(^lobby_only);\n", + ); + assert!(fixture.rune().is_err()); +} + +#[test] +fn lobby_declarations_conflict_with_shared_ones_only_in_the_lobby() { + let fixture = Fixture::new(); + fixture.write( + "scripts/lobby/values.constant", + "// @scope(lobby)\n^shared = 7\n", + ); + fixture.assert_lobby_error("constant 'shared' is declared in both shared and private scopes"); + assert!(fixture.rune().is_ok()); + assert!(fixture.client().is_ok()); + fixture.write("scripts/lobby/values.constant", "// @scope(lobby)\n"); + fixture.write( + "scripts/lobby/shadow.ls2", + "[proc,shared]()(int) return(7);\n[proc,lobby_shadow]()(int) return(~shared);\n", + ); + assert!(fixture.rune().is_ok()); + assert!(fixture.client().is_ok()); + assert!(fixture.lobby()); + assert!(fixture.errors(Scope::Lobby).is_empty()); + fixture.write( + "scripts/lobby/shadow.ls2", + "[proc,rune_entry]()(int) return(7);\n[login,_]\n", + ); + fixture.write("scripts/server/login.rs2", "[login,_]\nmes(\"server\");\n"); + assert!(fixture.rune().is_ok()); + assert!(fixture.lobby()); +} + +#[test] +fn only_minimal_triggers_are_accepted() { + let fixture = Fixture::new(); + let mut accepted = String::from( + "[login,_]\n[logout,_]\n[if_button,lobby_panel:button]\n[if_buttond,lobby_panel:button]\n[if_close,lobby_panel]\n[label,lobby_label]\n", + ); + for button in 1..=10 { + accepted.push_str(&format!("[if_button{button},lobby_panel:button]\n")); + } + fixture.write("scripts/lobby/triggers.ls2", &accepted); + assert!(fixture.lobby()); + assert!(fixture.errors(Scope::Lobby).is_empty()); + for (header, trigger) in [ + ("[opnpc1,nothing]", "opnpc1"), + ("[ai_queue1,nothing]", "ai_queue1"), + ("[opheld1,shared_obj]", "opheld1"), + ("[debugproc,lobby_debug]", "debugproc"), + ("[queue,lobby_queue]", "queue"), + ("[clientscript,lobby_client]", "clientscript"), + ] { + fixture.write("scripts/lobby/triggers.ls2", &format!("{header}\n")); + fixture.assert_lobby_error(&format!( + "The trigger type '{trigger}' is not available in lobbyscript." + )); + assert!(fixture.rune().is_ok(), "{header}"); + } + + let mut project = Project::new(Target::Lobby, SymbolRegistry::new(), Options::default()); + let source = project.open("memory:lobby", Scope::Lobby, 1, "[opnpc1,nothing]\n"); + let errors = project.analyze().diagnostics; + assert!( + errors + .errors() + .iter() + .any(|error| error.message + == "The trigger type 'opnpc1' is not available in lobbyscript."), + "{errors:?}" + ); + project.update(source, 2, "[login,_]\n").unwrap(); + assert!(!project.analyze().diagnostics.has_errors()); +} + +#[test] +fn commands_are_declared_only_in_engine_ls2() { + let fixture = Fixture::new(); + fixture.write("scripts/lobby/greet.ls2", "[command,greet]\nmes(\"hi\");\n"); + fixture.assert_lobby_error("The trigger type 'command' is not available in lobbyscript."); + assert!(fixture.rune().is_ok()); + + let mut project = Project::new(Target::Lobby, SymbolRegistry::new(), Options::default()); + let engine = project.open( + "lobby/engine.ls2", + Scope::Lobby, + 1, + "[command,mes](string $text)\n", + ); + let main = project.open("lobby/main.ls2", Scope::Lobby, 1, "["); + let offers_command = |source| { + project + .completions(source, 1, 100) + .iter() + .any(|item| item.label == "command") + }; + assert!(offers_command(engine)); + assert!(!offers_command(main)); + project.update(main, 2, "[command,greet]\n").unwrap(); + let errors = project.analyze().diagnostics; + assert_eq!( + errors + .errors() + .iter() + .map(|error| (error.file.clone(), error.message.as_str())) + .collect::>(), + [( + PathBuf::from("lobby/main.ls2"), + "The trigger type 'command' is not available in lobbyscript." + )] + ); +} + +#[test] +fn secondary_player_forms_are_errors() { + let fixture = Fixture::new(); + for (body, form) in [ + ("\n.mes(\"hi\");\n", ".mes"), + ("\n.%shared_var = 1;\n", ".%shared_var"), + ("()(int)\nreturn(.%shared_var);\n", ".%shared_var"), + ] { + fixture.write( + "scripts/lobby/secondary.ls2", + &format!("[proc,lobby_secondary]{body}"), + ); + fixture.assert_lobby_error(&format!( + "'{form}' uses the secondary player pointer, which is not available in lobbyscript." + )); + } + fixture.write( + "scripts/lobby/secondary.ls2", + "[proc,lobby_secondary]\nmes(\"hi\");\n%shared_var = 1;\n", + ); + assert!(fixture.lobby()); + + let mut registry = SymbolRegistry::new(); + registry.register_command("findhero".into(), 2018, vec![], vec![Type::Boolean]); + let mut project = Project::new(Target::Lobby, registry, Options::default()); + project.open( + "memory:hero.ls2", + Scope::Lobby, + 1, + "[proc,hero]()(boolean)\nreturn(findhero);\n", + ); + let errors = project.analyze().diagnostics; + assert!( + errors.errors().iter().any(|error| error.message + == "'findhero' uses the secondary player pointer, which is not available in lobbyscript."), + "{errors:?}" + ); +} + +#[test] +fn server_commands_are_unresolved_in_lobby() { + let fixture = Fixture::new(); + fixture.write( + "scripts/server/delay.rs2", + "[proc,rune_delay]\np_delay(1);\n", + ); + assert!(fixture.rune().is_ok()); + fixture.write( + "scripts/lobby/delay.ls2", + "[proc,lobby_delay]\np_delay(1);\n", + ); + fixture.assert_lobby_error("'p_delay' cannot be resolved to a command."); + assert!(fixture.rune().is_ok()); +} + +#[test] +fn lobby_callbacks_resolve_clientscripts_like_the_server() { + let fixture = Fixture::new(); + fixture.write( + "pack/ls2_command.pack", + "2062=mes\n2186=runclientscript\n2187=runclientscriptvararg\n", + ); + fixture.write( + "pack/clientscript.pack", + "1=[proc,shared]\n2=[proc,client_entry]\n7=[clientscript,refresh]\n", + ); + fixture.write( + "scripts/client/refresh.cs2", + "[clientscript,refresh](int $value)\n", + ); + fixture.write( + "scripts/lobby/callback.ls2", + "[proc,lobby_refresh]\nrunclientscript(\"refresh(1)\");\n", + ); + assert!(fixture.lobby()); + assert!(fixture.errors(Scope::Lobby).is_empty()); + fixture.write( + "scripts/lobby/callback.ls2", + "[proc,lobby_refresh]\nrunclientscript(\"refresh()\");\n", + ); + assert!(!fixture.lobby()); + assert!(!fixture.errors(Scope::Lobby).is_empty()); +} + +#[test] +fn lobby_script_ids_are_independent_of_server_ids() { + let fixture = Fixture::new(); + fixture.write( + "scripts/server/login.rs2", + "[login,_]\n[proc,lobby_helper]()(int) return(1);\n", + ); + fixture.write("scripts/lobby/login.ls2", "[login,_]\nmes(\"lobby\");\n"); + let mut server = ScriptIds::new(); + runec::compile_memory_with_ids(&fixture.scripts(), Some(&fixture.pack()), &mut server).unwrap(); + let mut lobby = ScriptIds::new(); + let (_, idx) = + runec::compile_lobby_memory_with_ids(&fixture.scripts(), Some(&fixture.pack()), &mut lobby) + .unwrap(); + assert_eq!(idx_slots(&idx), 3); + let expected = |names: &[&str]| { + names + .iter() + .enumerate() + .map(|(id, name)| (name.to_string(), id as i32)) + .collect::() + }; + assert_eq!( + server, + expected(&[ + "login:_", + "proc:lobby_helper", + "proc:rune_entry", + "proc:shared" + ]) + ); + assert_eq!( + lobby, + expected(&["login:_", "proc:lobby_entry", "proc:lobby_helper"]) + ); + let mut reused = ScriptIds::from([("proc:lobby_helper".to_string(), 40)]); + runec::compile_lobby_memory_with_ids(&fixture.scripts(), Some(&fixture.pack()), &mut reused) + .unwrap(); + assert_eq!(reused["proc:lobby_helper"], 40); + assert_eq!(reused["login:_"], 41); +} + +#[test] +fn editor_projects_keep_lobby_documents_in_the_lobby_target() { + let fixture = Fixture::new(); + let labels = |scope: Scope| { + let project = + editor_project_for_scope(&fixture.scripts(), Some(&fixture.pack()), scope).unwrap(); + project + .documents() + .filter(|document| document.config.is_none()) + .map(|document| { + ( + document.scope, + document.label.to_string_lossy().into_owned(), + ) + }) + .collect::>() + }; + let lobby = labels(Scope::Lobby); + assert!( + lobby + .iter() + .any(|(scope, label)| *scope == Scope::Lobby && label.ends_with("lobby/main.ls2")) + ); + assert!(lobby.iter().any(|(scope, _)| *scope == Scope::Client)); + assert!( + lobby + .iter() + .all(|(scope, _)| matches!(scope, Scope::Lobby | Scope::Client)) + ); + for scope in [Scope::Rune, Scope::Client] { + assert!( + labels(scope) + .iter() + .all(|(scope, _)| *scope != Scope::Lobby), + "{scope:?}" + ); + } + let server = editor_project(&fixture.scripts(), Some(&fixture.pack()), false).unwrap(); + assert!( + server + .documents() + .all(|document| document.scope != Scope::Lobby) + ); + assert!( + editor_project_for_scope(&fixture.scripts(), Some(&fixture.pack()), Scope::Global).is_err() + ); + + fixture.write( + "scripts/lobby/main.ls2", + "[proc,lobby_entry]\nlobby_missing;\n", + ); + assert!(!fixture.errors(Scope::Lobby).is_empty()); + assert!(fixture.errors(Scope::Rune).is_empty()); +}