1use crate::parser::Expr;
3use crate::symbol::{SymbolKind, SymbolRegistry};
4use crate::symloader::{Comments, collect_all_files};
5use crate::types::Type;
6use std::collections::HashMap;
7use std::fs;
8use std::io;
9use std::io::BufRead;
10use std::path::{Path, PathBuf};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
13pub enum Scope {
14 Rune = 1,
15 Client = 2,
16 Global = 4,
17}
18
19impl Scope {
20 pub fn folder(self) -> &'static str {
21 match self {
22 Self::Rune => "runescript",
23 Self::Client => "clientscript",
24 Self::Global => "globalscript",
25 }
26 }
27
28 fn extension(self) -> &'static str {
29 match self {
30 Self::Rune => "rs2",
31 Self::Client => "cs2",
32 Self::Global => "gs2",
33 }
34 }
35
36 fn at(path: &Path) -> Option<Self> {
37 match path.file_name()?.to_str()? {
38 "runescript" => Some(Self::Rune),
39 "clientscript" => Some(Self::Client),
40 "globalscript" => Some(Self::Global),
41 _ => None,
42 }
43 }
44}
45
46fn namespace(path: &Path) -> Option<(&Path, Scope)> {
47 let candidates = || {
48 path.ancestors()
49 .filter_map(|path| Scope::at(path).map(|scope| (path, scope)))
50 };
51 candidates()
52 .find(|(path, _)| {
53 path.parent()
54 .and_then(Path::file_name)
55 .is_some_and(|name| name == "scripts")
56 })
57 .or_else(|| candidates().next())
58}
59
60pub(crate) fn target_dir(dir: &Path, scope: Scope) -> PathBuf {
62 let target = dir.join(scope.folder());
63 if Scope::at(dir).is_none() && target.is_dir() {
64 target
65 } else {
66 dir.to_path_buf()
67 }
68}
69
70pub fn roots(dir: &Path) -> Vec<PathBuf> {
72 let mut roots = vec![dir.to_path_buf()];
73 if let Some((root, scope)) = namespace(dir)
74 && scope != Scope::Global
75 && let Some(parent) = root.parent()
76 {
77 let global = parent.join(Scope::Global.folder());
78 if global.is_dir() {
79 roots.insert(0, global);
80 }
81 }
82 roots
83}
84
85pub fn config_files(dir: &Path) -> Vec<PathBuf> {
86 let mut files = Vec::new();
87 for root in roots(dir) {
88 collect_all_files(&root, &mut files);
89 }
90 files
91}
92
93pub fn script_files(dir: &Path, extension: &str) -> io::Result<Vec<PathBuf>> {
94 let dir = target_dir(
95 dir,
96 if extension == "cs2" {
97 Scope::Client
98 } else {
99 Scope::Rune
100 },
101 );
102 let mut files = Vec::new();
103 for root in roots(&dir) {
104 fs::read_dir(&root)?;
106 let mut candidates = Vec::new();
107 collect_all_files(&root, &mut candidates);
108 for path in candidates {
109 let Some(ext) = path.extension().and_then(|ext| ext.to_str()) else {
110 continue;
111 };
112 if !matches!(ext, "rs2" | "cs2" | "gs2") {
113 continue;
114 }
115 if let Some((_, scope)) = namespace(&path)
116 && ext != scope.extension()
117 {
118 return Err(io::Error::other(format!(
119 "{}: .{ext} source belongs in scripts/{}, not scripts/{}",
120 path.display(),
121 match ext {
122 "rs2" => "runescript",
123 "cs2" => "clientscript",
124 _ => "globalscript",
125 },
126 scope.folder(),
127 )));
128 }
129 if ext == extension || ext == "gs2" {
130 files.push(path);
131 }
132 }
133 }
134 files.sort();
135 Ok(files)
136}
137
138#[derive(Debug, Clone, Default)]
141pub struct Visibility {
142 active: bool,
143 documents: HashMap<PathBuf, Scope>,
144 owners: HashMap<String, HashMap<String, u8>>,
145 ids: HashMap<(Type, i32), String>,
146}
147
148fn config_kind(ty: Type) -> Option<&'static str> {
149 match ty {
150 Type::NamedObj | Type::Obj => Some("obj"),
151 Type::IdKit => Some("idk"),
152 Type::MapElement => Some("mel"),
153 Type::DbColumn => Some("dbtable"),
154 Type::Npc
155 | Type::Loc
156 | Type::Seq
157 | Type::Spotanim
158 | Type::MesAnim
159 | Type::Inv
160 | Type::Enum
161 | Type::Struct
162 | Type::Param
163 | Type::DbTable
164 | Type::DbRow
165 | Type::Varp
166 | Type::Varn
167 | Type::Vars
168 | Type::Varbit
169 | Type::Hunt
170 | Type::Controller
171 | Type::Hitmark
172 | Type::Area
173 | Type::Bas
174 | Type::Billboard
175 | Type::ParticleEffector
176 | Type::ParticleEmitter
177 | Type::Cursor
178 | Type::Flo
179 | Type::Flu
180 | Type::ItemCode
181 | Type::Light
182 | Type::Msi
183 | Type::Quest
184 | Type::Varc
185 | Type::VarClan
186 | Type::VarClanSetting
187 | Type::VarCon
188 | Type::Config44
189 | Type::VarNBit
190 | Type::VarObj => Some(ty.name()),
191 _ => None,
192 }
193}
194
195impl Visibility {
196 pub fn new() -> Self {
198 Self {
199 active: true,
200 ..Self::default()
201 }
202 }
203
204 pub fn bind(&mut self, label: impl Into<PathBuf>, scope: Scope) {
206 self.active = true;
207 self.documents.insert(label.into(), scope);
208 }
209
210 pub fn unbind(&mut self, label: &Path) {
211 self.documents.remove(label);
212 }
213
214 fn scope(&self, label: &Path) -> Option<Scope> {
215 self.documents
216 .get(label)
217 .copied()
218 .or_else(|| namespace(label).map(|(_, scope)| scope))
219 }
220
221 pub(crate) fn undeclare(&mut self, kind: &str, name: &str, scope: Scope) {
222 if let Some(names) = self.owners.get_mut(kind)
223 && let Some(owners) = names.get_mut(name)
224 {
225 *owners &= !(scope as u8);
226 if *owners == 0 {
227 names.remove(name);
228 }
229 }
230 }
231
232 pub(crate) fn load(dir: &Path, registry: &SymbolRegistry) -> Self {
233 let Some((root, _)) = namespace(dir) else {
234 return Self::default();
235 };
236 let Some(parent) = root.parent() else {
237 return Self::default();
238 };
239 let mut result = Self {
240 active: true,
241 ..Self::default()
242 };
243 for scope in [Scope::Global, Scope::Rune, Scope::Client] {
244 let mut files = Vec::new();
245 collect_all_files(&parent.join(scope.folder()), &mut files);
246 for file in files {
247 let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
248 continue;
249 };
250 let is_script = matches!(ext, "rs2" | "cs2" | "gs2");
251 if !is_script
252 && ext != "constant"
253 && !Type::from_name(ext).is_some_and(|ty| config_kind(ty).is_some())
254 {
255 continue;
256 }
257 let Ok(input) = fs::File::open(&file) else {
258 continue;
259 };
260 let mut input = io::BufReader::new(input);
261 let mut buffer = String::new();
262 let mut comments = Comments::default();
263 loop {
264 buffer.clear();
265 if !input.read_line(&mut buffer).is_ok_and(|count| count > 0) {
266 break;
267 }
268 let Some(line) = comments.line(&buffer) else {
269 continue;
270 };
271 if is_script {
272 if let Some(header) =
273 line.strip_prefix('[').and_then(|line| line.split_once(']'))
274 && let Some((trigger, name)) = header.0.split_once(',')
275 && trigger.trim() != "command"
276 {
277 result.declare(trigger.trim(), name.trim(), scope);
278 }
279 } else if ext == "constant" {
280 if let Some((name, _)) = line.split_once('=') {
281 result.declare("constant", name.trim().trim_start_matches('^'), scope);
282 }
283 } else if let Some(name) = line
284 .strip_prefix('[')
285 .and_then(|line| line.strip_suffix(']'))
286 {
287 if ext == "varc" {
288 result.declare("varc", name, scope);
289 result.declare("varcs", name, scope);
290 } else if ext == "varclansetting" {
291 for kind in [
292 "varclansetting",
293 "clansetting_int",
294 "clansetting_varbit",
295 "clansetting_long",
296 "clansetting_string",
297 ] {
298 result.declare(kind, name, scope);
299 }
300 } else {
301 result.declare(ext, name, scope);
302 }
303 }
304 }
305 }
306 }
307 result.index_registry(registry);
308 result
309 }
310
311 pub fn index_registry(&mut self, registry: &SymbolRegistry) {
313 self.ids.clear();
314 for (name, entry) in ®istry.entity_ids {
315 for &(ty, id) in &entry.variants {
316 if config_kind(ty).is_some() || ty == Type::Graphic {
317 self.ids.insert((ty, id), name.clone());
318 }
319 if ty == Type::Obj
323 && let Some(base) = name.strip_prefix("cert_")
324 && let Some(objects) = self.owners.get_mut("obj")
325 && let Some(&owner) = objects.get(base)
326 {
327 objects.entry(name.clone()).or_insert(owner);
328 }
329 }
330 }
331 for (name, symbol) in ®istry.game_vars {
332 if let SymbolKind::GameVar {
333 var_id, category, ..
334 } = &symbol.kind
335 && let Some(ty) = Type::from_name(category)
336 {
337 self.ids.insert((ty, *var_id), name.clone());
338 }
339 }
340 }
341
342 pub(crate) fn declare_source(&mut self, path: &Path, file: &crate::parser::ScriptFile) {
343 for script in &file.scripts {
344 self.declare_script(path, &script.trigger, &script.name);
345 }
346 }
347
348 pub(crate) fn declare_script(&mut self, path: &Path, trigger: &str, name: &str) {
349 if let Some(scope) = self.scope(path) {
350 self.declare(trigger, name, scope);
351 }
352 }
353
354 pub(crate) fn declaration(&self, path: &Path, trigger: &str, name: &str) -> Option<String> {
355 self.check(path, trigger, name, false)
356 }
357
358 pub fn declare(&mut self, kind: &str, name: &str, scope: Scope) {
359 let normalized;
360 let name = if Type::from_name(kind).is_some_and(|ty| config_kind(ty).is_some())
361 && !matches!(kind, "varp" | "varbit" | "varn" | "vars")
362 {
363 normalized = crate::symbol::normalize_entity_name(name);
364 normalized.as_ref()
365 } else {
366 name
367 };
368 *self
369 .owners
370 .entry(kind.to_owned())
371 .or_default()
372 .entry(name.to_owned())
373 .or_default() |= scope as u8;
374 }
375
376 pub(crate) fn check(
377 &self,
378 path: &Path,
379 kind: &str,
380 name: &str,
381 required: bool,
382 ) -> Option<String> {
383 if !self.active {
384 return None;
385 }
386 let scope = self.scope(path)?;
387 let name = if matches!(kind, "varp" | "varbit" | "varn" | "vars") {
388 name.trim_start_matches('.')
389 } else {
390 name
391 };
392 let name = if kind == "dbtable" {
393 name.split(':').next().unwrap_or(name)
394 } else {
395 name
396 };
397 let owners = self
398 .owners
399 .get(kind)
400 .and_then(|names| names.get(name))
401 .copied()
402 .unwrap_or(0);
403 if (kind == "constant" || kind == "proc")
404 && owners & Scope::Global as u8 != 0
405 && owners & (Scope::Rune as u8 | Scope::Client as u8) != 0
406 {
407 return Some(format!(
408 "{kind} '{name}' is declared in both globalscript and a private namespace; keep the shared declaration in globalscript"
409 ));
410 }
411 if owners == 0 && !required {
412 return None;
413 }
414 if owners & (scope as u8 | Scope::Global as u8) != 0 {
415 return None;
416 }
417 let allowed = if scope == Scope::Global {
418 "scripts/globalscript".to_owned()
419 } else {
420 format!("scripts/{} or scripts/globalscript", scope.folder())
421 };
422 Some(format!(
423 "{kind} '{name}' is not visible to {}; define it in {allowed}",
424 scope.folder()
425 ))
426 }
427
428 pub(crate) fn typed(
429 &self,
430 path: &Path,
431 name: &str,
432 ty: Type,
433 registry: &SymbolRegistry,
434 ) -> Option<String> {
435 if let Some(kind) = config_kind(ty) {
436 let normalized;
437 let name = if !matches!(ty, Type::Varp | Type::Varbit | Type::Varn | Type::Vars) {
438 normalized = crate::symbol::normalize_entity_name(name);
439 normalized.as_ref()
440 } else {
441 name
442 };
443 return self.check(path, kind, name, true);
444 }
445 match ty {
446 Type::Proc
447 | Type::Label
448 | Type::Queue
449 | Type::Timer
450 | Type::SoftTimer
451 | Type::Walktrigger => self.check(path, ty.name(), name, true),
452 Type::ClientScript => self.check(
453 path,
454 if registry
455 .lookup_script_by_trigger("clientscript", name)
456 .is_some()
457 {
458 "clientscript"
459 } else {
460 "proc"
461 },
462 name,
463 true,
464 ),
465 _ => None,
466 }
467 }
468
469 pub(crate) fn config_name(&self, ty: Type, id: i32) -> Option<&str> {
470 self.ids.get(&(ty, id)).map(String::as_str)
471 }
472
473 fn numeric(&self, path: &Path, id: i32, ty: Type) -> Option<String> {
474 if id < 0 {
476 return None;
477 }
478 let kind = config_kind(ty)?;
479 self.check(
480 path,
481 kind,
482 self.ids
483 .get(&(ty, id))
484 .map(String::as_str)
485 .unwrap_or(&id.to_string()),
486 true,
487 )
488 }
489
490 pub(crate) fn reference(
491 &self,
492 path: &Path,
493 expr: &Expr,
494 hint: Option<Type>,
495 registry: &SymbolRegistry,
496 ) -> Option<String> {
497 if !self.active {
498 return None;
499 }
500 match expr {
501 Expr::GameVar(name, _) => {
502 let kind = match registry.lookup_game_var(name).map(|s| &s.kind) {
503 Some(SymbolKind::GameVar { category, .. }) => category.as_str(),
504 _ => return None,
505 };
506 self.check(path, kind, name, true)
507 }
508 Expr::ConstantVar(name, _) => self.check(path, "constant", name, false).or_else(|| {
509 if let Some(SymbolKind::Constant {
510 int_value: Some(id),
511 ..
512 }) = registry.lookup_constant(name).map(|s| &s.kind)
513 {
514 self.numeric(path, *id, hint?)
515 } else {
516 None
517 }
518 }),
519 Expr::IntLiteral(id) => self.numeric(path, *id, hint?),
520 Expr::StringLiteral(name) => self.typed(path, name, hint?, registry),
521 Expr::Identifier(name) => {
522 if let Some(ty) = hint
523 && registry.lookup_reference(name, ty).is_some()
524 {
525 return self.typed(path, name, ty, registry);
526 }
527 if registry.lookup_constant(name).is_some() {
528 self.reference(path, &Expr::ConstantVar(name.clone(), 0), hint, registry)
529 } else if let Some(entity) = registry.lookup_entity_id(name)
530 && (entity.const_type != Type::Param
531 || hint == Some(Type::Param)
532 || !registry.type_chars.contains_key(name))
533 {
534 self.typed(path, name, entity.const_type, registry)
535 } else if registry
536 .lookup_command(name.trim_start_matches('.'))
537 .is_some()
538 || registry.type_chars.contains_key(name)
539 {
540 None
541 } else {
542 self.typed(path, name, hint?, registry)
543 }
544 }
545 Expr::ProcCall { name, .. } => self.check(
546 path,
547 if registry.lookup_script_by_trigger("proc", name).is_none()
548 && registry
549 .lookup_script_by_trigger("clientscript", name)
550 .is_some()
551 {
552 "clientscript"
553 } else {
554 "proc"
555 },
556 name,
557 true,
558 ),
559 Expr::JumpCall { name, .. } => self.check(path, "label", name, true),
560 Expr::BinaryOp {
561 op: crate::parser::BinOp::Add,
562 lhs,
563 rhs,
564 } => {
565 if let (Expr::Identifier(left), Expr::Identifier(right)) =
566 (lhs.as_ref(), rhs.as_ref())
567 {
568 let name = format!("{left}+{right}");
569 if let Some(entity) = registry.lookup_entity_id(&name) {
570 return self.typed(
571 path,
572 &name,
573 hint.unwrap_or(entity.const_type),
574 registry,
575 );
576 }
577 }
578 None
579 }
580 _ => None,
581 }
582 }
583}