From 5d9e8847dfa43a812637e0d30ff27b390364bb09 Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:34:36 +0100 Subject: [PATCH] script: Wave 5 decompiler source-likeness and Roslyn bind improvements - Multi-cell caller/callee parameter coalescing across signatures, overrides, natives, LoadBytes/copy_row/stored_field_row, and post-async locals::named (CS7036 84.9k -> 27.0k, v_ temps 3,972 -> 477, stack_ 1,885 -> 0) - Emit visibility for StoreBytes/LoadBytes/ZeroBytes/StepI32/Construct/inherited fields (CS0122 -> 0) and per-member unsafe for async classes/programs (CS4004 -> 0) - Boxed receiver method sugar (box_at(&p1).GetHashCode()), unsubclassed builtin virtuals (System.Random.Next/NextDouble), alloc_managed/hard_raw separation, and IEnumerator promotion - Concrete-type null-coalescing, lambda/zero_bytes addr(ref ...), value-type try_cast, bool virtual/local zero-test folding, uint/Hash casts, two-step enum casts, and element_ptr deref fixes - Prelude Cell.MoveNext/Current, mixed bitwise/operator disambiguation, Vector3 field dedup, System.Rage.CompareExchange, split-vector overloads, and try_cast helpers --- .../io/or-io/src/gta6/script/emit/access.rs | 439 +++++++++++- crates/io/or-io/src/gta6/script/emit/mod.rs | 405 +++++++++-- crates/io/or-io/src/gta6/script/emit/tests.rs | 359 +++++++++- .../src/gta6/script/passes/aggregates/mod.rs | 639 +++++++++++++----- .../gta6/script/passes/aggregates/tests.rs | 221 +++++- .../src/gta6/script/passes/interproc/mod.rs | 24 +- .../src/gta6/script/passes/interproc/tests.rs | 20 + .../gta6/script/passes/sugar_runtime/mod.rs | 87 ++- .../gta6/script/passes/sugar_runtime/tests.rs | 132 +++- .../src/gta6/script/passes/types/kinds.rs | 8 + .../or-io/src/gta6/script/passes/types/mod.rs | 225 +++++- .../src/gta6/script/passes/types/tests.rs | 136 ++++ .../gta6/script/passes/values/locals/mod.rs | 85 ++- .../gta6/script/passes/values/locals/tests.rs | 139 ++++ .../src/gta6/script/print/constructs/mod.rs | 20 + .../src/gta6/script/print/constructs/tests.rs | 109 ++- .../or-io/src/gta6/script/print/enums/mod.rs | 30 +- .../src/gta6/script/print/enums/tests.rs | 48 +- crates/io/or-io/src/gta6/script/print/mod.rs | 345 ++++++++-- .../src/gta6/script/print/prelude/mod.rs | 191 +++++- .../src/gta6/script/print/prelude/tests.rs | 183 ++++- .../io/or-io/src/gta6/script/print/tests.rs | 522 +++++++++++++- .../io/or-io/src/gta6/script/reparse/mod.rs | 6 + 23 files changed, 4009 insertions(+), 364 deletions(-) diff --git a/crates/io/or-io/src/gta6/script/emit/access.rs b/crates/io/or-io/src/gta6/script/emit/access.rs index 528d28055..9b4e7561c 100644 --- a/crates/io/or-io/src/gta6/script/emit/access.rs +++ b/crates/io/or-io/src/gta6/script/emit/access.rs @@ -12,8 +12,11 @@ use std::collections::{BTreeMap, BTreeSet}; -use super::super::class::{Class, Method, Unit}; -use super::super::ir::{Callee, Expr, ExprSugar, FunctionKey, Stmt, TypeKey, Var}; +use super::super::class::{Class, Method, Role, Unit}; +use super::super::ir::{ + Callee, Expr, ExprSugar, FunctionKey, Head, Kind, Stmt, TypeKey, Var, FUNCTION_OFFSET, +}; +use super::super::print::Lambdas; use super::super::tree::{self, Group, Sugar}; use super::super::Context; @@ -32,6 +35,8 @@ pub(super) struct Access { struct Owners { functions: BTreeMap>, parents: BTreeMap, + bases: BTreeMap, + default_ctors: BTreeMap>, } impl Owners { @@ -39,16 +44,26 @@ impl Owners { let mut owners = Owners { functions: BTreeMap::new(), parents: BTreeMap::new(), + bases: BTreeMap::new(), + default_ctors: BTreeMap::new(), }; for method in &unit.functions { owners.functions.insert(method.function.head.at, None); } let mut open: Vec<&Class> = unit.classes.iter().collect(); while let Some(class) = open.pop() { + if let Some(base) = class.base { + owners.bases.insert(class.key, base); + } for method in &class.methods { - owners - .functions - .insert(method.function.head.at, Some(class.key)); + let at = method.function.head.at; + owners.functions.insert(at, Some(class.key)); + if method.role == Role::Constructor + && !method.is_static + && method.function.head.params <= 1 + { + owners.default_ctors.entry(class.key).or_default().push(at); + } } for nested in &class.nested { owners.parents.insert(nested.key, class.key); @@ -76,7 +91,7 @@ impl Owners { impl Access { /// What code outside a member's own class reaches of `unit`, by every body of it. - pub(super) fn of(unit: &Unit, cx: &Context<'_>) -> Access { + pub(super) fn of(unit: &Unit, lambdas: &Lambdas<'_>, cx: &Context<'_>) -> Access { let owners = Owners::of(unit); let mut access = Access::default(); let mut bodies: Vec<(Option, &Method)> = @@ -86,16 +101,61 @@ impl Access { bodies.extend(class.methods.iter().map(|method| (Some(class.key), method))); open.extend(&class.nested); } + // An in-place lambda's body is emitted inside the method that binds it, not inside its + // closure class, so resolve its effective caller to that enclosing binder. + let mut raw_binder: BTreeMap, u32)> = BTreeMap::new(); + if !lambdas.is_empty() { + for &(caller, method) in &bodies { + let binder_at = method.function.head.at; + tree::each_expr(&method.function.body, &mut |top| { + top.walk(&mut |e| { + if let Expr::FunctionRef { program, at } = e { + if *program == unit.program { + let target = *at & FUNCTION_OFFSET; + if lambdas.contains_key(&target) { + raw_binder.entry(target).or_insert((caller, binder_at)); + } + } + } + }); + }); + } + } for (caller, method) in bodies { - access.read(&owners, caller, &method.function.body, unit.program, cx); + let mut effective = caller; + let mut cur = method.function.head.at; + if method.role == Role::Lambda && lambdas.contains_key(&cur) { + for _ in 0..16 { + let Some(&(binder_caller, binder_at)) = raw_binder.get(&cur) else { + break; + }; + effective = binder_caller; + if !lambdas.contains_key(&binder_at) || binder_at == cur { + break; + } + cur = binder_at; + } + } + access.read( + &owners, + effective, + caller.filter(|_| !method.is_static), + &method.function.head, + &method.function.body, + unit.program, + cx, + ); } access } + #[allow(clippy::too_many_arguments)] fn read( &mut self, owners: &Owners, caller: Option, + this_type: Option, + head: &Head, body: &[tree::Stmt], program: u32, cx: &Context<'_>, @@ -107,15 +167,48 @@ impl Access { } }; let field = |access: &mut Access, owner: TypeKey, offset: u32| { - if !owners.within(caller, Some(owner)) { - // ⚠ A field reached through a type is declared by it or by a base of it. - let mut ty = Some(owner); - let mut steps = 0; - while let (Some(key), true) = (ty, steps < 64) { + // ⚠ A field reached through a type is declared by it or by a base of it. + // Check `within` for each class in the hierarchy so a derived class accessing an + // inherited base-class field marks the base class's field `internal`. + let mut ty = Some(owner); + let mut steps = 0; + while let (Some(key), true) = (ty, steps < 64) { + if !owners.within(caller, Some(key)) { access.fields.insert((key, offset)); - ty = cx.project.types.get(&key).and_then(|facts| facts.base); - steps += 1; } + ty = cx + .project + .types + .get(&key) + .and_then(|facts| facts.base) + .or_else(|| owners.bases.get(&key).copied()); + steps += 1; + } + }; + let record_addr = |access: &mut Access, addr: &Expr, offset: u32| { + let mut offsets = vec![offset]; + let mut base = strip_wrappers(addr); + while let Expr::ByteOffset { + addr: inner, + offset: inner_off, + } = base + { + let Some(off) = const_u32(inner_off) else { + break; + }; + offsets.push(off); + base = strip_wrappers(inner); + } + let mut ty = expr_type(base, head, this_type, program, cx, 0); + for &off in offsets.iter().rev() { + let Some(owner) = ty else { + break; + }; + field(access, owner, off); + ty = cx + .project + .field(owner, off) + .and_then(|f| kind_type(&f.kind)); } }; let own_global = |var: &Var| matches!(var, Var::Global { program: p, .. } if *p == program); @@ -125,14 +218,57 @@ impl Access { callee: Callee::Local { at, .. }, .. } => reached(self, *at), - Expr::FunctionRef { program: p, at } if *p == program => reached(self, *at), + Expr::FunctionRef { program: p, at } if *p == program => { + reached(self, *at & FUNCTION_OFFSET); + } + Expr::NewObject(ty) => { + if let Some(owner) = TypeKey::of(ty) { + if !owners.within(caller, Some(owner)) { + if let Some(ctors) = owners.default_ctors.get(&owner) { + for &at in ctors { + self.functions.insert(at); + } + } + } + } + } Expr::Sugar { kind: ExprSugar::Field { owner }, e, - } => { - if let Expr::Load { offset, .. } = &**e { + } => match &**e { + Expr::Load { offset, .. } | Expr::LoadBytes { offset, .. } => { field(self, *owner, *offset); } + Expr::ByteOffset { offset, .. } => { + if let Some(off) = const_u32(offset) { + field(self, *owner, off); + } + } + _ => {} + }, + Expr::Load { addr, offset, .. } | Expr::LoadBytes { addr, offset, .. } => { + record_addr(self, addr, *offset); + } + Expr::ByteOffset { addr, offset } => { + if let Some(off) = const_u32(offset) { + record_addr(self, addr, off); + } + } + Expr::ExtractBytes { value, offset, .. } => { + let target = match strip_wrappers(value) { + Expr::Cells(items) if items.len() == 1 => { + Some((strip_wrappers(&items[0]), *offset)) + } + Expr::Cells(items) => items + .get((*offset / 8) as usize) + .map(|item| (strip_wrappers(item), *offset % 8)), + other => Some((other, *offset)), + }; + if let Some((base, off)) = target { + if let Some(owner) = expr_type(base, head, this_type, program, cx, 0) { + field(self, owner, off); + } + } } Expr::Var(var) | Expr::AddrOf { var, .. } if caller.is_some() && own_global(var) => @@ -146,24 +282,101 @@ impl Access { if caller.is_some() && s.targets().iter().any(own_global) { self.globals = true; } + match s { + Stmt::Store { addr, offset, .. } + | Stmt::StoreBytes { addr, offset, .. } + | Stmt::StoreF32Slots { addr, offset, .. } + | Stmt::StepI32 { addr, offset, .. } => { + record_addr(self, addr, *offset); + } + Stmt::ZeroBytes { addr, .. } => { + if let Expr::ByteOffset { + addr: inner, + offset, + } = strip_wrappers(addr) + { + if let Some(off) = const_u32(offset) { + record_addr(self, inner, off); + } + } + } + _ => {} + } }); tree::each_sugar(body, &mut |sugar| { let Sugar::Group { kind, parts } = sugar else { return; }; - let made = match kind { - Group::Field { owner } => Some(*owner), - // The fields an initialiser gives values are the made object's. - Group::Construct => parts.iter().find_map(made_type), - _ => None, - }; - let Some(owner) = made else { - return; - }; - for s in parts { - if let Stmt::Store { offset, .. } = s { - field(self, owner, *offset); + match kind { + Group::Field { owner } => { + for s in parts { + match s { + Stmt::Store { offset, .. } + | Stmt::StoreBytes { offset, .. } + | Stmt::StoreF32Slots { offset, .. } + | Stmt::StepI32 { offset, .. } => { + field(self, *owner, *offset); + } + Stmt::ZeroBytes { addr, .. } => { + let off = match strip_wrappers(addr) { + Expr::ByteOffset { offset, .. } => { + const_u32(offset).unwrap_or(0) + } + _ => 0, + }; + field(self, *owner, off); + } + _ => {} + } + } + } + // The fields an initialiser gives values are the made object's (including any + // nested objects constructed inside the same group). + Group::Construct => { + let mut made_vars: BTreeMap = BTreeMap::new(); + let mut first_owner: Option = None; + for s in parts { + if let Some((var, key)) = made_var_type(s) { + made_vars.insert(var, key); + if first_owner.is_none() { + first_owner = Some(key); + } + } + } + let target_owner = |addr: &Expr| -> Option { + if let Expr::Var(v) = strip_wrappers(addr) { + if let Some(&key) = made_vars.get(v) { + return Some(key); + } + } + first_owner + }; + for s in parts { + match s { + Stmt::Store { addr, offset, .. } + | Stmt::StoreBytes { addr, offset, .. } + | Stmt::StoreF32Slots { addr, offset, .. } + | Stmt::StepI32 { addr, offset, .. } => { + if let Some(owner) = target_owner(addr) { + field(self, owner, *offset); + } + } + Stmt::ZeroBytes { addr, .. } => { + if let Expr::ByteOffset { addr: base, offset } = + strip_wrappers(addr) + { + if let (Some(owner), Some(off)) = + (target_owner(base), const_u32(offset)) + { + field(self, owner, off); + } + } + } + _ => {} + } + } } + _ => {} } }); } @@ -191,13 +404,171 @@ impl Access { } } -/// The type of the object a statement of an initialiser makes, where it makes one. -fn made_type(s: &Stmt) -> Option { - let Stmt::Assign { value, .. } = s else { +/// The variable and type of the object a statement of an initialiser makes, where it makes one. +fn made_var_type(s: &Stmt) -> Option<(Var, TypeKey)> { + let Stmt::Assign { target, value } = s else { return None; }; - match value { - Expr::NewObject(ty) => TypeKey::of_name(&ty.name), + match strip_wrappers(value) { + Expr::NewObject(ty) => TypeKey::of(ty).map(|key| (*target, key)), + _ => None, + } +} + +/// Strips outer `Cast` and `Sugar` wrappers from an expression. +fn strip_wrappers(mut e: &Expr) -> &Expr { + loop { + match e { + Expr::Cast { e: inner, .. } | Expr::Sugar { e: inner, .. } => e = inner, + _ => return e, + } + } +} + +/// Extracts a `u32` byte offset from a constant expression. +fn const_u32(e: &Expr) -> Option { + match strip_wrappers(e) { + Expr::Const(c) => u32::try_from(c.bits).ok(), + _ => None, + } +} + +/// Extracts the `TypeKey` from a `Kind::Object` or `Kind::Value`. +fn kind_type(kind: &Kind) -> Option { + match kind { + Kind::Object(name) | Kind::Value { ty: name, .. } => TypeKey::of_name(name), + _ => None, + } +} + +/// Looks up the `Kind` of a program global or static from project facts. +fn global_kind(program: u32, offset: u32, statics: bool, cx: &Context<'_>) -> Option { + if let Some(info) = cx.project.programs.get(&program) { + let stated = match statics { + true => info.statics.get(&offset), + false => info.globals.get(&offset), + }; + if let Some(kind) = stated { + return Some(kind.clone()); + } + } + cx.project + .cell(program, offset, statics) + .map(|cell| cell.kind.clone()) +} + +/// Infers the `TypeKey` of an address or value expression when its type is known. +fn expr_type( + e: &Expr, + head: &Head, + this_type: Option, + program: u32, + cx: &Context<'_>, + depth: u8, +) -> Option { + let kind = expr_kind(e, head, this_type, program, cx, depth)?; + kind_type(&kind) +} + +/// Infers the `Kind` of an expression from `head.vars`, globals, field layouts, and call signatures. +fn expr_kind( + e: &Expr, + head: &Head, + this_type: Option, + program: u32, + cx: &Context<'_>, + depth: u8, +) -> Option { + if depth >= 8 { + return None; + } + match e { + Expr::Cast { e, .. } => expr_kind(e, head, this_type, program, cx, depth + 1), + Expr::Sugar { + kind: ExprSugar::Field { owner }, + e, + } => { + let off = match &**e { + Expr::Load { offset, .. } | Expr::LoadBytes { offset, .. } => Some(*offset), + Expr::ByteOffset { offset, .. } => const_u32(offset), + _ => None, + }?; + cx.project.field(*owner, off).map(|f| f.kind.clone()) + } + Expr::Sugar { e, .. } => expr_kind(e, head, this_type, program, cx, depth + 1), + Expr::Var(Var::Global { + program: p, + offset, + statics, + }) + | Expr::AddrOf { + var: + Var::Global { + program: p, + offset, + statics, + }, + cell: 0, + } => global_kind(*p, *offset, *statics, cx), + Expr::Var(var) | Expr::AddrOf { var, cell: 0 } => { + if let Some(info) = head.vars.get(var) { + if !matches!(info.kind, Kind::Unknown) { + return Some(info.kind.clone()); + } + } + if *var == Var::Param(0) { + return this_type.map(|key| Kind::Object(key.to_string())); + } + None + } + Expr::NewObject(ty) => TypeKey::of(ty).map(|key| Kind::Object(key.to_string())), + Expr::Call { + callee: Callee::Intrinsic { name, ty, .. }, + args, + .. + } => { + if name == "array_element_address" || name == "array_get_u64" { + let arr = args.first()?; + return match expr_kind(arr, head, this_type, program, cx, depth + 1)? { + Kind::Array(elem) => Some(*elem), + _ => None, + }; + } + if let Some(vm_ty) = ty { + if name.starts_with("cast<") + || name.starts_with("try_cast<") + || name.starts_with("box<") + { + return TypeKey::of(vm_ty).map(|key| Kind::Object(key.to_string())); + } + } + None + } + Expr::Call { + callee: Callee::Local { at, .. }, + .. + } => cx + .project + .signatures + .get(&FunctionKey::new(program, *at)) + .map(|sig| sig.result.clone()), + Expr::Call { + callee: Callee::Import { program: p, at, .. }, + .. + } => cx + .project + .signatures + .get(&FunctionKey::new(*p, *at)) + .map(|sig| sig.result.clone()), + Expr::Load { addr, offset, .. } | Expr::LoadBytes { addr, offset, .. } => { + let owner = expr_type(addr, head, this_type, program, cx, depth + 1)?; + cx.project.field(owner, *offset).map(|f| f.kind.clone()) + } + Expr::ByteOffset { addr, offset } => { + let off = const_u32(offset)?; + let owner = expr_type(addr, head, this_type, program, cx, depth + 1)?; + cx.project.field(owner, off).map(|f| f.kind.clone()) + } _ => None, } } diff --git a/crates/io/or-io/src/gta6/script/emit/mod.rs b/crates/io/or-io/src/gta6/script/emit/mod.rs index da61348fb..20fe94c4b 100644 --- a/crates/io/or-io/src/gta6/script/emit/mod.rs +++ b/crates/io/or-io/src/gta6/script/emit/mod.rs @@ -92,57 +92,369 @@ fn source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> String { format!("{header}\n{lines}{body}") } -/// `text`, a file, with `unsafe` on each declaration at its margin whose text uses a pointer: a pointer's type, `*p`, `&x`, `p->f`, or a name the file declares a member of a pointer's type. -// ⚠ C# takes a pointer only in an unsafe context, and a type's `unsafe` makes one of all it holds. -// A call of a method that takes or gives a pointer is one too, so the word goes on the type and not -// on the members that show a pointer; an `await` of the type's then stands in an unsafe context, -// which C# refuses, as it refuses a pointer in an `async` method. +/// `text`, a file, with `unsafe` on declarations that use a pointer: a pointer's type, `*p`, `&x`, `p->f`, or a name the file declares a member of a pointer's type. +/// +/// Types that contain no `async` method or `await` receive `unsafe` on the type header itself. +/// Types that contain an `async` method or `await` (directly or in a nested type) omit `unsafe` on +/// the enclosing type header — because C# refuses `await` inside an `unsafe` context (`CS4004`) — +/// and place `unsafe` individually on each pointer-using field, global, non-`async` non-iterator +/// member, and non-`async` nested type. fn unsafe_where_pointed(text: &str) -> String { let lines: Vec<&str> = text.split_inclusive('\n').collect(); let pointers = pointer_names(&lines); - let uses = |line: &str| holds_pointer(line) || names_any(line, &pointers); + let callables = pointer_callables(&lines); let mut out = String::with_capacity(text.len() + 64); let mut n = 0; while n < lines.len() { - let line = lines[n]; - let head = ["static partial class ", "class ", "struct ", "interface "] - .iter() - .find(|start| line.starts_with(*start)); - let Some(start) = head else { - out.push_str(line); + if let Some((kind, brace, end)) = type_block_end(&lines, n, 0) { + emit_type_block( + &lines[n..=end], + 0, + kind, + brace - n, + &pointers, + &callables, + &mut out, + ); + n = end + 1; + } else { + out.push_str(lines[n]); n += 1; + } + } + out +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum TypeBlockKind { + /// `static partial class` or `public static partial class` (program file class). + FileClass, + /// `class`, `struct`, or `interface`. + UnsafeCapable, + /// `enum` (never takes `unsafe`). + Enum, +} + +/// Classifies a type declaration header line (already trimmed of leading indentation). +fn type_head_kind(trimmed: &str) -> Option { + if trimmed.is_empty() || trimmed.starts_with("//") { + return None; + } + if trimmed.starts_with("static partial class ") + || trimmed.starts_with("public static partial class ") + { + return Some(TypeBlockKind::FileClass); + } + let mut rest = trimmed; + for kw in [ + "public ", + "internal ", + "private ", + "protected ", + "static ", + "partial ", + ] { + if let Some(after) = rest.strip_prefix(kw) { + rest = after; + } + } + if rest.starts_with("class ") || rest.starts_with("struct ") || rest.starts_with("interface ") { + Some(TypeBlockKind::UnsafeCapable) + } else if rest.starts_with("enum ") { + Some(TypeBlockKind::Enum) + } else { + None + } +} + +/// If `lines[start]` opens a type declaration at `depth`, returns `(kind, brace_line, close_line)`. +fn type_block_end( + lines: &[&str], + start: usize, + depth: usize, +) -> Option<(TypeBlockKind, usize, usize)> { + let pad = " ".repeat(depth); + let line = lines.get(start)?; + let rest = line.strip_prefix(pad.as_str())?; + if rest.starts_with(' ') { + return None; + } + let kind = type_head_kind(rest)?; + let mut brace = start; + while lines[brace].trim_end().ends_with(',') && brace + 1 < lines.len() { + brace += 1; + } + brace += 1; + let open_brace = format!("{pad}{{"); + if lines.get(brace).map(|l| l.trim_end()) != Some(open_brace.as_str()) { + return None; + } + let close_brace = format!("{pad}}}"); + let end = (brace + 1..lines.len()).find(|&m| lines[m].trim_end() == close_brace)?; + Some((kind, brace, end)) +} + +/// Emits one type block (`block[0..=end]`) with class-level `unsafe` if it contains no `async`/`await`, +/// or per-member `unsafe` if it (or any nested type inside it) contains `async`/`await`. +fn emit_type_block( + block: &[&str], + depth: usize, + kind: TypeBlockKind, + brace: usize, + pointers: &BTreeSet, + callables: &BTreeSet, + out: &mut String, +) { + if kind == TypeBlockKind::Enum { + out.push_str(&block.concat()); + return; + } + let uses = + |line: &str| holds_pointer(line) || names_any(line, pointers) || names_any(line, callables); + if !block.iter().any(|line| uses(line)) { + out.push_str(&block.concat()); + return; + } + // A nested `public static partial class` (dotted program name) never takes `unsafe` on its own + // header so `reparse::unfiled` keeps reading it unchanged; its members take `unsafe` instead. + let nested_file_class = depth > 0 && kind == TypeBlockKind::FileClass; + if !has_async_or_await(block) && !nested_file_class { + let head = with_unsafe(&join_laid(&block[..brace])); + indent(out, depth); + out.push_str(&print::laid(&head, depth)); + out.push('\n'); + out.push_str(&block[brace..].concat()); + return; + } + // Contains `async`/`await`: keep the enclosing type header safe and mark individual members. + out.push_str(&block[..=brace].concat()); + let member_depth = depth + 1; + let member_pad = " ".repeat(member_depth); + let member_open = format!("{member_pad}{{"); + let member_close = format!("{member_pad}}}"); + let body_end = block.len() - 1; + let mut i = brace + 1; + while i < body_end { + let trimmed = block[i].trim(); + if trimmed.is_empty() || trimmed.starts_with("//") { + out.push_str(block[i]); + i += 1; continue; - }; - let end = (n + 1..lines.len()) - .find(|m| lines[*m].trim_end() == "}") - .unwrap_or(lines.len() - 1); - if !lines[n..=end].iter().any(|line| uses(line)) { - out.push_str(&lines[n..=end].concat()); - n = end + 1; + } + if let Some((nested_kind, nested_brace, nested_end)) = + type_block_end(&block[..body_end], i, member_depth) + { + emit_type_block( + &block[i..=nested_end], + member_depth, + nested_kind, + nested_brace - i, + pointers, + callables, + out, + ); + i = nested_end + 1; continue; } - // A head laid over lines goes on under itself, each line but its last ending with a comma; - // with its word it is laid again at the width. - let mut last = n; - while lines[last].trim_end().ends_with(',') && last < end { - last += 1; + let at_member = block[i] + .strip_prefix(member_pad.as_str()) + .is_some_and(|rest| !rest.starts_with(' ')); + if !at_member { + out.push_str(block[i]); + i += 1; + continue; } - let head: Vec<&str> = lines[n..=last].iter().map(|line| line.trim()).collect(); - let head = head.join(" "); - let head = match *start { - "static partial class " => { - format!("static unsafe partial class {}", &head[start.len()..]) + let mut j = i; + let mut handled = false; + while j < body_end { + if j > i && block[j].trim_end() == member_open { + if let Some(close) = + (j + 1..body_end).find(|&k| block[k].trim_end() == member_close) + { + let member_slice = &block[i..=close]; + // Non-async, non-iterator methods inside a pointer-using async class may access + // cross-file `void*` fields/globals invisible to single-file text scanning; marking + // every such member `unsafe` avoids `CS0214` while keeping `async` methods `CS4004`-free. + if !has_async_or_await(member_slice) && !has_yield(member_slice) { + let head = with_unsafe(&join_laid(&block[i..j])); + indent(out, member_depth); + out.push_str(&print::laid(&head, member_depth)); + out.push('\n'); + out.push_str(&block[j..=close].concat()); + } else { + out.push_str(&member_slice.concat()); + } + i = close + 1; + handled = true; + } + break; } - _ => format!("unsafe {head}"), - }; - out.push_str(&print::laid(&head, 0)); - out.push('\n'); - out.push_str(&lines[last + 1..=end].concat()); - n = end + 1; + let code = block[j].split(" //").next().unwrap_or(block[j]).trim_end(); + if code.ends_with(';') { + let member_slice = &block[i..=j]; + if !has_async_or_await(member_slice) + && member_slice.iter().any(|l| l.contains("=>") || uses(l)) + { + let head = with_unsafe(&join_laid(member_slice)); + indent(out, member_depth); + out.push_str(&print::laid(&head, member_depth)); + out.push('\n'); + } else { + out.push_str(&member_slice.concat()); + } + i = j + 1; + handled = true; + break; + } + j += 1; + } + if !handled { + out.push_str(block[i]); + i += 1; + } + } + out.push_str(block[body_end]); +} + +/// Inserts `unsafe ` into a type or member header in valid C# modifier order. +fn with_unsafe(head: &str) -> String { + if head.starts_with("unsafe ") || head.contains(" unsafe ") { + return head.to_owned(); + } + for access in ["public ", "internal ", "private ", "protected "] { + if let Some(rest) = head.strip_prefix(access) { + return format!("{access}unsafe {rest}"); + } + } + if let Some(rest) = head.strip_prefix("static partial class ") { + return format!("static unsafe partial class {rest}"); + } + format!("unsafe {head}") +} + +/// Rejoins lines previously broken by [`print::laid`] into a single string without adding spaces after `(` or `{`. +fn join_laid(lines: &[&str]) -> String { + let mut out = String::new(); + for (i, line) in lines.iter().enumerate() { + let trimmed = line.trim(); + if i > 0 && !out.ends_with('(') && !out.ends_with('{') { + out.push(' '); + } + out.push_str(trimmed); } out } +/// Whether `lines` contain an `async` modifier or an `await` expression outside comments and strings. +fn has_async_or_await(lines: &[&str]) -> bool { + lines + .iter() + .any(|line| line_has_keyword(line, "async ") || line_has_keyword(line, "await ")) +} + +/// Whether `lines` contain a `yield return` or `yield break` statement outside comments and strings. +fn has_yield(lines: &[&str]) -> bool { + lines + .iter() + .any(|line| line_has_keyword(line, "yield return") || line_has_keyword(line, "yield break")) +} + +/// Whether `line` contains `phrase` as a C# keyword outside comments and string/char literals. +fn line_has_keyword(line: &str, phrase: &str) -> bool { + let trimmed = line.trim_start(); + if trimmed.starts_with("//") { + return false; + } + let bytes = trimmed.as_bytes(); + let needle = phrase.as_bytes(); + if needle.is_empty() || bytes.len() < needle.len() { + return false; + } + let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_'; + let mut i = 0; + let mut quote: Option = None; + while i < bytes.len() { + let b = bytes[i]; + if let Some(q) = quote { + if b == b'\\' { + i += 2; + continue; + } + if b == q { + quote = None; + } + i += 1; + continue; + } + if b == b'/' && bytes.get(i + 1) == Some(&b'/') { + break; + } + if b == b'"' || b == b'\'' { + quote = Some(b); + i += 1; + continue; + } + if bytes[i..].starts_with(needle) { + let before_ok = + i == 0 || (!is_word(bytes[i - 1]) && bytes[i - 1] != b'@' && bytes[i - 1] != b'.'); + let after_idx = i + needle.len(); + let after_ok = needle.last() == Some(&b' ') + || after_idx == bytes.len() + || !is_word(bytes[after_idx]); + if before_ok && after_ok { + return true; + } + } + i += 1; + } + false +} + +/// The names of `func_*` functions/methods declared in `lines` whose signature holds a pointer. +fn pointer_callables(lines: &[&str]) -> BTreeSet { + let mut names = BTreeSet::new(); + let mut i = 0; + while i < lines.len() { + let trimmed = lines[i].trim_start(); + if trimmed.is_empty() || trimmed.starts_with("//") { + i += 1; + continue; + } + let code = trimmed.split(" //").next().unwrap_or(trimmed).trim_end(); + if !code.contains('(') || code.ends_with(';') { + i += 1; + continue; + } + let Some((before, _)) = code.split_once('(') else { + i += 1; + continue; + }; + if before.contains(['=', '.', '!']) { + i += 1; + continue; + } + let mut words = before.split_whitespace(); + let Some(name) = words.next_back() else { + i += 1; + continue; + }; + // A method declaration always has at least a return type before its name. + if words.next().is_none() || !name.starts_with("func_") { + i += 1; + continue; + } + let mut j = i; + while lines[j].trim_end().ends_with(',') && j + 1 < lines.len() { + j += 1; + } + if lines[i..=j].iter().any(|l| holds_pointer(l)) { + names.insert(name.to_owned()); + } + i = j + 1; + } + names +} + /// The names `lines` declare a member of a pointer's type: a field or a global, `void* f_8;`, /// `static void* a, b;`, including declarations laid across multiple lines. // ⚠ Another type's code reads such a member with no pointer in sight, and still needs an unsafe context. @@ -273,7 +585,7 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool let parts: Vec<&str> = path.split('.').collect(); // ⚠ The form of old says nothing of who may reach a member, nor does true C# with `access` off. let access = (print::true_csharp(&cx.options) && cx.options.on(Pass::Modifiers)) - .then(|| Access::of(unit, cx)); + .then(|| Access::of(unit, &lambdas, cx)); let shared = access .as_ref() .is_some_and(|access| access.globals(unit.program, cx)); @@ -480,7 +792,7 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool } } let word = access.as_ref().and_then(|access| { - member_access( + let primary = member_access( access, class, method, @@ -488,7 +800,24 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool cx, depth > 0, explicit.is_some(), - ) + ); + let secondary = match part { + print::IndexerPart::Getter(Some(setter)) => member_access( + access, + class, + setter, + unit, + cx, + depth > 0, + explicit.is_some(), + ), + _ => None, + }; + match (primary, secondary) { + (Some("public "), _) | (_, Some("public ")) => Some("public "), + (Some(w), _) | (_, Some(w)) => Some(w), + (None, None) => None, + } }); match word { Some(word) => out.push_str(&modified(&text, depth + 1, word)), diff --git a/crates/io/or-io/src/gta6/script/emit/tests.rs b/crates/io/or-io/src/gta6/script/emit/tests.rs index 29fe95125..f88c61a16 100644 --- a/crates/io/or-io/src/gta6/script/emit/tests.rs +++ b/crates/io/or-io/src/gta6/script/emit/tests.rs @@ -938,14 +938,23 @@ struct type_B ] { assert_eq!(holds_pointer(line), pointed, "{line}"); } - // A type that only reads a member of a pointer's type another declares needs the word too, - // and takes it whole, its `async` methods too. + // A type that only reads a member of a pointer's type another declares needs the word too: + // on the type whole where it holds no `async` method, and on the reading member alone where + // the type holds `async`/`await` so `await` does not stand in an unsafe context (`CS4004`). let text = "\ class type_P { internal void* f_8; } +class type_R +{ + void Read(type_P p1) + { + DEMO.USE(p1.f_8); + } +} + class type_Q { int f_10; @@ -968,8 +977,15 @@ class type_Q "; let made = unsafe_where_pointed(text); assert!(made.starts_with("unsafe class type_P\n"), "{made}"); - assert!(made.contains("\nunsafe class type_Q\n"), "{made}"); - assert!(made.contains("\n void Read(type_P p1)\n"), "{made}"); + assert!(made.contains("\nunsafe class type_R\n"), "{made}"); + assert!(made.contains("\nclass type_Q\n"), "{made}"); + assert!(!made.contains("\nunsafe class type_Q\n"), "{made}"); + assert!( + made.contains("\n unsafe void Read(type_P p1)\n"), + "{made}" + ); + assert!(made.contains("\n async Task Wait()\n"), "{made}"); + assert!(made.contains("\n unsafe int Plain()\n"), "{made}"); // A head the word passes the width with is laid again at it. let bases: Vec = (0..4).map(|n| format!("type_00000000000000B{n}")).collect(); let head = format!("class type_A0123456789ABCDE : {}", bases.join(", ")); @@ -1435,3 +1451,338 @@ class type_Clean assert!(made.contains("\nunsafe class type_SecondLine\n"), "{made}"); assert!(made.contains("\nclass type_Clean\n"), "{made}"); } + +#[test] +fn cs0122_store_bytes_load_bytes_construct_and_inherited_fields_are_internal() { + let outer_key = TypeKey(0x4845_535A_02F8_5996); + let inner_key = TypeKey(0x4845_535A_02F8_5997); + let base_key = TypeKey(0x4845_535A_02F8_5998); + let derived_key = TypeKey(0x4845_535A_02F8_5999); + let vm_ty = |key: TypeKey| VmType { + name: key.to_string(), + byte_size: 0x60, + id: 5, + flags: 0, + }; + + // Free function constructs `outer_key` with `StoreBytes` (16-byte handle field `f_2C`), + // constructs a nested `inner_key` with `StoreBytes` (`f_10`) inside the same `Group::Construct`, + // reads `outer_key.f_3C` via `ExprSugar::Field` + `LoadBytes`, takes `&outer_key.f_4C` via + // `ExprSugar::Field` + `ByteOffset`, and writes `outer_key.f_50` via an unwrapped `StoreBytes` + // on a typed local. + let construct_parts = vec![ + Stmt::Assign { + target: Var::Local(0), + value: Expr::NewObject(vm_ty(outer_key)), + }, + Stmt::StoreBytes { + addr: Expr::Var(Var::Local(0)), + offset: 0x2C, + bytes: 16, + value: Expr::ZeroSlots(2), + }, + Stmt::Assign { + target: Var::Local(1), + value: Expr::NewObject(vm_ty(inner_key)), + }, + Stmt::StoreBytes { + addr: Expr::Var(Var::Local(1)), + offset: 0x10, + bytes: 16, + value: Expr::ZeroSlots(2), + }, + Stmt::Store { + kind: StoreKind::Ref, + addr: Expr::Var(Var::Local(0)), + offset: 0x8, + value: Expr::Var(Var::Local(1)), + }, + ]; + let load_bytes = Expr::sugar( + ExprSugar::Field { owner: outer_key }, + Expr::LoadBytes { + addr: Box::new(Expr::Var(Var::Local(0))), + offset: 0x3C, + bytes: 16, + }, + ); + let byte_off = Expr::sugar( + ExprSugar::Field { owner: outer_key }, + Expr::ByteOffset { + addr: Box::new(Expr::Var(Var::Local(0))), + offset: Box::new(Expr::Const(Const::i32(0x4C))), + }, + ); + let mut free_fn = function( + 0x10, + 0, + Returns::Void, + vec![ + tree::Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: tree::Group::Construct, + parts: construct_parts, + })), + tree::Stmt::Simple(Stmt::Assign { + target: Var::Local(2), + value: load_bytes, + }), + tree::Stmt::Simple(Stmt::Assign { + target: Var::Local(3), + value: byte_off, + }), + tree::Stmt::Simple(Stmt::StoreBytes { + addr: Expr::Var(Var::Local(0)), + offset: 0x50, + bytes: 16, + value: Expr::ZeroSlots(2), + }), + ], + ); + let mut obj_var = VarInfo::new(Width::Cell); + obj_var.kind = Kind::Object(outer_key.to_string()); + free_fn.head.vars.insert(Var::Local(0), obj_var); + + // Derived class reads inherited `f_8` declared on `base_key`, while `base_key.f_10` stays private. + let derived_read = Expr::sugar( + ExprSugar::Field { owner: derived_key }, + Expr::Load { + ty: Scalar::I32, + addr: Box::new(p(0)), + offset: 0x8, + }, + ); + let derived_fn = function( + 0x40, + 1, + Returns::Cell, + vec![tree::Stmt::Return(Some(derived_read))], + ); + + let mut outer = class(outer_key.0, ClassKind::Class); + outer.fields = vec![ + field(0x8, 8, Kind::Object(inner_key.to_string()), false), + field(0x2C, 16, Kind::Handle, false), + field(0x3C, 16, Kind::Handle, false), + field(0x4C, 4, Kind::I32, false), + field(0x50, 16, Kind::Handle, false), + field(0x60, 4, Kind::I32, false), + ]; + let mut inner = class(inner_key.0, ClassKind::Class); + inner.fields = vec![ + field(0x10, 16, Kind::Handle, false), + field(0x20, 4, Kind::I32, false), + ]; + let mut base = class(base_key.0, ClassKind::Class); + base.fields = vec![ + field(0x8, 4, Kind::I32, false), + field(0x10, 4, Kind::I32, false), + ]; + let mut derived = class(derived_key.0, ClassKind::Class); + derived.base = Some(base_key); + derived.methods = vec![member(Role::Method, false, derived_fn)]; + + let unit = Unit { + program: PROGRAM, + imports: Vec::new(), + classes: vec![outer, inner, base, derived], + functions: vec![Method::free(free_fn)], + front: None, + }; + let mut closed = Project::default(); + closed.outside.closed = vec![PROGRAM]; + closed.outside.unnamed = vec![ + (outer_key, PROGRAM), + (inner_key, PROGRAM), + (base_key, PROGRAM), + (derived_key, PROGRAM), + ]; + closed.outside.unnamed.sort_unstable(); + closed.types.insert( + derived_key, + TypeFacts { + base: Some(base_key), + ..TypeFacts::default() + }, + ); + + let text = file(&unit, &Names::default(), &closed, Options::default()).text; + for expected in [ + " internal type_4845535A02F85997 f_8;", + " internal Handle f_2C;", + " internal Handle f_3C;", + " internal int f_4C;", + " internal Handle f_50;", + " internal Handle f_10;", + " internal int f_8;", + ] { + assert!( + text.lines().any(|l| l == expected), + "missing `{expected}` in:\n{text}" + ); + } + // Unreached fields stay private. + assert!(text.contains("\n int f_60;\n"), "{text}"); + assert!(text.contains("\n int f_20;\n"), "{text}"); + assert!(text.contains("\n int f_10;\n"), "{text}"); +} + +#[test] +fn cs4004_async_classes_and_program_classes_emit_per_member_unsafe_and_reparse() { + use crate::gta6::script::reparse::unfiled; + + // 1. Program static partial class with both `void*` globals/functions and an `async` function: + // `static partial class` must NOT be `unsafe`, pointer globals & non-async functions get + // per-member `unsafe`, and `reparse::unfiled` still reads the file cleanly. + let prog = "\ +// OpenRage: GTA VI script, program 0x1234ABCD + +static partial class program_1234ABCD +{ + // the globals and statics of this program that its code names + internal static void* Global_0, Global_8; + internal static int Global_10; + + internal static void func_000000(void* p0) + { + DEMO.USE(p0); + } + + internal static async Task func_000020() + { + await DEMO.LATER(); + } + + internal static void func_000040() + { + DEMO.USE(Global_10); + } +} +"; + let made = unsafe_where_pointed(prog); + assert!( + made.contains("\nstatic partial class program_1234ABCD\n"), + "{made}" + ); + assert!(!made.contains("static unsafe partial class"), "{made}"); + assert!( + made.contains("\n internal unsafe static void* Global_0, Global_8;\n"), + "{made}" + ); + assert!( + made.contains("\n internal static int Global_10;\n"), + "{made}" + ); + assert!( + made.contains("\n internal unsafe static void func_000000(void* p0)\n"), + "{made}" + ); + assert!( + made.contains("\n internal static async Task func_000020()\n"), + "{made}" + ); + assert!( + made.contains("\n internal unsafe static void func_000040()\n"), + "{made}" + ); + let parsed = unfiled(&made).expect("per-member unsafe file must reparse cleanly"); + assert_eq!(parsed.program, "program_1234ABCD"); + assert!( + parsed + .members + .contains("internal unsafe static void func_000000(void* p0)"), + "{}", + parsed.members + ); + + // 2. Class with `async` method, pointer field, pointer virtual method, pointer property, + // and non-async nested class with pointer field: + // outer class stays safe; pointer members get per-member `unsafe`; non-async nested class + // gets `internal unsafe class`. + // 3. Non-async outer class whose nested class has `async`: + // outer class stays safe so nested `await` does not inherit an unsafe context. + let classes = "\ +class type_AsyncHost +{ + internal void* f_8; + int f_10; + + internal Cell Prop => *f_8; // func_000060 + + public virtual void Method_3(int p1) // func_000080 + { + DEMO.USE(&p1); + } + + public override async Task Method_10(int p1) // func_0000A0 + { + await DEMO.LATER(); + } + + internal class type_NestedSync + { + internal void* f_8; + } +} + +class type_OuterWithAsyncNested +{ + internal void* f_8; + + internal class type_NestedAsync + { + async Task Wait() + { + await DEMO.LATER(); + } + } +} + +class type_PureSync +{ + internal void* f_8; + + void Run() + { + DEMO.USE(f_8); + } +} +"; + let made = unsafe_where_pointed(classes); + assert!(made.starts_with("class type_AsyncHost\n"), "{made}"); + assert!( + made.contains("\n internal unsafe void* f_8;\n"), + "{made}" + ); + assert!(made.contains("\n int f_10;\n"), "{made}"); + assert!( + made.contains("\n internal unsafe Cell Prop => *f_8; // func_000060\n"), + "{made}" + ); + assert!( + made.contains("\n public unsafe virtual void Method_3(int p1) // func_000080\n"), + "{made}" + ); + assert!( + made.contains("\n public override async Task Method_10(int p1) // func_0000A0\n"), + "{made}" + ); + assert!( + made.contains("\n internal unsafe class type_NestedSync\n"), + "{made}" + ); + assert!( + made.contains("\nclass type_OuterWithAsyncNested\n"), + "{made}" + ); + assert!( + !made.contains("\nunsafe class type_OuterWithAsyncNested\n"), + "{made}" + ); + assert!( + made.contains("\n internal class type_NestedAsync\n"), + "{made}" + ); + // Pure non-async class keeps class-level `unsafe`. + assert!(made.contains("\nunsafe class type_PureSync\n"), "{made}"); + assert!(made.contains("\n void Run()\n"), "{made}"); +} diff --git a/crates/io/or-io/src/gta6/script/passes/aggregates/mod.rs b/crates/io/or-io/src/gta6/script/passes/aggregates/mod.rs index efd30f30a..379a1a252 100644 --- a/crates/io/or-io/src/gta6/script/passes/aggregates/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/aggregates/mod.rs @@ -13,10 +13,11 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::gta6::script::cfg; use crate::gta6::script::ir::{ - Callee, Expr, FunctionKey, Head, Kind, Scalar, Stmt, Var, VarInfo, Width, + Callee, Expr, FunctionKey, Head, Kind, Scalar, Stmt, StoreKind, TypeKey, Var, VarInfo, Width, }; -use crate::gta6::script::project::{Project, Signature}; -use crate::gta6::script::{Context, Pass, Stats}; +use crate::gta6::script::project::signatures::settled; +use crate::gta6::script::project::{Param, Project}; +use crate::gta6::script::{Context, Names, Pass, Stats}; mod kinds; pub use kinds::copied_kinds; @@ -241,27 +242,157 @@ fn spread<'a>(widths: &BTreeMap, stmts: &'a [Stmt]) -> Option<(Run, &' Some((run, &**base)) } -/// Notes the function's own parameters of several cells, as the project's signature of it has them. -// ⚠ A signature whose cells are not the function's own says nothing of this function. -fn own_parameters(f: &cfg::Function, project: &Project, wanted: &mut Wanted) { +/// The runtime's own comparisons of two 16-byte handles, each handle given as two cells. +const HANDLE_TESTS: [&str; 2] = ["System.Guid.op_Equality", "System.Guid.op_Inequality"]; +/// The base types a walk up a line of types follows: no line is that deep, and a ring of bases must end. +const MAX_BASES: usize = 64; + +/// Whether cell `first` of `params` is the receiver (`this`) of an instance method, which is always one cell. +fn is_receiver(f: &cfg::Function, project: &Project, params: bool, first: u32) -> bool { + if !params || first != 0 { + return false; + } let key = FunctionKey::new(f.head.program, f.head.at); - let Some(signature) = project.signatures.get(&key) else { - return; + project.members.get(&key).is_some_and(|m| !m.is_static) +} + +/// Whether the function's own settled signature types any cell of `first + 1 .. first + cells` +/// as a one-cell parameter of a known kind, which `types` would later write back into `head.vars`. +fn later_param_typed(f: &cfg::Function, project: &Project, first: u32, cells: u32) -> bool { + let key = FunctionKey::new(f.head.program, f.head.at); + let Some(sig) = project.signatures.get(&key).filter(|s| settled(s)) else { + return false; + }; + let total = sig + .params + .iter() + .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); + if total != Some(f.head.params) { + return false; + } + let end = u64::from(first) + u64::from(cells); + let mut at = 0u32; + for param in &sig.params { + if param.cells == 1 && param.kind != Kind::Unknown && at > first && u64::from(at) < end { + return true; + } + at = at.saturating_add(param.cells); + } + false +} + +/// Whether the function's own settled signature already types any cell of `first .. first + cells` +/// as a one-cell managed reference, pointer, bool, or 64-bit float incompatible with a native +/// multi-cell handle or vector, or types any later cell at all. +fn param_blocks_native(f: &cfg::Function, project: &Project, first: u32, cells: u32) -> bool { + let key = FunctionKey::new(f.head.program, f.head.at); + let Some(sig) = project.signatures.get(&key).filter(|s| settled(s)) else { + return false; }; - let total = signature + let total = sig .params .iter() .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); + if total != Some(f.head.params) { + return false; + } + let end = u64::from(first) + u64::from(cells); + let mut at = 0u32; + for param in &sig.params { + if param.cells == 1 && u64::from(at) >= u64::from(first) && u64::from(at) < end { + let incompatible = matches!( + param.kind, + Kind::Object(_) + | Kind::Array(_) + | Kind::String + | Kind::Pointer + | Kind::Bool + | Kind::F64 + ); + if incompatible || (at > first && param.kind != Kind::Unknown) { + return true; + } + } + at = at.saturating_add(param.cells); + } + false +} + +/// Whether `cells` parameter cells from `first` on may be coalesced from indirect or local evidence. +fn param_ok(f: &cfg::Function, project: &Project, first: u32, cells: u32) -> bool { + cells >= 2 + && !is_receiver(f, project, true, first) + && u64::from(first) + u64::from(cells) <= u64::from(f.head.params) + && !later_param_typed(f, project, first, cells) +} + +/// Whether `cells` cells of frame space `params` from `first` on may be coalesced from indirect or local evidence. +fn frame_ok(f: &cfg::Function, project: &Project, params: bool, first: u32, cells: u32) -> bool { + match params { + true => param_ok(f, project, first, cells), + false => cells >= 2 && u64::from(first) + u64::from(cells) <= u64::from(f.head.locals), + } +} + +/// Notes each multi-cell parameter from `params` when their cells add up to `f.head.params`. +fn want_params( + f: &cfg::Function, + project: &Project, + params: &[Param], + from_own_sig: bool, + wanted: &mut Wanted, +) { + let total = params + .iter() + .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); if total != Some(f.head.params) { return; } let mut first = 0u32; - for param in &signature.params { - wanted.want(true, first, param.cells, ¶m.kind); + for param in params { + if param.cells >= 2 && (from_own_sig || param_ok(f, project, first, param.cells)) { + wanted.want(true, first, param.cells, ¶m.kind); + } first = first.saturating_add(param.cells); } } +/// Notes the function's own parameters of several cells, as the project's signature, its virtual slot's parameters, or an ancestor's signature has them. +// ⚠ A signature whose cells are not the function's own says nothing of this function. +fn own_parameters(f: &cfg::Function, project: &Project, wanted: &mut Wanted) { + let key = FunctionKey::new(f.head.program, f.head.at); + if let Some(signature) = project.signatures.get(&key).filter(|sig| settled(sig)) { + want_params(f, project, &signature.params, true, wanted); + } + if let Some(params) = project.slot_params.get(&key) { + want_params(f, project, params, false, wanted); + } + // A virtual override inherits multi-cell parameters from its slot's ancestor signatures so overrides match their base. + if let Some(member) = project.members.get(&key) { + if let Some(slot) = member.slot { + let mut seen = BTreeSet::from([member.owner]); + let mut cur = project.types.get(&member.owner).and_then(|t| t.base); + for _ in 0..MAX_BASES { + let Some(base) = cur else { + break; + }; + if !seen.insert(base) { + break; + } + if let Some(base_fn) = project.slot(base, slot).filter(|base_fn| *base_fn != key) { + if let Some(sig) = project.signatures.get(&base_fn).filter(|sig| settled(sig)) { + want_params(f, project, &sig.params, false, wanted); + } + if let Some(params) = project.slot_params.get(&base_fn) { + want_params(f, project, params, false, wanted); + } + } + cur = project.types.get(&base).and_then(|t| t.base); + } + } + } +} + /// Notes each run of locals that a statement, or a row of them, writes whole: a value of several cells spread over it, or its bytes cleared. fn written_whole(f: &cfg::Function, widths: &BTreeMap, wanted: &mut Wanted) { for block in &f.cfg.blocks { @@ -288,13 +419,15 @@ fn written_whole(f: &cfg::Function, widths: &BTreeMap, wanted: &mut Wa } } -/// Notes each run of locals a call passes where the callee's signature takes one value of as many cells. +/// Notes each run of locals or parameters a call passes where the callee's signature takes one value of as many cells. // ⚠ A call that does not pass the cells its callee's signature takes says nothing. fn passed( - head: &Head, + f: &cfg::Function, + project: &Project, widths: &BTreeMap, - signature: &Signature, + params: &[Param], args: &[Expr], + native: bool, wanted: &mut Wanted, ) { // The cell each argument starts at. @@ -302,100 +435,165 @@ fn passed( let mut cell = 0u32; for arg in args { starts.push(cell); - let next = cells_of(head, widths, arg, DEPTH).and_then(|cells| cell.checked_add(cells)); + let next = cells_of(&f.head, widths, arg, DEPTH).and_then(|cells| cell.checked_add(cells)); match next { Some(next) => cell = next, None => return, } } - let taken = signature - .params + let taken = params .iter() .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); if taken != Some(cell) { return; } let mut first = 0u32; - for param in &signature.params { + for param in params { let at = starts.partition_point(|start| *start < first); - if let (true, Some(Expr::Var(Var::Local(local)))) = (param.cells >= 2, args.get(at)) { - let run = args.get(at..at.saturating_add(param.cells as usize)); - let in_order = run.is_some_and(|run| { - run.iter().zip(0u32..).all(|(arg, i)| { - matches!(arg, Expr::Var(Var::Local(n)) if local.checked_add(i) == Some(*n)) - }) - }); - if in_order && starts.get(at) == Some(&first) { - wanted.want(false, *local, param.cells, ¶m.kind); + if let (true, Some(Expr::Var(var))) = (param.cells >= 2, args.get(at)) { + if let Some((is_param, start_cell)) = frame_cell(*var) { + let run = args.get(at..at.saturating_add(param.cells as usize)); + let in_order = run.is_some_and(|run| { + run.iter().zip(0u32..).all(|(arg, i)| { + matches!( + arg, + Expr::Var(v) if frame_cell(*v) == start_cell.checked_add(i).map(|n| (is_param, n)) + ) + }) + }); + let allowed = !is_param + || (param_ok(f, project, start_cell, param.cells) + && (!native || !param_blocks_native(f, project, start_cell, param.cells))); + if in_order && allowed && starts.get(at) == Some(&first) { + wanted.want(is_param, start_cell, param.cells, ¶m.kind); + } } } first = first.saturating_add(param.cells); } } -/// Notes the runs of locals passed to the functions the project has a signature of. +/// Notes the runs of locals and parameters passed to functions, virtual slots, natives, or handle comparisons taking multi-cell values. fn passed_whole( f: &cfg::Function, project: &Project, + names: &Names, + use_natives: bool, widths: &BTreeMap, wanted: &mut Wanted, ) { - if project.signatures.is_empty() { - return; - } + let handle_pair = [ + Param { + kind: Kind::Handle, + cells: 2, + }, + Param { + kind: Kind::Handle, + cells: 2, + }, + ]; each_top(&f.cfg, &mut |top| { top.walk(&mut |e| { let Expr::Call { callee, args, .. } = e else { return; }; - let key = match callee { - Callee::Local { at, .. } => FunctionKey::new(f.head.program, *at), - Callee::Import { program, at, .. } => FunctionKey::new(*program, *at), - _ => return, - }; - if let Some(signature) = project.signatures.get(&key) { - passed(&f.head, widths, signature, args, wanted); + match callee { + Callee::Local { at, .. } => { + let key = FunctionKey::new(f.head.program, *at); + if let Some(sig) = project.signatures.get(&key).filter(|sig| settled(sig)) { + passed(f, project, widths, &sig.params, args, false, wanted); + } + } + Callee::Import { program, at, .. } => { + let key = FunctionKey::new(*program, *at); + if let Some(sig) = project.signatures.get(&key).filter(|sig| settled(sig)) { + passed(f, project, widths, &sig.params, args, false, wanted); + } + } + Callee::Virtual { ty, slot, .. } => { + if let Some(params) = + TypeKey::of_name(ty).and_then(|ty| project.slot_parameters(ty, *slot)) + { + passed(f, project, widths, params, args, false, wanted); + } + } + Callee::Native { hash, .. } if use_natives => { + if let Some(params) = names + .native_signature(*hash) + .and_then(|sig| sig.params.as_ref()) + { + if params.iter().any(|p| p.ty.cells >= 2) { + let native_params: Vec = params + .iter() + .map(|p| { + let kind = if p.ty.cells >= 2 + && matches!(p.ty.kind, Kind::Handle | Kind::Vector) + { + p.ty.kind.clone() + } else if p.ty.cells >= 2 { + Kind::Aggregate(p.ty.cells) + } else { + Kind::Unknown + }; + Param { + kind, + cells: p.ty.cells, + } + }) + .collect(); + passed(f, project, widths, &native_params, args, true, wanted); + } + } + } + Callee::Builtin { path, .. } if HANDLE_TESTS.contains(&path.as_str()) => { + passed(f, project, widths, &handle_pair, args, false, wanted); + } + _ => {} } }); }); } -/// A run of locals the code's own use of the cells suggests. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// A run of frame cells the code's own use of the cells suggests. +#[derive(Clone, Debug, PartialEq, Eq)] struct Hint { cells: u32, - /// Whether nothing but a copy of another run into it suggests it. + /// Whether nothing but a copy to or from another run suggests it. tied: bool, + /// Named kind known for the run, where one was proved by a copy or field layout. + kind: Option, } -/// The runs suggested, by first local; of two from one local the longer stays. -type Hints = BTreeMap; +/// The runs suggested, by `(params, first)`; of two from one start cell the longer stays. +type Hints = BTreeMap<(bool, u32), Hint>; -/// Notes that the code uses `cells` locals from `first` on as one value. -fn hint(hints: &mut Hints, first: u32, cells: u32, tied: bool) { +/// Notes that the code uses `cells` frame cells from `key` on as one value. +fn hint(hints: &mut Hints, key: (bool, u32), cells: u32, tied: bool, kind: Option) { if cells < 2 { return; } - let tied = match hints.get(&first) { + let kind = kind.filter(|k| kind_cells(k) == Some(cells)); + let (tied, kind) = match hints.get(&key) { Some(held) if held.cells > cells => return, - Some(held) if held.cells == cells => held.tied && tied, - _ => tied, + Some(held) if held.cells == cells => (held.tied && tied, held.kind.clone().or(kind)), + _ => (tied, kind), }; - hints.insert(first, Hint { cells, tied }); + hints.insert(key, Hint { cells, tied, kind }); } -/// The locals a list of expressions is, where it is two or more of them in a row and nothing else: the first and how many. -fn local_row(items: &[Expr]) -> Option<(u32, u32)> { - let Some(Expr::Var(Var::Local(first))) = items.first() else { +/// The frame cells a list of expressions is, where it is two or more of them in a row in the same space and nothing else: `(params, first)` and how many. +fn frame_row(items: &[Expr]) -> Option<((bool, u32), u32)> { + let Some(Expr::Var(first_var)) = items.first() else { return None; }; + let (params, first) = frame_cell(*first_var)?; let cells = u32::try_from(items.len()) .ok() .filter(|cells| *cells >= 2)?; - let in_order = (0..cells).zip(items).all( - |(at, item)| matches!(item, Expr::Var(Var::Local(n)) if first.checked_add(at) == Some(*n)), - ); - in_order.then_some((*first, cells)) + let in_order = (0..cells).zip(items).all(|(at, item)| { + matches!(item, Expr::Var(v) if frame_cell(*v) == first.checked_add(at).map(|n| (params, n))) + }); + in_order.then_some(((params, first), cells)) } /// The frame cell a statement assigns and the frame cell it copies there, where it is `x = y` over two of them. @@ -432,23 +630,21 @@ fn apart(a: (bool, u32), b: (bool, u32), cells: u32) -> bool { a.0 != b.0 || a.1.abs_diff(b.1) >= cells } -/// The locals a load of `bytes` bytes through the first one's own address takes every byte of, where they are two or more: the first and how many. -fn loaded_whole(addr: &Expr, offset: u32, bytes: u32) -> Option<(u32, u32)> { - let Expr::AddrOf { - var: Var::Local(first), - cell: 0, - } = addr - else { +/// The frame cells a load of `bytes` bytes through the first one's own address takes every byte of, where they are two or more: `(params, first)` and how many. +fn loaded_whole(addr: &Expr, offset: u32, bytes: u32) -> Option<((bool, u32), u32)> { + let Expr::AddrOf { var, cell: 0 } = addr else { return None; }; + let key = frame_cell(*var)?; let cells = bytes / 8; - (offset == 0 && bytes.is_multiple_of(8) && cells >= 2).then_some((*first, cells)) + (offset == 0 && bytes.is_multiple_of(8) && cells >= 2).then_some((key, cells)) } -/// Records the span in cells of a local accessed past one cell through its address. +/// Records the span in cells of a frame variable (local or parameter) accessed past one cell through its address. fn note_wide_span( - wide_end: &mut BTreeMap, - locals: u32, + wide_end: &mut BTreeMap<(bool, u32), u32>, + f: &cfg::Function, + project: &Project, addr: &Expr, offset: u32, bytes: u32, @@ -469,83 +665,125 @@ fn note_wide_span( } cur = &**inner; } - let Expr::AddrOf { - var: Var::Local(first), - cell: 0, - } = cur - else { + let Expr::AddrOf { var, cell: 0 } = cur else { + return; + }; + let Some((params, first)) = frame_cell(*var) else { return; }; let end = total.saturating_add(u64::from(bytes.max(1))); if end > 8 { if let Ok(cells) = u32::try_from(end.div_ceil(8)) { - if u64::from(*first) + u64::from(cells) <= u64::from(locals) { - let entry = wide_end.entry(*first).or_insert(0); + if frame_ok(f, project, params, first, cells) { + let entry = wide_end.entry((params, first)).or_insert(0); *entry = (*entry).max(cells); } } } } -/// The runs of locals the code uses as one value: gathered into a group whole, loaded whole through the first one's address, cleared through it, accessed past one cell through its address, or copied cell by cell to or from another row. -// ⚠ A copy says no more of the row copied into than the row copied from holds: such a run is tied. +/// A consecutive row of 8-byte stores of parameters `p{first}..p{first+cells}` into a single +/// multi-cell field of `owner` on `this` (`Param(0)`): `(first, cells, kind)`. +fn stored_field_row( + f: &cfg::Function, + project: &Project, + owner: TypeKey, + stmts: &[Stmt], +) -> Option<(u32, u32, Option)> { + let Stmt::Store { + kind: StoreKind::U64, + addr: Expr::Var(Var::Param(0)), + offset, + value: Expr::Var(Var::Param(first)), + } = stmts.first()? + else { + return None; + }; + let field = project.field(owner, *offset)?; + if field.bytes < 16 || !field.bytes.is_multiple_of(8) { + return None; + } + let cells = field.bytes / 8; + if !param_ok(f, project, *first, cells) { + return None; + } + let row = stmts.get(..cells as usize)?; + let in_order = row.iter().zip(0u32..).all(|(stmt, i)| { + let wanted_off = i.checked_mul(8).and_then(|by| offset.checked_add(by)); + let wanted_param = first.checked_add(i); + matches!( + stmt, + Stmt::Store { + kind: StoreKind::U64, + addr: Expr::Var(Var::Param(0)), + offset: off, + value: Expr::Var(Var::Param(n)), + } if wanted_off == Some(*off) && wanted_param == Some(*n) + ) + }); + if !in_order { + return None; + } + let kind = (kind_cells(&field.kind) == Some(cells)).then(|| field.kind.clone()); + Some((*first, cells, kind)) +} + +/// The runs of locals and parameters the code uses as one value: gathered into a group whole, loaded whole through the first one's address, cleared through it, accessed past one cell through its address, stored cell by cell into a multi-cell field, or copied cell by cell to or from another row. +// ⚠ A copy says no more of the row copied into (or a parameter row copied into a local row) than the other run holds: such a run is tied. fn suggested(f: &cfg::Function, project: &Project, stated: &Wanted) -> Hints { let mut hints = Hints::new(); - let mut wide_end: BTreeMap = BTreeMap::new(); - let mut skip_wide: BTreeSet = BTreeSet::new(); - let locals = f.head.locals; + let mut wide_end: BTreeMap<(bool, u32), u32> = BTreeMap::new(); + let mut skip_wide: BTreeSet<(bool, u32)> = BTreeSet::new(); each_top(&f.cfg, &mut |top| { top.walk(&mut |e| { let used = match e { - Expr::Cells(items) => local_row(items), + Expr::Cells(items) => frame_row(items), Expr::LoadBytes { addr, offset, bytes, } => { - note_wide_span(&mut wide_end, locals, addr, *offset, *bytes); + note_wide_span(&mut wide_end, f, project, addr, *offset, *bytes); loaded_whole(addr, *offset, *bytes) } Expr::Load { ty, addr, offset } => { - note_wide_span(&mut wide_end, locals, addr, *offset, ty.bytes()); + note_wide_span(&mut wide_end, f, project, addr, *offset, ty.bytes()); None } Expr::ByteOffset { addr, offset } => { if let Expr::Const(c) = &**offset { if let Ok(off) = u32::try_from(c.bits) { - note_wide_span(&mut wide_end, locals, addr, off, 1); + note_wide_span(&mut wide_end, f, project, addr, off, 1); } } None } Expr::Call { callee, args, .. } => { // A value-type member call or a known callee whose reach exceeds one cell - // reveals the span of a struct-wide local passed by address. - if let Some(Expr::AddrOf { - var: Var::Local(first), - cell: 0, - }) = args.first() - { - let owner = match callee { - Callee::Virtual { ty, .. } => { - crate::gta6::script::ir::TypeKey::of_name(ty) - } - _ => super::super::project::signatures::key_of(f.head.program, callee) + // reveals the span of a struct-wide local or parameter passed by address. + if let Some(Expr::AddrOf { var, cell: 0 }) = args.first() { + if let Some((params, first)) = frame_cell(*var) { + let owner = match callee { + Callee::Virtual { ty, .. } => TypeKey::of_name(ty), + _ => super::super::project::signatures::key_of( + f.head.program, + callee, + ) .and_then(|key| project.members.get(&key)) .filter(|m| !m.is_static) .map(|m| m.owner), - }; - if let Some(facts) = owner.and_then(|k| project.types.get(&k)) { - // ⚠ Leave compiler-generated value types (async state machines) alone so kick-offs hide their machine cleanly. - const GENERATED: u32 = 0x10_0000; - if facts.is_value() && facts.flags & GENERATED != 0 { - skip_wide.insert(*first); - } else if facts.is_value() && facts.byte_size > 8 { - let cells = facts.byte_size.div_ceil(8); - if u64::from(*first) + u64::from(cells) <= u64::from(f.head.locals) - { - let entry = wide_end.entry(*first).or_insert(0); - *entry = (*entry).max(cells); + }; + if let Some(facts) = owner.and_then(|k| project.types.get(&k)) { + // ⚠ Leave compiler-generated value types (async state machines) alone so kick-offs hide their machine cleanly. + const GENERATED: u32 = 0x10_0000; + if facts.is_value() && facts.flags & GENERATED != 0 { + skip_wide.insert((params, first)); + } else if facts.is_value() && facts.byte_size > 8 { + let cells = facts.byte_size.div_ceil(8); + if frame_ok(f, project, params, first, cells) { + let entry = wide_end.entry((params, first)).or_insert(0); + *entry = (*entry).max(cells); + } } } } @@ -555,23 +793,20 @@ fn suggested(f: &cfg::Function, project: &Project, stated: &Wanted) -> Hints { { let mut cell = 0u32; for arg in args { - if let Expr::AddrOf { - var: Var::Local(first), - cell: 0, - } = arg - { - if let Some(reach) = - project.reach.get(&key).and_then(|m| m.get(&cell)) - { - if reach.bytes != super::super::project::reach::UNBOUNDED - && reach.bytes > 8 + if let Expr::AddrOf { var, cell: 0 } = arg { + if let Some((params, first)) = frame_cell(*var) { + if let Some(reach) = + project.reach.get(&key).and_then(|m| m.get(&cell)) { - let cells = reach.bytes.div_ceil(8); - if u64::from(*first) + u64::from(cells) - <= u64::from(f.head.locals) + if reach.bytes != super::super::project::reach::UNBOUNDED + && reach.bytes > 8 { - let entry = wide_end.entry(*first).or_insert(0); - *entry = (*entry).max(cells); + let cells = reach.bytes.div_ceil(8); + if frame_ok(f, project, params, first, cells) { + let entry = + wide_end.entry((params, first)).or_insert(0); + *entry = (*entry).max(cells); + } } } } @@ -583,39 +818,55 @@ fn suggested(f: &cfg::Function, project: &Project, stated: &Wanted) -> Hints { } _ => None, }; - if let Some((first, cells)) = used { - hint(&mut hints, first, cells, false); + if let Some((key, cells)) = used { + if frame_ok(f, project, key.0, key.1, cells) { + hint(&mut hints, key, cells, false, None); + } } }); }); for block in &f.cfg.blocks { for stmt in &block.stmts { if let Some((addr, offset, Some(bytes))) = stored(stmt) { - note_wide_span(&mut wide_end, locals, addr, offset, bytes); + note_wide_span(&mut wide_end, f, project, addr, offset, bytes); } } } - for (first, cells) in wide_end { - if !skip_wide.contains(&first) { - hint(&mut hints, first, cells, false); + for (key, cells) in wide_end { + if !skip_wide.contains(&key) && frame_ok(f, project, key.0, key.1, cells) { + hint(&mut hints, key, cells, false, None); } } - let known = |key: (bool, u32)| stated.runs.get(&key).map(|(cells, _)| *cells); + let owner = project + .members + .get(&FunctionKey::new(f.head.program, f.head.at)) + .filter(|m| !m.is_static) + .map(|m| m.owner); for block in &f.cfg.blocks { let mut at = 0; while at < block.stmts.len() { if let Stmt::ZeroBytes { - addr: - Expr::AddrOf { - var: Var::Local(first), - cell: 0, - }, + addr: Expr::AddrOf { var, cell: 0 }, bytes, } = &block.stmts[at] { - // Bytes that end inside a cell are a value's own size, and the value holds that cell whole. - if *bytes > 8 && !bytes.is_multiple_of(8) { - hint(&mut hints, *first, bytes.div_ceil(8), false); + if let Some((params, first)) = frame_cell(*var) { + // Bytes that end inside a cell are a value's own size, and the value holds that cell whole. + // For parameters, `written_whole` only ran for locals, so whole-cell clears count here too. + let whole_or_tail = *bytes > 8 && (params || !bytes.is_multiple_of(8)); + let cells = bytes.div_ceil(8); + if whole_or_tail && frame_ok(f, project, params, first, cells) { + hint(&mut hints, (params, first), cells, false, None); + } + } + } + if let Some(owner) = owner { + if let Some((first, cells, kind)) = + stored_field_row(f, project, owner, &block.stmts[at..]) + { + hint(&mut hints, (true, first), cells, false, kind); + at += cells as usize; + continue; } } let Some((to, from, row)) = copy_row(&block.stmts[at..]) else { @@ -627,7 +878,51 @@ fn suggested(f: &cfg::Function, project: &Project, stated: &Wanted) -> Hints { while done < row { let (to, from) = ((to.0, to.1 + done), (from.0, from.1 + done)); let left = row - done; - let said = known(to).or_else(|| known(from)); + if !to.0 && from.0 { + // Copying parameters into a local run: only suggest the parameter run when the + // target local run is already known/suggested as a multi-cell value, and vice versa. + let to_known = stated + .runs + .get(&to) + .map(|(c, k)| (*c, Some(k.clone()))) + .or_else(|| { + hints + .get(&to) + .filter(|h| !h.tied) + .map(|h| (h.cells, h.kind.clone())) + }); + let from_known = stated + .runs + .get(&from) + .map(|(c, k)| (*c, Some(k.clone()))) + .or_else(|| { + hints + .get(&from) + .filter(|h| !h.tied) + .map(|h| (h.cells, h.kind.clone())) + }); + if let Some((cells, kind)) = to_known { + if cells >= 2 + && cells <= left + && apart(to, from, cells) + && param_ok(f, project, from.1, cells) + { + hint(&mut hints, from, cells, true, kind); + done += cells; + continue; + } + } else if let Some((cells, _)) = from_known { + if cells >= 2 && cells <= left && apart(to, from, cells) { + hint(&mut hints, to, cells, true, None); + done += cells; + continue; + } + } + done += 1; + continue; + } + let stated_cells = |key: (bool, u32)| stated.runs.get(&key).map(|(c, _)| *c); + let said = stated_cells(to).or_else(|| stated_cells(from)); let cells = said.unwrap_or(left); if cells < 2 || cells > left || !apart(to, from, cells) { // A row nothing states the cells of is one copy or none. @@ -637,11 +932,11 @@ fn suggested(f: &cfg::Function, project: &Project, stated: &Wanted) -> Hints { }; continue; } - if !to.0 && (!from.0 || known(from).is_some()) { - hint(&mut hints, to.1, cells, true); + if !to.0 && (!from.0 || stated_cells(from).is_some()) { + hint(&mut hints, to, cells, true, None); } if !from.0 { - hint(&mut hints, from.1, cells, false); + hint(&mut hints, from, cells, false, None); } done += cells; } @@ -651,27 +946,40 @@ fn suggested(f: &cfg::Function, project: &Project, stated: &Wanted) -> Hints { hints } -/// Takes into `wanted` each run suggested that shares no cell with a run something states. +/// Takes into `wanted` each run suggested that shares no cell with a run something states in the same frame space. fn take_hints(wanted: &mut Wanted, hints: Hints) { - // The stated runs of locals by first cell, each with the furthest end of those up to it. - let mut reach = 0u64; - let locals = wanted.runs.range((false, 0u32)..(true, 0u32)); - let stated: Vec<(u32, u64)> = locals - .map(|((_, first), (cells, _))| { + let mut stated_locals: Vec<(u32, u64)> = Vec::new(); + let mut stated_params: Vec<(u32, u64)> = Vec::new(); + for is_param in [false, true] { + let mut reach = 0u64; + let out = if is_param { + &mut stated_params + } else { + &mut stated_locals + }; + for ((_, first), (cells, _)) in wanted.runs.range((is_param, 0u32)..=(is_param, u32::MAX)) { reach = reach.max(u64::from(*first) + u64::from(*cells)); - (*first, reach) - }) - .collect(); - for (first, hint) in hints { + out.push((*first, reach)); + } + } + for ((params, first), hint) in hints { + let stated = if params { + &stated_params + } else { + &stated_locals + }; let end = u64::from(first) + u64::from(hint.cells); let before = stated.partition_point(|(start, _)| u64::from(*start) < end); let last = before.checked_sub(1).and_then(|at| stated.get(at)); if last.is_some_and(|(_, far)| *far > u64::from(first)) { continue; } - let key = (false, first); - let held = (hint.cells, Kind::Aggregate(hint.cells)); - wanted.runs.insert(key, held); + let key = (params, first); + let kind = hint + .kind + .filter(|k| kind_cells(k) == Some(hint.cells)) + .unwrap_or(Kind::Aggregate(hint.cells)); + wanted.runs.insert(key, (hint.cells, kind)); wanted.weak.insert(key); if hint.tied { wanted.tied.insert(key); @@ -879,8 +1187,9 @@ fn sound( } let cells: Runs = runs.iter().map(|(key, (n, _))| (*key, *n)).collect(); - // The tied runs each run is copied whole into. + // The tied runs each run is copied whole into (or, for a tied parameter run, from). let mut copies: BTreeMap<(bool, u32), Vec<(bool, u32)>> = BTreeMap::new(); + let mut param_tied_linked: BTreeSet<(bool, u32)> = BTreeSet::new(); for block in &f.cfg.blocks { let mut at = 0; while at < block.stmts.len() { @@ -895,8 +1204,14 @@ fn sound( let from = from.filter(|from| cells.get(from) == Some(&run.cells)); let is_tied = tied.contains(&run.key()); if !is_tied || from.is_some() { - if let (true, Some(from)) = (is_tied, from) { - copies.entry(from).or_default().push(run.key()); + if let Some(from) = from { + if is_tied { + copies.entry(from).or_default().push(run.key()); + } + if from.0 && tied.contains(&from) { + copies.entry(run.key()).or_default().push(from); + param_tied_linked.insert(from); + } } at += run.cells as usize; continue; @@ -914,6 +1229,11 @@ fn sound( at += 1; } } + for key in &tied { + if key.0 && !param_tied_linked.contains(key) { + gone.insert(*key); + } + } each_top(&f.cfg, &mut |top| { top.walk(&mut |e| { let span = match e { @@ -1518,7 +1838,7 @@ pub fn run(f: &mut cfg::Function, cx: &Context<'_>, _stats: &mut Stats) { if !cx.options.on(Pass::Aggregates) || f.head.incomplete.is_some() { return; } - let done = apply(f, cx.project); + let done = apply_in(f, cx.project, cx.names, cx.options.on(Pass::NativeTypes)); tracing::trace!( function = %f.head.name, params = done.params, @@ -1529,14 +1849,13 @@ pub fn run(f: &mut cfg::Function, cx: &Context<'_>, _stats: &mut Stats) { ); } -/// [`run`] whatever the options say, with the count of what it did. -pub(crate) fn apply(f: &mut cfg::Function, project: &Project) -> Made { +fn apply_in(f: &mut cfg::Function, project: &Project, names: &Names, use_natives: bool) -> Made { let mut done = Made::default(); let widths = widths(f); let mut wanted = Wanted::default(); own_parameters(f, project, &mut wanted); written_whole(f, &widths, &mut wanted); - passed_whole(f, project, &widths, &mut wanted); + passed_whole(f, project, names, use_natives, &widths, &mut wanted); let hints = suggested(f, project, &wanted); take_hints(&mut wanted, hints); let made = sound(f, &widths, wanted); diff --git a/crates/io/or-io/src/gta6/script/passes/aggregates/tests.rs b/crates/io/or-io/src/gta6/script/passes/aggregates/tests.rs index 462ec7134..90c74be0a 100644 --- a/crates/io/or-io/src/gta6/script/passes/aggregates/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/aggregates/tests.rs @@ -1,8 +1,11 @@ use super::*; +use crate::gta5::script::natives::{NativeDb, NativeName, NativeParam}; use crate::gta6::script::cfg::{Block, Cfg, Function, Terminator}; +use crate::gta6::script::class::Role; +use crate::gta6::script::exec; use crate::gta6::script::ir::{Const, Returns, Scalar}; -use crate::gta6::script::project::Param; -use crate::gta6::script::{Level, Names, Options}; +use crate::gta6::script::project::{FieldFacts, Member, Param, Signature, TypeFacts}; +use crate::gta6::script::{print, reparse, Level, Names, Options}; const PROGRAM: u32 = 0x1122_3344; /// The function every test groups. @@ -300,3 +303,217 @@ fn a_local_addressed_past_its_first_cell_is_widened_to_a_multi_cell_aggregate() Some((Width::Cells, Kind::Aggregate(2))) ); } + +#[test] +fn parameters_passed_to_multi_cell_callees_natives_and_groups_coalesce_and_agree() { + const WAVE: u64 = 0x7E57_1001; + let wave_native = NativeName { + namespace: Some("DEMO".to_owned()), + name: "WAVE_AT_PED".to_owned(), + params: vec![ + NativeParam { + ty: "Ped".to_owned(), + name: "ped".to_owned(), + }, + NativeParam { + ty: "int".to_owned(), + name: "times".to_owned(), + }, + ], + returns: Some("void".to_owned()), + }; + let names = Names { + natives: Some(NativeDb::from_names("test", [(WAVE, wave_native)])), + ..Names::default() + }; + let native_call = Expr::Call { + callee: Callee::Native { + namespace: Some("DEMO".to_owned()), + name: "_0x000000007E571001".to_owned(), + hash: WAVE, + rva: 0, + }, + args: vec![param(0), param(1), param(2)], + returns: Some(0), + }; + let before = function(3, vec![Stmt::Eval(native_call)], leaves()); + let project = Project::default(); + + // With NativeTypes off, native signatures are not consulted. + let no_native = Options::at(Level::Source).without(Pass::NativeTypes); + let mut untouched = before.clone(); + run( + &mut untouched, + &Context::new(&names, &project, no_native), + &mut Stats::default(), + ); + assert_eq!(shape(&untouched, Var::Param(0)), None); + + // With NativeTypes on, `(p0, p1)` coalesces into a single 2-cell Handle parameter. + let opts = Options::at(Level::Source); + let mut after = before.clone(); + let cx = Context::new(&names, &project, opts); + run(&mut after, &cx, &mut Stats::default()); + assert_eq!( + shape(&after, Var::Param(0)), + Some((Width::Cells, Kind::Handle)) + ); + assert!(!after.head.vars.contains_key(&Var::Param(1))); + assert!( + !exec::agree(&before, &after, exec::Limits::DEFAULT, &project) + .expect("coalesced param agrees under oracle") + .skipped + ); + + // Printing and reparsing agree, and the printed signature takes two C# parameters instead of three. + let tree_fn = cfg::flat(after); + let mut text = String::new(); + print::function_in(&mut text, &tree_fn, &cx); + reparse::agrees_source_named(&tree_fn, &text, opts, &project, &names) + .unwrap_or_else(|why| panic!("{why} in {text}")); + assert!(!text.contains("p1"), "p1 should be coalesced away:\n{text}"); +} + +#[test] +fn parameters_in_cells_group_or_copied_to_multi_cell_local_or_stored_to_wide_field_coalesce() { + // 1. `Expr::Cells([p1, p2])` coalesces `p1..p2`, even without a project signature. + let group = Expr::Cells(vec![param(1), param(2)]); + let before = function(3, vec![used(0x100, vec![group])], leaves()); + let after = grouped(before.clone(), Project::empty(), on()); + assert_eq!( + shape(&after, Var::Param(1)), + Some((Width::Cells, Kind::Aggregate(2))) + ); + assert_eq!(after.cfg.blocks[0].stmts, [used(0x100, vec![param(1)])]); + assert!( + !exec::agree(&before, &after, exec::Limits::DEFAULT, Project::empty()) + .expect("cells param agrees") + .skipped + ); + + // 2. Copying `(p0, p1)` into a multi-cell local run coalesces `(p0, p1)` too, + // while copying into unrelated single-cell locals leaves `(p0, p1)` separate. + let project = knowing(0x200, takes(&[(2, Kind::Handle)])); + let copied_wide = vec![ + set(Var::Local(0), param(0)), + set(Var::Local(1), param(1)), + used(0x200, vec![local(0), local(1)]), + ]; + let after_copy = grouped(function(2, copied_wide, leaves()), &project, on()); + assert_eq!( + shape(&after_copy, Var::Param(0)), + Some((Width::Cells, Kind::Handle)) + ); + assert_eq!( + shape(&after_copy, Var::Local(0)), + Some((Width::Cells, Kind::Handle)) + ); + + let copied_plain = vec![ + set(Var::Local(0), param(0)), + set(Var::Local(1), param(1)), + used(0x300, vec![local(0)]), + used(0x300, vec![local(1)]), + ]; + let plain = grouped(function(2, copied_plain, leaves()), Project::empty(), on()); + assert_eq!(shape(&plain, Var::Param(0)), None); + + // 3. Storing `(p1, p2)` into a 16-byte field of `this` coalesces `(p1, p2)`, + // and never coalesces `Param(0)` (`this`) of an instance method. + let owner = TypeKey(0xCAFE); + let mut field_project = Project::default(); + field_project.members.insert( + FunctionKey::new(PROGRAM, AT), + Member { + owner, + role: Role::Method, + is_static: false, + slot: None, + }, + ); + field_project.fields.insert( + owner, + vec![FieldFacts { + offset: 0x20, + bytes: 16, + kind: Kind::Handle, + }], + ); + let stores = vec![ + Stmt::Store { + kind: StoreKind::U64, + addr: param(0), + offset: 0x20, + value: param(1), + }, + Stmt::Store { + kind: StoreKind::U64, + addr: param(0), + offset: 0x28, + value: param(2), + }, + ]; + let after_store = grouped(function(3, stores, leaves()), &field_project, on()); + assert_eq!( + shape(&after_store, Var::Param(1)), + Some((Width::Cells, Kind::Handle)) + ); + + // Instance method receiver `p0` is never coalesced with `p1`. + let bad_receiver = function( + 2, + vec![used(0x100, vec![Expr::Cells(vec![param(0), param(1)])])], + leaves(), + ); + let kept = grouped(bad_receiver, &field_project, on()); + assert_eq!(shape(&kept, Var::Param(0)), None); +} + +#[test] +fn virtual_override_inherits_base_multi_cell_param_unless_later_cell_is_typed() { + let base_ty = TypeKey(0x1001); + let derived_ty = TypeKey(0x1002); + let base_fn = FunctionKey::new(PROGRAM, 0x200); + let derived_fn = FunctionKey::new(PROGRAM, AT); + + let mut project = Project::default(); + let mut base_facts = TypeFacts::default(); + base_facts.slots.insert(4, base_fn); + let mut derived_facts = TypeFacts { + base: Some(base_ty), + ..TypeFacts::default() + }; + derived_facts.slots.insert(4, derived_fn); + project.types.insert(base_ty, base_facts); + project.types.insert(derived_ty, derived_facts); + project.members.insert( + derived_fn, + Member { + owner: derived_ty, + role: Role::Method, + is_static: false, + slot: Some(4), + }, + ); + project + .signatures + .insert(base_fn, takes(&[(1, Kind::Unknown), (2, Kind::Handle)])); + + // Derived body only reads `p1` alone, yet inherits the 2-cell Handle parameter from base. + let f = function(3, vec![used(0x300, vec![param(1)])], leaves()); + let done = grouped(f.clone(), &project, on()); + assert_eq!( + shape(&done, Var::Param(1)), + Some((Width::Cells, Kind::Handle)) + ); + + // If derived's own signature types `p2` as a known 1-cell kind, `types` would re-insert `p2`, + // so coalescing is skipped to avoid emitting both `Handle p1` and `int p2`. + let mut blocked = project.clone(); + blocked.signatures.insert( + derived_fn, + takes(&[(1, Kind::Unknown), (1, Kind::Unknown), (1, Kind::I32)]), + ); + let skipped = grouped(f, &blocked, on()); + assert_eq!(shape(&skipped, Var::Param(1)), None); +} diff --git a/crates/io/or-io/src/gta6/script/passes/interproc/mod.rs b/crates/io/or-io/src/gta6/script/passes/interproc/mod.rs index aad5de744..576715b58 100644 --- a/crates/io/or-io/src/gta6/script/passes/interproc/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/interproc/mod.rs @@ -63,7 +63,10 @@ pub fn run(f: &mut cfg::Function, cx: &Context<'_>, _stats: &mut Stats) { /// [`run`] whatever the options say, with the count of what it did. pub(crate) fn apply(f: &mut cfg::Function, project: &Project) -> Applied { let mut done = Applied::default(); - if project.signatures.is_empty() && project.slot_results.is_empty() { + if project.signatures.is_empty() + && project.slot_results.is_empty() + && project.slot_params.is_empty() + { return done; } done.sized = sized(f, project); @@ -99,15 +102,24 @@ pub(crate) fn apply(f: &mut cfg::Function, project: &Project) -> Applied { done.kinds += usize::from(declare(f, *var, kind)); } // A parameter this code only passes on is typed by no reading of its own: its kind is the callees'. + let key = FunctionKey::new(program, f.head.at); let own = project .signatures - .get(&FunctionKey::new(program, f.head.at)); - let own = own + .get(&key) .filter(|held| settled(held) && held.params.iter().any(|param| one_kind(param).is_some())); - if let Some(own) = own { + let slot = project.slot_params.get(&key).filter(|params| { + let total = params + .iter() + .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); + total == Some(f.head.params) && params.iter().any(|param| one_kind(param).is_some()) + }); + if own.is_some() || slot.is_some() { for cell in passed_on(f) { - let param = param_at(own, cell).and_then(|n| own.params.get(n)); - if let Some(kind) = param.and_then(one_kind) { + let kind = own + .and_then(|own| param_at(own, cell).and_then(|n| own.params.get(n))) + .and_then(one_kind) + .or_else(|| slot.and_then(|params| starting(params, cell).and_then(one_kind))); + if let Some(kind) = kind { done.kinds += usize::from(declare(f, Var::Param(cell), kind)); } } diff --git a/crates/io/or-io/src/gta6/script/passes/interproc/tests.rs b/crates/io/or-io/src/gta6/script/passes/interproc/tests.rs index cf6a5541c..606910706 100644 --- a/crates/io/or-io/src/gta6/script/passes/interproc/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/interproc/tests.rs @@ -206,3 +206,23 @@ fn an_argument_after_one_of_cells_not_said_is_matched_back_from_the_last_paramet let done = apply(&mut f, &project(vec![of(Kind::F32)], 0, Kind::Unknown)); assert_eq!((passed(&f), done.consts), (was, 0)); } + +#[test] +fn slot_params_alone_type_passed_on_parameters() { + let body = "func_000020(p0); return;"; + let mut f = lowered("void", body); + let mut project = Project::default(); + project.slot_params.insert( + FunctionKey::new(1, 0x10), + vec![Param { + kind: Kind::F32, + cells: 1, + }], + ); + let done = apply(&mut f, &project); + assert_eq!(done.kinds, 1); + assert_eq!( + f.head.vars.get(&Var::Param(0)).map(|info| &info.kind), + Some(&Kind::F32) + ); +} diff --git a/crates/io/or-io/src/gta6/script/passes/sugar_runtime/mod.rs b/crates/io/or-io/src/gta6/script/passes/sugar_runtime/mod.rs index b8491a751..20a71e321 100644 --- a/crates/io/or-io/src/gta6/script/passes/sugar_runtime/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/sugar_runtime/mod.rs @@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::gta6::script::ir::{self, Callee, Expr, ExprSugar, Kind, Scalar, Var, VarInfo, Width}; use crate::gta6::script::tree::{self, Group, Stmt, Sugar}; -use crate::gta6::script::{Context, Pass, Stats}; +use crate::gta6::script::{Context, Pass, Project, Stats}; use super::sugar_expressions::Reached; @@ -46,12 +46,15 @@ pub fn run(f: &mut tree::Function, cx: &Context<'_>, _stats: &mut Stats) { let body = &mut f.body; let frame = Frame::of(body, &f.head.vars); let made = made(body, &frame, &f.head.vars); + let mut subclassed: Option> = None; // An explicit stack: a body nests as deep as its listing does. let mut work: Vec<&mut Vec> = vec![body]; while let Some(list) = work.pop() { construct(list, &frame); for stmt in list { - tops(stmt, &mut |top, taken| read_all(top, taken, &made)); + tops(stmt, &mut |top, taken| { + read_all(top, taken, &made, cx.project, &mut subclassed); + }); work.extend(tree::nested_mut(stmt)); } } @@ -96,7 +99,13 @@ fn simple_tops(stmt: &mut ir::Stmt, f: &mut impl FnMut(&mut Expr, bool)) { } /// Reads every call inside `top` the table says what it is, but a call another reading already holds. -fn read_all(top: &mut Expr, taken: bool, made: &BTreeMap) { +fn read_all( + top: &mut Expr, + taken: bool, + made: &BTreeMap, + project: &Project, + subclassed: &mut Option>, +) { let mut held: BTreeSet<*const Expr> = BTreeSet::new(); top.walk(&mut |e| { if let Expr::Sugar { e: inner, .. } = e { @@ -111,12 +120,18 @@ fn read_all(top: &mut Expr, taken: bool, made: &BTreeMap) { if held.contains(&at) { return; } - read(e, taken || at != whole, made); + read(e, taken || at != whole, made, project, subclassed); }); } /// Reads one call as the method call or the use of a type's property it is; `taken` says whether its value is. -fn read(e: &mut Expr, taken: bool, made: &BTreeMap) { +fn read( + e: &mut Expr, + taken: bool, + made: &BTreeMap, + project: &Project, + subclassed: &mut Option>, +) { let Expr::Call { callee: Callee::Builtin { path, ty, .. }, args, @@ -128,11 +143,14 @@ fn read(e: &mut Expr, taken: bool, made: &BTreeMap) { let kind = match table::reading(path, args.len()) { Some(Reading::Method) if args.first().is_some_and(object) => ExprSugar::Method, // ⚠ `x.M()` of a method an override may replace runs the override: the call reads so only - // on an object of exactly the type that declares it. + // on an object of exactly the type that declares it, on a freshly boxed value (`box` / + // `box_at`), or when the project proves no script class derives from the builtin type. Some(Reading::Virtual) - if args - .first() - .is_some_and(|receiver| exact(receiver, made) == Some(*ty & !BUILTIN)) => + if args.first().is_some_and(|receiver| { + exact(receiver, made) == Some(*ty & !BUILTIN) + || boxed_receiver(path, receiver) + || (object(receiver) && unsubclassed(path, *ty, project, subclassed)) + }) => { ExprSugar::Method } @@ -145,6 +163,57 @@ fn read(e: &mut Expr, taken: bool, made: &BTreeMap) { *e = Expr::sugar(kind, std::mem::replace(e, Expr::GuidEmpty)); } +/// Whether `e` is a freshly boxed value (`box(..)` or `box_at(..)`) calling a `ValueType` or `Object` member. +fn boxed_receiver(path: &str, e: &Expr) -> bool { + if !(path.starts_with("System.ValueType.") || path.starts_with("System.Object.")) { + return false; + } + let mut e = e; + loop { + match e { + Expr::Sugar { e: inner, .. } + | Expr::Cast { + to: Scalar::U64 | Scalar::I64, + e: inner, + } => e = &**inner, + Expr::Call { + callee: Callee::Intrinsic { name, .. }, + .. + } => { + return name == "box_at" + || name.starts_with("box_at<") + || name == "box" + || name.starts_with("box<"); + } + _ => return false, + } + } +} + +/// Whether the loaded project proves no script type derives from the builtin type `ty` (excluding root `Object` and `ValueType`). +fn unsubclassed( + path: &str, + ty: u32, + project: &Project, + subclassed: &mut Option>, +) -> bool { + if project.types.is_empty() + || path.starts_with("System.Object.") + || path.starts_with("System.ValueType.") + { + return false; + } + let derived = subclassed.get_or_insert_with(|| { + project + .types + .values() + .filter_map(|facts| facts.base.and_then(|base| base.builtin())) + .map(|id| id & !BUILTIN) + .collect() + }); + !derived.contains(&(ty & !BUILTIN)) +} + /// Whether `e` may be a reference a method can be called on: no address, no constant, no load narrower than a cell and no address of an element. // ⚠ A value type's method is handed the value's address, which `x.M()` would have to write as // the place, not the address: the table reads no member of a value type on its receiver. diff --git a/crates/io/or-io/src/gta6/script/passes/sugar_runtime/tests.rs b/crates/io/or-io/src/gta6/script/passes/sugar_runtime/tests.rs index 57d41d4ae..0d1a35021 100644 --- a/crates/io/or-io/src/gta6/script/passes/sugar_runtime/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/sugar_runtime/tests.rs @@ -2,9 +2,9 @@ use std::collections::BTreeMap; use super::table::{reading, Form, Reading, TYPES}; use super::*; -use crate::gta6::script::ir::{Const, Head, Returns, VmType}; -use crate::gta6::script::project::Project; -use crate::gta6::script::{Names, Options}; +use crate::gta6::script::ir::{Const, Head, Returns, TypeKey, VmType}; +use crate::gta6::script::project::{Project, TypeFacts}; +use crate::gta6::script::{print, reparse, Names, Options}; /// The index in the runtime's table of the builtin type these tests call. const INDEX: u32 = 0x3E; @@ -228,3 +228,129 @@ fn every_kind_the_table_states_is_of_a_member_of_its_type_that_answers_once_and_ assert_eq!(names.len(), ty.results.len(), "{}", ty.name); } } + +#[test] +fn boxed_value_type_calls_rewrite_to_receiver_methods_and_round_trip() { + let box_at = Expr::Call { + callee: Callee::Intrinsic { + name: "box_at".to_owned(), + ty: Some(VmType { + name: "type_00000000000000AA".to_owned(), + byte_size: 16, + id: 7, + flags: 0x04, + }), + wrapper: None, + }, + args: vec![Expr::AddrOf { + var: Var::Param(1), + cell: 0, + }], + returns: Some(1), + }; + let box_val = Expr::Call { + callee: Callee::Intrinsic { + name: "box".to_owned(), + ty: None, + wrapper: None, + }, + args: vec![p(0)], + returns: Some(1), + }; + let mut f = tree::Function { + head: head(), + body: vec![ + assign( + Var::Local(0), + builtin("System.ValueType.GetHashCode", vec![box_at.clone()], 1), + ), + assign( + Var::Local(1), + builtin("System.ValueType.Equals", vec![box_at, p(0)], 1), + ), + eval(builtin("System.Object.GetHashCode", vec![box_val], 1)), + ], + }; + let names = Names::default(); + let options = Options::default(); + let cx = Context::new(&names, Project::empty(), options); + run(&mut f, &cx, &mut Stats::default()); + assert!(on_receiver(&f.body, "System.ValueType.GetHashCode")); + assert!(on_receiver(&f.body, "System.ValueType.Equals")); + assert!(on_receiver(&f.body, "System.Object.GetHashCode")); + + let mut text = String::new(); + print::function_in(&mut text, &f, &cx); + assert!( + text.contains("box_at(&p1).GetHashCode()"), + "{text}" + ); + assert!( + text.contains("box_at(&p1).Equals(p0)"), + "{text}" + ); + assert!(text.contains("box(p0).GetHashCode()"), "{text}"); + let read = reparse::agrees_source_with(&f, &text, options, false, Project::empty()); + assert_eq!(read, Ok(()), "{text}"); +} + +#[test] +fn unsubclassed_builtin_virtual_methods_rewrite_on_globals_and_round_trip() { + let global = Expr::Var(Var::Global { + program: 0x1122_3344, + offset: 0x1C0, + statics: false, + }); + let body = vec![ + assign( + Var::Local(0), + builtin( + "System.Random.Next", + vec![global.clone(), int(5000), int(10000)], + 1, + ), + ), + assign( + Var::Local(1), + builtin("System.Random.NextDouble", vec![global], 1), + ), + // Unboxed `System.Object` virtual call must never rewrite even with a populated project. + eval(builtin("System.Object.GetHashCode", vec![p(1)], 1)), + ]; + let names = Names::default(); + let options = Options::default(); + + // Populated project with no script class deriving from `System.Random`. + let mut project = Project::default(); + project.types.insert(TypeKey(0xAA), TypeFacts::default()); + let cx = Context::new(&names, &project, options); + let mut f = tree::Function { + head: head(), + body: body.clone(), + }; + run(&mut f, &cx, &mut Stats::default()); + assert!(on_receiver(&f.body, "System.Random.Next")); + assert!(on_receiver(&f.body, "System.Random.NextDouble")); + assert!(!on_receiver(&f.body, "System.Object.GetHashCode")); + + let mut text = String::new(); + print::function_in(&mut text, &f, &cx); + assert!(text.contains(".Next(5000, 10000)"), "{text}"); + assert!(text.contains(".NextDouble()"), "{text}"); + let read = reparse::agrees_source_with(&f, &text, options, false, &project); + assert_eq!(read, Ok(()), "{text}"); + + // When a script class derives from `System.Random`, its virtual calls stay static. + project.types.insert( + TypeKey(0xBB), + TypeFacts { + base: Some(TypeKey(u64::from(BUILTIN | INDEX))), + ..TypeFacts::default() + }, + ); + let cx_sub = Context::new(&names, &project, options); + let mut f_sub = tree::Function { head: head(), body }; + run(&mut f_sub, &cx_sub, &mut Stats::default()); + assert!(!on_receiver(&f_sub.body, "System.Random.Next")); + assert!(!on_receiver(&f_sub.body, "System.Random.NextDouble")); +} diff --git a/crates/io/or-io/src/gta6/script/passes/types/kinds.rs b/crates/io/or-io/src/gta6/script/passes/types/kinds.rs index eec7fcf1f..819f9d693 100644 --- a/crates/io/or-io/src/gta6/script/passes/types/kinds.rs +++ b/crates/io/or-io/src/gta6/script/passes/types/kinds.rs @@ -7,11 +7,19 @@ use crate::gta6::script::names::{NativeSignature, NativeType}; /// The .NET root reference type for a managed heap reference of no concrete class. pub(super) const OBJECT: &str = "System.Object"; +/// The .NET non-generic enumerator interface. +pub(super) const IENUMERATOR: &str = "System.Collections.IEnumerator"; + /// A managed heap reference of no concrete class (`object` in C#). pub(super) fn object_kind() -> Kind { Kind::Object(OBJECT.to_owned()) } +/// An enumerator reference (`IEnumerator` in C#). +pub(super) fn enumerator_kind() -> Kind { + Kind::Object(IENUMERATOR.to_owned()) +} + /// What the evidence so far says a one-cell value is. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(super) enum Lat { diff --git a/crates/io/or-io/src/gta6/script/passes/types/mod.rs b/crates/io/or-io/src/gta6/script/passes/types/mod.rs index 734b9690a..48f81682c 100644 --- a/crates/io/or-io/src/gta6/script/passes/types/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/types/mod.rs @@ -259,8 +259,9 @@ impl<'a> Around<'a> { } /// What two pieces of evidence say together. - // Where `kinds` is on, two named references are the one the other derives from, else some - // reference for good: `Lat::join` alone would let a third type take the place of two. + // Where `kinds` is on, two named references are the one the other derives from, else their + // nearest common script base class, else some reference for good: `Lat::join` alone would let + // a third type take the place of two. fn join(&self, a: &Lat, b: &Lat) -> Lat { match (a, b) { (Lat::Is(x), Lat::Is(y)) @@ -273,12 +274,46 @@ impl<'a> Around<'a> { match (key(x), key(y)) { (Some(from), Some(to)) if self.project.is_a(from, to) => Lat::Is(y.clone()), (Some(to), Some(from)) if self.project.is_a(from, to) => Lat::Is(x.clone()), + (Some(from), Some(other)) => match self.common_script_base(from, other) { + Some(base) => Lat::Is(Kind::Object(base.to_string())), + None => Lat::Refs, + }, _ => Lat::Refs, } } _ => a.join(b), } } + + /// Whether script class `ty` derives from `ancestor` along the single-inheritance class chain. + fn derives_class(&self, mut ty: TypeKey, ancestor: TypeKey) -> bool { + for _ in 0..64 { + if ty == ancestor { + return true; + } + let Some(base) = self.project.types.get(&ty).and_then(|facts| facts.base) else { + return false; + }; + ty = base; + } + false + } + + /// The nearest non-value script class that both `a` and `b` derive from, if any (never a builtin root). + fn common_script_base(&self, a: TypeKey, b: TypeKey) -> Option { + let mut at = self.project.types.get(&a)?.base?; + for _ in 0..64 { + if at.builtin().is_some() { + return None; + } + let facts = self.project.types.get(&at)?; + if !facts.is_value() && self.derives_class(b, at) { + return Some(at); + } + at = facts.base?; + } + None + } } /// How the expression around one takes its value. @@ -383,8 +418,12 @@ struct Facts { dereferenced: HashSet, /// Variables proved to hold a managed heap reference where `kinds` is on. managed: HashSet, - /// Variables used as a raw pointer base (`Load`/`Store`/`ByteOffset`, `bytes_equal_*`, `cast_mode_*`, native pointer params). + /// Variables used as a memory access base (`Load`/`Store`/`ByteOffset`). raw_base: HashSet, + /// Variables with definite raw pointer uses (`bytes_equal_*`, `cast_mode_*`, native pointer params). + hard_raw: HashSet, + /// Variables with `IEnumerator` calls (`MoveNext`, `get_Current`, or `System.Collections.IEnumerator` slots). + enumerators: HashSet, /// Variables indexed as an array (`array_get_*`, `array_set_*`, `array_element_address`). array_indexed: HashSet, /// Primitive element scalar inferred for each variable used as the array of `array_get_` / `array_set_`. @@ -1343,6 +1382,7 @@ impl Scan<'_> { } if self.around.kinds { self.note_intrinsic(callee, args); + self.note_enumerator(callee, args); } let reads = self.around.arg_reads(callee, args, self.wide); if self.around.kinds && matches!(callee, Callee::Native { .. }) { @@ -1350,7 +1390,7 @@ impl Scan<'_> { if matches!(read, Read::Hint(Lat::Is(Kind::Pointer))) { if let Expr::Var(var) = peeled(arg, 8) { if !self.untyped(*var) { - self.facts.raw_base.insert(*var); + self.facts.hard_raw.insert(*var); } } } @@ -1490,7 +1530,7 @@ impl Scan<'_> { self.facts.array_indexed.insert(*var); } if name.starts_with("cast_mode_") || name.starts_with("bytes_equal_") { - self.facts.raw_base.insert(*var); + self.facts.hard_raw.insert(*var); } } } @@ -1506,7 +1546,7 @@ impl Scan<'_> { if name.starts_with("bytes_equal_") { if let Some(Expr::Var(var)) = args.get(1).map(|arg| peeled(arg, 8)) { if !self.untyped(*var) { - self.facts.raw_base.insert(*var); + self.facts.hard_raw.insert(*var); } } } @@ -1517,6 +1557,45 @@ impl Scan<'_> { } } + /// Notes when a call invokes `System.Collections.IEnumerator` (`MoveNext`, `get_Current`, `Reset`) on a variable. + fn note_enumerator(&mut self, callee: &Callee, args: &[Expr]) { + let Some(Expr::Var(var)) = args.first().map(|arg| peeled(arg, 8)) else { + return; + }; + if self.untyped(*var) { + return; + } + let is_enum = match callee { + Callee::Virtual { + ty, method, slot, .. + } => { + let ty_name = self.around.names.listed_type(ty).unwrap_or(ty.as_str()); + if ty_name == kinds::IENUMERATOR { + true + } else if args.len() == 1 { + let called = TypeKey::of_name(ty) + .and_then(|key| self.around.names.method(key, *slot)) + .unwrap_or(method.as_str()); + matches!(called, "MoveNext" | "get_Current") + } else { + false + } + } + Callee::Builtin { path, .. } => matches!( + path.as_str(), + "System.Collections.IEnumerator.MoveNext" + | "System.Collections.IEnumerator.get_Current" + | "System.Collections.IEnumerator.Reset" + ), + _ => false, + }; + if is_enum { + self.facts.enumerators.insert(*var); + self.facts.managed.insert(*var); + self.facts.dereferenced.insert(*var); + } + } + fn note_array_elem(&mut self, var: Var, elem: ArrayElem) { self.facts .array_elems @@ -1885,7 +1964,11 @@ impl Typing<'_> { let Some(scalar) = elem.scalar() else { continue; }; - if self.typed(var) && self.open(var) && !self.facts.raw_base.contains(&var) { + if self.typed(var) + && self.open(var) + && !self.facts.raw_base.contains(&var) + && !self.facts.hard_raw.contains(&var) + { self.known .insert(var, Lat::Is(Kind::Array(Box::new(scalar.kind())))); changed = true; @@ -3035,9 +3118,9 @@ impl Typing<'_> { } } } - let (managed, raw) = match self.around.kinds { + let (managed, raw, alloc_managed) = match self.around.kinds { true => self.resolve_managed(&f.cfg), - false => (HashSet::new(), HashSet::new()), + false => (HashSet::new(), HashSet::new(), HashSet::new()), }; for (var, lat) in &self.known { let mut kind = lat.kind(); @@ -3046,7 +3129,13 @@ impl Typing<'_> { && managed.contains(var) && !raw.contains(var) { - kind = kinds::object_kind(); + kind = match *lat == Lat::Is(Kind::Pointer) + && self.facts.enumerators.contains(var) + && !alloc_managed.contains(var) + { + true => kinds::enumerator_kind(), + false => kinds::object_kind(), + }; } found.insert(*var, kind); } @@ -3074,20 +3163,16 @@ impl Typing<'_> { } } - /// Separates managed heap references (promoted to `System.Object` when no concrete class is - /// known) from raw pointers (which must stay `Kind::Pointer`). - fn resolve_managed(&self, cfg: &cfg::Cfg) -> (HashSet, HashSet) { + /// Separates managed heap references (promoted to `System.Object` or `IEnumerator` when no + /// concrete class is known) from raw pointers (which must stay `Kind::Pointer`). + fn resolve_managed(&self, cfg: &cfg::Cfg) -> (HashSet, HashSet, HashSet) { let mut managed = self.facts.managed.clone(); - // A field load on a concrete class or an element read on a typed array is not a raw pointer dereference. - let untyped_ptr = |var: &&Var| !matches!(self.lat(**var), Lat::Is(k) if kinds::named(&k)); - let mut raw: HashSet = self - .facts - .raw_base - .iter() - .filter(untyped_ptr) - .copied() - .collect(); - raw.extend(self.facts.array_indexed.iter().filter(untyped_ptr).copied()); + // Variables directly holding a newly allocated managed object/array/string. Soft field + // stores/loads on these (such as object initializers) do not make them `void*`. + let mut alloc_managed: HashSet = HashSet::new(); + // Definite raw pointer sources and `void*` boundaries (fields, globals, returns). + let mut hard_raw: HashSet = self.facts.hard_raw.clone(); + for (&var, lat) in &self.known { if matches!(lat, Lat::Refs) || matches!(lat, Lat::Is(k) if kinds::named(k)) { managed.insert(var); @@ -3109,20 +3194,30 @@ impl Typing<'_> { stack.push(els); } Expr::Var(from) if self.typed(*from) => copies.push((target, *from)), + Expr::Var(global @ Var::Global { .. }) => { + if self.lat(*global) == Lat::Is(Kind::Pointer) { + hard_raw.insert(target); + } + } Expr::AddrOf { .. } | Expr::ByteOffset { .. } => { - raw.insert(target); + hard_raw.insert(target); } Expr::NewObject(_) | Expr::NewArray { .. } | Expr::StringConstant { .. } => { managed.insert(target); + alloc_managed.insert(target); + } + Expr::Load { ty, addr, offset } => { + if self.field(addr, *offset, ty.bytes(), 0) == Lat::Is(Kind::Pointer) { + hard_raw.insert(target); + } } Expr::Call { callee, returns, .. } => { if kinds::raw_ptr_yield(callee) - || (matches!(callee, Callee::Native { .. }) - && self.around.yields(callee, *returns).0 == Lat::Is(Kind::Pointer)) + || self.around.yields(callee, *returns).0 == Lat::Is(Kind::Pointer) { - raw.insert(target); + hard_raw.insert(target); } else if kinds::managed_yield(callee, *returns) { managed.insert(target); } @@ -3136,6 +3231,27 @@ impl Typing<'_> { seed_expr(target, value); } }); + let mut note_raw_expr = |e: &Expr| { + let mut stack = vec![e]; + let mut steps = 0u32; + while let Some(node) = stack.pop() { + if steps > MAX_DEPTH { + break; + } + steps += 1; + match peeled(node, 8) { + Expr::Sugar { e: inner, .. } => stack.push(inner), + Expr::Select { then, els, .. } => { + stack.push(then); + stack.push(els); + } + Expr::Var(var) if self.typed(*var) => { + hard_raw.insert(*var); + } + _ => {} + } + } + }; let mut compared: Vec<(Var, Var)> = Vec::new(); let mut note_eq = |top: &Expr| { top.walk(&mut |e| { @@ -3156,12 +3272,65 @@ impl Typing<'_> { }; for block in &cfg.blocks { for stmt in &block.stmts { + match stmt { + Stmt::Store { + kind, + addr, + offset, + value, + } if self.field(addr, *offset, kind.bytes(), 0) == Lat::Is(Kind::Pointer) => { + note_raw_expr(value); + } + Stmt::Assign { + target: target @ Var::Global { .. }, + value, + } if self.lat(*target) == Lat::Is(Kind::Pointer) => { + note_raw_expr(value); + } + _ => {} + } stmt.each_expr(&mut note_eq); } + if let Terminator::Return(Some(e)) = &block.term { + if self.around.returned == Lat::Is(Kind::Pointer) { + note_raw_expr(e); + } + } if let Some(e) = block.term.expr() { note_eq(e); } } + // Propagate `alloc_managed` forward through copies that never hit a hard raw boundary. + for _ in 0..MAX_ROUNDS { + let before = alloc_managed.len(); + for &(target, from) in &copies { + if alloc_managed.contains(&from) && !hard_raw.contains(&target) { + alloc_managed.insert(target); + } + } + if alloc_managed.len() == before { + break; + } + } + // A field load on a concrete class or an element read on a typed array is not a raw pointer + // dereference; neither is a field access on a newly allocated managed object unless mixed + // with a hard raw pointer. + let untyped_ptr = |var: &&Var| !matches!(self.lat(**var), Lat::Is(k) if kinds::named(&k)); + let mut raw: HashSet = hard_raw.iter().filter(untyped_ptr).copied().collect(); + raw.extend( + self.facts + .raw_base + .iter() + .filter(|var| untyped_ptr(var) && !alloc_managed.contains(*var)) + .copied(), + ); + raw.extend( + self.facts + .array_indexed + .iter() + .filter(|var| untyped_ptr(var) && !alloc_managed.contains(*var)) + .copied(), + ); for _ in 0..MAX_ROUNDS { let before = (managed.len(), raw.len()); for &(target, from) in &copies { @@ -3191,7 +3360,7 @@ impl Typing<'_> { break; } } - (managed, raw) + (managed, raw, alloc_managed) } /// What a value of several cells is, by the expression that makes it. diff --git a/crates/io/or-io/src/gta6/script/passes/types/tests.rs b/crates/io/or-io/src/gta6/script/passes/types/tests.rs index 2bcf90cd1..24e546eb3 100644 --- a/crates/io/or-io/src/gta6/script/passes/types/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/types/tests.rs @@ -1128,3 +1128,139 @@ fn primitive_scalar_arrays_are_inferred_from_array_intrinsics_without_clobbering Kind::Array(Box::new(object(THING))) ); } + +#[test] +fn new_objects_with_field_stores_do_not_become_void_ptr_and_share_common_script_base() { + use crate::gta6::script::project::TypeFacts; + + const BASE: &str = "type_00000000000000CC"; + let stmts = vec![ + set(0, made(THING)), + store(StoreKind::I32, local(0), 0x10, int(1)), + set(0, made(OTHER)), + store(StoreKind::I32, local(0), 0x18, int(2)), + set(1, local(0)), + set(2, load(Scalar::I32, local(1), 0x10)), + ]; + + // Unrelated NewObjects with field stores/loads -> System.Object (never void*). + let unrelated = typed_in(stmts.clone(), Project::empty()); + assert_eq!(kind_of(&unrelated, Var::Local(0)), object("System.Object")); + assert_eq!(kind_of(&unrelated, Var::Local(1)), object("System.Object")); + + // Sibling subclasses sharing a common script base class -> common base class. + let mut project = Project::default(); + project.types.insert(TypeKey(0xCC), TypeFacts::default()); + project.types.insert( + TypeKey(0xAA), + TypeFacts { + base: Some(TypeKey(0xCC)), + ..TypeFacts::default() + }, + ); + project.types.insert( + TypeKey(0xBB), + TypeFacts { + base: Some(TypeKey(0xCC)), + ..TypeFacts::default() + }, + ); + let shared = typed_in(stmts, &project); + assert_eq!(kind_of(&shared, Var::Local(0)), object(BASE)); + assert_eq!(kind_of(&shared, Var::Local(1)), object(BASE)); +} + +#[test] +fn variables_at_pointer_field_or_return_boundaries_stay_void_ptr() { + let mut project = Project::default(); + project.fields.insert( + TypeKey(0xAA), + vec![ + FieldFacts { + offset: 0x8, + bytes: 8, + kind: Kind::Pointer, + }, + FieldFacts { + offset: 0x10, + bytes: 8, + kind: object("System.Object"), + }, + ], + ); + let own = FunctionKey::new(0x1122_3344, 0); + project.signatures.insert( + own, + Signature { + params: vec![ + Param { + kind: Kind::Unknown, + cells: 1, + }; + 4 + ], + returns: 1, + result: Kind::Pointer, + }, + ); + let mut f = function(vec![ + set(0, made(THING)), + // Stored into `void* f_8` -> stays Kind::Pointer. + store(StoreKind::Ref, local(0), 0x8, param(0)), + // Stored into `object f_10` -> promoted to System.Object. + store(StoreKind::Ref, local(0), 0x10, param(1)), + // Loaded from `void* f_8` and also stored via Ref -> stays Kind::Pointer. + set(1, load(Scalar::U64, local(0), 0x8)), + store(StoreKind::Ref, local(0), 0x10, local(1)), + // Stored via Ref and returned as `void*` -> stays Kind::Pointer. + store(StoreKind::Ref, local(0), 0x10, param(2)), + ]); + f.head.returns = Returns::Cell; + f.cfg.blocks[0].term = Terminator::Return(Some(param(2))); + let names = Names::default(); + run_in(&mut f, &kinded(&names, &project), &mut Stats::default()); + + assert_eq!(kind_of(&f, Var::Param(0)), Kind::Pointer); + assert_eq!(kind_of(&f, Var::Param(1)), object("System.Object")); + assert_eq!(kind_of(&f, Var::Local(1)), Kind::Pointer); + assert_eq!(kind_of(&f, Var::Param(2)), Kind::Pointer); +} + +#[test] +fn enumerator_variables_with_movenext_or_current_become_ienumerator() { + let ienumerator = object("System.Collections.IEnumerator"); + let vcall = |ty: &str, method: &str, slot: u32, recv: Expr| Expr::Call { + callee: Callee::Virtual { + class: ty.to_owned(), + method: method.to_owned(), + ty: ty.to_owned(), + slot, + }, + args: vec![recv], + returns: Some(1), + }; + let mut names = Names::default(); + names + .types + .insert(0x8000_0053, "System.Collections.IEnumerator".to_owned()); + + let mut f = function(vec![ + // Builtin IEnumerator slot (index 83, missing from BUILTIN_TYPES) -> IEnumerator. + set(3, vcall("type_80000053", "Method_0", 0, local(0))), + // Named MoveNext + unrelated Dispose -> IEnumerator instead of System.Object. + set(4, vcall("type_00000000000000DD", "MoveNext", 0, local(1))), + Stmt::Eval(vcall("type_00000000000000EE", "Dispose", 0, local(1))), + // Concrete NewObject class calling MoveNext keeps its concrete class. + set(2, made(THING)), + set(5, vcall("type_80000053", "Method_0", 0, local(2))), + ]); + run_in( + &mut f, + &kinded(&names, Project::empty()), + &mut Stats::default(), + ); + + assert_eq!(kind_of(&f, Var::Local(0)), ienumerator); + assert_eq!(kind_of(&f, Var::Local(1)), ienumerator); + assert_eq!(kind_of(&f, Var::Local(2)), object(THING)); +} diff --git a/crates/io/or-io/src/gta6/script/passes/values/locals/mod.rs b/crates/io/or-io/src/gta6/script/passes/values/locals/mod.rs index 2f4ae0a0d..d5d604dc6 100644 --- a/crates/io/or-io/src/gta6/script/passes/values/locals/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/values/locals/mod.rs @@ -89,6 +89,26 @@ fn uses(body: &[Stmt]) -> BTreeMap { found } +/// `e` under any source-reading sugar around it. +fn bare(mut e: &Expr) -> &Expr { + while let Expr::Sugar { e: inner, .. } = e { + e = inner; + } + e +} + +/// `e` under any 64-bit casts around it. +fn bits(mut e: &Expr) -> &Expr { + while let Expr::Cast { + to: ir::Scalar::I64 | ir::Scalar::U64, + e: inner, + } = e + { + e = inner; + } + e +} + /// Whether `made` has the shape the printer actually collapses into one expression when inlined. fn form_inlines(made: &Stmt) -> bool { match made { @@ -97,15 +117,42 @@ fn form_inlines(made: &Stmt) -> bool { tree::Sugar::Group { kind: Group::Delegate, parts, - } => parts.len() == 2, + } => match parts.as_slice() { + [ir::Stmt::Assign { target, value }, ir::Stmt::Eval(call)] => { + matches!(bare(value), Expr::NewObject(_)) + && matches!( + bare(call), + Expr::Call { args, .. } + if args.len() == 3 && *bare(bits(&args[0])) == Expr::Var(*target) + ) + } + _ => false, + }, tree::Sugar::Group { kind: Group::Collection, parts, - } => (2..=4097).contains(&parts.len()), + } => match parts.split_first() { + Some((ir::Stmt::Assign { value, .. }, sets)) => { + !sets.is_empty() + && sets.len() <= 4096 + && matches!( + bare(value), + Expr::NewArray { len, .. } + if matches!(bits(len), Expr::Const(c) if c.bits == sets.len() as u64) + ) + } + _ => false, + }, tree::Sugar::Group { kind: Group::Construct, parts, - } => parts.len() >= 2, + } => { + parts.len() >= 2 + && matches!( + parts.first(), + Some(ir::Stmt::Assign { value, .. }) if matches!(bare(value), Expr::NewObject(_)) + ) + } _ => false, }, _ => false, @@ -118,15 +165,20 @@ fn read_next(body: &[Stmt], head: &ir::Head) -> BTreeSet { let mut found = BTreeSet::new(); let mut work: Vec<&[Stmt]> = vec![body]; while let Some(list) = work.pop() { - for pair in list.windows(2) { - if !form_inlines(&pair[0]) { - continue; - } - if let Some(var) = made_in_place(&pair[0], &pair[1], &tally, head) { - if var.is_temporary() { - found.insert(var); + let mut i = 0; + while i + 1 < list.len() { + if form_inlines(&list[i]) { + if let Some(var) = made_in_place(&list[i], &list[i + 1], &tally, head) { + if var.is_temporary() { + found.insert(var); + } + // The printer consumes both statements when folding a pair, so `list[i + 1]` + // will not be folded into `list[i + 2]`. + i += 2; + continue; } } + i += 1; } for stmt in list { match stmt { @@ -269,6 +321,19 @@ fn names_of(f: &tree::Function) -> BTreeSet { /// Gives each temporary of a lambda that goes by a name a function binding the lambda holds the next name of its word that neither holds, so that the lambda written in place hides nothing of its binder's. // ⚠ [`named`] names each function alone, and a lambda's body may be written inside its binder's. pub(crate) fn apart_in_place(unit: &mut Unit) { + // Async step inlining (`joined_steps`) clears variable names copied from step functions, and + // state-machine hoisting can expose unnamed temporaries after per-function `named` already ran. + let empty_names = Names::default(); + for method in &mut unit.functions { + named(&mut method.function, &empty_names); + } + let mut open_mut: Vec<&mut Class> = unit.classes.iter_mut().collect(); + while let Some(class) = open_mut.pop() { + for method in &mut class.methods { + named(&mut method.function, &empty_names); + } + open_mut.extend(class.nested.iter_mut()); + } let program = unit.program; let mut binders: BTreeMap> = BTreeMap::new(); let mut open: Vec<&Class> = unit.classes.iter().collect(); diff --git a/crates/io/or-io/src/gta6/script/passes/values/locals/tests.rs b/crates/io/or-io/src/gta6/script/passes/values/locals/tests.rs index 758183f57..bb206fe53 100644 --- a/crates/io/or-io/src/gta6/script/passes/values/locals/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/values/locals/tests.rs @@ -279,3 +279,142 @@ fn temporaries_not_inlined_by_made_in_place_are_named_by_kind() { assert_eq!(name_of(&f, tested), Some("obj_2")); assert_eq!(name_of(&f, intrinsic_arg), Some("obj_3")); } + +#[test] +fn malformed_groups_refused_by_printer_are_named_by_kind() { + let ty = || ir::VmType { + name: "type_0000000000000001".to_owned(), + byte_size: 16, + id: 1, + flags: 0, + }; + let (bad_arr, bad_del) = (temp(1), temp(2)); + let arr_kind = Kind::Array(Box::new(Kind::I32)); + let obj_kind = Kind::Object("type_0000000000000001".to_owned()); + + // `Group::Collection` whose declared array length (3) does not match its 1 element store: + // the printer refuses to fold it, so `bad_arr` must be named. + let mismatched_collection = Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: Group::Collection, + parts: vec![ + ir::Stmt::Assign { + target: bad_arr, + value: Expr::NewArray { + ty: ty(), + len: Box::new(Expr::Const(Const::i32(3))), + wrapper: String::new(), + }, + }, + ir::Stmt::Eval(Expr::Call { + callee: Callee::Intrinsic { + name: "array_set_u32".to_owned(), + ty: None, + wrapper: None, + }, + args: vec![ + Expr::Var(bad_arr), + Expr::Const(Const::i32(0)), + Expr::Const(Const::i32(7)), + ], + returns: Some(0), + }), + ], + })); + // `Group::Delegate` whose bind call does not take 3 arguments: + // the printer refuses to fold it, so `bad_del` must be named. + let malformed_delegate = Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: Group::Delegate, + parts: vec![ + ir::Stmt::Assign { + target: bad_del, + value: Expr::NewObject(ty()), + }, + ir::Stmt::Eval(Expr::Call { + callee: Callee::Local { + at: 0x300, + name: "Bind".to_owned(), + }, + args: vec![Expr::Var(bad_del)], + returns: Some(0), + }), + ], + })); + + let body = vec![ + mismatched_collection, + used(vec![Expr::Var(bad_arr)]), + malformed_delegate, + used(vec![Expr::Var(bad_del)]), + ]; + let mut f = function( + body, + &[ + (bad_arr, arr_kind, Width::Cell), + (bad_del, obj_kind, Width::Cell), + ], + ); + named(&mut f, &Names::default()); + assert_eq!(name_of(&f, bad_arr), Some("array")); + assert_eq!(name_of(&f, bad_del), Some("obj")); +} + +#[test] +fn apart_in_place_names_temporaries_left_unnamed_after_async_step_inlining() { + use crate::gta6::script::class::{Class, ClassKind, Method, Unit}; + use crate::gta6::script::ir::TypeKey; + + let step_temp = Var::Value { + at: 0x000475, + index: 3, + }; + let stack_temp = Var::Stack { + at: 0x02313C, + index: 1, + }; + let free_temp = Var::Value { + at: 0x0584C7, + index: 1, + }; + let async_fn = function( + vec![ + set(step_temp, Expr::Var(Var::Param(0))), + set(stack_temp, Expr::Const(Const::i32(9))), + used(vec![Expr::Var(step_temp), Expr::Var(stack_temp)]), + ], + &[ + (step_temp, Kind::Unknown, Width::Cell), + (stack_temp, Kind::I32, Width::Cell), + ], + ); + let free_fn = function( + vec![ + set(free_temp, Expr::Var(Var::Param(0))), + used(Vec::new()), + used(vec![Expr::Var(free_temp)]), + ], + &[(free_temp, Kind::Bool, Width::Cell)], + ); + let mut unit = Unit { + program: 1, + imports: Vec::new(), + classes: vec![Class { + key: TypeKey(9), + kind: ClassKind::Class, + base: None, + interfaces: Vec::new(), + fields: Vec::new(), + methods: vec![Method::free(async_fn)], + nested: Vec::new(), + }], + functions: vec![Method::free(free_fn)], + front: None, + }; + apart_in_place(&mut unit); + let f = &unit.classes[0].methods[0].function; + assert_eq!(name_of(f, step_temp), Some("cell")); + assert_eq!(name_of(f, stack_temp), Some("num")); + assert_eq!( + name_of(&unit.functions[0].function, free_temp), + Some("flag") + ); +} diff --git a/crates/io/or-io/src/gta6/script/print/constructs/mod.rs b/crates/io/or-io/src/gta6/script/print/constructs/mod.rs index 263b43504..d926e854d 100644 --- a/crates/io/or-io/src/gta6/script/print/constructs/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/constructs/mod.rs @@ -929,6 +929,26 @@ impl Writer<'_> { } _ => item, }, + ( + None, + Expr::Call { + callee: Callee::Intrinsic { name, .. }, + args, + .. + }, + ) if self.sharp && name == "array_set_u32" => { + match (ty_name.as_str(), args.as_slice()) { + ("int", [_, _, elem_val]) => { + self.store_rhs_target(StoreKind::I32, elem_val, StoreTarget::SignedI32) + } + ("uint", [_, _, elem_val]) => self.store_rhs_target( + StoreKind::I32, + elem_val, + StoreTarget::UnsignedU32, + ), + _ => item, + } + } _ => item, }; items.push(item); diff --git a/crates/io/or-io/src/gta6/script/print/constructs/tests.rs b/crates/io/or-io/src/gta6/script/print/constructs/tests.rs index 2d75d9598..2545e7901 100644 --- a/crates/io/or-io/src/gta6/script/print/constructs/tests.rs +++ b/crates/io/or-io/src/gta6/script/print/constructs/tests.rs @@ -580,7 +580,7 @@ void func_000040(Cell p0) let block = " DEMO.USE((Cell p1) => { Cell local_3 = 0; - DEMO.USE(p1, &local_3); + DEMO.USE(p1, addr(ref local_3)); }); "; let text = bound_in(&binder(), &scratch); @@ -1357,6 +1357,113 @@ fn field_store_and_initialiser_int_to_uint_and_enum_array_initialiser_read_back( .expect("int->uint field/initialiser stores and enum array initialiser read back"); } +#[test] +fn int_array_initialiser_and_object_initialiser_cast_high_hex_and_hash_native_to_int_and_read_back() +{ + use crate::gta5::script::natives::{NativeDb, NativeName}; + use crate::gta6::script::reparse; + let owner = TypeKey(0xAB); + let mut project = Project::default(); + project.fields.insert( + owner, + vec![FieldFacts { + offset: 0x20, + bytes: 4, + kind: Kind::I32, + }], + ); + let hash_native = NativeName { + namespace: Some("PLAYER".to_owned()), + name: "GET_HASH".to_owned(), + params: Vec::new(), + returns: Some("Hash".to_owned()), + }; + let names = Names { + natives: Some(NativeDb::from_names("test", [(0x55AA, hash_native)])), + ..Names::default() + }; + let mut h = kinds(&[ + (Var::Param(0), Kind::Object(owner.to_string())), + (Var::Param(1), Kind::U32), + ]); + h.params = 2; + let int_vm = VmType { + name: "System.Int32".to_owned(), + byte_size: 4, + id: 2, + flags: 0x04, + }; + let get_hash = || Expr::Call { + callee: Callee::Native { + namespace: Some("PLAYER".to_owned()), + name: "GET_HASH".to_owned(), + hash: 0x55AA, + rva: 0, + }, + args: Vec::new(), + returns: Some(1), + }; + let field_set = group( + Group::Field { owner }, + vec![store(StoreKind::I32, param(0), 0x20, get_hash())], + ); + let init_parts = vec![ + assign(Var::Local(0), Expr::NewObject(object())), + store(StoreKind::I32, local(0), 0x20, get_hash()), + ]; + let arr_parts = vec![ + assign( + Var::Local(1), + Expr::NewArray { + ty: int_vm, + len: Box::new(int(4)), + wrapper: "new_arr".to_owned(), + }, + ), + Stmt::Eval(intrinsic( + "array_set_u32", + vec![local(1), int(0), constant_of(0x7994_84A4, Kind::U32)], + )), + Stmt::Eval(intrinsic( + "array_set_u32", + vec![local(1), int(1), constant_of(0xFD92_05DA, Kind::U32)], + )), + Stmt::Eval(intrinsic( + "array_set_u32", + vec![local(1), int(2), get_hash()], + )), + Stmt::Eval(intrinsic("array_set_u32", vec![local(1), int(3), param(1)])), + ]; + let f = function_of( + h, + vec![ + field_set, + group(Group::Construct, init_parts), + group(Group::Collection, arr_parts), + used(vec![local(0), local(1)]), + ], + ); + let cx = Context::new(&names, &project, Options::default()); + let text = written_in(&f, &cx); + assert!( + text.contains(" p0.f_20 = (int)PLAYER.GET_HASH();\n"), + "{text}" + ); + assert!( + text.contains("new type_00000000000000AB { f_20 = (int)PLAYER.GET_HASH() }"), + "{text}" + ); + let flat = text.split_whitespace().collect::>().join(" "); + assert!( + flat.contains( + "new int[] { 0x799484A4, unchecked((int)0xFD9205DA), (int)PLAYER.GET_HASH(), (int)p1 }" + ), + "{text}" + ); + reparse::agrees_source_named(&f, &text, cx.options, &project, &names) + .expect("int array initialiser and Hash->int object initialiser read back"); +} + /// An enumerator taken from `p0` and gone through, each item handed to a function. fn enumerated() -> Sugar { Sugar::Foreach { diff --git a/crates/io/or-io/src/gta6/script/print/enums/mod.rs b/crates/io/or-io/src/gta6/script/print/enums/mod.rs index f2c1f0024..a1b6efe12 100644 --- a/crates/io/or-io/src/gta6/script/print/enums/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/enums/mod.rs @@ -397,20 +397,44 @@ impl Writer<'_> { match labels { Labels::Read(key) => { let name = types::display(self.project, self.names, key); + let via = self + .sharp + .then(|| types::enumeration(self.project, key)) + .flatten() + .map(|of| super::enum_underlying_keyword(&of.underlying)); let inner = within_32(bits(value)); match whole_read(inner) { Some((Some(owner), addr, offset)) => { let base = self.field_base(addr); - return format!("({name}){base}{}", self.field_name(Some(owner), offset)); + let field = format!("{base}{}", self.field_name(Some(owner), offset)); + let primitive = self + .project + .field(owner, offset) + .is_some_and(|f| f.kind.is_integer()); + return match via.filter(|_| !primitive) { + Some(via) => format!("({name})({via}){field}"), + None => format!("({name}){field}"), + }; } Some((None, addr, offset)) => { let (place, binds) = self.place_of(addr, offset, false, Some(4)); - return format!("({name}){}", super::cast_wrap(&name, place, binds)); + let primitive = self + .named_field(addr, offset, 4) + .is_some_and(|f| f.kind.is_integer()); + return match via.filter(|_| !primitive) { + Some(via) => { + format!("({name})({via}){}", super::cast_wrap(via, place, binds)) + } + None => format!("({name}){}", super::cast_wrap(&name, place, binds)), + }; } None => {} } let (text, binds) = self.spelled(inner); - format!("({name}){}", super::cast_wrap(&name, text, binds)) + match via.filter(|_| self.prints_non_primitive_switch(inner)) { + Some(via) => format!("({name})({via}){}", super::cast_wrap(via, text, binds)), + None => format!("({name}){}", super::cast_wrap(&name, text, binds)), + } } _ => match super::enum_field(self.project, value) { Some((_, addr, owner, offset)) => { diff --git a/crates/io/or-io/src/gta6/script/print/enums/tests.rs b/crates/io/or-io/src/gta6/script/print/enums/tests.rs index 45ccf28c2..7077dd55e 100644 --- a/crates/io/or-io/src/gta6/script/print/enums/tests.rs +++ b/crates/io/or-io/src/gta6/script/print/enums/tests.rs @@ -201,7 +201,7 @@ fn a_switch_whose_labels_are_values_of_one_enum_reads_its_value_as_of_it_where_a let cx = Context::new(&names, &project, Options::default()); let text = written_in(&f, &cx); assert!( - has(&text, " switch ((type_00000000000000E2)p0)"), + has(&text, " switch ((type_00000000000000E2)(uint)p0)"), "{text}" ); assert!( @@ -215,7 +215,10 @@ fn a_switch_whose_labels_are_values_of_one_enum_reads_its_value_as_of_it_where_a ); reads_back(&f, &text, cx.options, &project, &names); // ⚠ The cast is held: the same text without it is another switch. - let uncast = ("switch ((type_00000000000000E2)p0)", "switch ((uint)p0)"); + let uncast = ( + "switch ((type_00000000000000E2)(uint)p0)", + "switch ((uint)p0)", + ); edited_differs(&f, &text, uncast, &cx); // ⚠ A cast to an enum no list names, before labels none of which is a member, says nothing // the numbers do not: no reading. @@ -227,7 +230,7 @@ fn a_switch_whose_labels_are_values_of_one_enum_reads_its_value_as_of_it_where_a let mut named = none.clone(); named.types.insert(state.0, "ZqState".to_owned()); let text = written_in(&f, &Context::new(&named, &project, Options::default())); - assert!(has(&text, " switch ((ZqState)p0)"), "{text}"); + assert!(has(&text, " switch ((ZqState)(uint)p0)"), "{text}"); assert!(has(&text, " case (ZqState)0xC3D2E1F0:"), "{text}"); reads_back(&f, &text, Options::default(), &project, &named); let numbers = |text: &str| has(text, " case 0x2B3C4D5E:") && !text.contains("type_"); @@ -249,7 +252,7 @@ fn a_switch_whose_labels_are_values_of_one_enum_reads_its_value_as_of_it_where_a } let text = written_in(&f, &Context::new(&names, &twice, Options::default())); assert!( - has(&text, " switch ((type_00000000000000E3)p0)"), + has(&text, " switch ((type_00000000000000E3)(uint)p0)"), "{text}" ); // A label the enum does not hold, small labels alone, or one label alone, read nothing. @@ -317,11 +320,11 @@ fn a_switch_read_from_its_labels_casts_only_an_integer_whose_bits_the_cast_keeps let f = switch_on(field_read(owner), &labels); let text = written_in(&f, &Context::new(&names, &typed, options)); assert!(!text.contains("type_"), "{text}"); - // A field of four bytes no layout gives a kind is cast whole, whatever its read. + // A field of four bytes no layout gives a kind is cast through the enum's underlying integer. let (read, f, text) = reads(field_read(owner)); assert!(read, "{text}"); assert!( - has(&text, " switch ((type_00000000000000E2)p0.f_10)"), + has(&text, " switch ((type_00000000000000E2)(uint)p0.f_10)"), "{text}" ); reads_back(&f, &text, options, &project, &names); @@ -329,12 +332,16 @@ fn a_switch_read_from_its_labels_casts_only_an_integer_whose_bits_the_cast_keeps let inside = Expr::cast(Scalar::I32, load(Scalar::U32, param(0), 0x10)); let read = Expr::sugar(ExprSugar::Field { owner }, inside); let (_, f, text) = reads(Expr::cast(Scalar::I32, read)); - let line = " switch ((type_00000000000000E2)p0.f_10)"; + let line = " switch ((type_00000000000000E2)(uint)p0.f_10)"; assert!(has(&text, line), "{text}"); reads_back(&f, &text, options, &project, &names); // So are four bytes no field names, read through a reference. let (read, f, text) = reads(Expr::cast(Scalar::I32, load(Scalar::I32, param(0), 0x10))); assert!(read, "{text}"); + assert!( + has(&text, " switch ((type_00000000000000E2)(uint)p0.f_10)"), + "{text}" + ); assert!(!text.contains("(type_00000000000000E2)(int)"), "{text}"); reads_back(&f, &text, options, &project, &names); // A native's result no list states the kind of is a number of no stated kind, as the local @@ -516,3 +523,30 @@ fn a_case_that_runs_into_the_next_goes_on_to_its_label_as_a_value_of_the_enum_an assert!(has(&text, line), "{text}"); reads_back(&f, &text, Options::default(), &project, &names); } + +#[test] +fn enum_switch_subject_casts_cell_via_underlying_int_and_keeps_primitive_int_single_cast() { + let signed_enum = TypeKey(0xE4); + let project = with_enum(signed_enum, &[SECOND, THIRD]); + let mut names = Names::default(); + names.types.insert(signed_enum.0, "ZqSigned".to_owned()); + let options = Options::default(); + let cx = Context::new(&names, &project, options); + + // Untyped `Cell` scrutinee uses two-step `(ZqSigned)(int)p0`. + let f_cell = switch_on(Expr::cast(Scalar::I32, param(0)), &[SECOND, THIRD]); + let text_cell = written_in(&f_cell, &cx); + assert!( + has(&text_cell, " switch ((ZqSigned)(int)p0)"), + "{text_cell}" + ); + reads_back(&f_cell, &text_cell, options, &project, &names); + + // Typed `int` scrutinee keeps single-step `(ZqSigned)p0`. + let mut f_int = switch_on(Expr::cast(Scalar::I32, param(0)), &[SECOND, THIRD]); + f_int.head = kinds(&[(Var::Param(0), Kind::I32)]); + let text_int = written_in(&f_int, &cx); + assert!(has(&text_int, " switch ((ZqSigned)p0)"), "{text_int}"); + assert!(!text_int.contains("(ZqSigned)(int)"), "{text_int}"); + reads_back(&f_int, &text_int, options, &project, &names); +} diff --git a/crates/io/or-io/src/gta6/script/print/mod.rs b/crates/io/or-io/src/gta6/script/print/mod.rs index c0370ca9d..37459b2ee 100644 --- a/crates/io/or-io/src/gta6/script/print/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/mod.rs @@ -1190,6 +1190,7 @@ impl<'a> Writer<'a> { let narrow = narrow.or_else(|| self.returned_implied(value)); let text = match narrow { Some(text) => text, + None if signed_i32 && self.prints_u32(value) => self.cast(Scalar::I32, bits(value)).0, None if unsigned_u32 && self.prints_i32(value) => self.cast(Scalar::U32, bits(value)).0, None => self.value(value), }; @@ -1899,10 +1900,11 @@ impl<'a> Writer<'a> { if let Ok(off) = u32::try_from(c.bits) { let base = self.field_base(addr); let name = self.field_name(Some(owner), off); - let stack_local = matches!( - bits(addr), - Expr::AddrOf { var, cell: 0 } if !matches!(var, Var::Global { .. }) - ); + let stack_local = self.bound.is_none() + && matches!( + bits(addr), + Expr::AddrOf { var, cell: 0 } if !matches!(var, Var::Global { .. }) + ); if self.sharp && !base.contains("->") && !stack_local { return (format!("addr(ref {base}{name})"), POSTFIX); } @@ -1943,18 +1945,31 @@ impl<'a> Writer<'a> { let lhs = bits(then); let rhs = bits(els); let left = self.expr(lhs, 2); - let right = if self.sharp && reference(&self.kind_of(lhs)) { + let l_kind = self.kind_of(lhs); + let right = if self.sharp && reference(&l_kind) { if is_zero(rhs) { "null".to_owned() } else { + let ty_text = self.kind_text(&l_kind); + let target = (ty_text != "object").then_some(ty_text); match self.kind_of(rhs) { Kind::Pointer => { let (operand, binds) = self.spelled(rhs); - format!("(object)(Cell){}", cast_wrap("Cell", operand, binds)) + let boxed = + format!("(object)(Cell){}", cast_wrap("Cell", operand, binds)); + match target { + Some(ty) => format!("({ty}){boxed}"), + None => boxed, + } } Kind::Unknown => { let (operand, binds) = self.spelled(rhs); - format!("(object){}", cast_wrap("object", operand, binds)) + let boxed = + format!("(object){}", cast_wrap("object", operand, binds)); + match target { + Some(ty) => format!("({ty}){boxed}"), + None => boxed, + } } _ => self.expr(rhs, 2), } @@ -2551,6 +2566,9 @@ impl<'a> Writer<'a> { }; let text = match narrow { Some(text) => text, + None if signed_i32 && self.prints_u32(value) => { + self.cast(Scalar::I32, bits(value)).0 + } None if unsigned_u32 && self.prints_i32(value) => { self.cast(Scalar::U32, bits(value)).0 } @@ -2651,6 +2669,7 @@ impl<'a> Writer<'a> { }; let item = match given.or(narrow) { Some(item) => item, + None if signed_i32 && self.prints_u32(arg) => self.cast(Scalar::I32, bits(arg)).0, None if unsigned_u32 && self.prints_i32(arg) => self.cast(Scalar::U32, bits(arg)).0, None => self.value(arg), }; @@ -3083,8 +3102,18 @@ impl<'a> Writer<'a> { .get(&FunctionKey::new(*program, *at)) .filter(|sig| sig.returns == 1) .map(|sig| &sig.result), - Callee::Virtual { ty, slot, .. } => TypeKey::of_name(ty) - .and_then(|ty| self.project.slot_result(ty, *slot)), + Callee::Virtual { ty, slot, .. } => { + TypeKey::of_name(ty).and_then(|ty| { + self.project.slot_result(ty, *slot).or_else(|| { + let function = self.project.slot(ty, *slot)?; + self.project + .signatures + .get(&function) + .filter(|sig| sig.returns == 1) + .map(|sig| &sig.result) + }) + }) + } _ => None, }; match from_project { @@ -3157,8 +3186,59 @@ impl<'a> Writer<'a> { } } + /// Whether `e` (unwrapping `ExprSugar::Method` / `ExprSugar::Property`) is a project-typed call (`Callee::Local`, `Callee::Import`, or `Callee::Virtual`) whose declared C# return type is `bool`. + fn project_bool_call(&self, e: &Expr) -> bool { + if !self.sharp { + return false; + } + let inner = match e { + Expr::Sugar { + kind: ExprSugar::Method | ExprSugar::Property, + e: inner, + } => &**inner, + other => other, + }; + let Expr::Call { + callee, returns, .. + } = inner + else { + return false; + }; + if !matches!(*returns, None | Some(1)) { + return false; + } + let result = match callee { + Callee::Local { at, .. } => self + .project + .signatures + .get(&FunctionKey::new(self.head.program, *at)) + .filter(|sig| sig.returns == 1) + .map(|sig| &sig.result), + Callee::Import { program, at, .. } => self + .project + .signatures + .get(&FunctionKey::new(*program, *at)) + .filter(|sig| sig.returns == 1) + .map(|sig| &sig.result), + Callee::Virtual { ty, slot, .. } => TypeKey::of_name(ty).and_then(|ty| { + self.project.slot_result(ty, *slot).or_else(|| { + let function = self.project.slot(ty, *slot)?; + self.project + .signatures + .get(&function) + .filter(|sig| sig.returns == 1) + .map(|sig| &sig.result) + }) + }), + _ => None, + }; + result == Some(&Kind::Bool) + } + fn is_truth(&self, e: &Expr) -> bool { - self.kind_of(e) == Kind::Bool || self.dotnet_bool_expr(e).is_some() + self.kind_of(e) == Kind::Bool + || self.dotnet_bool_expr(e).is_some() + || self.project_bool_call(e) } /// [`Self::is_truth`], or under `truth-ops` a bitwise operator of two truths, which C# writes as a `bool` of `bool`s. @@ -3314,6 +3394,9 @@ impl<'a> Writer<'a> { var: var @ Var::Global { .. }, cell: 0, } if self.sharp => return (format!("addr(ref {})", self.var(*var)), POSTFIX), + Expr::AddrOf { var, cell: 0 } if self.sharp && self.bound.is_some() => { + return (format!("addr(ref {})", self.var(*var)), POSTFIX); + } Expr::AddrOf { var, cell: 0 } => return (format!("&{}", self.var(*var)), UNARY), Expr::AddrOf { var, cell } => { return (format!("&{}[{cell}]", self.var(*var)), UNARY); @@ -3553,19 +3636,9 @@ impl<'a> Writer<'a> { _ => (self.expr(call, POSTFIX), POSTFIX), }; } - if matches!( - unread(l), - Expr::Binary { - op: BinOp::And | BinOp::Or | BinOp::Xor, - .. - } - ) && self.truthy(l) - { - let inner = unread(l); - return match op { - BinOp::Eq => (format!("!{}", self.expr(inner, POSTFIX)), UNARY), - _ => self.spelled(inner), - }; + let inner = unread(l); + if self.truthy(inner) { + return self.truth(inner, op == BinOp::Eq, false); } } let typed = match self.sharp { @@ -3726,7 +3799,7 @@ impl<'a> Writer<'a> { /// Whether `e`, printed as-is by `self.expr`, has C# type `bool` (which cannot directly meet an integer in `&`/`|`/`^` or any ordering operator). fn prints_bool(&self, e: &Expr) -> bool { - if self.kind_of(e) == Kind::Bool { + if self.kind_of(e) == Kind::Bool || self.project_bool_call(e) { return true; } if matches!( @@ -4034,6 +4107,85 @@ impl<'a> Writer<'a> { } } + /// Whether `e` is a non-constant expression that prints with C# type `uint` (which C# refuses to implicitly convert to `int`). + pub(super) fn prints_u32(&self, e: &Expr) -> bool { + let inner = bits(e); + if spell::folded(inner).is_some() || self.prints_non_primitive_switch(inner) { + return false; + } + if matches!( + inner, + Expr::Cast { + to: Scalar::U32, + .. + } + ) || matches!( + inner, + Expr::Binary { op, .. } if op.is_comparison() || op.is_logical() + ) { + return false; + } + match self.kind_of(inner) { + Kind::U32 | Kind::Hash => return true, + Kind::Unknown => {} + _ => return false, + } + match inner { + Expr::Sugar { e: under, .. } => self.prints_u32(under), + Expr::Select { then, els, .. } => self.prints_u32(then) || self.prints_u32(els), + Expr::Var(Var::Global { + program, + offset, + statics, + }) => { + let info = self.project.programs.get(program); + let stated = info.and_then(|info| match statics { + true => info.statics.get(offset), + false => info.globals.get(offset), + }); + let cell = self.project.cell(*program, *offset, *statics); + let held = cell.and_then(crate::gta6::script::emit::held); + matches!(stated.or(held), Some(Kind::U32 | Kind::Hash)) + } + Expr::Call { + callee, returns, .. + } if matches!(*returns, None | Some(1)) => match callee { + Callee::Builtin { path, .. } => path == "System.Convert.ToUInt32", + Callee::Intrinsic { name, .. } => { + matches!(name.as_str(), "max_u32" | "min_u32" | "array_get_u32") + } + Callee::Local { at, .. } => self + .project + .signatures + .get(&FunctionKey::new(self.head.program, *at)) + .is_some_and(|sig| { + sig.returns == 1 && matches!(sig.result, Kind::U32 | Kind::Hash) + }), + Callee::Import { program, at, .. } => self + .project + .signatures + .get(&FunctionKey::new(*program, *at)) + .is_some_and(|sig| { + sig.returns == 1 && matches!(sig.result, Kind::U32 | Kind::Hash) + }), + Callee::Virtual { ty, slot, .. } => TypeKey::of_name(ty) + .and_then(|ty| { + self.project.slot_result(ty, *slot).or_else(|| { + let function = self.project.slot(ty, *slot)?; + self.project + .signatures + .get(&function) + .filter(|sig| sig.returns == 1) + .map(|sig| &sig.result) + }) + }) + .is_some_and(|k| matches!(k, Kind::U32 | Kind::Hash)), + _ => false, + }, + _ => false, + } + } + /// Formats a conversion `(T)value`, inserting an intermediate primitive cast `(int)`/`(uint)`/... when `T` is a script enum and `value` prints as `Cell`, `Bytes4`, or `void*` (C# does not chain user-defined `Cell -> int` + explicit `int -> Enum` in one cast). fn enum_cast(&mut self, raw_to: &str, value: &Expr) -> (String, u8) { let to = self.type_name(raw_to); @@ -4074,7 +4226,7 @@ impl<'a> Writer<'a> { var: Var::Global { .. }, cell: 0, } => true, - Expr::AddrOf { .. } => false, + Expr::AddrOf { .. } => self.bound.is_some(), Expr::Call { callee: Callee::Intrinsic { name, .. }, args, @@ -4084,13 +4236,46 @@ impl<'a> Writer<'a> { } base => { let kind = self.kind_of(base); + let own = matches!( + base, + Expr::Var(var) + if self.this == Some(*var) + || (self.bound.is_some() && self.var(*var) == "this") + ); matches!(kind, Kind::Object(_)) - || (matches!(kind, Kind::Value { .. }) - && matches!(base, Expr::Var(var) if self.this == Some(*var))) + || (own + && (matches!(kind, Kind::Value { .. }) + || !self.project.types.is_empty() + || self + .project + .members + .contains_key(&FunctionKey::new(self.head.program, self.head.at)))) + || matches!( + base, + Expr::Call { callee: Callee::Intrinsic { name, .. }, .. } + if name.starts_with("try_cast<") || name.starts_with("cast<") + ) } } } + /// A C# pointer expression (`Cell*`) for `array_element_address(array, index)` when used as the base of `->f_...` in true C#. + fn element_ptr(&mut self, array: &Expr, index: &Expr) -> String { + match self.kind_of(bits(array)) { + Kind::Array(_) => format!("((Cell*)(void*)addr(ref {}))", self.element(array, index)), + Kind::Pointer => format!("(&{})", self.element(array, index)), + Kind::Unknown | Kind::I64 | Kind::U64 | Kind::I32 | Kind::U32 => { + let idx = self + .implied(Scalar::I32, index, false) + .unwrap_or_else(|| self.value(index)); + let (arr_text, arr_binds) = self.spelled(array); + let arr = cast_wrap("void*", arr_text, arr_binds); + format!("(&((Cell*)(void*){arr})[{idx}])") + } + _ => format!("(&{})", self.element(array, index)), + } + } + /// The memory at byte `offset` from `addr`, as a field of what `addr` points at, and the strength the text binds at. // ⚠ `partial` is a write of fewer bytes than a cell. On a variable it is spelled `.f_0`, // because it leaves the cell's other bytes and an assignment would not. @@ -4168,15 +4353,24 @@ impl<'a> Writer<'a> { && name == "array_element_address" && args.len() == 2 => { - let element = self.element(&args[0], &args[1]); - let wide = match self.kind_of(&args[0]) { + let wide = match self.kind_of(bits(&args[0])) { Kind::Array(of) => element_bytes(&of), _ => None, }; - return match bytes.is_some() && wide == bytes { - true => (element, POSTFIX), - false => (format!("(&{element})->f_0"), POSTFIX), - }; + if bytes.is_some() && wide == bytes { + return (self.element(&args[0], &args[1]), POSTFIX); + } + return ( + format!("{}->f_0", self.element_ptr(&args[0], &args[1])), + POSTFIX, + ); + } + Expr::Call { + callee: Callee::Intrinsic { name, .. }, + args, + .. + } if sharp && name == "array_element_address" && args.len() == 2 => { + (self.element_ptr(&args[0], &args[1]), false) } pointer if own => (self.expr(bits(pointer), POSTFIX), false), // The first bytes of what a pointer points at are the thing itself. @@ -4252,6 +4446,9 @@ impl<'a> Writer<'a> { false => text, }; } + if self.sharp && signed_i32 && self.prints_u32(value) { + return self.cast(Scalar::I32, bits(value)).0; + } let text = if kind_bytes(&self.kind_of(value)) == Some(to.bytes()) { self.expr(value, 0) } else { @@ -4573,6 +4770,61 @@ impl<'a> Writer<'a> { self.line(indent, &format!("{word} ({text})")); } + /// Whether `raw_ty` names a non-nullable C# value type (struct, enum, primitive, or prelude handle), for which `x as T` triggers CS0077. + fn is_value_type(&self, raw_ty: &str) -> bool { + if TypeKey::of_name(raw_ty) + .and_then(|key| self.project.types.get(&key)) + .is_some_and(TypeFacts::is_value) + { + return true; + } + let name = self.type_name(raw_ty); + if name.ends_with("[]") || name.ends_with('?') || name.ends_with('*') { + return false; + } + let short = name.rsplit('.').next().unwrap_or(&name); + if matches!( + short, + "bool" + | "byte" + | "sbyte" + | "short" + | "ushort" + | "int" + | "uint" + | "long" + | "ulong" + | "float" + | "double" + | "decimal" + | "char" + | "nint" + | "nuint" + | "Vector3" + | "Handle" + | "Cell" + | "Guid" + | "DateTime" + | "TimeSpan" + | "Decimal" + | "IntPtr" + | "UIntPtr" + | "RuntimeTypeHandle" + | "DictionaryEntry" + ) { + return true; + } + if crate::gta6::script::names::natives::WIDE_HANDLES.contains(&short) { + return true; + } + let numbered = |prefix: &str| { + short + .strip_prefix(prefix) + .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())) + }; + numbered("Cells") || numbered("Bytes") + } + /// An intrinsic C# has an operator for, as that operator; `None` for one that stays a call. fn intrinsic(&mut self, name: &str, args: &[Expr]) -> Option<(String, u8)> { if let Some((l, r)) = self.whole_equality(name, args) { @@ -4594,6 +4846,10 @@ impl<'a> Writer<'a> { } [value] => { let ty = name.strip_prefix("try_cast<")?.strip_suffix('>')?; + if self.sharp && self.is_value_type(ty) { + let text = format!("try_cast<{}>({})", self.type_name(ty), self.expr(value, 0)); + return Some((text, POSTFIX)); + } // An `as` on the left of an `as` is read first: it needs no parentheses. let chained = matches!(bits(value), Expr::Call { callee: Callee::Intrinsic { name, .. }, args, .. } if name.starts_with("try_cast<") && args.len() == 1); @@ -4607,12 +4863,25 @@ impl<'a> Writer<'a> { Some((text, 6)) } [array, index] if name == "array_element_address" => { - let element = self.element(array, index); - if self.sharp && matches!(self.kind_of(bits(array)), Kind::Array(_)) { - Some((format!("addr(ref {element})"), POSTFIX)) - } else { - Some((format!("&{element}"), UNARY)) + if self.sharp { + match self.kind_of(bits(array)) { + Kind::Array(_) => { + let element = self.element(array, index); + return Some((format!("addr(ref {element})"), POSTFIX)); + } + Kind::Unknown => { + let idx = self + .implied(Scalar::I32, index, false) + .unwrap_or_else(|| self.value(index)); + let (arr_text, arr_binds) = self.spelled(array); + let arr = cast_wrap("void*", arr_text, arr_binds); + return Some((format!("&((Cell*)(void*){arr})[{idx}]"), UNARY)); + } + _ => {} + } } + let element = self.element(array, index); + Some((format!("&{element}"), UNARY)) } [array, index] if name == "array_get_value" => { Some((self.element(array, index), POSTFIX)) diff --git a/crates/io/or-io/src/gta6/script/print/prelude/mod.rs b/crates/io/or-io/src/gta6/script/print/prelude/mod.rs index 0ced5b71e..d7bb4a7b8 100644 --- a/crates/io/or-io/src/gta6/script/print/prelude/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/prelude/mod.rs @@ -56,11 +56,14 @@ pub struct Used { named_calls: BTreeMap<(String, String), BTreeSet>>, /// The types the sources declare, which the prelude leaves to them: a list may name one `Vector3`. declared: BTreeSet, + /// Which coordinate fields (`X`, `Y`, `Z`) a source-declared `struct Vector3` already declares. + vector3_fields: BTreeSet, } impl Used { /// Takes in what `text`, one source, names. pub fn read(&mut self, text: &str) { + record_vector3_fields(&mut self.vector3_fields, text); for line in text.lines() { let words: Vec<&str> = line.split_whitespace().take(8).collect(); let at = words @@ -158,6 +161,7 @@ impl Used { .extend(shapes.iter().cloned()); } self.declared.extend(other.declared.iter().cloned()); + self.vector3_fields.extend(&other.vector3_fields); for (n, args) in &other.barriers { let most = self.barriers.entry(*n).or_default(); *most = (*most).max(*args); @@ -165,6 +169,109 @@ impl Used { } } +/// Scans top-level `struct Vector3` declarations in `text` and records which of `X`, `Y`, `Z` +/// are already declared as fields or properties, so the prelude does not redeclare them (`CS0229`). +fn record_vector3_fields(fields: &mut BTreeSet, text: &str) { + let lines: Vec<&str> = text.lines().collect(); + let mut i = 0; + while i < lines.len() { + let line = lines[i]; + if line.starts_with([' ', '\t']) { + i += 1; + continue; + } + let code = line.split("//").next().unwrap_or(line); + let words: Vec<&str> = code.split_whitespace().take(8).collect(); + let is_vector3_struct = words + .iter() + .position(|w| *w == "struct") + .and_then(|at| words.get(at + 1)) + .is_some_and(|name| { + name.split(['<', ':', '{']) + .next() + .unwrap_or_default() + .trim_start_matches('@') + == "Vector3" + }); + if !is_vector3_struct { + i += 1; + continue; + } + let mut depth = 0usize; + let mut entered = false; + let mut j = i; + while j < lines.len() { + let member_line = lines[j].split("//").next().unwrap_or(lines[j]); + let opens = member_line.bytes().filter(|&b| b == b'{').count(); + let closes = member_line.bytes().filter(|&b| b == b'}').count(); + if entered && depth == 1 { + extract_vector3_member_names(fields, member_line); + } else if !entered { + if let Some((_, rest)) = member_line.split_once('{') { + let body = rest.rsplit_once('}').map_or(rest, |(b, _)| b); + for stmt in body.split(';') { + extract_vector3_member_names(fields, stmt); + } + } + } + if opens > 0 { + entered = true; + } + depth = depth.saturating_add(opens).saturating_sub(closes); + j += 1; + if entered && depth == 0 { + break; + } + } + i = j; + } +} + +/// Extracts any declared `X`, `Y`, or `Z` field or property names from a direct member line of `struct Vector3`. +fn extract_vector3_member_names(fields: &mut BTreeSet, line: &str) { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with(['{', '}', '[', '#']) || trimmed.contains('(') { + return; + } + let head = trimmed + .split([';', '{', '=']) + .next() + .unwrap_or_default() + .trim(); + if head.is_empty() { + return; + } + let mut parts = head.split(','); + let Some(first) = parts.next() else { + return; + }; + let mut first_tokens = first.split_whitespace(); + let _first_ty = first_tokens.next(); + if let Some(name) = first_tokens.last() { + record_xyz_ident(fields, name); + } + for extra in parts { + if let Some(name) = extra.split_whitespace().last() { + record_xyz_ident(fields, name); + } + } +} + +fn record_xyz_ident(fields: &mut BTreeSet, token: &str) { + match token.trim_start_matches('@') { + "X" => { + fields.insert('X'); + } + "Y" => { + fields.insert('Y'); + } + "Z" => { + fields.insert('Z'); + } + _ => {} + } +} + /// Whether `name` looks like a native namespace identifier (uppercase ASCII letters, digits, or `_`, with at least one letter). fn is_native_space(name: &str) -> bool { !name.is_empty() @@ -293,8 +400,8 @@ const NUMBERS: [&str; 12] = [ /// The numeric types that meet a cell in mixed binary operators without C# overload ambiguity. const MIXED_NUMBERS: [&str; 6] = ["int", "uint", "long", "ulong", "float", "double"]; -/// The integral and boolean types that meet a cell in mixed bitwise operators. -const MIXED_BITWISE: [&str; 5] = ["int", "uint", "long", "ulong", "bool"]; +/// The integral types that meet a cell in mixed bitwise operators (excluding `bool`, which would trigger `CS0217` on `&&`/`||`). +const MIXED_BITWISE: [&str; 4] = ["int", "uint", "long", "ulong"]; /// The members of a word that holds a number of no proved kind: made of and turned into any number, with every operator. fn numeric(ty: &str) -> String { @@ -398,6 +505,8 @@ fn whole(ty: &str) -> String { format!( " public static bool operator ==({ty} a, {ty} b) => default;\n \ public static bool operator !=({ty} a, {ty} b) => default;\n \ + public static bool operator ==(Cell a, {ty} b) => default;\n \ + public static bool operator !=(Cell a, {ty} b) => default;\n \ public static implicit operator {ty}(Cell v) => default;\n \ public Cell this[Cell i] {{ get => default; set {{ }} }}\n \ public override bool Equals(object o) => default;\n \ @@ -462,21 +571,49 @@ const HELPERS: &str = r#" public static AnyEnumerator GetEnumerator(this obje public static float ceilf(Cell v) => default; public static float powf(Cell a, Cell b) => default; public static Vector3 packed_vector_add(Vector3 a, Vector3 b) => default; + public static Vector3 packed_vector_add(object a, object b, object c) => default; + public static Vector3 packed_vector_add(object a, object b, object c, object d) => default; public static Vector3 packed_vector_subtract(Vector3 a, Vector3 b) => default; + public static Vector3 packed_vector_subtract(object a, object b, object c) => default; + public static Vector3 packed_vector_subtract(object a, object b, object c, object d) => default; public static Vector3 packed_vector_multiply(Vector3 a, Vector3 b) => default; + public static Vector3 packed_vector_multiply(object a, object b, object c) => default; + public static Vector3 packed_vector_multiply(object a, object b, object c, object d) => default; public static Vector3 packed_vector_divide(Vector3 a, Vector3 b) => default; + public static Vector3 packed_vector_divide(object a, object b, object c) => default; + public static Vector3 packed_vector_divide(object a, object b, object c, object d) => default; public static Vector3 packed_vector_min(Vector3 a, Vector3 b) => default; + public static Vector3 packed_vector_min(object a, object b, object c) => default; + public static Vector3 packed_vector_min(object a, object b, object c, object d) => default; public static Vector3 packed_vector_max(Vector3 a, Vector3 b) => default; + public static Vector3 packed_vector_max(object a, object b, object c) => default; + public static Vector3 packed_vector_max(object a, object b, object c, object d) => default; public static Vector3 packed_vector_clamp(Vector3 v, Vector3 low, Vector3 high) => default; + public static Vector3 packed_vector_clamp(object a, object b, object c, object d) => default; + public static Vector3 packed_vector_clamp(object a, object b, object c, object d, object e) => default; + public static Vector3 packed_vector_clamp(object a, object b, object c, object d, object e, object f) => default; public static Vector3 packed_vector_lerp(Vector3 a, Vector3 b, Vector3 t) => default; + public static Vector3 packed_vector_lerp(object a, object b, object c, object d) => default; + public static Vector3 packed_vector_lerp(object a, object b, object c, object d, object e) => default; + public static Vector3 packed_vector_lerp(object a, object b, object c, object d, object e, object f) => default; public static Vector3 packed_vector_fma(Vector3 a, Vector3 b, Vector3 c) => default; + public static Vector3 packed_vector_fma(object a, object b, object c, object d) => default; + public static Vector3 packed_vector_fma(object a, object b, object c, object d, object e) => default; + public static Vector3 packed_vector_fma(object a, object b, object c, object d, object e, object f) => default; public static Vector3 packed_vector_scale(Cell by, Vector3 v) => default; + public static Vector3 packed_vector_scale(object by, object v0, object v1) => default; public static Vector3 packed_vector_splat(Cell v) => default; public static Vector3 packed_vector_normalize3(Vector3 v) => default; + public static Vector3 packed_vector_normalize3(object v0, object v1) => default; public static Vector3 packed_vector_normalize4(Vector3 v) => default; + public static Vector3 packed_vector_normalize4(object v0, object v1) => default; public static Vector3 packed_vector_from_xyz(Cell x, Cell y, Cell z) => default; public static float packed_vector_dot3(Vector3 a, Vector3 b) => default; + public static float packed_vector_dot3(object a, object b, object c) => default; + public static float packed_vector_dot3(object a, object b, object c, object d) => default; public static float packed_vector_dot4(Vector3 a, Vector3 b) => default; + public static float packed_vector_dot4(object a, object b, object c) => default; + public static float packed_vector_dot4(object a, object b, object c, object d) => default; public static void zero_bytes(Cell at, int count) { } public static void zero_bytes(object at, int count) { } public static void store_bytes(Cell at, int offset, int count, Cell value) { } @@ -504,6 +641,8 @@ const HELPERS: &str = r#" public static AnyEnumerator GetEnumerator(this obje public static Cell box(params object[] cells) => default; public static Cell box_at(Cell at) => default; public static Cell box_at(object at) => default; + public static T try_cast(Cell v) => default; + public static T try_cast(object v) => default; public static Cell Hash(string text) => default; public static Cell BuiltinGlobal(int index) => default; public static Cell BuiltinFunction(int ty, int method) => default; @@ -551,6 +690,10 @@ fn cells_struct(out: &mut String, n: u32, own: &impl Fn(&str) -> bool) { out, " public static bool operator {op}(Vector3 a, Cells2 b) => default;" ); + let _ = writeln!( + out, + " public static bool operator {op}((Cell, Cell) a, Cells2 b) => default;" + ); } } out.push_str("}\n\n"); @@ -620,6 +763,8 @@ pub fn prelude(names: &Names, used: &Used) -> String { out, "public unsafe struct Cell\n{{\n{} \ public AnyEnumerator GetEnumerator() => default;\n \ + public bool MoveNext() => default;\n \ + public object Current => default;\n \ public static implicit operator Cell(void* v) => default;\n \ public static implicit operator void*(Cell v) => default;\n \ public static bool operator ==(Cell a, void* b) => default;\n \ @@ -687,6 +832,10 @@ pub fn prelude(names: &Names, used: &Used) -> String { out, " public static bool operator {op}(Cells2 a, Handle b) => default;" ); + let _ = writeln!( + out, + " public static bool operator {op}((Cell, Cell) a, Handle b) => default;" + ); } out.push_str("}\n\n"); } @@ -706,7 +855,7 @@ pub fn prelude(names: &Names, used: &Used) -> String { ); // ⚠ Only `(Other, handle)` lives on `handle` (never `(handle, Other)`): `handle == default` // then binds unambiguously to `(handle, handle)` while `(handle, Other)` lives on `Other`. - for other in ["Cells2", "Handle"] { + for other in ["Cells2", "Handle", "(Cell, Cell)"] { for op in ["==", "!="] { let _ = writeln!( out, @@ -747,9 +896,23 @@ pub fn prelude(names: &Names, used: &Used) -> String { } // ⚠ A list may name a script's own type `Vector3` too, which its source declares with // fields of no proved kind and no constructor: the vector a native takes is this one. + // Omit any `X`/`Y`/`Z` field that a source-declared `struct Vector3` already provides so + // member accesses never hit `CS0229` ambiguity. + let missing_xyz: Vec<&str> = [('X', "X"), ('Y', "Y"), ('Z', "Z")] + .into_iter() + .filter_map(|(ch, name)| (!used.vector3_fields.contains(&ch)).then_some(name)) + .collect(); + out.push_str("public struct Vector3\n{\n"); + if !missing_xyz.is_empty() { + let _ = writeln!(out, " public float {};", missing_xyz.join(", ")); + } + if used.vector3_fields.is_empty() { + out.push_str(" public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; }\n"); + } else { + out.push_str(" public Vector3(float x, float y, float z) { this = default; }\n"); + } out.push_str( - "public struct Vector3\n{\n public float X, Y, Z;\n \ - public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; }\n \ + " public Cell this[Cell i] { get => default; set { } }\n \ public static implicit operator Vector3(Cell v) => default;\n \ public static implicit operator Vector3(Cells2 v) => default;\n \ public static implicit operator Cells2(Vector3 v) => default;\n \ @@ -757,6 +920,8 @@ pub fn prelude(names: &Names, used: &Used) -> String { public static implicit operator Vector3((float, float, float) v) => default;\n \ public static bool operator ==(Vector3 a, Vector3 b) => default;\n \ public static bool operator !=(Vector3 a, Vector3 b) => default;\n \ + public static bool operator ==(Cell a, Vector3 b) => default;\n \ + public static bool operator !=(Cell a, Vector3 b) => default;\n \ public static bool operator ==(Cells2 a, Vector3 b) => default;\n \ public static bool operator !=(Cells2 a, Vector3 b) => default;\n \ public static Vector3 operator +(Vector3 a, Vector3 b) => default;\n \ @@ -808,6 +973,22 @@ pub fn prelude(names: &Names, used: &Used) -> String { } out.push_str("}\n\n"); natives(&mut out, names, used); + out.push_str( + "namespace System\n{\n public static unsafe class Rage\n {\n \ + public static Cell CompareExchange(Cell location, Cell value, Cell comparand) => default;\n \ + public static Cell CompareExchange(Cell location, Cell value, object comparand) => default;\n \ + public static Cell CompareExchange(Cell location, object value, Cell comparand) => default;\n \ + public static Cell CompareExchange(Cell location, object value, object comparand) => default;\n \ + public static Cell CompareExchange(object location, Cell value, Cell comparand) => default;\n \ + public static Cell CompareExchange(object location, Cell value, object comparand) => default;\n \ + public static Cell CompareExchange(object location, object value, Cell comparand) => default;\n \ + public static Cell CompareExchange(object location, object value, object comparand) => default;\n \ + public static Cell CompareExchange(ref T location, Cell value, Cell comparand) => default;\n \ + public static Cell CompareExchange(ref T location, Cell value, object comparand) => default;\n \ + public static Cell CompareExchange(ref T location, object value, Cell comparand) => default;\n \ + public static Cell CompareExchange(ref T location, object value, object comparand) => default;\n \ + public static Cell CompareExchange(params object[] args) => default;\n }\n}\n", + ); out } diff --git a/crates/io/or-io/src/gta6/script/print/prelude/tests.rs b/crates/io/or-io/src/gta6/script/print/prelude/tests.rs index 92efd44d9..1f9740a2c 100644 --- a/crates/io/or-io/src/gta6/script/print/prelude/tests.rs +++ b/crates/io/or-io/src/gta6/script/print/prelude/tests.rs @@ -157,7 +157,8 @@ fn mixed_operators_enumerators_pointers_and_tuples_bind_cleanly() { // Mixed operators on Cell and BytesN, shifts, and pointer equality without object ambiguity. " public static Cell operator +(Cell a, int b) => default;", " public static Cell operator +(float a, Cell b) => default;", - " public static Cell operator &(Cell a, bool b) => default;", + " public static Cell operator &(Cell a, int b) => default;", + " public static bool operator ==(Cell a, bool b) => default;", " public static Cell operator <<(Cell a, uint b) => default;", " public static Cell operator <<(Cell a, Cell b) => default;", " public static bool operator ==(Cell a, void* b) => default;", @@ -168,6 +169,8 @@ fn mixed_operators_enumerators_pointers_and_tuples_bind_cleanly() { " public static bool operator !=(Entity a, Ped b) => default;", // Enumerators for foreach on Cell and object. "public struct AnyEnumerator", + " public object Current => default;", + " public bool MoveNext() => default;", " public AnyEnumerator GetEnumerator() => default;", " public static AnyEnumerator GetEnumerator(this object self) => default;", // Pointer helpers: addr returns Cell so it boxes to object AND converts to void*; stack/byte_offset return Cell*. @@ -226,9 +229,12 @@ fn mixed_operators_enumerators_pointers_and_tuples_bind_cleanly() { "no line `{line}` in:\n{text}" ); } - // No bitwise operators on floats, no Cell == object ambiguity, and no tuple on Cells1/Cells9. + // No bitwise operators on floats or bool (which triggers CS0217 on &&/||), no Cell == object ambiguity, and no tuple on Cells1/Cells9. assert!(!text.contains("operator &(Cell a, float b)"), "{text}"); assert!(!text.contains("operator |(Cell a, double b)"), "{text}"); + assert!(!text.contains("operator &(Cell a, bool b)"), "{text}"); + assert!(!text.contains("operator |(bool a, Cell b)"), "{text}"); + assert!(!text.contains("operator ^(Cell a, bool b)"), "{text}"); assert!(!text.contains("operator ==(Cell a, object b)"), "{text}"); assert!(!text.contains("operator Cells1((Cell)"), "{text}"); assert!(!text.contains("operator Cells9(("), "{text}"); @@ -244,6 +250,25 @@ fn struct_body<'a>(prelude_text: &'a str, name: &str) -> &'a str { &rest[..end] } +fn split_top_level_params(params: &str) -> Vec<&str> { + let mut out = Vec::new(); + let mut depth = 0usize; + let mut start = 0usize; + for (idx, b) in params.bytes().enumerate() { + match b { + b'(' => depth += 1, + b')' => depth = depth.saturating_sub(1), + b',' if depth == 0 => { + out.push(params[start..idx].trim()); + start = idx + 1; + } + _ => {} + } + } + out.push(params[start..].trim()); + out +} + #[test] fn wide_struct_equality_operators_never_make_default_comparison_ambiguous() { let text = prelude(&Names::default(), &Used::default()); @@ -259,8 +284,8 @@ fn wide_struct_equality_operators_never_make_default_comparison_ambiguous() { .strip_prefix("public static bool operator ==(") .or_else(|| trimmed.strip_prefix("public static bool operator !=(")) { - let params = rest.split(')').next().unwrap_or_default(); - let parts: Vec<&str> = params.split(',').map(str::trim).collect(); + let params = rest.split(") =>").next().unwrap_or_default(); + let parts = split_top_level_params(params); assert_eq!(parts.len(), 2, "unexpected operator line in {ty}: {line}"); let rhs_ty = parts[1].split_whitespace().next().unwrap_or_default(); assert_eq!( @@ -270,7 +295,7 @@ fn wide_struct_equality_operators_never_make_default_comparison_ambiguous() { } } } - // Cross-type comparisons still have exact matches on the RHS type. + // Cross-type comparisons still have exact matches on the RHS type, including `Cell` and `(Cell, Cell)`. assert!(struct_body(&text, "Entity").contains("operator ==(Ped a, Entity b)")); assert!(struct_body(&text, "Ped").contains("operator ==(Entity a, Ped b)")); assert!(struct_body(&text, "Handle").contains("operator ==(Ped a, Handle b)")); @@ -279,6 +304,27 @@ fn wide_struct_equality_operators_never_make_default_comparison_ambiguous() { assert!(struct_body(&text, "Ped").contains("operator ==(Cells2 a, Ped b)")); assert!(struct_body(&text, "Cells2").contains("operator ==(Vector3 a, Cells2 b)")); assert!(struct_body(&text, "Vector3").contains("operator ==(Cells2 a, Vector3 b)")); + for ty in ["Ped", "Vehicle", "Entity", "Handle", "Cells2"] { + let body = struct_body(&text, ty); + assert!( + body.contains(&format!("operator ==((Cell, Cell) a, {ty} b)")), + "missing tuple == on {ty}:\n{body}" + ); + assert!( + body.contains(&format!("operator !=((Cell, Cell) a, {ty} b)")), + "missing tuple != on {ty}:\n{body}" + ); + assert!( + body.contains(&format!("operator ==(Cell a, {ty} b)")), + "missing Cell == on {ty}:\n{body}" + ); + assert!( + body.contains(&format!("operator !=(Cell a, {ty} b)")), + "missing Cell != on {ty}:\n{body}" + ); + } + assert!(struct_body(&text, "Vector3").contains("operator ==(Cell a, Vector3 b)")); + assert!(struct_body(&text, "Vector3").contains("operator !=(Cell a, Vector3 b)")); } #[test] @@ -485,3 +531,130 @@ fn named_native_calls_emit_matching_pointer_and_ref_overloads_without_db_collisi // Same-arity extra pointer does not downgrade non-pointer DB params to `object`. assert!(!text.contains("NON_PTR(object a0, Cell a1)"), "{text}"); } + +#[test] +fn cell_is_an_enumerator_and_any_enumerator_yields_object() { + let text = prelude(&Names::default(), &Used::default()); + let any_enum = struct_body(&text, "AnyEnumerator"); + assert!( + any_enum.contains("public object Current => default;"), + "{any_enum}" + ); + assert!( + any_enum.contains("public bool MoveNext() => default;"), + "{any_enum}" + ); + + let cell_header = "public unsafe struct Cell\n{\n"; + let start = text.find(cell_header).expect("Cell struct"); + let rest = &text[start + cell_header.len()..]; + let cell_body = &rest[..rest.find("\n}\n").unwrap_or(rest.len())]; + assert!( + cell_body.contains("public AnyEnumerator GetEnumerator() => default;"), + "{cell_body}" + ); + assert!( + cell_body.contains("public bool MoveNext() => default;"), + "{cell_body}" + ); + assert!( + cell_body.contains("public object Current => default;"), + "{cell_body}" + ); +} + +#[test] +fn vector3_omits_source_declared_xyz_fields_and_supports_indexing() { + // Without any source-declared `struct Vector3`, prelude declares all three fields and assigns them. + let plain = prelude(&Names::default(), &Used::default()); + let plain_vec = struct_body(&plain, "Vector3"); + assert!(plain_vec.contains("public float X, Y, Z;"), "{plain_vec}"); + assert!( + plain_vec.contains("public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; }"), + "{plain_vec}" + ); + assert!( + plain_vec.contains("public Cell this[Cell i] { get => default; set { } }"), + "{plain_vec}" + ); + + // When a source declares `struct Vector3` with X, Y, Z (even via `Used::add`), prelude omits them. + let mut used = Used::default(); + let mut other = Used::default(); + other.read( + "unsafe struct Vector3 : IEquatable\n\ + {\n\ + internal float X; // offset 0\n\ + internal float Y;\n\ + internal float Z;\n\ + internal float Length(float X) => X;\n\ + }\n", + ); + used.add(&other); + let merged = prelude(&Names::default(), &used); + let merged_vec = struct_body(&merged, "Vector3"); + assert!(!merged_vec.contains("public float "), "{merged_vec}"); + assert!( + merged_vec.contains("public Vector3(float x, float y, float z) { this = default; }"), + "{merged_vec}" + ); + assert!( + merged_vec.contains("public Cell this[Cell i] { get => default; set { } }"), + "{merged_vec}" + ); + + // Partial declaration (only `X` declared in source) keeps only `Y, Z` in prelude. + let mut partial = Used::default(); + partial.read( + "unsafe struct Vector3\n\ + {\n\ + float X;\n\ + struct Inner\n\ + {\n\ + float Y;\n\ + }\n\ + void Set(float Z) { }\n\ + }\n", + ); + let partial_text = prelude(&Names::default(), &partial); + let partial_vec = struct_body(&partial_text, "Vector3"); + assert!(partial_vec.contains("public float Y, Z;"), "{partial_vec}"); + assert!(!partial_vec.contains("public float X"), "{partial_vec}"); +} + +#[test] +fn system_rage_compare_exchange_and_split_packed_vector_overloads_are_declared() { + let text = prelude(&Names::default(), &Used::default()); + for line in [ + "namespace System", + " public static unsafe class Rage", + " public static Cell CompareExchange(Cell location, Cell value, Cell comparand) => default;", + " public static Cell CompareExchange(Cell location, object value, object comparand) => default;", + " public static Cell CompareExchange(object location, object value, object comparand) => default;", + " public static Cell CompareExchange(ref T location, Cell value, Cell comparand) => default;", + " public static Cell CompareExchange(ref T location, object value, object comparand) => default;", + " public static Cell CompareExchange(params object[] args) => default;", + " public static Vector3 packed_vector_subtract(Vector3 a, Vector3 b) => default;", + " public static Vector3 packed_vector_subtract(object a, object b, object c) => default;", + " public static Vector3 packed_vector_subtract(object a, object b, object c, object d) => default;", + " public static Vector3 packed_vector_add(object a, object b, object c) => default;", + " public static Vector3 packed_vector_add(object a, object b, object c, object d) => default;", + " public static Vector3 packed_vector_scale(object by, object v0, object v1) => default;", + " public static Vector3 packed_vector_normalize3(object v0, object v1) => default;", + " public static Vector3 packed_vector_normalize4(object v0, object v1) => default;", + " public static Vector3 packed_vector_lerp(object a, object b, object c, object d) => default;", + " public static Vector3 packed_vector_lerp(object a, object b, object c, object d, object e) => default;", + " public static Vector3 packed_vector_lerp(object a, object b, object c, object d, object e, object f) => default;", + " public static float packed_vector_dot3(object a, object b, object c) => default;", + " public static float packed_vector_dot4(object a, object b, object c, object d) => default;", + ] { + assert!( + text.lines().any(|l| l == line), + "no line `{line}` in:\n{text}" + ); + } + assert!( + !text.contains("CompareExchange(void*"), + "CompareExchange must not mix void* and object overloads:\n{text}" + ); +} diff --git a/crates/io/or-io/src/gta6/script/print/tests.rs b/crates/io/or-io/src/gta6/script/print/tests.rs index 93e30f8f0..428cb38c3 100644 --- a/crates/io/or-io/src/gta6/script/print/tests.rs +++ b/crates/io/or-io/src/gta6/script/print/tests.rs @@ -3066,9 +3066,10 @@ fn pointer_global_compares_with_null_and_coalesce_boxes_cell_or_pointer_and_read Kind::Object("type_00000000000000AB".to_owned()), ), (Var::Param(1), Kind::Unknown), + (Var::Param(2), Kind::Object("System.Object".to_owned())), ]); - h.params = 2; - h.locals = 3; + h.params = 3; + h.locals = 5; let g_0 = Expr::Var(Var::Global { program: 0x1122_3344, offset: 0x0, @@ -3079,12 +3080,12 @@ fn pointer_global_compares_with_null_and_coalesce_boxes_cell_or_pointer_and_read offset: 0xD0, statics: false, }); - let coalesce = |rhs: Expr| { + let coalesce = |lhs: Expr, rhs: Expr| { Expr::sugar( ExprSugar::Coalesce, Expr::Select { - cond: Box::new(Expr::binary(BinOp::Ne, param(0), int(0))), - then: Box::new(param(0)), + cond: Box::new(Expr::binary(BinOp::Ne, lhs.clone(), int(0))), + then: Box::new(lhs), els: Box::new(rhs), }, ) @@ -3100,12 +3101,14 @@ fn pointer_global_compares_with_null_and_coalesce_boxes_cell_or_pointer_and_read then: vec![tree::Stmt::Return(None)], els: Vec::new(), }, - simple(assign(Var::Local(0), coalesce(param(1)))), - simple(assign(Var::Local(1), coalesce(g_0))), - simple(assign(Var::Local(2), coalesce(int(0)))), + simple(assign(Var::Local(0), coalesce(param(0), param(1)))), + simple(assign(Var::Local(1), coalesce(param(0), g_0.clone()))), + simple(assign(Var::Local(2), coalesce(param(0), int(0)))), + simple(assign(Var::Local(3), coalesce(param(2), param(1)))), + simple(assign(Var::Local(4), coalesce(param(2), g_0))), simple(Stmt::Eval(native( "USE", - vec![local(0), local(1), local(2)], + vec![local(0), local(1), local(2), local(3), local(4)], ))), ]; let f = function_of(h, body); @@ -3113,9 +3116,17 @@ fn pointer_global_compares_with_null_and_coalesce_boxes_cell_or_pointer_and_read let cx = Context::new(&names, &project, Options::default()); let text = written_in(&f, &cx); assert!(text.contains("if (Global_D0 != null)"), "{text}"); - assert!(text.contains("p0 ?? (object)p1;"), "{text}"); - assert!(text.contains("p0 ?? (object)(Cell)Global_0;"), "{text}"); + assert!( + text.contains("p0 ?? (type_00000000000000AB)(object)p1;"), + "{text}" + ); + assert!( + text.contains("p0 ?? (type_00000000000000AB)(object)(Cell)Global_0;"), + "{text}" + ); assert!(text.contains("p0 ?? null;"), "{text}"); + assert!(text.contains("p2 ?? (object)p1;"), "{text}"); + assert!(text.contains("p2 ?? (object)(Cell)Global_0;"), "{text}"); reparse::agrees_source_with(&f, &text, cx.options, false, &project) .expect("pointer global null comparison and boxed coalesce read back"); } @@ -3404,3 +3415,492 @@ fn int_to_uint_targets_and_narrow_typed_stores_read_back() { reparse::agrees_source_with(&f, &off_text, no_implied, false, &project) .expect("narrow stores with Pass::ImpliedCasts off read back"); } + +#[test] +fn zero_bytes_on_implied_this_field_and_addr_of_local_inside_lambda_use_addr_ref_and_read_back() { + use crate::gta6::script::class::{Method, Role}; + use crate::gta6::script::ir::VmType; + use crate::gta6::script::project::TypeFacts; + use crate::gta6::script::reparse; + use crate::gta6::script::tree::Sugar; + // Part A (CS0212): `zero_bytes` on a class instance field via `this` with untyped Param(0). + let owner = TypeKey(0xAB); + let mut project = Project::default(); + project.types.insert( + owner, + TypeFacts { + byte_size: 40, + flags: 0, + ..TypeFacts::default() + }, + ); + project.fields.insert( + owner, + vec![FieldFacts { + offset: 0x10, + bytes: 24, + kind: Kind::Unknown, + }], + ); + let h = head(); + let field_addr = Expr::ByteOffset { + addr: Box::new(param(0)), + offset: Box::new(int(0x10)), + }; + let member = Method { + function: function_of( + h, + vec![simple(Stmt::ZeroBytes { + addr: field_addr, + bytes: 24, + })], + ), + role: Role::Method, + is_static: false, + is_async: false, + slot: None, + overrides: false, + }; + let names = Names::default(); + let cx = Context::new(&names, &project, Options::default()); + let mut out = String::new(); + method( + &mut out, + &member, + Some((owner, "type_00000000000000AB")), + 1, + &cx, + ); + assert!( + out.contains("zero_bytes(addr(ref this.f_10), 24);"), + "{out}" + ); + reparse::agrees_source_with(&member.function, &out, cx.options, true, &project) + .expect("zero_bytes(addr(ref this.f_10), 24) on class receiver reads back"); + + // Part B (CS1686): taking the address of a local inside an inlined lambda uses `addr(ref ...)`. + let closure = VmType { + name: "type_00000000000000CC".to_owned(), + byte_size: 16, + id: 5, + flags: 0, + }; + let delegate = VmType { + name: "System.Delegate".to_owned(), + byte_size: 32, + id: 9, + flags: 0, + }; + let bind_call = Expr::Call { + callee: Callee::Builtin { + path: "System.Delegate.Ctor".to_owned(), + ty: 9, + method: 0, + }, + args: vec![ + local(1), + local(0), + Expr::sugar( + ExprSugar::Lambda, + Expr::FunctionRef { + program: 0x1122_3344, + at: 0x200, + }, + ), + ], + returns: Some(0), + }; + let binder_body = vec![ + simple(assign(Var::Local(0), Expr::NewObject(closure))), + simple(Stmt::Store { + kind: StoreKind::U64, + addr: local(0), + offset: 8, + value: param(0), + }), + tree::Stmt::Sugar(Box::new(Sugar::Group { + kind: tree::Group::Delegate, + parts: vec![ + assign(Var::Local(1), Expr::NewObject(delegate)), + Stmt::Eval(bind_call), + ], + })), + simple(Stmt::Eval(native("RUN", vec![local(1)]))), + ]; + let binder = function_of(head(), binder_body); + let mut lam_head = head(); + lam_head.at = 0x200; + lam_head.name = "func_000200".to_owned(); + lam_head.params = 1; + lam_head.locals = 3; + let lambda_fn = function_of( + lam_head, + vec![ + simple(Stmt::ZeroBytes { + addr: address(Var::Local(2), 0), + bytes: 20, + }), + simple(Stmt::Eval(native( + "USE", + vec![address(Var::Local(2), 0), load(Scalar::U64, param(0), 8)], + ))), + ], + ); + let mut lambdas = Lambdas::new(); + lambdas.insert(0x200, &lambda_fn); + let cx_empty = Context::new(&names, Project::empty(), Options::default()); + let sited = bound_in_place(&binder, &lambdas, &cx_empty); + assert_eq!(sited.iter().copied().collect::>(), [0x200]); + let mut lam_out = String::new(); + method_in( + &mut lam_out, + &Method::free(binder.clone()), + None, + 0, + &cx_empty, + &lambdas, + ); + assert!( + lam_out.contains("zero_bytes(addr(ref local_2), 20);"), + "{lam_out}" + ); + assert!( + lam_out.contains("DEMO.USE(addr(ref local_2), local_0.f_8);"), + "{lam_out}" + ); + reparse::agrees_source_binding( + &binder, + &lam_out, + cx_empty.options, + cx_empty.project, + &lambdas, + &sited, + &names, + ) + .expect("addr(ref local) inside inlined lambda reads back"); +} + +#[test] +fn try_cast_to_value_type_uses_helper_while_is_and_reference_as_stay_operators_and_read_back() { + use crate::gta6::script::project::TypeFacts; + use crate::gta6::script::reparse; + let val_key = TypeKey(0xCD); + let ref_key = TypeKey(0xAB); + let val_ty = val_key.to_string(); + let ref_ty = ref_key.to_string(); + let mut project = Project::default(); + project.types.insert( + val_key, + TypeFacts { + byte_size: 16, + flags: 0x04, + ..TypeFacts::default() + }, + ); + project.types.insert( + ref_key, + TypeFacts { + byte_size: 16, + flags: 0, + ..TypeFacts::default() + }, + ); + project.fields.insert( + val_key, + vec![FieldFacts { + offset: 0x8, + bytes: 4, + kind: Kind::I32, + }], + ); + let mut h = kinds(&[(Var::Param(0), Kind::Unknown)]); + h.params = 1; + h.locals = 4; + let as_val = intrinsic(&format!("try_cast<{val_ty}>"), vec![param(0)]); + let as_val_field = Expr::sugar( + ExprSugar::Field { owner: val_key }, + load(Scalar::I32, as_val.clone(), 0x8), + ); + let as_u64 = intrinsic("try_cast", vec![param(0)]); + let as_ref = intrinsic(&format!("try_cast<{ref_ty}>"), vec![param(0)]); + let is_val = Expr::sugar( + ExprSugar::Is, + Expr::Binary { + op: BinOp::Ne, + at: Kind::U64, + l: Box::new(as_val.clone()), + r: Box::new(int(0)), + }, + ); + let f = function_of( + h, + vec![ + simple(assign(Var::Local(0), as_val)), + simple(assign(Var::Local(1), as_val_field)), + simple(assign(Var::Local(2), as_u64)), + simple(assign(Var::Local(3), as_ref)), + simple(Stmt::Eval(native( + "USE", + vec![is_val, local(0), local(1), local(2), local(3)], + ))), + ], + ); + let names = Names::default(); + let cx = Context::new(&names, &project, Options::default()); + let text = written_in(&f, &cx); + assert!(text.contains(&format!("try_cast<{val_ty}>(p0);")), "{text}"); + assert!( + text.contains(&format!("try_cast<{val_ty}>(p0).f_8;")), + "{text}" + ); + assert!(text.contains("try_cast(p0);"), "{text}"); + assert!( + text.contains(&format!("((object)p0) as {ref_ty};")), + "{text}" + ); + assert!( + text.contains(&format!("((object)p0) is {val_ty}")), + "{text}" + ); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("try_cast helper and reference as operator read back"); +} + +#[test] +fn bool_returning_virtual_and_local_methods_simplify_zero_tests_and_read_back() { + use crate::gta6::script::project::{Signature, TypeFacts}; + use crate::gta6::script::reparse; + let owner = TypeKey(0xAB); + let slot_82_fn = FunctionKey::new(0x1122_3344, 0x300); + let slot_83_fn = FunctionKey::new(0x1122_3344, 0x310); + let local_bool_fn = FunctionKey::new(0x1122_3344, 0x320); + let mut project = Project::default(); + let mut facts = TypeFacts::default(); + facts.slots.insert(82, slot_82_fn); + facts.slots.insert(83, slot_83_fn); + project.types.insert(owner, facts); + project.slot_results.insert(slot_82_fn, Kind::Bool); + project.signatures.insert( + slot_83_fn, + Signature { + params: Vec::new(), + returns: 1, + result: Kind::Bool, + }, + ); + project.signatures.insert( + local_bool_fn, + Signature { + params: Vec::new(), + returns: 1, + result: Kind::Bool, + }, + ); + let mut h = kinds(&[(Var::Param(0), Kind::Object(owner.to_string()))]); + h.params = 1; + h.locals = 2; + let vcall = |slot: u32| { + Expr::sugar( + ExprSugar::Method, + Expr::Call { + callee: Callee::Virtual { + class: owner.to_string(), + ty: owner.to_string(), + slot, + method: format!("Method_{slot}"), + }, + args: vec![param(0)], + returns: Some(1), + }, + ) + }; + let lcall = Expr::Call { + callee: Callee::Local { + at: 0x320, + name: "func_000320".to_owned(), + }, + args: Vec::new(), + returns: Some(1), + }; + let body = vec![ + tree::Stmt::If { + cond: Expr::binary(BinOp::Eq, vcall(82), int(0)), + then: vec![tree::Stmt::Return(None)], + els: Vec::new(), + }, + tree::Stmt::If { + cond: Expr::binary(BinOp::Ne, vcall(83), int(0)), + then: vec![tree::Stmt::Return(None)], + els: Vec::new(), + }, + simple(assign( + Var::Local(0), + Expr::binary(BinOp::Eq, lcall, int(0)), + )), + simple(assign( + Var::Local(1), + Expr::binary(BinOp::Ne, vcall(82), int(0)), + )), + simple(Stmt::Eval(native("USE", vec![local(0), local(1)]))), + ]; + let f = function_of(h, body); + let names = Names::default(); + let cx = Context::new(&names, &project, Options::default()); + let text = written_in(&f, &cx); + assert!(text.contains("if (!p0.Method_82())"), "{text}"); + assert!(text.contains("if (p0.Method_83())"), "{text}"); + assert!(text.contains("local_0 = !func_000320();"), "{text}"); + assert!(text.contains("local_1 = p0.Method_82();"), "{text}"); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("bool-returning virtual and local zero tests read back"); +} + +#[test] +fn u32_and_hash_values_cast_to_int_for_i32_targets_and_read_back() { + use crate::gta6::script::project::{Param, Signature}; + use crate::gta6::script::reparse; + let hash_native = NativeName { + namespace: Some("PLAYER".to_owned()), + name: "GET_HASH".to_owned(), + params: Vec::new(), + returns: Some("Hash".to_owned()), + }; + let names = Names { + natives: Some(NativeDb::from_names("test", [(0x55AA, hash_native)])), + ..Names::default() + }; + let mut project = Project::default(); + project.signatures.insert( + FunctionKey::new(0x1122_3344, 0x40), + Signature { + params: Vec::new(), + returns: 1, + result: Kind::I32, + }, + ); + project.signatures.insert( + FunctionKey::new(0x1122_3344, 0x400), + Signature { + params: vec![ + Param { + kind: Kind::I32, + cells: 1, + }, + Param { + kind: Kind::I32, + cells: 1, + }, + ], + returns: 0, + result: Kind::Unknown, + }, + ); + let mut h = kinds(&[ + (Var::Param(0), Kind::U32), + (Var::Param(1), Kind::Array(Box::new(Kind::I32))), + (Var::Local(0), Kind::I32), + (Var::Local(1), Kind::I32), + ]); + h.params = 2; + h.locals = 2; + h.returns = Returns::Cell; + let get_hash = || Expr::Call { + callee: Callee::Native { + namespace: Some("PLAYER".to_owned()), + name: "GET_HASH".to_owned(), + hash: 0x55AA, + rva: 0, + }, + args: Vec::new(), + returns: Some(1), + }; + let take_ints = Expr::Call { + callee: Callee::Local { + at: 0x400, + name: "func_000400".to_owned(), + }, + args: vec![param(0), get_hash()], + returns: Some(0), + }; + let body = vec![ + simple(assign(Var::Local(0), param(0))), + simple(assign(Var::Local(1), get_hash())), + simple(Stmt::Eval(intrinsic( + "array_set_u32", + vec![param(1), int(0), get_hash()], + ))), + simple(Stmt::Eval(take_ints)), + simple(Stmt::Eval(native("USE", vec![local(0), local(1)]))), + tree::Stmt::Return(Some(get_hash())), + ]; + let f = function_of(h, body); + let cx = Context::new(&names, &project, Options::default()); + let text = written_in(&f, &cx); + assert!(text.contains("int local_0 = (int)p0;"), "{text}"); + assert!( + text.contains("int local_1 = (int)PLAYER.GET_HASH();"), + "{text}" + ); + assert!(text.contains("p1[0] = (int)PLAYER.GET_HASH();"), "{text}"); + assert!( + text.contains("func_000400((int)p0, (int)PLAYER.GET_HASH());"), + "{text}" + ); + assert!(text.contains("return (int)PLAYER.GET_HASH();"), "{text}"); + reparse::agrees_source_named(&f, &text, cx.options, &project, &names) + .expect("u32 and Hash values cast to int for i32 targets read back"); +} + +#[test] +fn array_element_address_field_deref_casts_via_cell_ptr_and_reads_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[ + ( + Var::Param(0), + Kind::Array(Box::new(Kind::Value { + ty: "type_00000000000000EE".to_owned(), + cells: 4, + })), + ), + (Var::Param(1), Kind::I32), + (Var::Param(2), Kind::Unknown), + ]); + h.params = 3; + h.locals = 2; + let managed_elem = intrinsic("array_element_address", vec![param(0), param(1)]); + let cell_elem = intrinsic("array_element_address", vec![param(2), param(1)]); + let elem_field_addr = Expr::ByteOffset { + addr: Box::new(managed_elem), + offset: Box::new(int(0xC)), + }; + let boxed = intrinsic("box_at", vec![elem_field_addr]); + let cell_field_read = load(Scalar::I32, cell_elem.clone(), 0); + let bytes_eq = intrinsic("bytes_equal_24", vec![cell_elem, address(Var::Local(0), 0)]); + let body = vec![ + simple(assign(Var::Local(0), boxed)), + simple(assign(Var::Local(1), cell_field_read)), + simple(Stmt::Eval(native( + "USE", + vec![bytes_eq, local(0), local(1)], + ))), + ]; + let f = function_of(h, body); + let names = Names::default(); + let project = Project::default(); + let cx = Context::new(&names, &project, Options::default()); + let text = written_in(&f, &cx); + assert!( + text.contains("box_at(&((Cell*)(void*)addr(ref p0[p1]))->f_C);"), + "{text}" + ); + assert!( + text.contains("(int)(&((Cell*)(void*)p2)[p1])->f_0;"), + "{text}" + ); + assert!( + text.contains("bytes_equal_24(&((Cell*)(void*)p2)[p1], &local_0)"), + "{text}" + ); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("array_element_address pointer casts read back"); +} diff --git a/crates/io/or-io/src/gta6/script/reparse/mod.rs b/crates/io/or-io/src/gta6/script/reparse/mod.rs index 78494ea85..aa0195ad8 100644 --- a/crates/io/or-io/src/gta6/script/reparse/mod.rs +++ b/crates/io/or-io/src/gta6/script/reparse/mod.rs @@ -532,6 +532,12 @@ fn called(callee: Sk, mut args: Vec) -> Sk { return args.remove(0); } if let (Sk::Name(name), 1) = (&callee, args.len()) { + if let Some(ty) = name + .strip_prefix("try_cast<") + .and_then(|rest| rest.strip_suffix('>')) + { + return Sk::Op("as", vec![args.remove(0), Sk::Name(ty.to_owned())]); + } let reading = name .strip_prefix("as_") .is_some_and(|ty| Scalar::from_name(ty).is_some());