1use crate::clientscript::hooks;
3use crate::parser::{Expr, Statement, StringPart};
4use crate::pointer::PointerSet;
5use crate::project::{Project, SourceId};
6use crate::sources::Scope;
7use crate::symbol::SymbolRegistry;
8use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
9use std::ops::Range;
10use std::sync::Arc;
11
12#[derive(Clone, Debug)]
15pub struct ScriptEffects {
16 pub range: Range<usize>,
17 pub may_suspend: bool,
18 pub writes: Vec<String>,
20 pub incomplete: bool,
22 pub required: Option<PointerSet>,
24}
25
26impl ScriptEffects {
27 pub fn label(&self) -> Option<String> {
29 let mut parts = Vec::new();
30 if self.may_suspend {
31 parts.push("may suspend".to_owned());
32 }
33 if !self.writes.is_empty() {
34 let mut writes = format!(
35 "writes {}",
36 self.writes
37 .iter()
38 .take(6)
39 .map(|name| match name.strip_prefix('.') {
40 Some(name) => format!(".%{name}"),
41 None => format!("%{name}"),
42 })
43 .collect::<Vec<_>>()
44 .join(", ")
45 );
46 if self.writes.len() > 6 {
47 writes.push_str(&format!(" +{} more", self.writes.len() - 6));
48 }
49 parts.push(writes);
50 }
51 if self.incomplete {
52 parts.push("incomplete".to_owned());
53 }
54 (!parts.is_empty()).then(|| format!("@effects {}", parts.join("; ")))
55 }
56}
57
58#[derive(Clone, Default)]
59pub(crate) struct Summary {
60 pub may_suspend: bool,
61 pub writes: BTreeSet<String>,
62 pub incomplete: bool,
63}
64
65impl Summary {
66 fn include(&mut self, other: &Self) -> bool {
67 let before = (self.may_suspend, self.writes.len(), self.incomplete);
68 self.may_suspend |= other.may_suspend;
69 self.writes.extend(other.writes.iter().cloned());
70 self.incomplete |= other.incomplete;
71 before != (self.may_suspend, self.writes.len(), self.incomplete)
72 }
73}
74
75pub(crate) struct Effects {
76 pub generation: u64,
77 pub scripts: HashMap<(SourceId, usize, String), Summary>,
78}
79
80struct Node {
81 source: SourceId,
82 line: usize,
83 scope: Scope,
84 trigger: String,
85 name: String,
86 summary: Summary,
87 calls: Vec<(String, String)>,
88}
89
90struct Visitor<'a> {
91 registry: &'a SymbolRegistry,
92 commands: &'a HashMap<String, bool>,
93 server: bool,
94 script_names: &'a HashSet<String>,
95 callback_names: &'a HashSet<String>,
96 node: &'a mut Node,
97}
98
99impl Visitor<'_> {
100 fn callback(&mut self, callback: &Expr, transmits: bool) {
101 match callback {
102 Expr::StringLiteral(text) => match hooks::parse(text) {
103 Ok(values) => {
104 if !transmits && values.len() > 2 {
105 self.node.summary.incomplete = true;
106 }
107 if let Some(Expr::Identifier(target)) = values.first()
108 && !self.callback_names.contains(target)
109 && self
110 .registry
111 .lookup_script_by_trigger("clientscript", target)
112 .is_none()
113 && self
114 .registry
115 .lookup_script_by_trigger("proc", target)
116 .is_none()
117 {
118 self.node.summary.incomplete = true;
119 }
120 if let Some(Expr::Tuple(args)) = values.get(1) {
123 for arg in args {
124 self.expr(arg);
125 }
126 } else {
127 self.node.summary.incomplete = true;
128 }
129 }
130 Err(_) => self.node.summary.incomplete = true,
131 },
132 Expr::CommandCall { name, args, .. } if name == "__hook" => {
133 if let Some(Expr::Tuple(values)) = args.get(1) {
134 for value in values {
135 self.expr(value);
136 }
137 } else {
138 self.node.summary.incomplete = true;
139 }
140 }
141 Expr::NullLiteral => {}
142 _ => {
143 self.node.summary.incomplete = true;
144 self.expr(callback);
145 }
146 }
147 }
148
149 fn command(&mut self, name: &str) {
150 let primary = name.trim_start_matches('.');
151 match self.commands.get(primary) {
152 Some(false) => self.node.summary.incomplete = true,
153 Some(true) => {
154 self.node.summary.may_suspend |=
155 self.registry.command_suspends_for(name, self.server);
156 }
157 None if self.registry.lookup_command(primary).is_some() => {
158 self.node.summary.may_suspend |=
159 self.registry.command_suspends_for(name, self.server);
160 }
161 None => self.node.summary.incomplete = true,
162 }
163 }
164
165 fn write(&mut self, target: &Expr) {
166 match target {
167 Expr::GameVar(name, _) => {
168 self.node.summary.writes.insert(name.clone());
169 }
170 Expr::MultiAssign(targets, _) | Expr::Tuple(targets) => {
171 for target in targets {
172 self.write(target);
173 }
174 }
175 _ => {}
176 }
177 }
178
179 fn expr(&mut self, expr: &Expr) {
180 match expr {
181 Expr::CommandCall { name, args, .. } => {
182 let command = name.trim_start_matches('.');
183 if !matches!(
186 name.as_str(),
187 "__push"
188 | "__pop_int"
189 | "__pop_string"
190 | "__pop_long"
191 | "__join"
192 | "__get_array"
193 | "__set_array"
194 | "__define_array"
195 ) {
196 self.command(name);
197 }
198 if matches!(
199 command,
200 "runclientscript" | "runclientscript*" | "runclientscriptvararg"
201 ) {
202 if command == "runclientscript"
203 && matches!(args.as_slice(), [Expr::StringLiteral(_)])
204 {
205 self.callback(&args[0], false);
206 } else {
207 self.node.summary.incomplete = true;
208 for arg in args {
209 self.expr(arg);
210 }
211 }
212 return;
213 }
214 if let Some(&explicit) = self.registry.hook_commands.get(command) {
215 let target =
216 usize::from(explicit && self.registry.component_first_command(command));
217 if args.len() == 1 + usize::from(explicit) {
218 self.callback(&args[target], true);
219 if explicit {
220 self.expr(&args[1 - target]);
221 }
222 } else {
223 if args.len() < 1 + usize::from(explicit) {
224 self.node.summary.incomplete = true;
225 }
226 for (index, arg) in args.iter().enumerate() {
227 if index != target
228 || !matches!(arg, Expr::Identifier(_) | Expr::StringLiteral(_))
229 {
230 self.expr(arg);
231 }
232 }
233 }
234 return;
235 }
236 for arg in args {
237 self.expr(arg);
238 }
239 }
240 Expr::ProcCall { name, args, .. } | Expr::JumpCall { name, args, .. } => {
241 let trigger = if matches!(expr, Expr::JumpCall { .. }) {
242 "label"
243 } else {
244 "proc"
245 };
246 self.node.calls.push((trigger.to_owned(), name.clone()));
247 for arg in args {
248 self.expr(arg);
249 }
250 }
251 Expr::Identifier(name) => {
252 let component = name.split_once(':').is_some_and(|(interface, component)| {
254 self.registry
255 .lookup_component(interface, component)
256 .is_some()
257 });
258 if component
259 || self.registry.lookup_entity_id(name).is_some()
260 || self.registry.lookup_constant(name).is_some()
261 || self
262 .registry
263 .lookup_game_var(name.trim_start_matches('.'))
264 .is_some()
265 || self.registry.type_chars.contains_key(name)
266 {
267 return;
268 }
269 let command = name.trim_start_matches('.');
270 if !self.commands.contains_key(command)
271 && self.registry.lookup_command(command).is_none()
272 && (self.script_names.contains(name)
273 || self.registry.lookup_script(name).is_some())
274 {
275 return;
276 }
277 self.command(name);
278 }
279 Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
280 self.expr(lhs);
281 self.expr(rhs);
282 }
283 Expr::Calc(value) | Expr::ArrayAccess { index: value, .. } => self.expr(value),
284 Expr::JoinedString { parts } => {
285 for part in parts {
286 if let StringPart::Expr(value) = part {
287 self.expr(value);
288 }
289 }
290 }
291 Expr::MultiAssign(values, _) | Expr::Tuple(values) => {
292 for value in values {
293 self.expr(value);
294 }
295 }
296 _ => {}
297 }
298 }
299
300 fn body(&mut self, body: &[Statement]) {
301 for statement in body {
302 match statement {
303 Statement::VarDeclaration {
304 value: Some(value), ..
305 }
306 | Statement::ArrayDeclaration { size: value, .. }
307 | Statement::Expression { expr: value, .. } => self.expr(value),
308 Statement::Assignment { target, value, .. } => {
309 self.write(target);
310 self.expr(target);
311 self.expr(value);
312 }
313 Statement::Return { values, .. } => {
314 for value in values {
315 self.expr(value);
316 }
317 }
318 Statement::If {
319 condition,
320 body,
321 else_if,
322 else_body,
323 ..
324 } => {
325 self.expr(condition);
326 self.body(body);
327 for (condition, body, _) in else_if {
328 self.expr(condition);
329 self.body(body);
330 }
331 if let Some(body) = else_body {
332 self.body(body);
333 }
334 }
335 Statement::While {
336 condition, body, ..
337 } => {
338 self.expr(condition);
339 self.body(body);
340 }
341 Statement::Switch {
342 expr,
343 cases,
344 default,
345 ..
346 } => {
347 self.expr(expr);
348 for case in cases {
349 self.body(&case.body);
350 }
351 if let Some(body) = default {
352 self.body(body);
353 }
354 }
355 Statement::OrphanCase { case, .. } => {
356 self.node.summary.incomplete = true;
357 self.body(&case.body);
358 }
359 _ => {}
360 }
361 }
362 }
363}
364
365impl Effects {
366 fn build(project: &Project) -> Option<Self> {
367 let scope = project.target_scope();
368 let documents = project
369 .documents()
370 .filter(|document| document.scope == scope || document.scope == Scope::Global)
371 .collect::<Vec<_>>();
372 let mut commands = HashMap::new();
373 let mut script_names = HashSet::new();
374 let callback_names = project
375 .documents()
376 .filter(|document| matches!(document.scope, Scope::Client | Scope::Global))
377 .filter_map(|document| document.syntax())
378 .flat_map(|file| &file.scripts)
379 .filter(|script| matches!(script.trigger.as_str(), "proc" | "clientscript"))
380 .map(|script| script.name.clone())
381 .collect::<HashSet<_>>();
382 let mut nodes = Vec::new();
383 let mut definitions: HashMap<(Scope, String, String), Vec<usize>> = HashMap::new();
384 for document in &documents {
385 if project.analysis_cancelled() {
386 return None;
387 }
388 let Some(file) = document.syntax() else {
389 continue;
390 };
391 for script in &file.scripts {
392 if script.trigger == "command" {
393 let name = script.name.trim_start_matches('.').to_owned();
394 let valid = !document.diagnostics.has_errors();
395 commands
396 .entry(name)
397 .and_modify(|previous: &mut bool| *previous &= valid)
398 .or_insert(valid);
399 continue;
400 }
401 script_names.insert(script.name.clone());
402 definitions
403 .entry((document.scope, script.trigger.clone(), script.name.clone()))
404 .or_default()
405 .push(nodes.len());
406 nodes.push(Node {
407 source: document.id,
408 line: script.line,
409 scope: document.scope,
410 trigger: script.trigger.clone(),
411 name: script.name.clone(),
412 summary: Summary {
413 incomplete: document.diagnostics.has_errors(),
414 ..Summary::default()
415 },
416 calls: Vec::new(),
417 });
418 }
419 }
420 let mut next = 0;
421 for document in &documents {
422 let Some(file) = document.syntax() else {
423 continue;
424 };
425 for script in &file.scripts {
426 if project.analysis_cancelled() {
427 return None;
428 }
429 if script.trigger == "command" {
430 continue;
431 }
432 Visitor {
433 registry: project.registry(),
434 commands: &commands,
435 server: scope == Scope::Rune,
436 script_names: &script_names,
437 callback_names: &callback_names,
438 node: &mut nodes[next],
439 }
440 .body(&script.body);
441 next += 1;
442 }
443 }
444 let mut callers = vec![Vec::new(); nodes.len()];
445 for (index, node) in nodes.iter_mut().enumerate() {
446 if project.analysis_cancelled() {
447 return None;
448 }
449 let mut incomplete =
450 definitions[&(node.scope, node.trigger.clone(), node.name.clone())].len() != 1;
451 let mut callees = HashSet::new();
452 for (trigger, name) in &node.calls {
453 let mut found = Vec::new();
454 let triggers = if trigger == "proc" && scope == Scope::Client {
455 vec!["proc", "clientscript"]
456 } else {
457 vec![trigger.as_str()]
458 };
459 for trigger in triggers {
460 for owner in [Scope::Global, node.scope]
461 .into_iter()
462 .take(if node.scope == Scope::Global { 1 } else { 2 })
463 {
464 if let Some(ids) =
465 definitions.get(&(owner, trigger.to_owned(), name.clone()))
466 {
467 found.extend(ids.iter().copied());
468 }
469 }
470 if !found.is_empty() {
471 break;
472 }
473 }
474 found.sort_unstable();
475 found.dedup();
476 incomplete |= found.len() != 1;
477 callees.extend(found);
478 }
479 node.summary.incomplete |= incomplete;
480 for callee in callees {
481 callers[callee].push(index);
482 }
483 }
484 let mut pending = (0..nodes.len()).collect::<VecDeque<_>>();
485 let mut queued = vec![true; nodes.len()];
486 while let Some(callee) = pending.pop_front() {
487 if project.analysis_cancelled() {
488 return None;
489 }
490 queued[callee] = false;
491 let summary = nodes[callee].summary.clone();
492 for &caller in &callers[callee] {
493 if nodes[caller].summary.include(&summary) && !queued[caller] {
494 queued[caller] = true;
495 pending.push_back(caller);
496 }
497 }
498 }
499 Some(Self {
500 generation: project.generation,
501 scripts: nodes
502 .into_iter()
503 .map(|node| {
504 (
505 (
506 node.source,
507 node.line,
508 format!("[{},{}]", node.trigger, node.name),
509 ),
510 node.summary,
511 )
512 })
513 .collect(),
514 })
515 }
516}
517
518impl Project {
519 pub fn effects_ready(&self) -> bool {
521 self.effects
522 .lock()
523 .unwrap()
524 .as_ref()
525 .is_some_and(|effects| effects.generation == self.generation)
526 }
527
528 pub(crate) fn effect_summaries(&self) -> Option<Arc<Effects>> {
529 if let Some(effects) = self
530 .effects
531 .lock()
532 .unwrap()
533 .as_ref()
534 .filter(|effects| effects.generation == self.generation)
535 {
536 return Some(effects.clone());
537 }
538 let effects = Arc::new(Effects::build(self)?);
539 *self.effects.lock().unwrap() = Some(effects.clone());
540 Some(effects)
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547 use crate::clientscript::format::Format;
548 use crate::environment::EngineProfile;
549 use crate::pointer::{PointerHolder, default_command_pointers};
550 use crate::project::{CancellationToken, Options, Target};
551 use crate::types::Type;
552
553 fn project() -> Project {
554 let mut registry = SymbolRegistry::new();
555 registry.register_command("pause".into(), 1, vec![Type::Int], vec![]);
556 registry.set_command_suspends("pause", true);
557 Project::new(Target::Rune, registry, Options::default())
558 }
559
560 #[test]
561 fn suspension_uses_pointer_contracts_and_respects_target_and_profile_overrides() {
562 let mut registry = SymbolRegistry::new();
563 for (index, name) in [
564 "world_delay",
565 "p_delay",
566 "p_stringdialog",
567 "controller_del",
568 "custom_pause",
569 ]
570 .into_iter()
571 .enumerate()
572 {
573 registry.register_command(name.into(), index as i32 + 71, vec![Type::Int], vec![]);
574 }
575 assert!(registry.command_suspends("world_delay"));
576 assert!(registry.command_suspends(".p_delay"));
577 assert!(registry.command_suspends("p_loaddelay"));
578 assert!(registry.command_suspends("p_stringdialog"));
579 let deletion = &default_command_pointers()["controller_del"];
580 assert!(!deletion.corrupted.is_empty());
581 assert!(!deletion.may_suspend);
582 assert!(registry.command_suspends("p_namedialog"));
583 assert!(!registry.command_suspends("p_get_suggestion"));
584 let mut server = Project::new(Target::Rune, registry.clone(), Options::default());
585 let source = server.open("delays.rs2", Scope::Rune, 1,
586 "[command,p_delay](int $ticks)\n[proc,delayed]\np_delay(1);\n[proc,caller]\n~delayed;\n[proc,world]\nworld_delay(1);");
587 assert!(
588 server
589 .script_effects(source)
590 .iter()
591 .all(|hint| hint.may_suspend)
592 );
593
594 let format = Format::parse("0=PushConstantInt\n21=Return\n").unwrap();
595 let mut client = Project::new(Target::Client(format), registry.clone(), Options::default());
596 let source = client.open(
597 "delays.cs2",
598 Scope::Client,
599 1,
600 "[proc,client]\np_delay(1); world_delay(1);",
601 );
602 assert!(!client.script_effects(source)[0].may_suspend);
603
604 registry.set_command_suspends("p_delay", false);
605 assert!(!registry.command_suspends("p_delay"));
606 assert!(!registry.command_suspends(".p_delay"));
607 registry.set_command_suspends("custom_pause", true);
608 assert!(registry.command_suspends("custom_pause"));
609 let mut profile = EngineProfile::default();
610 profile.command_pointers.insert(
611 "custom_pause".into(),
612 PointerHolder {
613 may_suspend: true,
614 ..PointerHolder::default()
615 },
616 );
617 registry.set_engine_profile(profile);
618 assert!(!registry.command_suspends("world_delay"));
619 assert!(registry.command_suspends("custom_pause"));
620 registry.set_command_suspends("custom_pause", false);
621 assert!(!registry.command_suspends("custom_pause"));
622 }
623
624 #[test]
625 fn effects_follow_calls_cycles_and_edits_without_compiling() {
626 let mut project = project();
627 let leaf = project.open(
628 "leaf.rs2",
629 Scope::Rune,
630 1,
631 "[proc,leaf]\n%flag = 1; pause(1);",
632 );
633 let callers = project.open(
634 "callers.rs2",
635 Scope::Rune,
636 1,
637 "[proc,a]\n~b;\n[proc,b]\n~a; ~leaf; @done;\n[label,done]\n.%other = 2;",
638 );
639 let first = project.effect_summaries().unwrap();
640 assert!(project.effects_ready());
641 assert!(Arc::ptr_eq(&first, &project.effect_summaries().unwrap()));
642 let hints = project.script_effects(callers);
643 assert_eq!(hints.len(), 3);
644 for hint in &hints[..2] {
645 assert!(hint.may_suspend);
646 assert_eq!(hint.writes, [".other", "flag"]);
647 assert_eq!(
648 hint.label().as_deref(),
649 Some("@effects may suspend; writes .%other, %flag")
650 );
651 assert!(!hint.incomplete);
652 assert!(hint.required.is_none());
653 }
654 assert!(!project.pointer_requirements_ready());
655 project.update(leaf, 2, "[proc,leaf]\nreturn;").unwrap();
656 assert!(!project.effects_ready());
657 let updated = project.script_effects(callers);
658 assert!(!updated[0].may_suspend);
659 assert_eq!(updated[0].writes, [".other"]);
660 assert!(!Arc::ptr_eq(&first, &project.effect_summaries().unwrap()));
661 }
662
663 #[test]
664 fn unresolved_and_ambiguous_calls_stay_incomplete_and_source_scoped() {
665 let mut project = project();
666 let caller = project.open(
667 "caller.rs2",
668 Scope::Rune,
669 1,
670 "[proc,caller]\n~duplicate; ~missing; mystery();",
671 );
672 project.open("a.rs2", Scope::Rune, 1, "[proc,duplicate]\n%first = 1;");
673 project.open("b.rs2", Scope::Rune, 1, "[proc,duplicate]\n%second = 2;");
674 let client = project.open(
675 "client.cs2",
676 Scope::Client,
677 1,
678 "[proc,caller]\npause(1); %client = 1;",
679 );
680 let hint = project.script_effects(caller).remove(0);
681 assert!(hint.incomplete);
682 assert!(!hint.may_suspend);
683 assert_eq!(hint.writes, ["first", "second"]);
684 assert!(project.script_effects(client).is_empty());
685 assert!(hint.label().unwrap().ends_with("incomplete"));
686 }
687
688 #[test]
689 fn cancelled_analysis_does_not_cache_partial_effects() {
690 let mut project = project();
691 let source = project.open("source.rs2", Scope::Rune, 1, "[proc,leaf]\npause(1);");
692 let token = CancellationToken::default();
693 token.cancel();
694 project.set_cancellation(token);
695 assert!(project.script_effects(source).is_empty());
696 assert!(project.effects.lock().unwrap().is_none());
697 project.set_cancellation(CancellationToken::default());
698 assert!(project.script_effects(source)[0].may_suspend);
699 }
700
701 #[test]
702 fn callback_payload_effects_are_evaluated_without_the_deferred_body() {
703 let mut registry = SymbolRegistry::new();
704 registry.register_command("pause".into(), 1, vec![Type::Int], vec![]);
705 registry.set_command_suspends("pause", true);
706 registry.register_command(
707 "runclientscript".into(),
708 2,
709 vec![Type::ClientScript],
710 vec![],
711 );
712 registry.register_command(
713 "set_hook".into(),
714 3,
715 vec![Type::ClientScript, Type::String],
716 vec![],
717 );
718 registry.set_command_behavior("set_hook", true, Some(false), None);
719 let mut project = Project::new(Target::Rune, registry, Options::default());
720 let source = project.open("callbacks.rs2", Scope::Rune, 1,
721 "[proc,send]\nrunclientscript(\"callback(~capture())\"); set_hook(\"callback(~capture())\");\n[proc,capture]()(int)\n%captured = 1; pause(1); return(1);\n[proc,install]\nset_hook(\"callback(1)\");\n[proc,broken]\nset_hook(\"callback(\");");
722 project.open(
723 "callback.cs2",
724 Scope::Client,
725 1,
726 "[clientscript,callback](int $value)\n%deferred = 1;",
727 );
728 let effects = project.script_effects(source);
729 assert!(effects[0].may_suspend);
730 assert_eq!(effects[0].writes, ["captured"]);
731 assert!(!effects[0].incomplete);
732 assert!(effects[2].writes.is_empty());
733 assert!(!effects[2].may_suspend);
734 assert!(effects[3].incomplete);
735 let mut many = effects[0].clone();
736 many.writes = (0..8).map(|index| format!("variable{index}")).collect();
737 let label = many.label().unwrap();
738 assert!(label.contains("+2 more"));
739 assert!(!label.contains("%variable6"));
740 assert_eq!(many.writes.len(), 8);
741 }
742}