1use crate::arguments::{expression_types, stack_hints};
2use crate::lexer::Lexer;
3use crate::parser::{Expr, Parser, ScriptDeclaration, StringPart};
4use crate::symbol::{SymbolKind, SymbolRegistry, SymbolTable};
5use crate::types::{BaseVarType, Type};
6use std::path::PathBuf;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
10pub enum HookArg {
11 Int(i32),
12 String(String),
13}
14
15fn hook_value(
16 arg: &Expr,
17 hint: Option<Type>,
18 registry: &SymbolRegistry,
19) -> Result<HookArg, String> {
20 let string = hint.is_some_and(|ty| ty.base_type() == BaseVarType::String);
21 Ok(match arg {
22 Expr::IntLiteral(value) | Expr::CoordLiteral(value) => HookArg::Int(*value),
23 Expr::CharLiteral(value) => HookArg::Int(*value as i32),
24 Expr::BoolLiteral(value) => HookArg::Int(i32::from(*value)),
25 Expr::NullLiteral if string => HookArg::String("null".to_owned()),
26 Expr::NullLiteral => HookArg::Int(-1),
27 Expr::StringLiteral(name) => match hint
28 .filter(|_| !string)
29 .and_then(|ty| registry.lookup_reference(name, ty))
30 {
31 Some(id) => HookArg::Int(id),
32 None => HookArg::String(name.clone()),
33 },
34 Expr::JoinedString { parts } => {
35 let mut text = String::new();
36 for part in parts {
37 let StringPart::Literal(part) = part else {
38 return Err("A hook argument must be a constant value".to_owned());
39 };
40 text.push_str(part);
41 }
42 HookArg::String(text)
43 }
44 Expr::Identifier(name) | Expr::ConstantVar(name, _) => {
45 let component = name
46 .split_once(':')
47 .and_then(|(interface, component)| registry.lookup_component(interface, component));
48 let reference = hint.and_then(|ty| registry.lookup_reference(name, ty));
49 if let Some(id) = component.or(reference) {
50 return Ok(HookArg::Int(id));
51 }
52 if let Some(SymbolKind::Constant {
53 int_value,
54 string_value,
55 ..
56 }) = registry.lookup_constant(name).map(|symbol| &symbol.kind)
57 {
58 if let Some(value) = int_value {
59 return Ok(HookArg::Int(*value));
60 }
61 if let Some(value) = string_value {
62 return Ok(HookArg::String(value.clone()));
63 }
64 }
65 match registry.lookup_entity_id(name) {
66 Some(entity) => HookArg::Int(entity.id),
67 None => return Err(format!("Unknown hook argument '{name}'")),
68 }
69 }
70 _ => return Err("A hook argument must be a constant value".to_owned()),
71 })
72}
73
74pub fn component_hook(
77 text: &str,
78 kind: Option<&str>,
79 registry: &SymbolRegistry,
80) -> Result<(Vec<HookArg>, Vec<i32>), String> {
81 let values = parse(text)?;
82 let Expr::Tuple(args) = &values[1] else {
83 unreachable!()
84 };
85 let (script, params) = match &values[0] {
86 Expr::IntLiteral(id) => (*id, Vec::new()),
87 Expr::Identifier(name) => {
88 let id = registry
89 .lookup_reference(name, Type::ClientScript)
90 .or_else(|| name.strip_prefix("script")?.parse().ok())
91 .ok_or_else(|| format!("Unknown clientscript '{name}'"))?;
92 let params = match registry
93 .lookup_script_by_trigger("clientscript", name)
94 .or_else(|| registry.lookup_script_by_trigger("proc", name))
95 .map(|symbol| &symbol.kind)
96 {
97 Some(SymbolKind::Script { param_types, .. }) => param_types.clone(),
98 _ => Vec::new(),
99 };
100 (id, params)
101 }
102 _ => unreachable!(),
103 };
104 let hints = stack_hints(registry, ¶ms, args, &SymbolTable::new());
105 let mut hook = vec![HookArg::Int(script)];
106 for (arg, hint) in args.iter().zip(hints) {
107 hook.push(hook_value(arg, hint, registry)?);
108 }
109 let mut transmits = Vec::new();
110 if let Some(Expr::Tuple(list)) = values.get(2) {
111 let kind = kind.ok_or("This hook has no transmit list")?;
112 for value in list {
113 transmits.push(match value {
114 Expr::IntLiteral(id) => *id,
115 Expr::Identifier(name) => transmit_id(registry, kind, name)
116 .ok_or_else(|| format!("Unknown {kind} transmit trigger '{name}'"))?,
117 _ => return Err("A transmit trigger must be a name".to_owned()),
118 });
119 }
120 }
121 Ok((hook, transmits))
122}
123
124pub(crate) fn transmit_kind(command: &str) -> Option<&'static str> {
125 let command = command.trim_start_matches('.');
126 match command
127 .strip_prefix("cc_")
128 .or_else(|| command.strip_prefix("if_"))?
129 {
130 "setonvartransmit" => Some("varp"),
131 "setonvarctransmit" => Some("varc"),
132 "setonvarcstrtransmit" => Some("varcstr"),
133 "setoninvtransmit" => Some("inv"),
134 "setonstattransmit" => Some("stat"),
135 _ => None,
136 }
137}
138
139pub(crate) fn var_placeholder(kind: &str) -> &str {
141 match kind {
142 "varp" => "varplayer",
143 "varpbit" => "varplayerbit",
144 "varc" | "varcstr" => "varclient",
145 other => other,
146 }
147}
148
149pub(crate) fn transmit_id(registry: &SymbolRegistry, kind: &str, name: &str) -> Option<i32> {
150 if kind.starts_with("var") {
151 match registry.lookup_game_var(name).map(|symbol| &symbol.kind) {
152 Some(SymbolKind::GameVar {
153 var_id, category, ..
154 }) if category == kind => Some(*var_id),
155 None => name
156 .strip_prefix(var_placeholder(kind))?
157 .strip_prefix('_')?
158 .parse::<u16>()
159 .ok()
160 .map(i32::from),
161 _ => None,
162 }
163 } else {
164 registry.lookup_reference(name, Type::from_name(kind)?)
165 }
166}
167
168pub(crate) fn transmit_name(registry: &SymbolRegistry, kind: &str, id: i32) -> Option<String> {
169 if kind.starts_with("var") {
170 registry
171 .game_variables()
172 .filter_map(|(name, symbol)| {
173 matches!(&symbol.kind, SymbolKind::GameVar { var_id, category, .. }
174 if *var_id == id && category == kind && !name.starts_with('.'))
175 .then_some(name)
176 })
177 .min()
178 .map(str::to_owned)
179 .or_else(|| {
180 u16::try_from(id)
181 .ok()
182 .map(|_| format!("{}_{id}", var_placeholder(kind)))
183 })
184 } else {
185 let ty = Type::from_name(kind)?;
186 registry
187 .entity_ids
188 .iter()
189 .filter_map(|(name, entity)| {
190 entity.variants.contains(&(ty, id)).then_some(name.as_str())
191 })
192 .min()
193 .map(str::to_owned)
194 }
195}
196
197fn resolve_transmits(
198 values: &mut [Expr],
199 command: &str,
200 registry: &SymbolRegistry,
201) -> Result<(), String> {
202 if let Some(kind) = transmit_kind(command)
203 && let Some(Expr::Tuple(transmits)) = values.get_mut(2)
204 {
205 for value in transmits {
206 if let Expr::Identifier(name) = value {
207 let id = transmit_id(registry, kind, name)
208 .ok_or_else(|| format!("Unknown {kind} transmit trigger '{name}'"))?;
209 *value = Expr::IntLiteral(id);
210 }
211 }
212 }
213 Ok(())
214}
215
216pub(crate) fn lower(
217 registry: &SymbolRegistry,
218 name: &str,
219 args: &[Expr],
220 locals: &SymbolTable,
221 line: usize,
222) -> Result<Option<Vec<Expr>>, String> {
223 let Some(&explicit) = registry.hook_commands.get(name.trim_start_matches('.')) else {
224 return Ok(None);
225 };
226 if args.len() != 1 + usize::from(explicit) {
227 return Ok(None);
228 }
229 let component_first = explicit && registry.component_first_command(name);
230 let mut lowered = match &args[usize::from(component_first)] {
231 Expr::NullLiteral => vec![Expr::NullLiteral, Expr::StringLiteral(String::new())],
232 Expr::StringLiteral(text) => {
233 let mut values = parse_at(text, line)?;
234 resolve_transmits(&mut values, name, registry)?;
235 if let (Expr::Identifier(target), Expr::Tuple(args)) = (&values[0], &values[1])
236 && let Some(SymbolKind::Script { param_types, .. }) = registry
237 .lookup_script_by_trigger("clientscript", target)
238 .or_else(|| registry.lookup_script_by_trigger("proc", target))
239 .map(|symbol| &symbol.kind)
240 {
241 let expanded = expand(&values, registry, locals);
242 let Expr::StringLiteral(signature) = expanded.last().unwrap() else {
243 unreachable!()
244 };
245 let mut expected = [0usize; 3];
246 let mut actual = [0usize; 3];
247 let stack = |ty: Type| match ty.base_type() {
248 BaseVarType::Integer => 0,
249 BaseVarType::String => 1,
250 BaseVarType::Long => 2,
251 };
252 for ty in param_types {
253 expected[stack(*ty)] += 1;
254 }
255 for ch in signature.trim_end_matches('Y').chars() {
256 actual[stack(Type::from_char(ch).unwrap_or(Type::Int))] += 1;
257 }
258 if expected != actual {
259 return Err(format!(
260 "Hook '{target}' expects {expected:?} int/string/long arguments, got {actual:?} ({} expressions)",
261 args.len()
262 ));
263 }
264 }
265 expand(&values, registry, locals)
266 }
267 Expr::CommandCall {
268 name: marker, args, ..
269 } if marker == "__hook" => {
270 let mut values = args.clone();
271 resolve_transmits(&mut values, name, registry)?;
272 expand(&values, registry, locals)
273 }
274 _ => return Ok(None),
275 };
276 if explicit {
277 if component_first {
278 lowered.insert(0, args[0].clone());
279 } else {
280 lowered.push(args[1].clone());
281 }
282 }
283 Ok(Some(lowered))
284}
285
286pub(crate) fn parse(text: &str) -> Result<Vec<Expr>, String> {
287 parse_at(text, 1)
288}
289
290fn parse_at(text: &str, line: usize) -> Result<Vec<Expr>, String> {
291 let path = PathBuf::from("hook");
292 let mut tokens = Lexer::new(text, &path)
293 .tokenize()
294 .map_err(|e| e.to_string())?;
295 for token in &mut tokens {
296 token.line += line.saturating_sub(1);
297 }
298 Parser::new(tokens, &path)
299 .parse_hook()
300 .map_err(|e| e.to_string())
301}
302
303pub(crate) fn register_callbacks<'a>(
304 registry: &mut SymbolRegistry,
305 scripts: impl Iterator<Item = &'a ScriptDeclaration>,
306) {
307 let mut scripts: Vec<_> = scripts
308 .filter(|script| matches!(script.trigger.as_str(), "proc" | "clientscript"))
309 .collect();
310 scripts.sort_by_key(|script| script.trigger == "clientscript");
311 for script in scripts {
312 let id = registry
313 .script_id_for_trigger("clientscript", &script.name)
314 .or_else(|| {
315 script
316 .name
317 .strip_prefix("clientscript_")
318 .and_then(|id| id.parse::<i32>().ok())
319 .filter(|id| *id >= 0)
320 });
321 if let Some(id) = id {
322 registry.register_clientscript(
323 script.name.clone(),
324 id,
325 script.params.iter().map(|param| param.param_type).collect(),
326 );
327 }
328 }
329}
330
331pub(crate) fn server_call(
332 registry: &SymbolRegistry,
333 name: &str,
334 args: &[Expr],
335 locals: &SymbolTable,
336 line: usize,
337) -> Result<Option<Expr>, String> {
338 let command = name.trim_start_matches('.');
339 if !matches!(
340 command,
341 "runclientscript" | "runclientscript*" | "runclientscriptvararg"
342 ) {
343 return Ok(None);
344 }
345 let prefix = if name.starts_with('.') { "." } else { "" };
346 let syntax_error = || {
347 format!(
348 "Use {prefix}runclientscript(\"script(args)\"); the callback must be one quoted expression"
349 )
350 };
351 if command != "runclientscript" {
352 return Err(syntax_error());
353 }
354 let [Expr::StringLiteral(text)] = args else {
355 return Err(syntax_error());
356 };
357 let values = parse_at(text, line)?;
358 if values.len() > 2 {
359 return Err("runclientscript does not accept a transmit list".into());
360 }
361 let Expr::Identifier(target) = &values[0] else {
362 return Err("Expected clientscript name".into());
363 };
364 let id = registry
365 .script_id_for_trigger("clientscript", target)
366 .ok_or_else(|| format!("Unknown clientscript '{target}'"))?;
367 let params = registry
368 .client_script_params
369 .get(target)
370 .or_else(|| {
371 match registry
372 .lookup_script_by_trigger("clientscript", target)
373 .map(|symbol| &symbol.kind)
374 {
375 Some(SymbolKind::Script { param_types, .. }) => Some(param_types),
376 _ => None,
377 }
378 })
379 .ok_or_else(|| format!("Missing clientscript declaration for '{target}'"))?;
380 let Expr::Tuple(args) = &values[1] else {
381 unreachable!()
382 };
383 let hints = stack_hints(registry, params, args, locals);
384 let mut actual = [0usize; 3];
385 let mut expected = [0usize; 3];
386 let stack = |ty: Type| match ty.base_type() {
387 BaseVarType::Integer => 0,
388 BaseVarType::String => 1,
389 BaseVarType::Long => 2,
390 };
391 for ty in params {
392 expected[stack(*ty)] += 1;
393 }
394 let mut lowered = vec![Expr::IntLiteral(id)];
395 for (arg, hint) in args.iter().zip(hints) {
396 let mut arg = arg.clone();
397 if let (Expr::Identifier(value) | Expr::StringLiteral(value), Some(ty)) = (&arg, hint)
398 && let Some(id) = registry.lookup_reference(value, ty)
399 {
400 arg = Expr::IntLiteral(id);
401 }
402 for ty in expression_types(&arg, registry, locals) {
403 actual[stack(ty)] += 1;
404 }
405 lowered.push(arg);
406 }
407 if actual != expected {
408 return Err(format!(
409 "Clientscript '{target}' expects {expected:?} int/string/long arguments, got {actual:?}"
410 ));
411 }
412 if actual[2] != 0 {
413 return Err("runclientscript does not support long arguments".into());
414 }
415 let prefix = if name.starts_with('.') { "." } else { "" };
416 let suffix = if args.is_empty() { "" } else { "*" };
417 let count = lowered.len();
418 Ok(Some(Expr::CommandCall {
419 name: format!("{prefix}runclientscript{suffix}"),
420 args: lowered,
421 arg_lines: vec![line; count],
422 call_line: line,
423 }))
424}
425
426pub(crate) fn argument_hints(
428 registry: &SymbolRegistry,
429 script: &str,
430 args: &[Expr],
431 locals: &SymbolTable,
432) -> Vec<Option<Type>> {
433 match registry
434 .lookup_script_by_trigger("clientscript", script)
435 .or_else(|| registry.lookup_script_by_trigger("proc", script))
436 .map(|symbol| &symbol.kind)
437 {
438 Some(SymbolKind::Script { param_types, .. }) => {
439 stack_hints(registry, param_types, args, locals)
440 }
441 _ => vec![None; args.len()],
442 }
443}
444
445fn expand(values: &[Expr], registry: &SymbolRegistry, locals: &SymbolTable) -> Vec<Expr> {
446 let Expr::Tuple(args) = &values[1] else {
447 unreachable!()
448 };
449 let hints = if let Expr::Identifier(name) = &values[0] {
450 argument_hints(registry, name, args, locals)
451 } else {
452 vec![None; args.len()]
453 };
454 let mut signature = String::new();
455 for (arg, hint) in args.iter().zip(hints) {
456 let types = expression_types(arg, registry, locals);
457 if types.len() == 1 {
458 signature.push(hint.unwrap_or(types[0]).to_char());
459 } else {
460 signature.extend(types.iter().map(|ty| ty.to_char()));
461 }
462 }
463 let mut lowered = vec![values[0].clone()];
464 lowered.extend_from_slice(args);
465 if let Some(Expr::Tuple(transmits)) = values.get(2) {
466 lowered.extend_from_slice(transmits);
467 lowered.push(Expr::IntLiteral(transmits.len() as i32));
468 signature.push('Y');
469 }
470 lowered.push(Expr::StringLiteral(signature));
471 lowered
472}
473
474pub(crate) fn arguments_end(registry: &SymbolRegistry, name: &str, args: &[Expr]) -> Option<usize> {
476 let explicit = *registry.hook_commands.get(name.trim_start_matches('.'))?;
477 let component_first = explicit && registry.component_first_command(name);
478 let signature_index = args
479 .len()
480 .checked_sub(1 + usize::from(explicit && !component_first))?;
481 let Expr::StringLiteral(signature) = &args[signature_index] else {
482 return None;
483 };
484 if !signature.ends_with('Y') {
485 return Some(signature_index);
486 }
487 let Expr::IntLiteral(count) = args.get(signature_index.checked_sub(1)?)? else {
488 return None;
489 };
490 signature_index.checked_sub(usize::try_from(*count).ok()? + 1)
491}
492
493pub(crate) fn compact(
494 registry: &SymbolRegistry,
495 name: &str,
496 args: &mut Vec<Expr>,
497 locals: &SymbolTable,
498) {
499 let Some(&explicit) = registry.hook_commands.get(name.trim_start_matches('.')) else {
500 return;
501 };
502 let component_first = explicit && registry.component_first_command(name);
503 let target = usize::from(component_first);
504 let Some(signature_index) = args
505 .len()
506 .checked_sub(1 + usize::from(explicit && !component_first))
507 else {
508 return;
509 };
510 let Expr::StringLiteral(signature) = &args[signature_index] else {
511 return;
512 };
513 let mut end = signature_index;
514 let transmits = if signature.ends_with('Y') {
515 let Some(Expr::IntLiteral(count)) = end.checked_sub(1).and_then(|i| args.get(i)) else {
516 return;
517 };
518 let Ok(count) = usize::try_from(*count) else {
519 return;
520 };
521 let Some(start) = end.checked_sub(count + 1) else {
522 return;
523 };
524 let mut values = args[start..end - 1].to_vec();
525 if let Some(kind) = transmit_kind(name) {
526 for value in &mut values {
527 if let Expr::IntLiteral(id) = value
528 && let Some(name) = transmit_name(registry, kind, *id)
529 {
530 *value = Expr::Identifier(name);
531 }
532 }
533 }
534 end = start;
535 Some(Expr::Tuple(values))
536 } else {
537 None
538 };
539 if end <= target
540 || !matches!(
541 args[target],
542 Expr::Identifier(_) | Expr::IntLiteral(_) | Expr::NullLiteral
543 )
544 {
545 return;
546 }
547 let hook =
548 if matches!(args[target], Expr::NullLiteral) && signature.is_empty() && end == target + 1 {
549 Expr::NullLiteral
550 } else {
551 let mut values = vec![
552 args[target].clone(),
553 Expr::Tuple(args[target + 1..end].to_vec()),
554 ];
555 values.extend(transmits);
556 let expanded = expand(&values, registry, locals);
557 if !matches!(expanded.last(), Some(Expr::StringLiteral(value)) if value == signature) {
558 return;
559 }
560 Expr::CommandCall {
561 name: "__hook".into(),
562 args: values,
563 arg_lines: Vec::new(),
564 call_line: 0,
565 }
566 };
567 let mut compact = vec![hook];
568 if explicit {
569 if component_first {
570 compact.insert(0, args[0].clone());
571 } else {
572 compact.push(args[signature_index + 1].clone());
573 }
574 }
575 *args = compact;
576}