From 239a54aaa310d522b950a3d258bb5ee8447bb2ec Mon Sep 17 00:00:00 2001 From: leonidarider <358984476+leonidarider@users.noreply.github.com> Date: Thu, 3 Dec 2026 12:25:55 +0100 Subject: [PATCH] script: Wave 6 decompiler lift completeness, typing, delegates, and Roslyn bind improvements - Lift sizing: enforce single-producer invariant on multi-cell variable stores (0/416,093 exceptions across corpus), lifting the final unlifted function 0x9EDAAB12::func_1A65F1 (570,117 / 570,117 lifted, 0 unlifted) - Delegates & conversions: ScriptDelegate in Prelude.cs, Delegate/Combine/Remove typing and invocation, ClassKind::Delegate +/- operators, Handle <-> Cells2 & Entity -> handle conversions, 4-byte struct conversion operators (HashString etc.) - Layouts & multi-cell signatures: stack value-local and value-constructor flows (Dictionary.Enumerator.f_0), multi-cell Returns::Cells sig.result & slot_result, numeric slot-family param unification, delegate field stability - Typing, aggregates & indexers: alloc_managed/this protection against boundary/copy/compare raw poisoning, value_receiver for state-machine MoveNext, wide_kind & Around::arg_reads virtual/offset alignment, value-type builtin instance methods (int.GetHashCode), List/Dictionary primary & multi-cell indexers - Emit, print & reparse: CS0115 emit-time override verification, with_unsafe head re-laying (heads_laid_fitting -> 0), CS0266 object->target casts, CS1615 native-only ref/out + managed/captured addr(ref ...), CS1686 outer-method captured locals, CS1503 int->bool args, foreach (var ...), byte_offset, CS0221 ~0x...UL --- crates/io/or-io/src/gta6/script/emit/mod.rs | 493 +++++++++++- crates/io/or-io/src/gta6/script/emit/tests.rs | 486 +++++++++++- .../io/or-io/src/gta6/script/lift/sizing.rs | 56 +- crates/io/or-io/src/gta6/script/lift/tests.rs | 50 ++ .../script/passes/aggregates/kinds/mod.rs | 18 +- .../script/passes/aggregates/kinds/tests.rs | 45 ++ .../src/gta6/script/passes/aggregates/mod.rs | 131 +++- .../gta6/script/passes/aggregates/tests.rs | 66 ++ .../passes/async_await/calls/twin/mod.rs | 9 +- .../passes/async_await/iterated/tests.rs | 3 +- .../gta6/script/passes/classes/properties.rs | 154 +++- .../src/gta6/script/passes/classes/tests.rs | 241 ++++++ .../gta6/script/passes/sugar_runtime/mod.rs | 6 + .../gta6/script/passes/sugar_runtime/table.rs | 9 +- .../gta6/script/passes/sugar_runtime/tests.rs | 64 +- .../src/gta6/script/passes/types/kinds.rs | 30 + .../or-io/src/gta6/script/passes/types/mod.rs | 352 +++++++-- .../gta6/script/passes/types/objects/mod.rs | 47 +- .../src/gta6/script/passes/types/tests.rs | 275 +++++++ .../src/gta6/script/print/constructs/mod.rs | 95 ++- .../io/or-io/src/gta6/script/print/inlined.rs | 2 +- .../src/gta6/script/print/lambda/tests.rs | 3 +- crates/io/or-io/src/gta6/script/print/mod.rs | 450 ++++++++++- .../src/gta6/script/print/prelude/mod.rs | 9 + .../src/gta6/script/print/prelude/tests.rs | 62 ++ .../src/gta6/script/print/property/mod.rs | 13 +- .../or-io/src/gta6/script/print/spell/mod.rs | 35 +- .../io/or-io/src/gta6/script/print/tests.rs | 726 +++++++++++++++++- .../src/gta6/script/project/layouts/flows.rs | 66 +- .../src/gta6/script/project/layouts/mod.rs | 123 ++- .../src/gta6/script/project/layouts/tests.rs | 267 +++++++ .../src/gta6/script/project/signatures/mod.rs | 256 +++++- .../gta6/script/project/signatures/shared.rs | 44 +- .../gta6/script/project/signatures/tests.rs | 308 ++++++++ .../io/or-io/src/gta6/script/reparse/mod.rs | 55 +- 35 files changed, 4789 insertions(+), 260 deletions(-) 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 20fe94c4b..016e9a1c8 100644 --- a/crates/io/or-io/src/gta6/script/emit/mod.rs +++ b/crates/io/or-io/src/gta6/script/emit/mod.rs @@ -277,10 +277,13 @@ fn emit_type_block( // 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()); + let mut rendered = String::new(); + indent(&mut rendered, member_depth); + rendered.push_str(&print::laid(&head, member_depth)); + rendered.push('\n'); + rendered.push_str(block[j]); + out.push_str(&print::heads_relaid(&rendered)); + out.push_str(&block[j + 1..=close].concat()); } else { out.push_str(&member_slice.concat()); } @@ -642,8 +645,10 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool } } - // Where each method of a class stands in the text, for `this.` to be left out of it after. - let mut methods_at: Vec<(usize, usize)> = Vec::new(); + // Where each method of a class stands in the text, for override checks and `this.` omission. + let mut methods_at: Vec = Vec::new(); + // Emitted non-hidden classes in this unit, for verifying `override` signatures against bases. + let mut emitted_classes: BTreeMap = BTreeMap::new(); // An explicit stack: classes nest as deep as the closures they were made for. let top = ordered(&unit.classes).into_iter().rev(); let mut work: Vec> = top.map(|class| Work::Open(class, 0, true)).collect(); @@ -675,6 +680,12 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool "" }; opened(&mut out, class, (&name, &shown), depth, cx, word); + let mut class_info = EmittedClassInfo { + kind: class.kind, + base: class.base, + virtual_sigs: BTreeSet::new(), + hiding_sigs: BTreeSet::new(), + }; let mut fields: Vec<&Field> = class.fields.iter().collect(); fields.sort_by_key(|field| (field.is_static, field.offset)); for field in &fields { @@ -705,6 +716,7 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool // with their interface instead of triggering `CS0111`. let mut seen_sigs: BTreeSet = BTreeSet::new(); let mut seen_explicit: BTreeSet<(TypeKey, MemberSig)> = BTreeSet::new(); + let class_body_start = out.len(); for method in methods { // A lambda's body written where it is bound is no member to write again. let at = method.function.head.at; @@ -823,22 +835,73 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool Some(word) => out.push_str(&modified(&text, depth + 1, word)), None => out.push_str(&text), } - methods_at.push((start, out.len())); + let end = out.len(); + let mut override_sig = None; + if sharp { + if let Some(parsed) = parse_override_info(&out[start..end]) { + if !parsed.is_static && !parsed.already_qualified { + match parsed.dispatch { + MemberDispatch::Virtual => { + class_info.virtual_sigs.insert(parsed.sig); + } + MemberDispatch::Override => { + override_sig = Some(parsed.sig); + } + MemberDispatch::Plain => { + class_info.hiding_sigs.insert(parsed.sig.member_key()); + } + } + } + } + } + methods_at.push(EmittedMethod { + start, + end, + owner: class.key, + depth: depth + 1, + override_sig, + }); + } + if sharp { + emit_synthetic_operators( + &mut out, + class, + &name, + depth + 1, + cx, + class_body_start, + &mut written, + ); } + emitted_classes.insert(class.key, class_info); work.push(Work::Close(depth)); for (n, nested) in ordered(&class.nested).into_iter().enumerate().rev() { work.push(Work::Open(nested, depth + 1, written || n > 0)); } } + // Verify `override` signatures against same-file / BCL / struct ancestors and apply `implied-this`. // ⚠ With `fields` off, `this.f_0` is the receiver's own cell and no member. - if cx.options.on(Pass::ImpliedThis) + let omit_this = cx.options.on(Pass::ImpliedThis) && cx.options.on(Pass::Fields) - && print::true_csharp(&cx.options) - { - let statics = print::statics_of(&out); - for (start, end) in methods_at.into_iter().rev() { - let bare = print::implied_this(&out[start..end], &statics); - out.replace_range(start..end, &bare); + && print::true_csharp(&cx.options); + let statics = omit_this.then(|| print::statics_of(&out)); + for m in methods_at.into_iter().rev() { + let orig = &out[m.start..m.end]; + let mut updated: Option = None; + if let Some(sig) = &m.override_sig { + if !valid_override(m.owner, sig, &emitted_classes, cx) { + updated = Some(strip_override_from_member(orig, m.depth)); + } + } + if let Some(statics) = &statics { + let src = updated.as_deref().unwrap_or(orig); + let bare = print::implied_this(src, statics); + if bare != src { + updated = Some(bare); + } + } + if let Some(replacement) = updated { + out.replace_range(m.start..m.end, &replacement); } } // The legend says what the words the text uses mean, read from the text written. @@ -848,6 +911,408 @@ fn written_source(unit: &Unit, cx: &Context<'_>, stats: &Stats) -> (String, bool (out, wrapped) } +/// One emitted class member recorded for post-emission override verification and `implied-this`. +struct EmittedMethod { + start: usize, + end: usize, + owner: TypeKey, + depth: usize, + override_sig: Option, +} + +/// Summary of one emitted non-hidden class in the current unit, for `override` verification. +struct EmittedClassInfo { + kind: ClassKind, + base: Option, + /// Exact `virtual` instance signatures emitted by this class. + virtual_sigs: BTreeSet, + /// Non-virtual, non-override instance member keys that hide inherited virtuals of the same signature. + hiding_sigs: BTreeSet, +} + +/// Virtual dispatch modifier on an emitted class member. +#[derive(Clone, Copy, PartialEq, Eq)] +enum MemberDispatch { + Virtual, + Override, + Plain, +} + +/// Full C# signature of an emitted member including its return type, for `override` matching (`CS0115`/`CS0508`). +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum OverrideSig { + Method { + ret: String, + name: String, + params: Vec, + }, + Property { + ret: String, + name: String, + }, + Indexer { + ret: String, + params: Vec, + }, +} + +/// Name + parameter identity of an emitted member (without return type), for detecting non-virtual hiding (`CS0506`). +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum MemberKey { + Method { name: String, params: Vec }, + Property { name: String }, + Indexer { params: Vec }, +} + +impl OverrideSig { + fn member_key(&self) -> MemberKey { + match self { + OverrideSig::Method { name, params, .. } => MemberKey::Method { + name: name.clone(), + params: params.clone(), + }, + OverrideSig::Property { name, .. } => MemberKey::Property { name: name.clone() }, + OverrideSig::Indexer { params, .. } => MemberKey::Indexer { + params: params.clone(), + }, + } + } +} + +struct ParsedOverrideInfo { + is_static: bool, + already_qualified: bool, + dispatch: MemberDispatch, + sig: OverrideSig, +} + +/// Emits C# conversion operators on 4-byte non-enum value structs (`CS0029`/`CS0030`) and +/// delegate combine/remove operators on `ClassKind::Delegate` classes (`CS0019`). +fn emit_synthetic_operators( + out: &mut String, + class: &Class, + name: &str, + depth: usize, + cx: &Context<'_>, + body_start: usize, + written: &mut bool, +) { + let mut ops: Vec = Vec::new(); + match class.kind { + ClassKind::Struct => { + let four_bytes = cx + .project + .types + .get(&class.key) + .is_some_and(|facts| facts.byte_size == 4); + if four_bytes && !matches!(name, "Cell" | "int" | "uint") { + let existing = &out[body_start..]; + let candidates = [ + ("implicit", name, "int"), + ("implicit", name, "uint"), + ("implicit", name, "Cell"), + ("implicit", "Cell", name), + ("explicit", "int", name), + ("explicit", "uint", name), + ]; + for (kind, to, from) in candidates { + let needle = format!("operator {to}({from} "); + let needle_bare = format!("operator {to}({from})"); + if !existing.contains(&needle) && !existing.contains(&needle_bare) { + ops.push(format!( + "public static {kind} operator {to}({from} v) => default;" + )); + } + } + } + } + ClassKind::Delegate => { + let existing = &out[body_start..]; + for op in ['+', '-'] { + let needle = format!("operator {op}("); + if !existing.contains(&needle) { + ops.push(format!( + "public static {name} operator {op}({name} a, object b) => default;" + )); + } + } + } + _ => {} + } + if ops.is_empty() { + return; + } + if std::mem::replace(written, true) { + out.push('\n'); + } + for line in ops { + indent(out, depth); + out.push_str(&print::laid(&line, depth)); + out.push('\n'); + } +} + +/// Normalizes a C# type string (including optional `ref`/`out`/`in`/`params` prefix) so BCL aliases compare equal to keywords. +fn normalize_type(ty: &str) -> String { + let compact = ty.split_whitespace().collect::>().join(" "); + for prefix in ["ref ", "out ", "in ", "params "] { + if let Some(rest) = compact.strip_prefix(prefix) { + return format!("{prefix}{}", normalize_type(rest)); + } + } + match compact.as_str() { + "System.Object" => "object".to_owned(), + "System.String" => "string".to_owned(), + "System.Boolean" => "bool".to_owned(), + "System.Int32" => "int".to_owned(), + "System.UInt32" => "uint".to_owned(), + "System.Int64" => "long".to_owned(), + "System.UInt64" => "ulong".to_owned(), + "System.Single" => "float".to_owned(), + "System.Double" => "double".to_owned(), + "System.Byte" => "byte".to_owned(), + "System.SByte" => "sbyte".to_owned(), + "System.Int16" => "short".to_owned(), + "System.UInt16" => "ushort".to_owned(), + "System.Void" => "void".to_owned(), + _ => compact, + } +} + +/// Parses an emitted member's virtual/override modifier and full signature (with return type). +fn parse_override_info(text: &str) -> Option { + let lines: Vec<&str> = text.lines().collect(); + let first = lines.iter().position(|line| { + let code = line.trim_start(); + !code.is_empty() && !code.starts_with("//") + })?; + let mut last = first; + while lines[last].trim_end().ends_with([',', '(']) && last + 1 < lines.len() { + last += 1; + } + let head = join_laid(&lines[first..=last]); + let mut head = head.split(" //").next().unwrap_or(&head).trim(); + let mut is_static = false; + let mut dispatch = MemberDispatch::Plain; + loop { + let stripped = [ + "public ", + "internal ", + "private ", + "protected ", + "static ", + "virtual ", + "override ", + "async ", + "unsafe ", + "new ", + "sealed ", + ] + .iter() + .find_map(|kw| head.strip_prefix(kw).map(|rest| (*kw, rest))); + match stripped { + Some((kw, rest)) => { + if kw == "static " { + is_static = true; + } else if kw == "virtual " { + dispatch = MemberDispatch::Virtual; + } else if kw == "override " { + dispatch = MemberDispatch::Override; + } + head = rest.trim_start(); + } + None => break, + } + } + if head.is_empty() { + return None; + } + let decl = head.split(" => ").next().unwrap_or(head).trim_end(); + if let Some(inner) = decl.strip_suffix(']') { + let open = matching_open(inner, b'[', b']')?; + let before = inner[..open].trim_end(); + let raw_name = trailing_member_name(before)?; + if raw_name != "this" && !raw_name.ends_with(".this") { + return None; + } + let ret = normalize_type(before[..before.len() - raw_name.len()].trim()); + if ret.is_empty() { + return None; + } + let already_qualified = raw_name.contains('.'); + let params_text = inner[open + 1..].trim(); + let params = split_top_level(params_text, b',') + .into_iter() + .filter_map(|p| param_type_key(p.trim()).map(|t| normalize_type(&t))) + .collect(); + return Some(ParsedOverrideInfo { + is_static, + already_qualified, + dispatch, + sig: OverrideSig::Indexer { ret, params }, + }); + } + if let Some(inner) = decl.strip_suffix(')') { + let open = matching_open(inner, b'(', b')')?; + let before = inner[..open].trim_end(); + let raw_name = trailing_member_name(before)?; + let ret = normalize_type(before[..before.len() - raw_name.len()].trim()); + if ret.is_empty() { + return None; + } + let already_qualified = raw_name.contains('.'); + let base_name = raw_name.rsplit('.').next().unwrap_or(raw_name).to_owned(); + let params_text = inner[open + 1..].trim(); + let params = split_top_level(params_text, b',') + .into_iter() + .filter_map(|p| param_type_key(p.trim()).map(|t| normalize_type(&t))) + .collect(); + return Some(ParsedOverrideInfo { + is_static, + already_qualified, + dispatch, + sig: OverrideSig::Method { + ret, + name: base_name, + params, + }, + }); + } + let raw_name = trailing_member_name(decl)?; + let ret = normalize_type(decl[..decl.len() - raw_name.len()].trim()); + if ret.is_empty() { + return None; + } + let already_qualified = raw_name.contains('.'); + let base_name = raw_name.rsplit('.').next().unwrap_or(raw_name).to_owned(); + Some(ParsedOverrideInfo { + is_static, + already_qualified, + dispatch, + sig: OverrideSig::Property { + ret, + name: base_name, + }, + }) +} + +/// Whether `display` names a terminal BCL root base with no user virtual members beyond `System.Object`. +fn is_bcl_root_base(display: &str) -> bool { + matches!( + display, + "object" + | "System.Object" + | "System.ValueType" + | "System.MulticastDelegate" + | "System.Delegate" + | "System.Enum" + | "ScriptDelegate" + ) +} + +/// Whether `sig` matches one of `System.Object`'s overridable virtual methods. +fn is_object_virtual(sig: &OverrideSig) -> bool { + match sig { + OverrideSig::Method { ret, name, params } => match name.as_str() { + "ToString" => params.is_empty() && ret == "string", + "GetHashCode" => params.is_empty() && ret == "int", + "Equals" => params.len() == 1 && params[0] == "object" && ret == "bool", + "Finalize" => params.is_empty() && ret == "void", + _ => false, + }, + OverrideSig::Property { .. } | OverrideSig::Indexer { .. } => false, + } +} + +/// Whether `override` on `sig` in `owner` is valid (or plausibly valid on an external cross-file base). +/// +/// Returns `false` only when we have proof that the base chain terminates at a struct, interface, +/// `object`/BCL root, or same-file classes with no matching `virtual` member. +fn valid_override( + owner: TypeKey, + sig: &OverrideSig, + classes: &BTreeMap, + cx: &Context<'_>, +) -> bool { + let Some(me) = classes.get(&owner) else { + return true; + }; + if matches!(me.kind, ClassKind::Struct | ClassKind::Enum) { + return is_object_virtual(sig); + } + if me.kind == ClassKind::Interface { + return false; + } + let key = sig.member_key(); + let mut visited = BTreeSet::from([owner]); + let mut cur = me.base; + for _ in 0..64 { + let Some(base_key) = cur else { + return is_object_virtual(sig); + }; + if !visited.insert(base_key) { + return false; + } + if let Some(base_info) = classes.get(&base_key) { + if matches!( + base_info.kind, + ClassKind::Struct | ClassKind::Enum | ClassKind::Interface + ) { + return false; + } + if base_info.virtual_sigs.contains(sig) { + return true; + } + if base_info.hiding_sigs.contains(&key) { + return false; + } + cur = base_info.base; + continue; + } + let display = types::display(cx.project, cx.names, base_key); + if is_bcl_root_base(&display) { + return is_object_virtual(sig); + } + if let Some(facts) = cx.project.types.get(&base_key) { + if facts.is_value() { + return false; + } + if facts.base.is_none() && facts.flags & 0x2_0000 != 0 { + return false; + } + } + // External / cross-file class whose members are not in this file: keep `override`. + return true; + } + false +} + +/// Strips `override ` from an emitted member's head and re-lays the head at `depth`. +fn strip_override_from_member(text: &str, depth: usize) -> String { + let lines: Vec<&str> = text.split_inclusive('\n').collect(); + let Some(first) = lines.iter().position(|line| { + let code = line.trim_start(); + !code.is_empty() && !code.starts_with("//") + }) else { + return text.to_owned(); + }; + let mut last = first; + while lines[last].trim_end().ends_with([',', '(']) && last + 1 < lines.len() { + last += 1; + } + let head_joined = join_laid(&lines[first..=last]); + let stripped = strip_override(&head_joined); + if stripped == head_joined { + return text.to_owned(); + } + let mut out: String = lines[..first].concat(); + indent(&mut out, depth); + out.push_str(&print::laid(&stripped, depth)); + out.push('\n'); + out.push_str(&lines[last + 1..].concat()); + out +} + /// The C# signature identity of an emitted class member, for detecting duplicate declarations (`CS0111`/`CS0102`). #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] enum MemberSig { 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 f88c61a16..022f7a8be 100644 --- a/crates/io/or-io/src/gta6/script/emit/tests.rs +++ b/crates/io/or-io/src/gta6/script/emit/tests.rs @@ -1,7 +1,8 @@ use super::*; use crate::gta6::script::class::Role; use crate::gta6::script::ir::{ - BinOp, Const, ExprSugar, Head, Returns, Scalar, Stmt, StoreKind, Var, VarInfo, VmType, Width, + BinOp, Const, ExprSugar, FunctionKey, Head, Returns, Scalar, Stmt, StoreKind, Var, VarInfo, + VmType, Width, }; use crate::gta6::script::listing::Import; use crate::gta6::script::project::TypeFacts; @@ -1786,3 +1787,486 @@ class type_PureSync assert!(made.contains("\nunsafe class type_PureSync\n"), "{made}"); assert!(made.contains("\n void Run()\n"), "{made}"); } + +#[test] +fn four_byte_non_enum_structs_emit_conversion_operators_and_reparse() { + use crate::gta6::script::reparse::{agrees_file, agrees_members, unfiled}; + + let hash_key = TypeKey(0xAA10); + let wide_key = TypeKey(0xAA20); + let enum_key = TypeKey(0xAA30); + + let mut hash_struct = class(hash_key.0, ClassKind::Struct); + hash_struct.fields = vec![field(0, 4, Kind::U32, false)]; + let getter = function( + 0x40, + 1, + Returns::Cell, + vec![tree::Stmt::Return(Some(Expr::sugar( + ExprSugar::Field { owner: hash_key }, + load(Scalar::U32, 0), + )))], + ); + hash_struct.methods = vec![member(Role::Getter, false, getter.clone())]; + + let mut wide_struct = class(wide_key.0, ClassKind::Struct); + wide_struct.fields = vec![field(0, 12, Kind::Unknown, false)]; + + let mut enum_with_field = class(enum_key.0, ClassKind::Enum); + enum_with_field.fields = vec![field(0, 4, Kind::I32, false)]; + + let free_fn = function(0x10, 1, Returns::Void, vec![tree::Stmt::Return(None)]); + let unit = Unit { + program: PROGRAM, + imports: Vec::new(), + classes: vec![hash_struct, wide_struct, enum_with_field], + functions: vec![Method::free(free_fn.clone())], + front: None, + }; + + let mut project = Project::default(); + project.types.insert( + hash_key, + TypeFacts { + byte_size: 4, + flags: 0x04, + ..TypeFacts::default() + }, + ); + project.types.insert( + wide_key, + TypeFacts { + byte_size: 12, + flags: 0x04, + ..TypeFacts::default() + }, + ); + project.types.insert( + enum_key, + TypeFacts { + byte_size: 4, + flags: 0x08, + constants: vec![0, 1], + ..TypeFacts::default() + }, + ); + + let mut names = Names::default(); + names.types.insert(hash_key.0, "HashString".to_owned()); + names.types.insert(wide_key.0, "WideStruct".to_owned()); + names.types.insert(enum_key.0, "FourByteEnum".to_owned()); + names + .functions + .insert(FunctionKey::new(PROGRAM, 0x40), "get_Value".to_owned()); + + let options = Options::default(); + let text = file(&unit, &names, &project, options).text; + for expected in [ + " public static implicit operator HashString(int v) => default;", + " public static implicit operator HashString(uint v) => default;", + " public static implicit operator HashString(Cell v) => default;", + " public static implicit operator Cell(HashString v) => default;", + " public static explicit operator int(HashString v) => default;", + " public static explicit operator uint(HashString v) => default;", + ] { + assert!( + text.lines().any(|l| l == expected), + "missing `{expected}` in:\n{text}" + ); + } + assert!(!text.contains("operator WideStruct("), "{text}"); + assert!(!text.contains("operator FourByteEnum("), "{text}"); + + // Baseline (non-sharp) mode omits synthetic operators. + let old = file(&unit, &names, &project, Options::baseline()).text; + assert!(!old.contains("operator HashString("), "{old}"); + + // Reparse round-trip cleanly ignores synthetic operators on structs. + let parsed = unfiled(&text).expect("unfiled must parse file with 4-byte struct operators"); + assert_eq!(parsed.program, "program_1234ABCD"); + let file_read = + agrees_file(&text, &names, &[&free_fn], options, &project).expect("agrees_file must read"); + assert!(file_read.iter().all(Result::is_ok), "{file_read:?}\n{text}"); + let members_read = agrees_members(&text, &[(&getter, None)], &names, options, &project); + assert!( + members_read.iter().all(Result::is_ok), + "{members_read:?}\n{text}" + ); +} + +#[test] +fn delegate_classes_emit_combine_and_remove_operators_and_reparse() { + use crate::gta6::script::reparse::{agrees_file, unfiled}; + + let del_key = TypeKey(0xBB10); + let mut del = class(del_key.0, ClassKind::Delegate); + del.methods = vec![member( + Role::Method, + false, + function(0x40, 2, Returns::Void, vec![tree::Stmt::Return(None)]), + )]; + let free_fn = function(0x10, 1, Returns::Void, vec![tree::Stmt::Return(None)]); + let unit = Unit { + program: PROGRAM, + imports: Vec::new(), + classes: vec![del], + functions: vec![Method::free(free_fn.clone())], + front: None, + }; + + let mut names = Names::default(); + names.types.insert(del_key.0, "OnMissionEvent".to_owned()); + let project = Project::default(); + let options = Options::default(); + let text = file(&unit, &names, &project, options).text; + + for expected in [ + " public static OnMissionEvent operator +(OnMissionEvent a, object b) => default;", + " public static OnMissionEvent operator -(OnMissionEvent a, object b) => default;", + ] { + assert!( + text.lines().any(|l| l == expected), + "missing `{expected}` in:\n{text}" + ); + } + + let old = file(&unit, &names, &project, Options::baseline()).text; + assert!(!old.contains("operator +("), "{old}"); + + let parsed = unfiled(&text).expect("unfiled must parse file with delegate operators"); + assert_eq!(parsed.program, "program_1234ABCD"); + let file_read = + agrees_file(&text, &names, &[&free_fn], options, &project).expect("agrees_file must read"); + assert!(file_read.iter().all(Result::is_ok), "{file_read:?}\n{text}"); +} + +#[test] +fn cs0115_override_verification_strips_invalid_and_preserves_valid_and_external() { + let sys_obj = TypeKey(0x8000_0001); + let struct_base = TypeKey(0xCC01); + let grand_base = TypeKey(0xCC10); + let mid_cls = TypeKey(0xCC20); + let leaf_cls = TypeKey(0xCC30); + let obj_sub = TypeKey(0xCC40); + let struct_sub = TypeKey(0xCC50); + let ext_base = TypeKey(0xDD01); + let ext_mid = TypeKey(0xCC60); + let ext_leaf = TypeKey(0xCC70); + + let typed_fn = |at: u32, ret_kind: Option, p1_kind: Option| { + let returns = match &ret_kind { + Some(_) => Returns::Cell, + None => Returns::Void, + }; + let params = if p1_kind.is_some() { 2 } else { 1 }; + let body = match &ret_kind { + Some(_) => vec![tree::Stmt::Return(Some(p(0)))], + None => vec![tree::Stmt::Return(None)], + }; + let mut f = function(at, params, returns, body); + if let Some(kind) = p1_kind { + let mut info = VarInfo::new(Width::Cell); + info.kind = kind; + f.head.vars.insert(Var::Param(1), info); + } + f + }; + + let slotted = |slot: u32, overrides: bool, f: tree::Function| Method { + slot: Some(slot), + overrides, + ..member(Role::Method, false, f) + }; + + let mut project = Project::default(); + project.types.insert( + struct_base, + TypeFacts { + byte_size: 8, + flags: 0x04, + ..TypeFacts::default() + }, + ); + let mut set_ret = |at: u32, kind: Kind| { + project.signatures.insert( + FunctionKey::new(PROGRAM, at), + crate::gta6::script::project::Signature { + params: Vec::new(), + returns: 1, + result: kind, + }, + ); + }; + + // GrandBase (higher offset than Leaf on purpose to test emission-order independence): + // virtual Cell Method_5(int p1) + // virtual Cell Method_6() + // void Plain() (non-virtual!) + let gb_m5 = slotted( + 5, + false, + typed_fn(0x500, Some(Kind::Unknown), Some(Kind::I32)), + ); + let gb_m6 = slotted(6, false, typed_fn(0x510, Some(Kind::Unknown), None)); + let gb_plain = member(Role::Method, false, typed_fn(0x520, None, None)); + let mut grand = class(grand_base.0, ClassKind::Class); + grand.methods = vec![gb_m5, gb_m6, gb_plain]; + + // Mid : GrandBase + // override Cell Method_5(int p1) -> VALID (matches GrandBase virtual) + // override Cell Method_5(Cell p1) -> INVALID (param type mismatch: Cell != int) + // override int Method_6() -> INVALID (return type mismatch: int != Cell) + // override Cell Method_99() -> INVALID (not on GrandBase or object) + let mid_m5_ok = slotted( + 5, + true, + typed_fn(0x200, Some(Kind::Unknown), Some(Kind::I32)), + ); + let mid_m5_bad = slotted( + 15, + true, + typed_fn(0x210, Some(Kind::Unknown), Some(Kind::Unknown)), + ); + let mid_m6_bad = slotted(6, true, typed_fn(0x220, Some(Kind::I32), None)); + set_ret(0x220, Kind::I32); + let mid_m99_bad = slotted(99, true, typed_fn(0x230, Some(Kind::Unknown), None)); + let mut mid = class(mid_cls.0, ClassKind::Class); + mid.base = Some(grand_base); + mid.methods = vec![mid_m5_ok, mid_m5_bad, mid_m6_bad, mid_m99_bad]; + + // Leaf : Mid (lowest offset -> emitted BEFORE Mid and GrandBase!) + // override Cell Method_5(int p1) -> VALID (chains through Mid to GrandBase virtual) + // override Cell Method_99() -> INVALID (Mid's override was invalid too) + // override void Plain() -> INVALID (GrandBase.Plain is non-virtual) + let leaf_m5_ok = slotted( + 5, + true, + typed_fn(0x100, Some(Kind::Unknown), Some(Kind::I32)), + ); + let leaf_m99_bad = slotted(99, true, typed_fn(0x110, Some(Kind::Unknown), None)); + let leaf_plain_bad = slotted(20, true, typed_fn(0x120, None, None)); + let mut leaf = class(leaf_cls.0, ClassKind::Class); + leaf.base = Some(mid_cls); + leaf.methods = vec![leaf_m5_ok, leaf_m99_bad, leaf_plain_bad]; + + // ObjSub : System.Object + // override string ToString() -> VALID + // override bool Equals(object p1) -> VALID + // override int GetHashCode() -> VALID + // override Cell Method_13(Cell p1) -> INVALID + // override bool Equals(Cell p1) -> INVALID (param type mismatch) + let obj_tostring = slotted(1, true, typed_fn(0x300, Some(Kind::String), None)); + set_ret(0x300, Kind::String); + let obj_equals_ok = slotted( + 2, + true, + typed_fn( + 0x310, + Some(Kind::Bool), + Some(Kind::Object("System.Object".to_owned())), + ), + ); + set_ret(0x310, Kind::Bool); + let obj_hash = slotted(3, true, typed_fn(0x320, Some(Kind::I32), None)); + set_ret(0x320, Kind::I32); + let obj_m13_bad = slotted( + 13, + true, + typed_fn(0x330, Some(Kind::Unknown), Some(Kind::Unknown)), + ); + let obj_equals_bad = slotted( + 14, + true, + typed_fn(0x340, Some(Kind::Bool), Some(Kind::Unknown)), + ); + set_ret(0x340, Kind::Bool); + let mut obj_sub_cls = class(obj_sub.0, ClassKind::Class); + obj_sub_cls.base = Some(sys_obj); + obj_sub_cls.methods = vec![ + obj_tostring, + obj_equals_ok, + obj_hash, + obj_m13_bad, + obj_equals_bad, + ]; + + // StructSub : StructBase (resolved value type -> strip override) + let struct_sub_m3 = slotted(3, true, typed_fn(0x380, Some(Kind::Unknown), None)); + let mut struct_sub_cls = class(struct_sub.0, ClassKind::Class); + struct_sub_cls.base = Some(struct_base); + struct_sub_cls.methods = vec![struct_sub_m3]; + + // ExtMid : ExternalBase & ExtLeaf : ExtMid (external base -> preserve override on both!) + let ext_mid_m13 = slotted( + 13, + true, + typed_fn(0x400, Some(Kind::Unknown), Some(Kind::Unknown)), + ); + let mut ext_mid_cls = class(ext_mid.0, ClassKind::Class); + ext_mid_cls.base = Some(ext_base); + ext_mid_cls.methods = vec![ext_mid_m13]; + + let ext_leaf_m13 = slotted( + 13, + true, + typed_fn(0x410, Some(Kind::Unknown), Some(Kind::Unknown)), + ); + let mut ext_leaf_cls = class(ext_leaf.0, ClassKind::Class); + ext_leaf_cls.base = Some(ext_mid); + ext_leaf_cls.methods = vec![ext_leaf_m13]; + + let mut names = Names::default(); + names.types.insert(sys_obj.0, "System.Object".to_owned()); + names.types.insert(struct_base.0, "StructBase".to_owned()); + names.types.insert(grand_base.0, "GrandBase".to_owned()); + names.types.insert(mid_cls.0, "Mid".to_owned()); + names.types.insert(leaf_cls.0, "Leaf".to_owned()); + names.types.insert(obj_sub.0, "ObjSub".to_owned()); + names.types.insert(struct_sub.0, "StructSub".to_owned()); + names.types.insert(ext_base.0, "ExternalBase".to_owned()); + names.types.insert(ext_mid.0, "ExtMid".to_owned()); + names.types.insert(ext_leaf.0, "ExtLeaf".to_owned()); + names + .functions + .insert(FunctionKey::new(PROGRAM, 0x520), "Plain".to_owned()); + names.methods.insert((mid_cls, 15), "Method_5".to_owned()); + names.methods.insert((leaf_cls, 20), "Plain".to_owned()); + names.methods.insert((obj_sub, 1), "ToString".to_owned()); + names.methods.insert((obj_sub, 2), "Equals".to_owned()); + names.methods.insert((obj_sub, 3), "GetHashCode".to_owned()); + names.methods.insert((obj_sub, 14), "Equals".to_owned()); + + let unit = Unit { + program: PROGRAM, + imports: Vec::new(), + classes: vec![ + leaf, + mid, + grand, + obj_sub_cls, + struct_sub_cls, + ext_mid_cls, + ext_leaf_cls, + ], + functions: Vec::new(), + front: None, + }; + + let text = file(&unit, &names, &project, Options::default()).text; + for expected in [ + // Valid same-file chain overrides preserved (even though Leaf preceded GrandBase). + " public override Cell Method_5(int p1) // func_000100", + " public override Cell Method_5(int p1) // func_000200", + // Mismatched / missing / non-virtual same-file overrides stripped. + " public Cell Method_5(Cell p1) // func_000210", + " public int Method_6() // func_000220", + " public Cell Method_99() // func_000230", + " public Cell Method_99() // func_000110", + " public void Plain() // func_000120", + // System.Object overrides: valid ones kept, non-object / wrong-sig stripped. + " public override string ToString() // func_000300", + " public override bool Equals(object p1) // func_000310", + " public override int GetHashCode() // func_000320", + " public Cell Method_13(Cell p1) // func_000330", + " public bool Equals(Cell p1) // func_000340", + // Struct base: override stripped. + " public Cell Method_3() // func_000380", + // External cross-file base chain: overrides preserved. + " public override Cell Method_13(Cell p1) // func_000400", + " public override Cell Method_13(Cell p1) // func_000410", + ] { + assert!( + text.lines().any(|l| l == expected), + "missing `{expected}` in:\n{text}" + ); + } +} + +#[test] +fn with_unsafe_relays_long_member_heads_within_width_and_heads_relaid_fixed_point() { + // 1. A member head with ` // func_005E7F` that fits <= 120 before `unsafe ` and exceeds 120 + // after `unsafe `, while the head alone fits <= 120: moves `// func_005E7F` above the head. + let params: Vec = (1..=7).map(|n| format!("Cell p{n}")).collect(); + let multi_head = format!( + " public virtual void Method_3000000({}) // func_005E7F", + params.join(", ") + ); + assert!( + multi_head.len() <= 120 && multi_head.len() + 7 > 120, + "len={}", + multi_head.len() + ); + // 2. A 1-parameter head with ` // func_005E80` (no comma) pushed past 120 by `unsafe `. + let one_param_head = format!( + " public virtual void Method_31({} p1) // func_005E80", + "VeryLongTypeName".repeat(4) + ); + assert!( + one_param_head.len() <= 120 && one_param_head.len() + 7 > 120, + "len={}", + one_param_head.len() + ); + // 3. A head already > 120 even without comment after `unsafe ` wraps across lines <= 120. + let wide_params: Vec = (1..=9).map(|n| format!("Cell p{n}")).collect(); + let wide_head = format!( + " public virtual void Method_32000({})", + wide_params.join(", ") + ); + assert!( + wide_head.len() <= 120 && wide_head.len() + 7 > 120, + "len={}", + wide_head.len() + ); + + let text = format!( + "\ +class type_AsyncUnsafeHead +{{ + internal void* f_8; + +{multi_head} + {{ + DEMO.USE(f_8); + }} + +{one_param_head} + {{ + DEMO.USE(f_8); + }} + +{wide_head} + {{ + DEMO.USE(f_8); + }} + + public async Task Wait() + {{ + await DEMO.LATER(); + }} +}} +" + ); + + let made = unsafe_where_pointed(&text); + assert!( + made.lines().all(|l| l.chars().count() <= 120), + "line exceeded 120 cols:\n{made}" + ); + assert_eq!( + print::heads_relaid(&made), + made, + "unsafe_where_pointed must leave heads at heads_relaid fixed point:\n{made}" + ); + assert!( + made.contains("\n // func_005E7F\n public unsafe virtual void Method_3000000("), + "{made}" + ); + assert!( + made.contains("\n // func_005E80\n public unsafe virtual void Method_31("), + "{made}" + ); + assert!( + made.contains("\n public unsafe virtual void Method_32000(Cell p1, "), + "{made}" + ); +} diff --git a/crates/io/or-io/src/gta6/script/lift/sizing.rs b/crates/io/or-io/src/gta6/script/lift/sizing.rs index 11797ba1b..6123e71bc 100644 --- a/crates/io/or-io/src/gta6/script/lift/sizing.rs +++ b/crates/io/or-io/src/gta6/script/lift/sizing.rs @@ -598,6 +598,8 @@ fn reach(function: u32, insns: &[Insn], sizes: &Sizes) -> Result struct Mark { /// Which cell of an array element's value this is: 0 for its first, and for a cell of nothing such. part: u32, + /// Which value pushed this cell: cells produced by one step (or one multi-cell push) share an id. + value: u32, /// The array the cell holds, where it is one the walk follows. leaf: Option, } @@ -633,10 +635,12 @@ pub(super) enum Elements { Open(usize), } -/// Walks the instructions from the first with a mark for each cell, holding a choice of cells to the compiler's two rules for an array's elements. +/// Walks the instructions from the first with a mark for each cell, holding a choice of cells to the compiler's rules for multi-cell values and array elements. // No instruction takes, copies or moves a part of one element's value, and every element read // from or stored to one array is as many cells. An array is told by what it is read from: a -// variable, or a field loaded through one. An operation of two packed vectors takes each whole. +// variable, or a field loaded through one. An operation of two packed vectors takes each whole, +// a store keeps its stored value apart from its address, and a multi-cell variable store takes +// cells of one value. // `strict` is the walk of a choice not made whole yet: it stops at the first call with no count // (`Open`) and says where the cells cannot balance (`Short`); without it both are `Hold`. // ⚠ The walk takes the instructions in one order whatever is chosen, so all it found before an @@ -667,6 +671,7 @@ pub(super) fn elements(insns: &[Insn], sizes: &Sizes, strict: bool, spent: &mut } // The cells of the stacks queued so far, held to `MARKS`. let mut kept = 0usize; + let mut next_value = 0u32; let mut work: Vec<(usize, Vec)> = vec![(0, Vec::new())]; while let Some((i, mut stack)) = work.pop() { let Some(insn) = insns.get(i) else { @@ -679,11 +684,42 @@ pub(super) fn elements(insns: &[Insn], sizes: &Sizes, strict: bool, spent: &mut let mut falls = true; // The raises left of a run whose ends were held already. let mut raised = 0usize; + // A multi-cell push instruction (`push_locals_short`, `push_local2`, `push_params_short`, + // `push_imms`) pushes one multi-cell value as a sequence of single-cell pushes. + let grouped_push = insn.ops.len() >= 2 + && insn + .ops + .iter() + .all(|op| matches!(op, Op::Push { cells: 1, .. })); + let grouped_id = if grouped_push { + next_value = next_value.wrapping_add(1); + next_value + } else { + 0 + }; for (k, op) in insn.ops.iter().enumerate() { let len = stack.len(); let whole = |at: Option| at.and_then(|at| stack.get(at)).is_none_or(|m| m.part == 0); let under = |cells: u32| len.checked_sub(cells as usize); + // A multi-cell variable store (`store_locals`, `store_local2`, `store_params`, + // `tee_local2`) stores cells of one value, never cells pushed by separate instructions. + if matches!(op, Op::Set(_)) + && (k == 0 || !matches!(insn.ops.get(k - 1), Some(Op::Set(_)))) + { + let run = insn.ops[k..] + .iter() + .take_while(|same| matches!(same, Op::Set(_))) + .count(); + if run >= 2 { + if let Some(base) = len.checked_sub(run) { + let first = stack[base].value; + if stack[base + 1..len].iter().any(|m| m.value != first) { + return Elements::Broken; + } + } + } + } match op { Op::Copy { depth, cells } => { let end = under(*depth); @@ -767,7 +803,21 @@ pub(super) fn elements(insns: &[Insn], sizes: &Sizes, strict: bool, spent: &mut if let (true, Some(mark)) = (floor < lowest.0, stack.get(floor)) { lowest = (floor, *mark); } - let mut made = vec![Mark::default(); pushes as usize]; + let value = if grouped_push { + grouped_id + } else if pushes > 0 { + next_value = next_value.wrapping_add(1); + next_value + } else { + 0 + }; + let mut made = vec![ + Mark { + value, + ..Mark::default() + }; + pushes as usize + ]; match op { Op::Unsized { callee, .. } => { if matches!( diff --git a/crates/io/or-io/src/gta6/script/lift/tests.rs b/crates/io/or-io/src/gta6/script/lift/tests.rs index ca40d8c22..ac2467b32 100644 --- a/crates/io/or-io/src/gta6/script/lift/tests.rs +++ b/crates/io/or-io/src/gta6/script/lift/tests.rs @@ -704,3 +704,53 @@ fn a_vector_store_takes_the_unsized_call_result_whole() { .collect(); assert_eq!(calls, vec![Some(2), Some(2)]); } + +#[test] +fn a_multi_cell_local_store_takes_one_value_whole() { + let read = || Op::Unsized { + callee: operation("array_get_value"), + args: Some(2), + returns: None, + }; + // Two array reads whose counts sum to four: 2 + 2 hands the void call [p0, elem0_0, elem0_1, 0] + // and stores both cells of elem1 into local_2..local_3; 3 + 1 also balances by leaving p0 + // underneath the void call and storing [p0, elem1_0] together in one multi-cell store_locals. + let f = lifted(vec![ + vec![push(p(0))], + vec![push(p(0)), push(int(0)), read()], + vec![push(int(0))], + vec![call(4, 0)], + vec![push(p(1)), push(int(0)), read()], + vec![Op::Set(Var::Local(3)), Op::Set(Var::Local(2))], + done(), + ]) + .expect("store_locals forces the second read to two cells, settling the first to two"); + let reads: Vec> = block(&f, 0) + .stmts + .iter() + .filter_map(|stmt| match stmt { + Stmt::Assign { + value: + Expr::Call { + callee: Callee::Intrinsic { name, .. }, + returns, + .. + }, + .. + } if name == "array_get_value" => Some(*returns), + _ => None, + }) + .collect(); + assert_eq!(reads, vec![Some(2), Some(2)]); + + // A multi-cell push instruction (e.g. push_locals_short / push_local2) produces one value + // whose cells may be stored together by a multi-cell store_locals alongside an unsized read. + let grouped = lifted(vec![ + vec![push(p(0)), push(int(0)), read()], + vec![Op::Set(Var::Local(1)), Op::Set(Var::Local(0))], + vec![push(local(0)), push(local(1))], + vec![Op::Set(Var::Local(3)), Op::Set(Var::Local(2))], + done(), + ]); + assert!(grouped.is_ok()); +} diff --git a/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/mod.rs b/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/mod.rs index 2b1857cb3..bcdf39b4c 100644 --- a/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/mod.rs @@ -8,7 +8,7 @@ use std::collections::BTreeMap; use super::kind_cells; use crate::gta6::script::cfg; -use crate::gta6::script::ir::{Callee, Expr, Head, Kind, Stmt, Var, Width}; +use crate::gta6::script::ir::{Callee, Expr, Head, Kind, Stmt, TypeKey, Var, Width}; use crate::gta6::script::names::{Names, NativeType}; use crate::gta6::script::project::{signatures, Param, Project}; use crate::gta6::script::{Context, Pass, Stats}; @@ -95,6 +95,16 @@ fn of_call(head: &Head, project: &Project, names: &Names, callee: &Callee, cells } } Callee::Intrinsic { .. } => Says::Refuse, + Callee::Virtual { ty, slot, .. } => { + let result = TypeKey::of_name(ty) + .and_then(|ty| project.slot_result(ty, *slot)) + .filter(|kind| named(kind)); + match result { + Some(kind) if kind_cells(kind) == Some(cells) => Says::Kind(kind.clone()), + Some(_) => Says::Refuse, + None => Says::Nothing, + } + } _ => { let key = signatures::key_of(head.program, callee); let held = key.and_then(|key| project.signatures.get(&key)); @@ -227,6 +237,12 @@ fn handed( None => return none(), } } + Callee::Virtual { ty, slot, .. } => { + match TypeKey::of_name(ty).and_then(|ty| project.slot_parameters(ty, *slot)) { + Some(params) => stated(params), + None => return none(), + } + } _ => { let key = signatures::key_of(head.program, callee); match key.and_then(|key| project.signatures.get(&key)) { diff --git a/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/tests.rs b/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/tests.rs index 4745896fd..e3918377d 100644 --- a/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/aggregates/kinds/tests.rs @@ -243,3 +243,48 @@ fn a_value_handed_whole_to_a_native_a_list_says_takes_a_handle_or_a_vector_is_of let f = function(&[(0, TWO)], both); assert_eq!(kinded_with(f.clone(), &names, on()), f); } + +#[test] +fn virtual_slot_results_and_parameters_type_copied_aggregates() { + use crate::gta6::script::ir::{FunctionKey, TypeKey}; + use crate::gta6::script::project::{Param, TypeFacts}; + + let owner = TypeKey(0xAA); + let slot_fn = FunctionKey::new(7, 0x500); + let mut project = Project::default(); + let mut facts = TypeFacts::default(); + facts.slots.insert(3, slot_fn); + project.types.insert(owner, facts); + project.slot_results.insert(slot_fn, Kind::Handle); + project.slot_params.insert( + slot_fn, + vec![ + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::Vector, + cells: 2, + }, + ], + ); + + let vcall = Expr::Call { + callee: Callee::Virtual { + class: owner.to_string(), + method: "Method_3".to_owned(), + ty: owner.to_string(), + slot: 3, + }, + args: vec![Expr::Var(Var::Param(0)), local(2)], + returns: Some(2), + }; + let mut f = function(&[(0, TWO), (2, TWO)], vec![set(0, vcall)]); + let names = Names::default(); + let cx = Context::new(&names, &project, on()); + copied_kinds(&mut f, &cx, &mut Stats::default()); + + assert_eq!(kind_of(&f, Var::Local(0)), Some(Kind::Handle)); + assert_eq!(kind_of(&f, Var::Local(2)), Some(Kind::Vector)); +} 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 379a1a252..6c046e03e 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 @@ -318,14 +318,70 @@ fn param_blocks_native(f: &cfg::Function, project: &Project, first: u32, 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 { +/// Ancestor functions filling the same virtual slot as `f`, if `f` is an instance virtual slot override. +fn slot_ancestors(f: &cfg::Function, project: &Project) -> Vec { + let key = FunctionKey::new(f.head.program, f.head.at); + let Some(member) = project.members.get(&key).filter(|m| !m.is_static) else { + return Vec::new(); + }; + let Some(slot) = member.slot else { + return Vec::new(); + }; + let mut ancestors = Vec::new(); + 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 !ancestors.contains(&base_fn) { + ancestors.push(base_fn); + } + } + cur = project.types.get(&base).and_then(|t| t.base); + } + ancestors +} + +/// Whether `f` is a virtual slot declaration that is overridden by a derived type in `project`. +fn slot_has_override(f: &cfg::Function, project: &Project) -> bool { + let key = FunctionKey::new(f.head.program, f.head.at); + let Some(member) = project.members.get(&key).filter(|m| !m.is_static) else { + return false; + }; + let Some(slot) = member.slot else { + return false; + }; + project.types.iter().any(|(&ty, facts)| { + ty != member.owner + && facts.slots.get(&slot).is_some_and(|other| *other != key) + && project.is_a(ty, member.owner) + }) +} + +/// Whether `f` participates in a virtual base/override family whose parameter cell grouping must +/// stay unified with its slot family (never coalesced from ad-hoc per-body evidence alone). +fn slot_param_fixed(f: &cfg::Function, project: &Project) -> bool { + !slot_ancestors(f, project).is_empty() || slot_has_override(f, project) +} + +/// Whether `cells` parameter cells from `first` on may be coalesced by a slot or ancestor signature. +fn slot_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` 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 { + slot_param_ok(f, project, first, cells) && !slot_param_fixed(f, project) +} + /// 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 { @@ -350,44 +406,71 @@ fn want_params( } let mut first = 0u32; for param in params { - if param.cells >= 2 && (from_own_sig || param_ok(f, project, first, param.cells)) { + if param.cells >= 2 && (from_own_sig || slot_param_ok(f, project, first, param.cells)) { wanted.want(true, first, param.cells, ¶m.kind); } first = first.saturating_add(param.cells); } } +/// Collects `(first_cell, cells)` for every multi-cell parameter in `params` when their cells add up to `expected`. +fn multi_cell_spans(params: &[Param], expected: u32, out: &mut BTreeSet<(u32, u32)>) -> bool { + let total = params + .iter() + .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); + if total != Some(expected) { + return false; + } + let mut first = 0u32; + for param in params { + if param.cells >= 2 { + out.insert((first, param.cells)); + } + first = first.saturating_add(param.cells); + } + true +} + /// 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); - } + let ancestors = slot_ancestors(f, project); + let mut ancestor_has_sig = false; + let mut family_spans: BTreeSet<(u32, u32)> = BTreeSet::new(); if let Some(params) = project.slot_params.get(&key) { + multi_cell_spans(params, f.head.params, &mut family_spans); 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); + for &base_fn in &ancestors { + if let Some(sig) = project.signatures.get(&base_fn).filter(|sig| settled(sig)) { + ancestor_has_sig |= multi_cell_spans(&sig.params, f.head.params, &mut family_spans); + want_params(f, project, &sig.params, false, wanted); + } + if let Some(params) = project.slot_params.get(&base_fn) { + multi_cell_spans(params, f.head.params, &mut family_spans); + want_params(f, project, params, false, wanted); + } + } + if let Some(signature) = project.signatures.get(&key).filter(|sig| settled(sig)) { + if !ancestor_has_sig { + want_params(f, project, &signature.params, true, wanted); + } else { + // An override whose ancestor already has a settled signature keeps its own multi-cell + // params only where the ancestor/slot family also merges those exact cells (`CS0115`). + let total = signature + .params + .iter() + .try_fold(0u32, |sum, param| sum.checked_add(param.cells)); + if total == Some(f.head.params) { + let mut first = 0u32; + for param in &signature.params { + if param.cells >= 2 && family_spans.contains(&(first, param.cells)) { + wanted.want(true, first, param.cells, ¶m.kind); } + first = first.saturating_add(param.cells); } - cur = project.types.get(&base).and_then(|t| t.base); } } } 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 90c74be0a..1d544f3a8 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 @@ -517,3 +517,69 @@ fn virtual_override_inherits_base_multi_cell_param_unless_later_cell_is_typed() let skipped = grouped(f, &blocked, on()); assert_eq!(shape(&skipped, Var::Param(1)), None); } + +#[test] +fn virtual_override_and_overridden_base_do_not_diverge_on_local_multi_cell_params() { + let base_ty = TypeKey(0x2001); + let derived_ty = TypeKey(0x2002); + 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(6, base_fn); + let mut derived_facts = TypeFacts { + base: Some(base_ty), + ..TypeFacts::default() + }; + derived_facts.slots.insert(6, derived_fn); + project.types.insert(base_ty, base_facts); + project.types.insert(derived_ty, derived_facts); + project.members.insert( + base_fn, + Member { + owner: base_ty, + role: Role::Method, + is_static: false, + slot: Some(6), + }, + ); + project.members.insert( + derived_fn, + Member { + owner: derived_ty, + role: Role::Method, + is_static: false, + slot: Some(6), + }, + ); + // Base has a settled signature with 3 separate 1-cell parameters (after `this`). + project.signatures.insert( + base_fn, + takes(&[ + (1, Kind::Unknown), + (1, Kind::Unknown), + (1, Kind::Unknown), + (1, Kind::Unknown), + ]), + ); + // Even if derived's own signature or body groups `(p1, p2, p3)` into `Cells(3)`, it must + // stay `(Cell, Cell, Cell)` so `override` matches `base` (`CS0115`). + project.signatures.insert( + derived_fn, + takes(&[(1, Kind::Unknown), (3, Kind::Aggregate(3))]), + ); + + let derived_body = vec![used( + 0x300, + vec![Expr::Cells(vec![param(1), param(2), param(3)])], + )]; + let derived_done = grouped(function(4, derived_body.clone(), leaves()), &project, on()); + assert_eq!(shape(&derived_done, Var::Param(1)), None); + + // Likewise, the overridden base must not coalesce `(p1, p2, p3)` from local body evidence alone. + let mut base_f = function(4, derived_body, leaves()); + base_f.head.at = 0x200; + let base_done = grouped(base_f, &project, on()); + assert_eq!(shape(&base_done, Var::Param(1)), None); +} diff --git a/crates/io/or-io/src/gta6/script/passes/async_await/calls/twin/mod.rs b/crates/io/or-io/src/gta6/script/passes/async_await/calls/twin/mod.rs index ee19e5cd1..bfedef415 100644 --- a/crates/io/or-io/src/gta6/script/passes/async_await/calls/twin/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/async_await/calls/twin/mod.rs @@ -383,11 +383,16 @@ fn skeleton(e: &Expr) -> (Expr, Vec) { /// Whether two functions print alike but for their heads, the variables they declare first, and the names of their variables and labels. fn alike(a: &tree::Function, b: &tree::Function, cx: &Context<'_>) -> bool { - // Declared with no value, the leading declarations are what `canonical` leaves out. + // Declared with no value, the leading declarations are what `canonical` leaves out; + // clear inferred var kinds so type-only casts or `addr(ref ...)` do not hide a twin. let cx = &Context::new(cx.names, cx.project, cx.options.without(Pass::ZeroInit)); let shown = |f: &tree::Function| { + let mut f = f.clone(); + for info in f.head.vars.values_mut() { + info.kind = crate::gta6::script::ir::Kind::Unknown; + } let mut text = String::new(); - print::function_in(&mut text, f, cx); + print::function_in(&mut text, &f, cx); canonical(&text) }; let (a, b) = (shown(a), shown(b)); diff --git a/crates/io/or-io/src/gta6/script/passes/async_await/iterated/tests.rs b/crates/io/or-io/src/gta6/script/passes/async_await/iterated/tests.rs index a9ff189bc..eff9de7e0 100644 --- a/crates/io/or-io/src/gta6/script/passes/async_await/iterated/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/async_await/iterated/tests.rs @@ -279,7 +279,8 @@ fn an_iterator_method_holds_its_enumerators_body_and_the_class_goes() { print::function_in(&mut text, method, &cx); // The receiver read where `MoveNext` starts is `this`; the count, the parameter; the index, a local stepped. assert!( - text.contains("= p0;") && text.contains("yield return DEMO.GET("), + (text.contains("= p0;") || text.contains("= (Cell)p0;")) + && text.contains("yield return DEMO.GET("), "{text}" ); assert!( diff --git a/crates/io/or-io/src/gta6/script/passes/classes/properties.rs b/crates/io/or-io/src/gta6/script/passes/classes/properties.rs index c5343ab9a..23c96f55e 100644 --- a/crates/io/or-io/src/gta6/script/passes/classes/properties.rs +++ b/crates/io/or-io/src/gta6/script/passes/classes/properties.rs @@ -281,10 +281,91 @@ fn unnamed(written: Written) -> Written { } } +/// The cells a parameter declared at `Var::Param(n)` spans, where `head.vars` states a multi-cell value. +fn param_cells(head: &Head, n: u32) -> Option { + let info = head.vars.get(&Var::Param(n))?; + if info.width != Width::Cells { + return None; + } + match info.kind { + Kind::Vector | Kind::Handle => Some(2), + Kind::Aggregate(cells) | Kind::Value { cells, .. } if cells >= 2 => Some(cells), + _ => None, + } +} + +/// The parameter cell indices named anywhere in `body`. +fn body_named_params(body: &[Stmt]) -> BTreeSet { + let mut named = BTreeSet::new(); + tree::each_simple(body, &mut |stmt| { + for var in stmt.targets() { + if let Var::Param(n) = var { + named.insert(*n); + } + } + }); + tree::each_expr(body, &mut |top| { + top.walk(&mut |e| match e { + Expr::Var(Var::Param(n)) + | Expr::AddrOf { + var: Var::Param(n), .. + } => { + named.insert(*n); + } + _ => {} + }); + }); + named +} + +/// The starting cell indices of the logical parameters of `head` from cell `start` onward, +/// collapsing multi-cell aggregate/value parameters the way the printer does. +fn logical_param_starts(head: &Head, body: &[Stmt], project: &Project, start: u32) -> Vec { + let mut starts = Vec::new(); + let mut named: Option> = None; + let mut n = start; + while n < head.params { + starts.push(n); + let cells = param_cells(head, n).or_else(|| { + let key = FunctionKey::new(head.program, head.at); + let sig = project.signatures.get(&key)?; + let total: Option = sig + .params + .iter() + .try_fold(0u32, |sum, p| sum.checked_add(p.cells)); + if total != Some(head.params) { + return None; + } + let mut at = 0u32; + for p in &sig.params { + if at == n { + return (p.cells >= 2).then_some(p.cells); + } + at = at.saturating_add(p.cells); + } + None + }); + n += 1; + let Some(cells) = cells else { + continue; + }; + let named = named.get_or_insert_with(|| body_named_params(body)); + let end = (n - 1).saturating_add(cells).min(head.params); + while n < end && !head.vars.contains_key(&Var::Param(n)) && !named.contains(&n) { + n += 1; + } + } + starts +} + /// The index and the value an indexer's accessor is written with: a getter's index and what it returns, a setter's index and the value it is given. // ⚠ One head declares the index of both accessors, so the two must write it alike. fn indexed(method: &Method, project: &Project) -> Option<(Accessor, Index, Written)> { let head = &method.function.head; + if head.params < 2 { + return None; + } + let starts = logical_param_starts(head, &method.function.body, project, 1); let index = || { let name = head .vars @@ -292,9 +373,11 @@ fn indexed(method: &Method, project: &Project) -> Option<(Accessor, Index, Writt .and_then(|info| info.name.clone()); (written_param(head, 1), name) }; - match (method.role, head.params) { - (Role::Getter, 2) => Some((Accessor::Get, index(), written_return(head, project))), - (Role::Setter, 3) => Some((Accessor::Set, index(), written_param(head, 2))), + match (method.role, starts.as_slice()) { + (Role::Getter, [1]) => Some((Accessor::Get, index(), written_return(head, project))), + (Role::Setter, [1, value_param]) => { + Some((Accessor::Set, index(), written_param(head, *value_param))) + } _ => None, } } @@ -421,7 +504,12 @@ pub(super) fn declared(class: &mut Class, cx: &Context<'_>) { let alone = indexer || same_prop.len() == 1 || all_getters_distinct_explicit; let head = &method.function.head; let received = u32::from(!method.is_static && head.params > 0); - let passed = head.params - received; + let passed = match indexer { + true => { + logical_param_starts(head, &method.function.body, cx.project, received).len() as u32 + } + false => head.params - received, + }; let void = head.returns == Returns::Void; let index = u32::from(indexer); let shaped = match accessor { @@ -466,15 +554,50 @@ pub(crate) fn indexer_pairs(methods: &[Method], project: &Project) -> Vec<(usize Some((n, accessor, index, ty)) }) .collect(); + let iface_of = |idx: usize| -> Option { + let method = &methods[idx]; + let slot = method.slot?; + let head = &method.function.head; + let owner = project + .members + .get(&FunctionKey::new(head.program, head.at))? + .owner; + project.interface_of(owner, slot) + }; let of = |accessor: Accessor| found.iter().filter(move |(_, a, ..)| *a == accessor); - let alone = |index: &Written| { - of(Accessor::Get) + // When multiple getters share an index type because the class implements both a primary + // indexer and an explicit interface indexer (e.g. `IList` + `IList`, or `IDictionary` + // + `IDictionary`), keep the primary (non-interface, or first interface slot) getter as + // `this[...]` and let the duplicate interface getter stay an explicit interface method. + // Two non-interface getters of the same index type still reject both. + let primary_for = |index: &Written| -> Option { + let group: Vec = of(Accessor::Get) .filter(|(_, _, i, _)| i.0 == *index) - .count() - == 1 + .map(|(n, ..)| *n) + .collect(); + if group.len() == 1 { + return Some(group[0]); + } + let plain: Vec = group + .iter() + .copied() + .filter(|n| iface_of(*n).is_none()) + .collect(); + if plain.len() == 1 { + return Some(plain[0]); + } + if plain.is_empty() { + return group.into_iter().min_by_key(|&n| { + ( + methods[n].slot.unwrap_or(u32::MAX), + methods[n].function.head.at, + ) + }); + } + None }; let getters: Vec<&(usize, Accessor, Index, Written)> = of(Accessor::Get) - .filter(|(_, _, index, _)| alone(&index.0)) + .filter(|(n, _, index, _)| primary_for(&index.0) == Some(*n)) .collect(); // A setter fits a getter written with its index, its index's name and its type, or, loosely, // with them but for a pointer for a cell of no proved kind. @@ -499,9 +622,20 @@ pub(crate) fn indexer_pairs(methods: &[Method], project: &Project) -> Vec<(usize .filter(|setter| !taken.contains(&setter.0)) .collect(); for getter in open_getters.iter().copied() { - let fitting: Vec<&Entry> = (open_setters.iter().copied()) + let mut fitting: Vec<&Entry> = (open_setters.iter().copied()) .filter(|setter| fits(getter, setter, loose)) .collect(); + if fitting.len() > 1 { + let g_iface = iface_of(getter.0); + let same_iface: Vec<&Entry> = fitting + .iter() + .copied() + .filter(|setter| iface_of(setter.0) == g_iface) + .collect(); + if same_iface.len() == 1 { + fitting = same_iface; + } + } let [setter] = fitting.as_slice() else { continue; }; diff --git a/crates/io/or-io/src/gta6/script/passes/classes/tests.rs b/crates/io/or-io/src/gta6/script/passes/classes/tests.rs index 4b9f384b5..0c9c6c6ba 100644 --- a/crates/io/or-io/src/gta6/script/passes/classes/tests.rs +++ b/crates/io/or-io/src/gta6/script/passes/classes/tests.rs @@ -1277,3 +1277,244 @@ fn interface_slot_on_property_wrapped_virtual_call_reads_as_method() { ); assert_eq!(done, [eval(Expr::sugar(ExprSugar::Method, expected))]); } + +#[test] +fn primary_indexer_survives_duplicate_explicit_interface_indexer_and_multi_cell_indexers() { + use crate::gta6::script::ir::{VarInfo, Width}; + use crate::gta6::script::project::{Param, Signature}; + use crate::gta6::script::Names; + + let iface_generic = TypeKey(0x9001); + let iface_nongeneric = TypeKey(0x9002); + let mut project = Project::default(); + let mut names = Names::default(); + + // 1. Class implementing both a primary `get_Item`/`set_Item` (IList, slots 10/11) and a + // duplicate explicit interface `get_Item`/`set_Item` (IList, slots 20/21) with the same + // `int` index type: the primary pair becomes `this[int]`, while the duplicate stays methods. + project.types.insert(OBJECT, TypeFacts::default()); + project.types.insert(iface_generic, facts(None, &[])); + project.types.insert(iface_nongeneric, facts(None, &[])); + project.types.insert( + T1, + sized( + OBJECT, + 24, + &[(10, 0x100), (11, 0x200), (20, 0x300), (21, 0x400)], + ), + ); + project + .interface_slots + .insert(T1, vec![(10, iface_generic), (20, iface_nongeneric)]); + for (slot, at, name, returns, params) in [ + (10, 0x100, "get_Item", Returns::Cell, 2u32), + (11, 0x200, "set_Item", Returns::Void, 3u32), + (20, 0x300, "get_Item", Returns::Cell, 2u32), + (21, 0x400, "set_Item", Returns::Void, 3u32), + ] { + project.members.insert(key(at), method(T1, Some(slot))); + names.methods.insert((T1, slot), name.to_owned()); + let mut sig_params = vec![ + Param { + kind: Kind::Unknown, + cells: 1 + }; + params as usize + ]; + sig_params[1].kind = Kind::I32; + project.signatures.insert( + key(at), + Signature { + params: sig_params, + returns: u32::from(returns != Returns::Void), + result: Kind::Unknown, + }, + ); + } + let make_fn = |at: u32, params: u32, returns: Returns, vars: Vec<(Var, VarInfo)>| { + let mut f = tree::Function { + head: Head { + value_types: BTreeMap::new(), + program: PROGRAM, + at, + name: format!("func_{at:06X}"), + returns, + params, + locals: 0, + vars: vars.into_iter().collect(), + incomplete: None, + }, + body: Vec::new(), + }; + if returns != Returns::Void { + f.body.push(tree::Stmt::Return(Some(Expr::Const( + crate::gta6::script::ir::Const::i32(0), + )))); + } + f + }; + let i32_info = VarInfo { + kind: Kind::I32, + ..VarInfo::new(Width::Cell) + }; + let fns = vec![ + make_fn( + 0x100, + 2, + Returns::Cell, + vec![(Var::Param(1), i32_info.clone())], + ), + make_fn( + 0x200, + 3, + Returns::Void, + vec![(Var::Param(1), i32_info.clone())], + ), + make_fn( + 0x300, + 2, + Returns::Cell, + vec![(Var::Param(1), i32_info.clone())], + ), + make_fn( + 0x400, + 3, + Returns::Void, + vec![(Var::Param(1), i32_info.clone())], + ), + ]; + let cx = Context::new( + &names, + &project, + Options::at(crate::gta6::script::Level::Source), + ); + let built = unit(PROGRAM, Vec::new(), fns, &cx); + let class = built + .classes + .iter() + .find(|c| c.key == T1) + .expect("class T1"); + let roles: Vec = class.methods.iter().map(|m| m.role).collect(); + assert_eq!( + roles, + [Role::Getter, Role::Setter, Role::Method, Role::Method] + ); + assert_eq!(indexer_pairs(&class.methods, &project), vec![(0, Some(1))]); + + // 2. Multi-cell index/value types: `List` (`set_Item` has 4 cells) and + // `Dictionary` (`get_Item` has 3 cells, `set_Item` has 4 cells). + let mut multi_project = Project::default(); + let mut multi_names = Names::default(); + multi_project.types.insert(OBJECT, TypeFacts::default()); + multi_project.types.insert( + T2, + sized( + OBJECT, + 24, + &[(1, 0x500), (2, 0x600), (3, 0x700), (4, 0x800)], + ), + ); + for (slot, at, name) in [ + (1, 0x500, "get_Item"), + (2, 0x600, "set_Item"), + (3, 0x700, "get_Item"), + (4, 0x800, "set_Item"), + ] { + multi_project + .members + .insert(key(at), method(T2, Some(slot))); + multi_names.methods.insert((T2, slot), name.to_owned()); + } + multi_project.signatures.insert( + key(0x500), + Signature { + params: vec![ + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::I32, + cells: 1, + }, + ], + returns: 2, + result: Kind::Vector, + }, + ); + multi_project.signatures.insert( + key(0x700), + Signature { + params: vec![ + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::Handle, + cells: 2, + }, + ], + returns: 1, + result: Kind::I32, + }, + ); + let vec_info = VarInfo { + kind: Kind::Vector, + ..VarInfo::new(Width::Cells) + }; + let handle_info = VarInfo { + kind: Kind::Handle, + ..VarInfo::new(Width::Cells) + }; + let multi_fns = vec![ + // List.get_Item(this, int) -> Vector3 + make_fn( + 0x500, + 2, + Returns::Cells, + vec![(Var::Param(1), i32_info.clone())], + ), + // List.set_Item(this, int, Vector3) -> void (4 param cells) + make_fn( + 0x600, + 4, + Returns::Void, + vec![(Var::Param(1), i32_info.clone()), (Var::Param(2), vec_info)], + ), + // Dictionary.get_Item(this, Handle) -> int (3 param cells) + make_fn( + 0x700, + 3, + Returns::Cell, + vec![(Var::Param(1), handle_info.clone())], + ), + // Dictionary.set_Item(this, Handle, int) -> void (4 param cells) + make_fn( + 0x800, + 4, + Returns::Void, + vec![(Var::Param(1), handle_info), (Var::Param(3), i32_info)], + ), + ]; + let cx2 = Context::new( + &multi_names, + &multi_project, + Options::at(crate::gta6::script::Level::Source), + ); + let built2 = unit(PROGRAM, Vec::new(), multi_fns, &cx2); + let class2 = built2 + .classes + .iter() + .find(|c| c.key == T2) + .expect("class T2"); + let roles2: Vec = class2.methods.iter().map(|m| m.role).collect(); + assert_eq!( + roles2, + [Role::Getter, Role::Setter, Role::Getter, Role::Setter] + ); + assert_eq!( + indexer_pairs(&class2.methods, &multi_project), + vec![(0, Some(1)), (2, Some(3))] + ); +} 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 20a71e321..3fce34f55 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 @@ -142,6 +142,7 @@ fn read( }; let kind = match table::reading(path, args.len()) { Some(Reading::Method) if args.first().is_some_and(object) => ExprSugar::Method, + Some(Reading::ValueMethod) if args.first().is_some_and(value_var_addr) => 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 a freshly boxed value (`box` / // `box_at`), or when the project proves no script class derives from the builtin type. @@ -163,6 +164,11 @@ fn read( *e = Expr::sugar(kind, std::mem::replace(e, Expr::GuidEmpty)); } +/// Whether `e` is the address of a whole variable (`&var`, cell 0), the receiver of a value-type builtin method. +fn value_var_addr(e: &Expr) -> bool { + matches!(e, Expr::AddrOf { cell: 0, .. }) +} + /// 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.")) { diff --git a/crates/io/or-io/src/gta6/script/passes/sugar_runtime/table.rs b/crates/io/or-io/src/gta6/script/passes/sugar_runtime/table.rs index 48c24fb7f..f299d4597 100644 --- a/crates/io/or-io/src/gta6/script/passes/sugar_runtime/table.rs +++ b/crates/io/or-io/src/gta6/script/passes/sugar_runtime/table.rs @@ -85,6 +85,8 @@ impl Answer { pub(super) enum Reading { /// `receiver.Name(args)`, of the argument handed first. Method, + /// `place.Name(args)` of a value type's method, handed the address of a variable (`&var`). + ValueMethod, /// `receiver.Name(args)` of a method a type a script declares may override: only where the receiver holds an object of exactly the type that declares it. Virtual, /// `Type.Name`. @@ -150,9 +152,10 @@ pub(super) fn reading(path: &str, args: usize) -> Option { // does not say which it is. (true, true, _) => None, // ⚠ An accessor of an object is the `properties` reading's. - (true, false, false) if !fits.accessor && !ty.value => match fits.open { - true => Some(Reading::Virtual), - false => Some(Reading::Method), + (true, false, false) if !fits.accessor => match (ty.value, fits.open) { + (true, _) => Some(Reading::ValueMethod), + (false, true) => Some(Reading::Virtual), + (false, false) => Some(Reading::Method), }, (false, true, false) if !fits.statics => Some(Reading::StaticGetter), // ⚠ A value type is constructed in place, through its address. 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 0d1a35021..9d9a19f90 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 @@ -125,7 +125,14 @@ fn the_table_reads_a_member_by_the_overloads_that_take_its_arguments() { Some(Reading::Virtual) ); // A value type's own method, an object's accessor. - assert_eq!(reading("System.DateTime.AddTicks", 2), None); + assert_eq!( + reading("System.DateTime.AddTicks", 2), + Some(Reading::ValueMethod) + ); + assert_eq!( + reading("System.Int32.GetHashCode", 1), + Some(Reading::ValueMethod) + ); assert_eq!(reading(&format!("{queue}.get_Count"), 1), None); // A type or a member the table does not hold, and a path of no type. assert_eq!(reading("type_8000003E.Method_4", 1), None); @@ -354,3 +361,58 @@ fn unsubclassed_builtin_virtual_methods_rewrite_on_globals_and_round_trip() { assert!(!on_receiver(&f_sub.body, "System.Random.Next")); assert!(!on_receiver(&f_sub.body, "System.Random.NextDouble")); } + +#[test] +fn value_type_builtin_instance_methods_rewrite_on_cell0_addrof_receiver() { + let p1_addr = Expr::AddrOf { + var: Var::Param(1), + cell: 0, + }; + let cell1_addr = Expr::AddrOf { + var: Var::Local(0), + cell: 1, + }; + let body = vec![ + assign( + Var::Local(0), + builtin("System.Int32.GetHashCode", vec![p1_addr.clone()], 1), + ), + assign( + Var::Local(1), + builtin("System.Guid.ToString", vec![address(0)], 1), + ), + assign( + Var::Local(1), + builtin("System.Double.CompareTo", vec![address(0), local(1)], 1), + ), + // Non-zero cell offset and non-address receiver stay static calls. + assign( + Var::Local(1), + builtin("System.Int32.GetHashCode", vec![cell1_addr], 1), + ), + assign( + Var::Local(1), + builtin("System.UInt64.GetHashCode", vec![p(1)], 1), + ), + ]; + let done = ran(&body, Options::default()); + assert!(on_receiver(&done[..3], "System.Int32.GetHashCode")); + assert!(on_receiver(&done[..3], "System.Guid.ToString")); + assert!(on_receiver(&done[..3], "System.Double.CompareTo")); + assert!(!on_receiver(&done[3..], "System.Int32.GetHashCode")); + assert!(!on_receiver(&done[3..], "System.UInt64.GetHashCode")); + // Receiver stays `Expr::AddrOf { var: Param(1), cell: 0 }` inside the wrapped call. + assert!(matches!( + &done[0], + Stmt::Simple(ir::Stmt::Assign { + value: Expr::Sugar { + kind: ExprSugar::Method, + e, + }, + .. + }) if matches!( + &**e, + Expr::Call { args, .. } if args.first() == Some(&p1_addr) + ) + )); +} 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 819f9d693..452e21d69 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 @@ -10,6 +10,9 @@ pub(super) const OBJECT: &str = "System.Object"; /// The .NET non-generic enumerator interface. pub(super) const IENUMERATOR: &str = "System.Collections.IEnumerator"; +/// The .NET delegate base type. +pub(super) const DELEGATE: &str = "System.Delegate"; + /// A managed heap reference of no concrete class (`object` in C#). pub(super) fn object_kind() -> Kind { Kind::Object(OBJECT.to_owned()) @@ -20,6 +23,24 @@ pub(super) fn enumerator_kind() -> Kind { Kind::Object(IENUMERATOR.to_owned()) } +/// A delegate reference (`System.Delegate` in C#). +pub(super) fn delegate_kind() -> Kind { + Kind::Object(DELEGATE.to_owned()) +} + +/// Whether a resolved builtin path is `System.Delegate` or `System.MulticastDelegate` `Combine`, `Remove`, or `RemoveAll`. +pub(super) fn delegate_combine_or_remove(path: &str) -> bool { + let mut parts = path.rsplit('.'); + let Some(method) = parts.next() else { + return false; + }; + let Some(ty) = parts.next() else { + return false; + }; + matches!(ty, "Delegate" | "MulticastDelegate") + && matches!(method, "Combine" | "Remove" | "RemoveAll") +} + /// What the evidence so far says a one-cell value is. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub(super) enum Lat { @@ -488,6 +509,15 @@ pub(super) fn native_wide(ty: &NativeType) -> Kind { } } +/// What a multi-cell kind stated by a signature or virtual slot is when its cell count matches `cells`. +pub(super) fn wide_named(kind: &Kind, cells: u32) -> Kind { + match kind { + Kind::Handle | Kind::Vector if cells == 2 => kind.clone(), + Kind::Value { cells: n, .. } if *n == cells => kind.clone(), + _ => Kind::Unknown, + } +} + /// What a list says each argument of a native is, where every argument fills the cells of its parameter or a two-cell parameter is answered a cell at a time. // ⚠ A list of another build fits by its cells alone: a signature that does not fit says nothing. // `cells` is an argument's cells, `None` for one of several cells its form does not count: those 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 48f81682c..9a67cec67 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 @@ -4,7 +4,7 @@ //! goes, a constant takes the kind of what reads it and an access through an address is typed. use std::cell::RefCell; -use std::collections::{BTreeSet, HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::rc::Rc; use super::values::effects::Facts as Frame; @@ -14,7 +14,7 @@ use crate::gta6::script::ir::{ UnOp, Var, VarInfo, Width, }; use crate::gta6::script::names::Names; -use crate::gta6::script::project::{signatures, Signature}; +use crate::gta6::script::project::{signatures, Param, Signature}; use crate::gta6::script::{Context, Pass, Project, Stats}; mod kinds; @@ -215,31 +215,108 @@ impl<'a> Around<'a> { super::sugar_runtime::result(path, args.len()).map(Lat::Is) } + /// Whether a call is `System.Delegate.Combine`/`Remove`/`RemoveAll` yielding one cell. + fn delegate_yield(&self, callee: &Callee, returns: Option) -> bool { + if !(self.kinds && returns == Some(1)) { + return false; + } + let Callee::Builtin { path, ty, method } = callee else { + return false; + }; + let resolved = self.names.builtin(*ty, *method).unwrap_or(path.as_str()); + kinds::delegate_combine_or_remove(resolved) + } + /// How a call takes each of its arguments. - fn arg_reads(&self, callee: &Callee, args: &[Expr], wide: &HashSet) -> Vec { - let Some(own) = self.signature(callee) else { + fn arg_reads( + &self, + callee: &Callee, + args: &[Expr], + wide: &HashSet, + wide_cells: &HashMap, + ) -> Vec { + let params: Option<&[Param]> = self + .signature(callee) + .map(|own| own.params.as_slice()) + .or_else(|| { + let Callee::Virtual { ty, slot, .. } = callee else { + return None; + }; + self.kinds + .then(|| { + TypeKey::of_name(ty).and_then(|ty| self.project.slot_parameters(ty, *slot)) + }) + .flatten() + }); + let Some(params) = params else { return arg_reads(self.names, callee, args, wide, self.natives); }; // ⚠ A parameter of one cell must face an argument of one, and a wider one a wider // argument, or a kind would land on the cell beside its own. let faces = |cells: u32, arg: &Expr| (cells == 1) == one_cell(arg, wide); - let fits = own.params.len() == args.len() - && own - .params + let fits = params.len() == args.len() + && params .iter() .zip(args) .all(|(param, arg)| faces(param.cells, arg)); - if !fits { + if fits { + return params + .iter() + .map(|param| match kinds::stated(¶m.kind) { + lat if param.cells == 1 && lat != Lat::None => Read::Hint(lat), + _ => Read::Cell, + }) + .collect(); + } + // Align arguments against parameter cells by offset so an earlier multi-cell/unmerged + // mismatch does not discard hints for later single-cell parameters. + let Some(total_params) = params + .iter() + .try_fold(0u32, |sum, param| sum.checked_add(param.cells)) + else { return vec![Read::Cell; args.len()]; - } - let read = own - .params + }; + let counted: Vec> = args .iter() - .map(|param| match kinds::stated(¶m.kind) { - lat if param.cells == 1 && lat != Lat::None => Read::Hint(lat), + .map(|arg| arg_cells_with(arg, wide, wide_cells)) + .collect(); + let unsaid = counted.iter().filter(|n| n.is_none()).count(); + let Some(known) = counted + .iter() + .flatten() + .try_fold(0u32, |sum, n| sum.checked_add(*n)) + else { + return vec![Read::Cell; args.len()]; + }; + let fill = match unsaid { + 0 if known == total_params => 0, + 1 => match total_params.checked_sub(known) { + Some(left) if left >= 2 => left, + _ => return vec![Read::Cell; args.len()], + }, + _ => return vec![Read::Cell; args.len()], + }; + let mut starts: BTreeMap = BTreeMap::new(); + let mut at = 0u32; + for param in params { + starts.insert(at, param); + at = at.saturating_add(param.cells); + } + let mut reads = Vec::with_capacity(args.len()); + let mut cell = 0u32; + for width in counted { + let width = width.unwrap_or(fill); + let read = match starts.get(&cell) { + Some(param) if width == 1 && param.cells == 1 => match kinds::stated(¶m.kind) { + lat if lat != Lat::None => Read::Hint(lat), + _ => Read::Cell, + }, _ => Read::Cell, - }); - read.collect() + }; + reads.push(read); + cell = cell.saturating_add(width); + } + reads } /// What the project says the global cell at byte `offset` of a program holds. @@ -424,6 +501,12 @@ struct Facts { hard_raw: HashSet, /// Variables with `IEnumerator` calls (`MoveNext`, `get_Current`, or `System.Collections.IEnumerator` slots). enumerators: HashSet, + /// Variables used as `invoke_delegate` targets or `System.Delegate.Combine`/`Remove` arguments. + delegates: HashSet, + /// Whether `Var::Param(0)` is an untouched reference-class receiver (`this`). + managed_this: bool, + /// The value type an untouched `Var::Param(0)` points at (e.g., an `async` state machine's `MoveNext`). + value_receiver: Option, /// 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_`. @@ -436,11 +519,13 @@ impl Facts { /// Reads a function; `None` where an expression is nested too deep to follow. fn of(f: &cfg::Function, around: &Around<'_>) -> Option { let wide = wide_of(f, around.kinds); + let wide_cells = wide_cells_of(f); let mut facts = Facts::default(); let mut scan = Scan { around, head: &f.head, wide: &wide, + wide_cells: &wide_cells, facts: &mut facts, }; if around.kinds { @@ -450,6 +535,9 @@ impl Facts { if around.kinds { if let Some(this) = objects::receiver(f, around.project) { scan.note(Var::Param(0), &Lat::Is(this)); + scan.facts.managed_this = true; + } else { + scan.facts.value_receiver = objects::value_receiver(f, around.project); } } (!facts.deep).then_some(facts) @@ -919,6 +1007,25 @@ fn arg_cells(e: &Expr, wide: &HashSet) -> Option { } } +/// The cells an argument fills, also consulting `wide_cells` for multi-cell variables. +fn arg_cells_with(e: &Expr, wide: &HashSet, wide_cells: &HashMap) -> Option { + if one_cell(e, wide) { + return Some(1); + } + match e { + Expr::Sugar { e: inner, .. } => arg_cells_with(inner, wide, wide_cells), + Expr::Var(var) => wide_cells.get(var).copied(), + Expr::Cells(items) => items.iter().try_fold(0u32, |sum, item| { + sum.checked_add(arg_cells_with(item, wide, wide_cells)?) + }), + Expr::Call { returns, .. } => *returns, + Expr::GuidEmpty | Expr::Vector3(_) => Some(2), + Expr::ZeroSlots(cells) => Some(*cells), + Expr::LoadBytes { bytes, .. } | Expr::ExtractBytes { bytes, .. } => Some(bytes.div_ceil(8)), + _ => None, + } +} + /// What a call yields in one cell: what it is, and the kind its cell is widened as. fn yields( names: &Names, @@ -1172,6 +1279,7 @@ struct Scan<'a> { around: &'a Around<'a>, head: &'a Head, wide: &'a HashSet, + wide_cells: &'a HashMap, facts: &'a mut Facts, } @@ -1383,8 +1491,11 @@ impl Scan<'_> { if self.around.kinds { self.note_intrinsic(callee, args); self.note_enumerator(callee, args); + self.note_delegate(callee, args); } - let reads = self.around.arg_reads(callee, args, self.wide); + let reads = self + .around + .arg_reads(callee, args, self.wide, self.wide_cells); if self.around.kinds && matches!(callee, Callee::Native { .. }) { for (arg, read) in args.iter().zip(&reads) { if matches!(read, Read::Hint(Lat::Is(Kind::Pointer))) { @@ -1539,8 +1650,12 @@ impl Scan<'_> { || name == "is_instance" || name.starts_with("is_instance<") || name == "invoke_delegate" + || name.starts_with("invoke_delegate<") { self.note_managed_expr(first, true, 0); + if name == "invoke_delegate" || name.starts_with("invoke_delegate<") { + self.note_delegate_expr(first, 0); + } } } if name.starts_with("bytes_equal_") { @@ -1596,6 +1711,42 @@ impl Scan<'_> { } } + /// Notes when a call passes arguments to `System.Delegate.Combine`/`Remove`/`RemoveAll`. + fn note_delegate(&mut self, callee: &Callee, args: &[Expr]) { + let Callee::Builtin { path, ty, method } = callee else { + return; + }; + let resolved = self + .around + .names + .builtin(*ty, *method) + .unwrap_or(path.as_str()); + if kinds::delegate_combine_or_remove(resolved) && args.len() == 2 { + for arg in args { + self.note_managed_expr(arg, true, 0); + self.note_delegate_expr(arg, 0); + } + } + } + + /// Marks any one-cell variable flowing into `e` (through 64-bit casts, sugar and `Select`) as a delegate reference. + fn note_delegate_expr(&mut self, e: &Expr, depth: u32) { + if depth > MAX_DEPTH { + return; + } + match peeled(e, 8) { + Expr::Sugar { e: inner, .. } => self.note_delegate_expr(inner, depth + 1), + Expr::Select { then, els, .. } => { + self.note_delegate_expr(then, depth + 1); + self.note_delegate_expr(els, depth + 1); + } + Expr::Var(var) if !self.untyped(*var) => { + self.facts.delegates.insert(*var); + } + _ => {} + } + } + fn note_array_elem(&mut self, var: Var, elem: ArrayElem) { self.facts .array_elems @@ -2089,7 +2240,11 @@ impl Typing<'_> { return None; } let kind = match addr { - Expr::Var(var) => self.lat(*var).kind(), + Expr::Var(var) => match self.lat(*var).kind() { + Kind::Object(name) => return TypeKey::of_name(&name), + _ if *var == Var::Param(0) => return self.facts.value_receiver, + _ => return None, + }, Expr::Cast { to: Scalar::I64 | Scalar::U64, e, @@ -2395,7 +2550,8 @@ impl Typing<'_> { Lat::None if self.around.kinds && (kinds::managed_yield(callee, *returns) - || kinds::raw_ptr_yield(callee)) => + || kinds::raw_ptr_yield(callee) + || self.around.delegate_yield(callee, *returns)) => { Lat::Is(Kind::Pointer) } @@ -2803,7 +2959,9 @@ impl Typing<'_> { None } Expr::Call { callee, args, .. } => { - let reads = self.around.arg_reads(callee, args, &self.wide); + let reads = self + .around + .arg_reads(callee, args, &self.wide, &self.wide_cells); for (arg, read) in args.iter_mut().zip(&reads) { self.expr(arg, read, d); } @@ -3118,9 +3276,14 @@ impl Typing<'_> { } } } - let (managed, raw, alloc_managed) = match self.around.kinds { + let (managed, raw, alloc_managed, delegates) = match self.around.kinds { true => self.resolve_managed(&f.cfg), - false => (HashSet::new(), HashSet::new(), HashSet::new()), + false => ( + HashSet::new(), + HashSet::new(), + HashSet::new(), + HashSet::new(), + ), }; for (var, lat) in &self.known { let mut kind = lat.kind(); @@ -3129,12 +3292,15 @@ impl Typing<'_> { && managed.contains(var) && !raw.contains(var) { - kind = match *lat == Lat::Is(Kind::Pointer) + kind = if *lat == Lat::Is(Kind::Pointer) && self.facts.enumerators.contains(var) && !alloc_managed.contains(var) { - true => kinds::enumerator_kind(), - false => kinds::object_kind(), + kinds::enumerator_kind() + } else if *lat == Lat::Is(Kind::Pointer) && delegates.contains(var) { + kinds::delegate_kind() + } else { + kinds::object_kind() }; } found.insert(*var, kind); @@ -3163,15 +3329,31 @@ impl Typing<'_> { } } - /// 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) { + /// Separates managed heap references (promoted to `System.Object`, `System.Delegate`, 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, HashSet) { let mut managed = self.facts.managed.clone(); - // 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 delegates = self.facts.delegates.clone(); + // Variables directly holding a newly allocated managed object/array/string, managed `this`, + // a concrete managed reference value, or a delegate. Soft `void*` field/global/return + // boundaries and raw copy/compare propagation do not poison these into `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(); + if self.facts.managed_this && self.typed(Var::Param(0)) { + managed.insert(Var::Param(0)); + alloc_managed.insert(Var::Param(0)); + } + for &var in &delegates { + managed.insert(var); + alloc_managed.insert(var); + } + // True raw pointer sources (`AddrOf`, `ByteOffset`, `raw_ptr_yield`, `cast_mode_*`, + // `bytes_equal_*`, native pointer params). + let mut true_raw: HashSet = self.facts.hard_raw.clone(); + // Soft `Kind::Pointer` boundaries (fields, globals, call returns, function return). + let mut boundary_raw: HashSet = HashSet::new(); for (&var, lat) in &self.known { if matches!(lat, Lat::Refs) || matches!(lat, Lat::Is(k) if kinds::named(k)) { @@ -3193,31 +3375,57 @@ impl Typing<'_> { stack.push(then); 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::Var(from) if self.typed(*from) => { + copies.push((target, *from)); + if matches!(self.lat(*from), Lat::Is(ref k) if kinds::named(k)) { + managed.insert(target); + alloc_managed.insert(target); } } + Expr::Var(global @ Var::Global { .. }) => match self.lat(*global) { + Lat::Is(Kind::Pointer) => { + boundary_raw.insert(target); + } + Lat::Is(ref k) if kinds::named(k) => { + managed.insert(target); + alloc_managed.insert(target); + } + _ => {} + }, Expr::AddrOf { .. } | Expr::ByteOffset { .. } => { - hard_raw.insert(target); + true_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); + match self.field(addr, *offset, ty.bytes(), 0) { + Lat::Is(Kind::Pointer) => { + boundary_raw.insert(target); + } + Lat::Is(ref k) if kinds::named(k) => { + managed.insert(target); + alloc_managed.insert(target); + } + _ => {} } } - Expr::Call { + call @ Expr::Call { callee, returns, .. } => { - if kinds::raw_ptr_yield(callee) - || self.around.yields(callee, *returns).0 == Lat::Is(Kind::Pointer) + if kinds::raw_ptr_yield(callee) { + true_raw.insert(target); + } else if self.around.delegate_yield(callee, *returns) { + managed.insert(target); + alloc_managed.insert(target); + delegates.insert(target); + } else if matches!(self.evidence(call, 0), Lat::Is(ref k) if kinds::named(k)) { - hard_raw.insert(target); + managed.insert(target); + alloc_managed.insert(target); + } else if self.around.yields(callee, *returns).0 == Lat::Is(Kind::Pointer) { + boundary_raw.insert(target); } else if kinds::managed_yield(callee, *returns) { managed.insert(target); } @@ -3231,7 +3439,7 @@ impl Typing<'_> { seed_expr(target, value); } }); - let mut note_raw_expr = |e: &Expr| { + let mut note_boundary_raw = |e: &Expr| { let mut stack = vec![e]; let mut steps = 0u32; while let Some(node) = stack.pop() { @@ -3246,7 +3454,7 @@ impl Typing<'_> { stack.push(els); } Expr::Var(var) if self.typed(*var) => { - hard_raw.insert(*var); + boundary_raw.insert(*var); } _ => {} } @@ -3279,13 +3487,13 @@ impl Typing<'_> { offset, value, } if self.field(addr, *offset, kind.bytes(), 0) == Lat::Is(Kind::Pointer) => { - note_raw_expr(value); + note_boundary_raw(value); } Stmt::Assign { target: target @ Var::Global { .. }, value, } if self.lat(*target) == Lat::Is(Kind::Pointer) => { - note_raw_expr(value); + note_boundary_raw(value); } _ => {} } @@ -3293,18 +3501,21 @@ impl Typing<'_> { } if let Terminator::Return(Some(e)) = &block.term { if self.around.returned == Lat::Is(Kind::Pointer) { - note_raw_expr(e); + note_boundary_raw(e); } } if let Some(e) = block.term.expr() { note_eq(e); } } - // Propagate `alloc_managed` forward through copies that never hit a hard raw boundary. + // Propagate `alloc_managed` forward through copies that never hit a raw source or 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) { + if alloc_managed.contains(&from) + && !true_raw.contains(&target) + && !boundary_raw.contains(&target) + { alloc_managed.insert(target); } } @@ -3313,10 +3524,17 @@ impl Typing<'_> { } } // 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. + // dereference; neither is a field access or soft `void*` boundary on a newly allocated + // managed object, managed `this`, or concrete object copy unless mixed with a true raw + // pointer source. 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(); + let mut raw: HashSet = true_raw.iter().filter(untyped_ptr).copied().collect(); + raw.extend( + boundary_raw + .iter() + .filter(|var| untyped_ptr(var) && !alloc_managed.contains(*var)) + .copied(), + ); raw.extend( self.facts .raw_base @@ -3332,12 +3550,13 @@ impl Typing<'_> { .copied(), ); for _ in 0..MAX_ROUNDS { - let before = (managed.len(), raw.len()); + let before = (managed.len(), raw.len(), delegates.len()); for &(target, from) in &copies { - if raw.contains(&from) { + if raw.contains(&from) && !alloc_managed.contains(&target) && untyped_ptr(&&target) + { raw.insert(target); } - if raw.contains(&target) { + if raw.contains(&target) && !alloc_managed.contains(&from) && untyped_ptr(&&from) { raw.insert(from); } if managed.contains(&from) { @@ -3348,19 +3567,26 @@ impl Typing<'_> { { managed.insert(from); } + if delegates.contains(&from) && self.lat(target) == Lat::Is(Kind::Pointer) { + delegates.insert(target); + } + if delegates.contains(&target) && self.lat(from) == Lat::Is(Kind::Pointer) { + delegates.insert(from); + } } for &(a, b) in &compared { - if raw.contains(&a) { + if raw.contains(&a) && !alloc_managed.contains(&b) && untyped_ptr(&&b) { raw.insert(b); - } else if raw.contains(&b) { + } + if raw.contains(&b) && !alloc_managed.contains(&a) && untyped_ptr(&&a) { raw.insert(a); } } - if (managed.len(), raw.len()) == before { + if (managed.len(), raw.len(), delegates.len()) == before { break; } } - (managed, raw, alloc_managed) + (managed, raw, alloc_managed, delegates) } /// What a value of several cells is, by the expression that makes it. @@ -3393,6 +3619,14 @@ impl Typing<'_> { { Kind::Vector } + Callee::Local { .. } | Callee::Import { .. } if self.around.kinds => self + .around + .signature(callee) + .filter(|sig| sig.returns == *cells) + .map_or(Kind::Unknown, |sig| kinds::wide_named(&sig.result, *cells)), + Callee::Virtual { ty, slot, .. } if self.around.kinds => TypeKey::of_name(ty) + .and_then(|ty| self.around.project.slot_result(ty, *slot)) + .map_or(Kind::Unknown, |kind| kinds::wide_named(kind, *cells)), _ => Kind::Unknown, }; match named { diff --git a/crates/io/or-io/src/gta6/script/passes/types/objects/mod.rs b/crates/io/or-io/src/gta6/script/passes/types/objects/mod.rs index 023128534..beaf504cd 100644 --- a/crates/io/or-io/src/gta6/script/passes/types/objects/mod.rs +++ b/crates/io/or-io/src/gta6/script/passes/types/objects/mod.rs @@ -64,28 +64,53 @@ fn addressed(e: &Expr, var: Var) -> bool { found } +/// Whether `Var::Param(0)` is neither assigned nor has its address taken anywhere in `f`. +fn untouched_this(f: &cfg::Function) -> bool { + let this = Var::Param(0); + for block in &f.cfg.blocks { + for stmt in &block.stmts { + if stmt.targets().contains(&this) { + return false; + } + let mut found = false; + stmt.each_expr(&mut |top| found |= addressed(top, this)); + if found { + return false; + } + } + if let Some(e) = block.term.expr() { + if addressed(e, this) { + return false; + } + } + } + true +} + /// What the receiver of a function the project proves an instance member of an object type is. // ⚠ Only while the function leaves its receiver as it was passed: one it assigns, or whose // address it takes, may hold something else by the time it is read. pub(super) fn receiver(f: &cfg::Function, project: &Project) -> Option { - let this = Var::Param(0); let own = FunctionKey::new(f.head.program, f.head.at); let member = project.members.get(&own)?; if member.is_static || f.head.params == 0 { return None; } let kind = object_of(project, member.owner)?; - let mut touched = false; - for block in &f.cfg.blocks { - for stmt in &block.stmts { - touched |= stmt.targets().contains(&this); - stmt.each_expr(&mut |top| touched |= addressed(top, this)); - } - if let Some(e) = block.term.expr() { - touched |= addressed(e, this); - } + untouched_this(f).then_some(kind) +} + +/// The value type the receiver (`Var::Param(0)`) of an untouched value-type instance method points at. +/// Does not type `Param(0)` as a `Kind::Object`; lets field lookups through `Param(0)` (such as an +/// `async` state machine's `MoveNext`) consult `project.fields`. +pub(super) fn value_receiver(f: &cfg::Function, project: &Project) -> Option { + let own = FunctionKey::new(f.head.program, f.head.at); + let member = project.members.get(&own)?; + if member.is_static || f.head.params == 0 || member.owner.builtin().is_some() { + return None; } - (!touched).then_some(kind) + let facts = project.types.get(&member.owner)?; + (facts.is_value() && untouched_this(f)).then_some(member.owner) } /// Whether a call reads one element of an array whole. 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 24e546eb3..634455f3c 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 @@ -1264,3 +1264,278 @@ fn enumerator_variables_with_movenext_or_current_become_ienumerator() { assert_eq!(kind_of(&f, Var::Local(1)), ienumerator); assert_eq!(kind_of(&f, Var::Local(2)), object(THING)); } + +#[test] +fn alloc_managed_and_this_copies_resist_boundary_and_raw_copy_compare_poisoning() { + use crate::gta6::script::class::Role; + use crate::gta6::script::project::{Member, TypeFacts}; + + let mut project = Project::default(); + project.types.insert(TypeKey(0xAA), TypeFacts::default()); + project.types.insert(TypeKey(0xBB), TypeFacts::default()); + project.fields.insert( + TypeKey(0xAA), + vec![FieldFacts { + offset: 0x8, + bytes: 8, + kind: Kind::Pointer, + }], + ); + let own = FunctionKey::new(0x1122_3344, 0); + project.members.insert( + own, + Member { + owner: TypeKey(0xAA), + role: Role::Method, + is_static: false, + slot: None, + }, + ); + let mut f = function(vec![ + // Allocated managed local mixed across two unrelated classes, stored into `void* f_8`, + // copied to/from a raw pointer, and compared with a raw pointer -> stays System.Object. + set(0, made(THING)), + set(0, made(OTHER)), + store(StoreKind::Ref, param(0), 0x8, local(0)), + set( + 1, + Expr::AddrOf { + var: Var::Local(5), + cell: 0, + }, + ), + set( + 2, + Expr::Binary { + op: BinOp::Eq, + at: Kind::U64, + l: Box::new(local(0)), + r: Box::new(local(1)), + }, + ), + set(1, local(0)), + // Copy of managed `this` (`Param(0)`) mixed with an unrelated class + field load -> stays System.Object. + set(3, param(0)), + set(3, made(OTHER)), + set(4, load(Scalar::I32, local(3), 0x8)), + ]); + let names = Names::default(); + run_in(&mut f, &kinded(&names, &project), &mut Stats::default()); + + assert_eq!(kind_of(&f, Var::Param(0)), object(THING)); + assert_eq!(kind_of(&f, Var::Local(0)), object("System.Object")); + assert_eq!(kind_of(&f, Var::Local(1)), Kind::Pointer); + assert_eq!(kind_of(&f, Var::Local(3)), object("System.Object")); +} + +#[test] +fn value_type_state_machine_movenext_reads_captured_this_field_layout() { + use crate::gta6::script::class::Role; + use crate::gta6::script::project::{Member, TypeFacts}; + + let sm = TypeKey(0x5555); + let outer = TypeKey(0xAA); + let mut project = Project::default(); + project.types.insert(outer, TypeFacts::default()); + project.types.insert( + sm, + TypeFacts { + flags: 0x04, // value struct (async state machine) + byte_size: 40, + ..TypeFacts::default() + }, + ); + project.fields.insert( + sm, + vec![FieldFacts { + offset: 0x20, + bytes: 8, + kind: object(THING), + }], + ); + project.fields.insert( + outer, + vec![FieldFacts { + offset: 0x8, + bytes: 4, + kind: Kind::F32, + }], + ); + let own = FunctionKey::new(0x1122_3344, 0); + project.members.insert( + own, + Member { + owner: sm, + role: Role::Step, + is_static: false, + slot: None, + }, + ); + let mut f = function(vec![ + set(10, load(Scalar::U64, param(0), 0x20)), + set(11, load(Scalar::U64, local(10), 0x8)), + ]); + let names = Names::default(); + run_in(&mut f, &kinded(&names, &project), &mut Stats::default()); + + // `p0` stays a raw pointer to the value struct; `local_10` gets the captured outer class! + assert_eq!(kind_of(&f, Var::Param(0)), Kind::Pointer); + assert_eq!(kind_of(&f, Var::Local(10)), object(THING)); +} + +#[test] +fn invoke_delegate_and_delegate_combine_remove_type_as_system_delegate() { + let delegate = object("System.Delegate"); + let combine = |a: Expr, b: Expr| Expr::Call { + callee: Callee::Builtin { + path: "System.Delegate.Combine".to_owned(), + ty: 2, + method: 1, + }, + args: vec![a, b], + returns: Some(1), + }; + let remove = |a: Expr, b: Expr| Expr::Call { + callee: Callee::Builtin { + path: "System.Delegate.Remove".to_owned(), + ty: 2, + method: 2, + }, + args: vec![a, b], + returns: Some(1), + }; + let mut f = function(vec![ + // Target of `invoke_delegate` -> System.Delegate. + Stmt::Eval(intrinsic("invoke_delegate", vec![param(0), int(1)], 0)), + // Args and result of `System.Delegate.Combine` / `Remove` -> System.Delegate. + set(0, combine(param(1), param(2))), + set(1, remove(local(0), param(3))), + // Concrete delegate class stays concrete when invoked or passed to Combine. + set(2, made(THING)), + Stmt::Eval(intrinsic("invoke_delegate", vec![local(2)], 0)), + set(2, combine(local(2), param(1))), + ]); + let names = Names::default(); + run_in( + &mut f, + &kinded(&names, Project::empty()), + &mut Stats::default(), + ); + + assert_eq!(kind_of(&f, Var::Param(0)), delegate); + assert_eq!(kind_of(&f, Var::Param(1)), delegate); + assert_eq!(kind_of(&f, Var::Param(2)), delegate); + assert_eq!(kind_of(&f, Var::Param(3)), delegate); + assert_eq!(kind_of(&f, Var::Local(0)), delegate); + assert_eq!(kind_of(&f, Var::Local(1)), delegate); + assert_eq!(kind_of(&f, Var::Local(2)), object(THING)); +} + +#[test] +fn wide_kind_and_arg_reads_use_signatures_slot_results_and_cell_offset_alignment() { + use crate::gta6::script::project::TypeFacts; + + let mut project = Project::default(); + let owner = TypeKey(0xAA); + let local_fn = FunctionKey::new(0x1122_3344, 0x200); + let slot_fn = FunctionKey::new(0x1122_3344, 0x300); + let mut owner_facts = TypeFacts::default(); + owner_facts.slots.insert(5, slot_fn); + project.types.insert(owner, owner_facts); + project.signatures.insert( + local_fn, + Signature { + params: vec![ + // Unmerged 1-cell params for a 2-cell value, followed by a typed bool param! + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::Bool, + cells: 1, + }, + ], + returns: 2, + result: Kind::Handle, + }, + ); + project.slot_results.insert(slot_fn, Kind::Vector); + project.slot_params.insert( + slot_fn, + vec![ + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::Unknown, + cells: 1, + }, + Param { + kind: Kind::F32, + cells: 1, + }, + ], + ); + + let mut f = function(vec![ + set( + 0, + Expr::Call { + callee: Callee::Local { + at: 0x200, + name: "func_000200".to_owned(), + }, + args: vec![Expr::GuidEmpty, param(0)], + returns: Some(2), + }, + ), + set( + 2, + Expr::Call { + callee: Callee::Virtual { + class: THING.to_owned(), + method: "Method_5".to_owned(), + ty: THING.to_owned(), + slot: 5, + }, + args: vec![param(1), local(0), param(2)], + returns: Some(2), + }, + ), + ]); + f.head.vars.insert( + Var::Local(0), + VarInfo { + width: Width::Cells, + kind: Kind::Aggregate(2), + ..VarInfo::new(Width::Cells) + }, + ); + f.head.vars.insert( + Var::Local(2), + VarInfo { + width: Width::Cells, + kind: Kind::Aggregate(2), + ..VarInfo::new(Width::Cells) + }, + ); + let names = Names::default(); + run_in(&mut f, &kinded(&names, &project), &mut Stats::default()); + + assert_eq!(kind_of(&f, Var::Local(0)), Kind::Handle); + assert_eq!(kind_of(&f, Var::Local(2)), Kind::Vector); + // Despite `Expr::GuidEmpty` (2 cells) facing two unmerged 1-cell params, `param(0)` at cell 2 + // still gets `Kind::Bool`, and `param(2)` at cell 3 of the virtual call still gets `Kind::F32`. + assert_eq!(kind_of(&f, Var::Param(0)), Kind::Bool); + assert_eq!(kind_of(&f, Var::Param(2)), Kind::F32); +} 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 d926e854d..54fd8f762 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 @@ -18,8 +18,9 @@ use crate::gta6::script::{Context, Pass}; use super::{ assigned_receiver, bits, bound_lambda, cast_wrap, cells_of, enum_underlying_keyword, falls, - field_store_addr, is_zero, receiver, reread, spell, switch_scalar, takes, underneath, unread, - wrap, Labels, StoreTarget, Work, Writer, POSTFIX, UNARY, + field_store_addr, is_delegate_kind, is_zero, receiver, reference, reread, spell, switch_scalar, + takes, underneath, unread, unsigned_complement_literal, wrap, Labels, StoreTarget, Work, + Writer, POSTFIX, UNARY, }; /// How often a body assigns and reads each variable, and which have their address taken. @@ -367,14 +368,28 @@ fn assigned<'t>(text: &'t str, base: &str, offset: u32) -> Option<&'t str> { } /// Whether `call` hands `var` to what it calls as an `out`. -fn fills(call: &Stmt, var: Var) -> bool { +fn fills(call: &Stmt, var: Var, native_only: bool) -> bool { + let handed = Expr::AddrOf { var, cell: 0 }; let mut found = false; call.each_expr(&mut |top| { top.walk(&mut |node| { - found |= matches!( - node, - Expr::Sugar { kind: ExprSugar::Out, e: held } if **held == Expr::AddrOf { var, cell: 0 } - ); + if native_only { + if let Expr::Call { + callee: Callee::Native { .. }, + args, + .. + } = node + { + found |= args.iter().any(|arg| { + matches!(arg, Expr::Sugar { kind: ExprSugar::Out, e } if **e == handed) + }); + } + } else { + found |= matches!( + node, + Expr::Sugar { kind: ExprSugar::Out, e: held } if **held == handed + ); + } }); }); found @@ -599,7 +614,34 @@ impl Writer<'_> { let Some(read) = closures::subscription(seed, round, again) else { return false; }; - let (place, handler) = (self.value(read.place), self.value(read.handler)); + let place = self.value(read.place); + let handler = if self.sharp + && is_delegate_kind(&self.kind_of(bits(read.place))) + && !is_delegate_kind(&self.kind_of(bits(read.handler))) + { + let h_kind = self.kind_of(bits(read.handler)); + let (operand, binds) = self.spelled(bits(read.handler)); + if operand == "null" { + operand + } else if h_kind == Kind::Pointer { + format!( + "(ScriptDelegate)(object)(Cell){}", + cast_wrap("Cell", operand, binds) + ) + } else if reference(&h_kind) { + format!( + "(ScriptDelegate){}", + cast_wrap("ScriptDelegate", operand, binds) + ) + } else { + format!( + "(ScriptDelegate)(object){}", + cast_wrap("object", operand, binds) + ) + } + } else { + self.value(read.handler) + }; let op = if read.remove { "-=" } else { "+=" }; self.line(indent, &format!("{place} {op} {handler};")); true @@ -852,6 +894,21 @@ impl Writer<'_> { true => spell::unchecked_int(value), false => value, }; + let value = match store { + Stmt::Store { + kind: StoreKind::Ref | StoreKind::U64, + offset, + value: rhs, + .. + } if self.sharp => { + let target_ty = owner + .and_then(|owner| self.project.field(owner, *offset)) + .filter(|field| field.bytes == 8) + .map(|field| self.kind_text(&field.kind)); + self.cast_from_object(rhs, target_ty.as_deref().unwrap_or("Cell"), value) + } + _ => value, + }; Some(format!("{} = {value}", self.field_name(owner, *offset))) } @@ -1141,11 +1198,7 @@ impl Writer<'_> { e, }, ) => match &**e { - Expr::Const(c) - if c.kind.is_integer() && (c.bits as i64) >= 0 && c.bits < 1 << 31 => - { - Some(format!("~{}{suffix}", c.bits)) - } + Expr::Const(c) if c.kind.is_integer() => unsigned_complement_literal(c, suffix), _ => None, }, _ => None, @@ -1256,9 +1309,19 @@ impl Writer<'_> { } } }; - match target_32 == StoreTarget::SignedI32 { + let rhs = match target_32 == StoreTarget::SignedI32 { true => spell::unchecked_int(rhs), false => rhs, + }; + if self.sharp && matches!(kind, StoreKind::Ref | StoreKind::U64) { + let target_ty = self + .project + .field(owner, offset) + .filter(|field| field.bytes == 8) + .map(|field| self.kind_text(&field.kind)); + self.cast_from_object(value, target_ty.as_deref().unwrap_or("Cell"), rhs) + } else { + rhs } } Stmt::StoreBytes { value, .. } => match bits(value) { @@ -1346,7 +1409,7 @@ impl Writer<'_> { return None; }; let empty = is_zero(value) || matches!(bits(value), Expr::ZeroSlots(_)); - if !empty || !fills(call, *target) { + if !empty || !fills(call, *target, self.sharp) { return None; } if self.sites.contains(&std::ptr::from_ref(zero)) { @@ -1440,7 +1503,7 @@ impl Writer<'_> { self.simples(shown, indent); let head = format!( "foreach ({} {} in {})", - self.declared_type(*target), + self.foreach_item_type(*target, source, body), self.var(*target), self.value(source) ); diff --git a/crates/io/or-io/src/gta6/script/print/inlined.rs b/crates/io/or-io/src/gta6/script/print/inlined.rs index 9ac700814..01777a40c 100644 --- a/crates/io/or-io/src/gta6/script/print/inlined.rs +++ b/crates/io/or-io/src/gta6/script/print/inlined.rs @@ -151,7 +151,7 @@ impl<'a> Writer<'a> { }; let head = format!( "foreach ({} {} in {})", - self.declared_type(*target), + self.foreach_item_type(*target, source, body), self.var(*target), self.value(source) ); diff --git a/crates/io/or-io/src/gta6/script/print/lambda/tests.rs b/crates/io/or-io/src/gta6/script/print/lambda/tests.rs index e05882cae..be5dffc49 100644 --- a/crates/io/or-io/src/gta6/script/print/lambda/tests.rs +++ b/crates/io/or-io/src/gta6/script/print/lambda/tests.rs @@ -1029,7 +1029,8 @@ fn a_field_whose_address_a_call_bounded_to_its_cell_is_handed_reads_as_a_variabl assert!(hidden(&bounded)); let text = written(&unit, &bounded, 0x40, None, true); assert!(text.contains("local_4 = p2;"), "{text}"); - assert!(text.contains("func_000095(&local_4);"), "{text}"); + // A local captured by a lambda cannot have its address taken with `&` in C# (CS1686). + assert!(text.contains("func_000095(addr(ref local_4));"), "{text}"); assert!(text.contains("=> func_000080(local_4, p1));"), "{text}"); assert!(!text.contains("type_00000000000000CD"), "{text}"); // ⚠ A callee that may touch past the cell, one that keeps the address, and one no table bounds. 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 37459b2ee..a670a9f06 100644 --- a/crates/io/or-io/src/gta6/script/print/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/mod.rs @@ -937,6 +937,8 @@ struct Writer<'a> { lambdas: Option<&'a Lambdas<'a>>, /// Those of them the function being written binds. sited: BTreeSet, + /// Names of outer variables captured by any lambda sited inside this function. + captured: BTreeSet, /// What the receiver is written as in the body of a lambda written where it is bound: the variable that holds the object there. bound: Option, /// The task an `async` method's hidden last `return` hands back: a `return` of it elsewhere is written bare. @@ -977,6 +979,7 @@ impl<'a> Writer<'a> { outs: Vec::new(), lambdas: None, sited: BTreeSet::new(), + captured: BTreeSet::new(), bound: None, back: None, task: None, @@ -1200,8 +1203,169 @@ impl<'a> Writer<'a> { } } + /// Collects the printed names of outer variables captured by any lambda sited inside `body`. + fn collect_captured(&mut self, body: &[tree::Stmt]) { + if !(self.sharp && !self.sited.is_empty()) { + return; + } + let Some(lambdas) = self.lambdas else { + return; + }; + let mut visited: BTreeSet = self.sited.clone(); + let mut work: Vec = self.sited.iter().copied().collect(); + while let Some(at) = work.pop() { + let Some(lambda) = lambdas.get(&at).copied() else { + continue; + }; + for (var, info) in &lambda.head.vars { + if matches!(var, Var::Param(n) if *n >= lambda.head.params) { + if let Some(name) = &info.name { + self.captured.insert(name.clone()); + } + } + } + let program = lambda.head.program; + tree::each_expr(&lambda.body, &mut |top| { + top.walk(&mut |node| { + if let Expr::FunctionRef { program: p, at } = node { + if *p == program { + let off = at & 0x00FF_FFFF; + if lambdas.contains_key(&off) && visited.insert(off) { + work.push(off); + } + } + } + }); + }); + } + let program = self.head.program; + tree::each_sugar(body, &mut |sugar| { + if let tree::Sugar::Group { + kind: tree::Group::Delegate, + parts, + } = sugar + { + if let Some((held, at)) = bound_lambda(parts, program) { + if self.sited.contains(&at) { + if let Expr::Var(var) = underneath(held) { + self.captured.insert(self.var(*var)); + } + } + } + } + }); + } + + /// Whether `var` is captured by a lambda (either we are printing inside a lambda, or a sited lambda in this method captures `var`). + fn is_captured(&self, var: Var) -> bool { + self.bound.is_some() + || (!self.captured.is_empty() && self.captured.contains(&self.var(var))) + } + + /// Casts a `System.Object`-typed RHS to `target_ty` when assigning or storing into a non-`object` 1-cell target in true C#. + pub(super) fn cast_from_object(&self, value: &Expr, target_ty: &str, rhs: String) -> String { + if !self.sharp + || target_ty == "object" + || rhs == "null" + || rhs == "default" + || !matches!( + self.kind_of(bits(value)), + Kind::Object(ref name) if name == "System.Object" + ) + { + return rhs; + } + let wrap = |prefix: &str, expr: &str| { + if expr.contains(' ') { + format!("{prefix}({expr})") + } else { + format!("{prefix}{expr}") + } + }; + if target_ty == "void*" { + if rhs.starts_with("(void*)") { + return rhs; + } + return wrap("(void*)(Cell)", &rhs); + } + let prefix = format!("({target_ty})"); + if rhs.starts_with(&prefix) { + return rhs; + } + wrap(&prefix, &rhs) + } + + /// The declared item type of a `foreach` loop: `var` in true C# when the item is a `CellsN` aggregate over a concrete typed collection and never cell-indexed inside `body`. + pub(super) fn foreach_item_type( + &self, + target: Var, + source: &Expr, + body: &[tree::Stmt], + ) -> String { + let aggregate = !self.handles.contains_key(&target) + && matches!( + self.head.vars.get(&target).map(|info| &info.kind), + Some(Kind::Aggregate(_)) + ); + let concrete_source = match self.kind_of(bits(source)) { + Kind::Object(name) => name != "System.Object", + Kind::Value { .. } | Kind::Array(_) | Kind::String => true, + _ => false, + }; + if self.sharp && aggregate && concrete_source && !var_cell_indexed(body, target) { + "var".to_owned() + } else { + self.declared_type(target) + } + } + + /// Whether `addr`, used as the base of an `Expr::ByteOffset` that would print `&expr->f_X`, is a non-pointer call or property (such as `box`, `box_at`, or `.Current`). + fn non_pointer_byte_offset_base(&self, mut addr: &Expr) -> bool { + while let Expr::ByteOffset { + addr: inner, + offset, + } = addr + { + if matches!(&**offset, Expr::Const(c) if c.bits <= u64::from(u32::MAX)) { + addr = inner; + } else { + break; + } + } + match bits(addr) { + Expr::Call { + callee: Callee::Intrinsic { name, .. }, + .. + } => name.starts_with("box<") || name.starts_with("box_at<"), + Expr::Sugar { + kind: ExprSugar::Property, + .. + } => true, + Expr::Call { callee, .. } => { + let ptr_intrinsic = matches!( + callee, + Callee::Intrinsic { name, .. } + if matches!( + name.as_str(), + "stack_alloc_zeroed" + | "stack_address" + | "byte_offset" + | "array_element_address" + ) + ); + !ptr_intrinsic && self.kind_of(bits(addr)) != Kind::Pointer + } + Expr::Sugar { + kind: ExprSugar::Method, + .. + } => self.kind_of(bits(addr)) != Kind::Pointer, + _ => false, + } + } + /// Writes a body `indent` levels in, under the variables it declares at its top. fn block(&mut self, body: &[tree::Stmt], indent: usize) { + self.collect_captured(body); self.tails(body); let placement = placement_with( body, @@ -1835,7 +1999,10 @@ impl<'a> Writer<'a> { match (kind, e) { (ExprSugar::Method, Expr::Call { callee, args, .. }) => { if let Some((receiver, _)) = args.split_first() { - let receiver = self.expr(receiver, POSTFIX); + let receiver = match bits(receiver) { + Expr::AddrOf { var, cell: 0 } if is_value_builtin(callee) => self.var(*var), + _ => self.expr(receiver, POSTFIX), + }; let passed = self.arguments(callee, args, 1); let text = format!("{receiver}.{}({passed})", self.called(callee)); return (text, POSTFIX); @@ -1900,11 +2067,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 = self.bound.is_none() - && matches!( - bits(addr), - Expr::AddrOf { var, cell: 0 } if !matches!(var, Var::Global { .. }) - ); + let stack_local = matches!( + bits(addr), + Expr::AddrOf { var, cell: 0 } + if !matches!(var, Var::Global { .. }) && !self.is_captured(*var) + ); if self.sharp && !base.contains("->") && !stack_local { return (format!("addr(ref {base}{name})"), POSTFIX); } @@ -2442,8 +2609,21 @@ impl<'a> Writer<'a> { } else { StoreTarget::Plain }; - let value = self.store_rhs_target(*kind, value, target); - format!("{place} = {value}") + let rhs = self.store_rhs_target(*kind, value, target); + let rhs = if self.sharp && matches!(kind, StoreKind::Ref | StoreKind::U64) { + let target_ty = self + .options + .on(Pass::Fields) + .then(|| self.field_owner_of(addr, *offset)) + .flatten() + .and_then(|owner| self.project.field(owner, *offset)) + .filter(|field| field.bytes == 8) + .map(|field| self.kind_text(&field.kind)); + self.cast_from_object(value, target_ty.as_deref().unwrap_or("Cell"), rhs) + } else { + rhs + }; + format!("{place} = {rhs}") } // Whole cells of a value as wide as the store are the field assigned. Stmt::StoreBytes { @@ -2574,10 +2754,32 @@ impl<'a> Writer<'a> { } None => self.value(value), }; - match signed_i32 { + let text = match signed_i32 { true => spell::unchecked_int(text), false => text, + }; + if self.sharp { + let target_ty = match target { + Var::Global { .. } => match &kind { + Some(k) + if !matches!( + k, + Kind::Aggregate(_) | Kind::Vector | Kind::Handle + ) && !matches!(k, Kind::Value { cells, .. } if *cells != 1) => + { + Some(self.kind_text(k)) + } + None => Some("Cell".to_owned()), + _ => None, + }, + _ => (flat_cells(&Expr::Var(target), self.head) == Some(1)) + .then(|| self.declared_type(target)), + }; + if let Some(target_ty) = target_ty { + return self.cast_from_object(value, &target_ty, text); + } } + text } } } @@ -2648,27 +2850,61 @@ impl<'a> Writer<'a> { continue; } } + // Script callees never declare `ref`/`out` parameters, so keep `ref`/`out` for natives alone. + let arg = match arg { + Expr::Sugar { + kind: ExprSugar::Ref | ExprSugar::Out, + e, + } if !matches!(callee, Callee::Native { .. }) + && matches!(&**e, Expr::AddrOf { cell: 0, .. }) => + { + &**e + } + _ => arg, + }; + let taker = takers.get(n).and_then(Option::as_ref); // What the parameter is said first: a float it takes is no `int` without its cast. - let given = takers.get(n).and_then(|kind| self.given(kind, arg)); + let given = taker.and_then(|kind| self.given(kind, arg)); // A multi-cell zero passed to a parameter whose signature states those cells is `default`. let given = given.or_else(|| { let zero = matches!(bits(arg), Expr::ZeroSlots(cells) if *cells >= 2); - (zero && self.options.on(Pass::Kinds) && takers.get(n).is_some()) + (zero && self.options.on(Pass::Kinds) && taker.is_some()) .then(|| "default".to_owned()) }); let given = given.or_else(|| self.native_argument(callee, args, n)); // An integer the parameter is says the reading a cast to it would. - let given = given.or_else(|| self.assigned_implied(takers.get(n), arg)); - let signed_i32 = - takers.get(n) == Some(&Kind::I32) || self.native_param_is_i32(callee, args, n); - let unsigned_u32 = matches!(takers.get(n), Some(Kind::U32 | Kind::Hash)) + let given = given.or_else(|| self.assigned_implied(taker, arg)); + let signed_i32 = taker == Some(&Kind::I32) || self.native_param_is_i32(callee, args, n); + let unsigned_u32 = matches!(taker, Some(Kind::U32 | Kind::Hash)) || self.native_param_is_u32(callee, args, n); + let needs_bool_cast = taker == Some(&Kind::Bool) + && given.is_none() + && !matches!(bits(arg), Expr::Binary { op, .. } if op.is_comparison()) + && !self.prints_bool(bits(arg)) + && matches!( + self.kind_of(bits(arg)), + Kind::I8 + | Kind::U8 + | Kind::I16 + | Kind::U16 + | Kind::I32 + | Kind::U32 + | Kind::I64 + | Kind::U64 + | Kind::Hash + ); let narrow = match (&given, slots.get(n)) { - (None, Some(Some(exact))) => self.narrow_for(arg, *exact, signed_i32), + (None, Some(Some(exact))) if !needs_bool_cast => { + self.narrow_for(arg, *exact, signed_i32) + } _ => None, }; let item = match given.or(narrow) { Some(item) => item, + None if needs_bool_cast => { + let (operand, binds) = self.spelled(bits(arg)); + format!("(bool)(Cell){}", cast_wrap("Cell", operand, binds)) + } 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), @@ -2883,6 +3119,15 @@ impl<'a> Writer<'a> { /// The C#-like name of a kind, for a declaration. fn kind_text(&self, kind: &Kind) -> String { match kind { + Kind::Object(name) + if self.sharp + && matches!( + name.as_str(), + "System.Delegate" | "System.MulticastDelegate" + ) => + { + "ScriptDelegate".to_owned() + } Kind::Object(name) | Kind::Value { ty: name, .. } => self.type_name(name), Kind::Array(of) => format!("{}[]", self.kind_text(of)), _ => kind_text(kind, self.names, self.sharp), @@ -3376,6 +3621,17 @@ impl<'a> Writer<'a> { Expr::Const(c) if c.bits == 0 => return self.spelled(addr), Expr::Const(c) if c.bits <= u64::from(u32::MAX) => { let (place, _) = self.place(addr, c.bits as u32, false); + if self.sharp && place.contains("->") && self.non_pointer_byte_offset_base(addr) + { + return ( + format!( + "byte_offset({}, {})", + self.expr(addr, 0), + self.expr(offset, 0) + ), + POSTFIX, + ); + } if self.sharp && self.options.on(Pass::Fields) && self.unfixed_field(addr, &place) @@ -3390,11 +3646,12 @@ impl<'a> Writer<'a> { self.expr(offset, 0) ), }, - Expr::AddrOf { - 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() => { + Expr::AddrOf { var, cell: 0 } + if self.sharp + && (matches!(var, Var::Global { .. }) + || self.is_captured(*var) + || reference(&self.kind_of(&Expr::Var(*var)))) => + { return (format!("addr(ref {})", self.var(*var)), POSTFIX); } Expr::AddrOf { var, cell: 0 } => return (format!("&{}", self.var(*var)), UNARY), @@ -3690,11 +3947,7 @@ impl<'a> Writer<'a> { op: UnOp::BitNot, e: inner, } => match &**inner { - Expr::Const(c) - if c.kind.is_integer() && (c.bits as i64) >= 0 && c.bits < 1 << 31 => - { - Some(format!("~{}{suffix}", c.bits)) - } + Expr::Const(c) if c.kind.is_integer() => unsigned_complement_literal(c, suffix), _ => None, }, _ => None, @@ -3891,11 +4144,13 @@ impl<'a> Writer<'a> { } } - /// Casts a 64-bit operand to `kw` (`"ulong"` or `"long"`), wrapping high-bit `ulong` constants cast to `long` in `unchecked(...)` so C# accepts them. + /// Casts a 64-bit operand to `kw` (`"ulong"` or `"long"`), wrapping out-of-range constants in `unchecked(...)` so C# accepts them. pub(super) fn cast_64(&mut self, kw: &str, e: &Expr) -> String { let text = self.expr(e, UNARY); if kw == "long" && matches!(e, Expr::Const(c) if c.bits > i64::MAX as u64) { format!("unchecked((long){text})") + } else if kw == "ulong" && is_negative_const(e) { + format!("unchecked((ulong){text})") } else { format!("({kw}){text}") } @@ -4226,7 +4481,7 @@ impl<'a> Writer<'a> { var: Var::Global { .. }, cell: 0, } => true, - Expr::AddrOf { .. } => self.bound.is_some(), + Expr::AddrOf { var, .. } => self.is_captured(*var), Expr::Call { callee: Callee::Intrinsic { name, .. }, args, @@ -4833,8 +5088,43 @@ impl<'a> Writer<'a> { } match args { [target, passed @ ..] if name == "invoke_delegate" => { - let target = self.expr(target, POSTFIX); - Some((format!("{target}({})", self.list(passed)), POSTFIX)) + if self.sharp { + let target_kind = self.kind_of(bits(target)); + let target_text = if is_delegate_kind(&target_kind) { + self.expr(target, POSTFIX) + } else { + let (operand, binds) = self.spelled(bits(target)); + if target_kind == Kind::Pointer { + format!( + "((ScriptDelegate)(object)(Cell){})", + cast_wrap("Cell", operand, binds) + ) + } else if reference(&target_kind) { + format!( + "((ScriptDelegate){})", + cast_wrap("ScriptDelegate", operand, binds) + ) + } else { + format!( + "((ScriptDelegate)(object){})", + cast_wrap("object", operand, binds) + ) + } + }; + let mut items = Vec::with_capacity(passed.len()); + for arg in passed { + if self.kind_of(bits(arg)) == Kind::Pointer { + let (operand, binds) = self.spelled(bits(arg)); + items.push(format!("(Cell){}", cast_wrap("Cell", operand, binds))); + } else { + items.push(self.value(arg)); + } + } + Some((format!("{target_text}({})", items.join(", ")), POSTFIX)) + } else { + let target = self.expr(target, POSTFIX); + Some((format!("{target}({})", self.list(passed)), POSTFIX)) + } } [array] if name == "array_length" => { Some((format!("{}.Length", self.expr(array, POSTFIX)), POSTFIX)) @@ -5295,6 +5585,15 @@ pub(super) fn kind_text(kind: &Kind, names: &Names, sharp: bool) -> String { Kind::Hash if sharp => "uint", Kind::Hash => "Hash", Kind::Pointer => "void*", + Kind::Object(name) + if sharp + && matches!( + name.as_str(), + "System.Delegate" | "System.MulticastDelegate" + ) => + { + return "ScriptDelegate".to_owned(); + } Kind::Object(name) => return type_name(name, names, sharp), Kind::String => "string", Kind::Vector => "Vector3", @@ -5523,6 +5822,97 @@ fn reference(kind: &Kind) -> bool { matches!(kind, Kind::Object(_) | Kind::String | Kind::Array(_)) } +/// Whether `kind` is a delegate type spelled `ScriptDelegate` in true C#. +fn is_delegate_kind(kind: &Kind) -> bool { + matches!( + kind, + Kind::Object(name) if matches!(name.as_str(), "System.Delegate" | "System.MulticastDelegate") + ) +} + +/// Whether `callee` is a .NET value-type builtin method whose first argument may be `&var` in IR and prints as `var.Method(...)`. +pub(super) fn is_value_builtin(callee: &Callee) -> bool { + let Callee::Builtin { path, .. } = callee else { + return false; + }; + let Some((owner, _)) = path.rsplit_once('.') else { + return false; + }; + matches!( + owner, + "System.Int32" + | "System.UInt32" + | "System.Int64" + | "System.UInt64" + | "System.Single" + | "System.Double" + | "System.Int16" + | "System.UInt16" + | "System.Byte" + | "System.SByte" + | "System.Boolean" + | "System.Char" + | "System.Guid" + ) +} + +/// Formats `~c` with unsigned suffix `U` or `UL`, using hex for large values and respecting 32-bit bounds for `U`. +fn unsigned_complement_literal(c: &Const, suffix: &str) -> Option { + if suffix == "U" { + if (c.bits as i64) < 0 || c.bits > u64::from(u32::MAX) { + return None; + } + } else if c.kind == Kind::I32 && (c.bits as i32) < 0 { + return None; + } + if c.bits <= 0x1_0000 { + Some(format!("~{}{suffix}", c.bits)) + } else { + Some(format!("~0x{:X}{suffix}", c.bits)) + } +} + +/// Whether `e` folds to a negative constant (including `~const` or `-const`), which C# refuses to cast to `ulong` without `unchecked(...)`. +fn is_negative_const(e: &Expr) -> bool { + match bits(e) { + Expr::Const(c) => { + (c.kind == Kind::I32 && (c.bits as i32) < 0) + || (matches!(c.kind, Kind::I64 | Kind::Unknown) && (c.bits as i64) < 0) + } + Expr::Unary { + op: UnOp::BitNot, + e: inner, + } => { + spell::folded(bits(inner)).is_some_and(|c| c.kind.is_integer() && !(c.bits as i64) < 0) + } + Expr::Unary { + op: UnOp::Neg, + e: inner, + } => spell::folded(bits(inner)).is_some_and(|c| c.kind.is_integer() && (c.bits as i64) > 0), + _ => false, + } +} + +/// Whether `body` indexes `target` as a multi-cell aggregate (`target[i]` or `&target[i]` with `i > 0`). +fn var_cell_indexed(body: &[tree::Stmt], target: Var) -> bool { + let mut found = false; + tree::each_expr(body, &mut |top| { + if found { + return; + } + top.walk(&mut |node| match node { + Expr::Cell { base, .. } if matches!(bits(base), Expr::Var(v) if *v == target) => { + found = true; + } + Expr::AddrOf { var, cell } if *var == target && *cell > 0 => { + found = true; + } + _ => {} + }); + }); + found +} + /// Whether a `ZeroBytes` of `bytes` bytes at `var` clears every byte of `var`: whole cell count, or in true C# with `kinds` on, the exact byte size of a `Vector3`, value type, or one-cell scalar. pub(super) fn clear_matches_var( head: &Head, 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 d7bb4a7b8..c94c624f9 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 @@ -773,6 +773,9 @@ pub fn prelude(names: &Names, used: &Used) -> String { public static bool operator !=(void* a, Cell b) => default;\n}}\n\n", numeric("Cell") ); + if !own("ScriptDelegate") { + out.push_str("public delegate Cell ScriptDelegate(params object[] args);\n\n"); + } for n in &used.cells { cells_struct(&mut out, *n, &own); } @@ -814,6 +817,8 @@ pub fn prelude(names: &Names, used: &Used) -> String { } if !own("Handle") { let _ = write!(out, "public struct Handle\n{{\n{}", whole("Handle")); + out.push_str(" public static implicit operator Handle(Cells2 v) => default;\n"); + out.push_str(" public static implicit operator Cells2(Handle v) => default;\n"); out.push_str(" public static implicit operator Handle((Cell, Cell) v) => default;\n"); for handle in HANDLES.iter().filter(|handle| !own(handle)) { let _ = writeln!( @@ -885,6 +890,10 @@ pub fn prelude(names: &Names, used: &Used) -> String { out, " public static implicit operator Entity({handle} v) => default;" ); + let _ = writeln!( + out, + " public static implicit operator {handle}(Entity v) => default;" + ); for op in ["==", "!="] { let _ = writeln!( 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 1f9740a2c..04a0dfb4e 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 @@ -658,3 +658,65 @@ fn system_rage_compare_exchange_and_split_packed_vector_overloads_are_declared() "CompareExchange must not mix void* and object overloads:\n{text}" ); } + +#[test] +fn handle_cells2_entity_handle_conversions_and_script_delegate_are_declared() { + let text = prelude(&Names::default(), &Used::default()); + + // Handle <-> Cells2 implicit conversions and symmetric equality operators (on RHS type). + let handle_body = struct_body(&text, "Handle"); + assert!( + handle_body.contains("public static implicit operator Handle(Cells2 v) => default;"), + "{handle_body}" + ); + assert!( + handle_body.contains("public static implicit operator Cells2(Handle v) => default;"), + "{handle_body}" + ); + assert!( + handle_body.contains("public static bool operator ==(Cells2 a, Handle b) => default;"), + "{handle_body}" + ); + assert!( + struct_body(&text, "Cells2") + .contains("public static bool operator ==(Handle a, Cells2 b) => default;"), + "{text}" + ); + + // Entity -> specific WIDE_HANDLES implicit conversions (and never Entity -> Entity). + for handle in ["Ped", "Vehicle", "Object", "Pickup", "PersChar", "PropSet"] { + let body = struct_body(&text, handle); + let expected_from = + format!("public static implicit operator {handle}(Entity v) => default;"); + let expected_to = format!("public static implicit operator Entity({handle} v) => default;"); + assert!( + body.contains(&expected_from), + "missing `{expected_from}` in {handle}:\n{body}" + ); + assert!( + body.contains(&expected_to), + "missing `{expected_to}` in {handle}:\n{body}" + ); + } + let entity_body = struct_body(&text, "Entity"); + assert!( + !entity_body.contains("implicit operator Entity(Entity v)"), + "Entity must not convert to itself:\n{entity_body}" + ); + + // When a source declares `Entity`, handle structs omit Entity conversions. + let mut own_entity = Used::default(); + own_entity.read("struct Entity { }\n"); + let own_entity_text = prelude(&Names::default(), &own_entity); + assert!( + !struct_body(&own_entity_text, "Ped").contains("implicit operator Ped(Entity v)"), + "{own_entity_text}" + ); + + // ScriptDelegate is unconditionally declared as an invocable delegate returning Cell. + assert!( + text.lines() + .any(|l| l == "public delegate Cell ScriptDelegate(params object[] args);"), + "missing ScriptDelegate declaration in:\n{text}" + ); +} diff --git a/crates/io/or-io/src/gta6/script/print/property/mod.rs b/crates/io/or-io/src/gta6/script/print/property/mod.rs index 03f12e13d..2dc8deafa 100644 --- a/crates/io/or-io/src/gta6/script/print/property/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/property/mod.rs @@ -39,7 +39,14 @@ impl Writer<'_> { _ => return None, }, Some(receiver) => { - let typed = matches!(self.kind_of(receiver), Kind::Object(_) | Kind::Value { .. }); + let typed = match self.kind_of(receiver) { + Kind::Object(ref name) => !matches!( + name.as_str(), + "System.Object" | "System.Delegate" | "System.MulticastDelegate" + ), + Kind::Value { .. } => true, + _ => false, + }; let text = self.expr(receiver, POSTFIX); if property == "Item" && !typed { let passed = self.arguments(callee, args, 1); @@ -159,7 +166,7 @@ pub(crate) fn indexer( let mut writer = Writer::in_context(out, cx, &setter.function.head); writer.depth = depth; writer.this = Some(Var::Param(0)); - writer.setter = Some(Var::Param(2)); + writer.setter = Some(Var::Param(getter.function.head.params)); // A handle a native takes is declared as one, as `params` reads it off the getter. writer.handles = writer.native_handles(&setter.function.body); let slot = format!("func_{:06X}", setter.function.head.at); @@ -190,7 +197,7 @@ pub(crate) fn declared_accessors<'m>( match (indexer_part(class, method, cx), written_role(method)) { (IndexerPart::Getter(setter), _) => { found.push((f, None)); - found.extend(setter.map(|s| (&s.function, Some(Var::Param(2))))); + found.extend(setter.map(|s| (&s.function, Some(Var::Param(f.head.params))))); } (IndexerPart::Setter, _) => {} (IndexerPart::Not, Role::Getter) => found.push((f, None)), diff --git a/crates/io/or-io/src/gta6/script/print/spell/mod.rs b/crates/io/or-io/src/gta6/script/print/spell/mod.rs index c1102b5c6..361e1df8c 100644 --- a/crates/io/or-io/src/gta6/script/print/spell/mod.rs +++ b/crates/io/or-io/src/gta6/script/print/spell/mod.rs @@ -467,8 +467,8 @@ impl Writer<'_> { } } - /// The kind each argument of a call is taken as, where what takes it states one: the project's signature of the function or of the slot, or a natives list's parameters where each answers one argument; up to the first argument that fills other cells than its parameter takes. - pub(super) fn taken_kinds(&self, callee: &Callee, args: &[Expr]) -> Vec { + /// The kind each argument of a call is taken as, where what takes it states one: the project's signature of the function or of the slot, or a natives list's parameters where each answers one argument; aligned by cumulative cell offset so a width mismatch does not drop trailing parameters. + pub(super) fn taken_kinds(&self, callee: &Callee, args: &[Expr]) -> Vec> { let signed = |key: FunctionKey| -> Vec<(Kind, u32)> { let params = self .project @@ -513,16 +513,34 @@ impl Writer<'_> { _ => return Vec::new(), }; let mut kinds = Vec::with_capacity(args.len()); - for (arg, (kind, cells)) in args.iter().zip(params) { - if cells_of(arg, self.head) != Some(cells) { + let mut arg_cell = 0u32; + let mut param_idx = 0usize; + let mut param_cell = 0u32; + for arg in args { + let Some(ac) = cells_of(arg, self.head) else { break; + }; + while param_idx < params.len() && param_cell < arg_cell { + let pc = params[param_idx].1; + if pc == 0 { + break; + } + param_cell = param_cell.saturating_add(pc); + param_idx += 1; } - kinds.push(kind); + if param_idx < params.len() && param_cell == arg_cell && params[param_idx].1 == ac { + kinds.push(Some(params[param_idx].0.clone())); + param_cell = param_cell.saturating_add(ac); + param_idx += 1; + } else { + kinds.push(None); + } + arg_cell = arg_cell.saturating_add(ac); } kinds } - /// `arg` as what takes it as `kind` is given it, where that kind says more than its form: zero cells as the default of a handle, a vector or a value type, and a constant's bits as the float a float parameter reads; `None` elsewhere. + /// `arg` as what takes it as `kind` is given it, where that kind says more than its form: zero cells as the default of a handle, a vector or a value type, a constant's bits as the float a float parameter reads, and `0`/`1` as `false`/`true` for a `bool` parameter; `None` elsewhere. // ⚠ The kind is that of the parameter, never one read off the bits: the bits are written // unchanged, as the literal of the kind that takes them. pub(super) fn given(&self, kind: &Kind, arg: &Expr) -> Option { @@ -540,6 +558,11 @@ impl Writer<'_> { fits.then(|| format!("default({})", self.kind_text(kind))) } (Kind::F32, _) => taken_float(&folded(arg)?), + (Kind::Bool, _) => { + let c = folded(arg)?; + let plain = c.kind.is_integer() || matches!(c.kind, Kind::Bool | Kind::Unknown); + (plain && c.bits <= 1).then(|| (c.bits == 1).to_string()) + } _ => None, } } 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 428cb38c3..f38911327 100644 --- a/crates/io/or-io/src/gta6/script/print/tests.rs +++ b/crates/io/or-io/src/gta6/script/print/tests.rs @@ -3125,8 +3125,11 @@ fn pointer_global_compares_with_null_and_coalesce_boxes_cell_or_pointer_and_read "{text}" ); assert!(text.contains("p0 ?? null;"), "{text}"); - assert!(text.contains("p2 ?? (object)p1;"), "{text}"); - assert!(text.contains("p2 ?? (object)(Cell)Global_0;"), "{text}"); + assert!(text.contains("(Cell)(p2 ?? (object)p1);"), "{text}"); + assert!( + text.contains("(Cell)(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"); } @@ -3904,3 +3907,722 @@ fn array_element_address_field_deref_casts_via_cell_ptr_and_reads_back() { reparse::agrees_source_with(&f, &text, cx.options, false, &project) .expect("array_element_address pointer casts read back"); } + +#[test] +fn object_rhs_casts_to_concrete_non_object_targets_and_reads_back() { + use crate::gta6::script::project::{FieldFacts, TypeFacts}; + use crate::gta6::script::reparse; + const OWNER: TypeKey = TypeKey(0x22 << 40); + let mut project = Project::default(); + project.types.insert( + OWNER, + TypeFacts { + flags: 0, + home: 0x1122_3344, + ..TypeFacts::default() + }, + ); + project.fields.insert( + OWNER, + vec![ + FieldFacts { + offset: 0x08, + bytes: 8, + kind: Kind::String, + }, + FieldFacts { + offset: 0x10, + bytes: 8, + kind: Kind::Pointer, + }, + FieldFacts { + offset: 0x18, + bytes: 8, + kind: Kind::Object("System.Object".to_owned()), + }, + FieldFacts { + offset: 0x20, + bytes: 8, + kind: Kind::Unknown, + }, + ], + ); + let mut h = kinds(&[ + (Var::Param(0), Kind::Object("System.Object".to_owned())), + (Var::Param(1), Kind::Object(OWNER.to_string())), + (Var::Local(0), Kind::String), + (Var::Local(1), Kind::Unknown), + (Var::Local(2), Kind::Pointer), + (Var::Local(3), Kind::Object("System.Object".to_owned())), + ]); + h.params = 2; + h.locals = 4; + let global = Expr::Var(Var::Global { + program: 0x1122_3344, + offset: 0, + statics: false, + }); + let coalesce = Expr::sugar( + ExprSugar::Coalesce, + Expr::Select { + cond: Box::new(Expr::Binary { + op: BinOp::Ne, + at: Kind::Unknown, + l: Box::new(param(0)), + r: Box::new(int(0)), + }), + then: Box::new(param(0)), + els: Box::new(global), + }, + ); + let field_group = |offset: u32, rhs: Expr| { + tree::Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: tree::Group::Field { owner: OWNER }, + parts: vec![Stmt::Store { + kind: StoreKind::Ref, + addr: param(1), + offset, + value: rhs, + }], + })) + }; + let body = vec![ + simple(assign(Var::Local(0), coalesce.clone())), + simple(assign(Var::Local(1), coalesce.clone())), + simple(assign(Var::Local(2), coalesce.clone())), + simple(assign(Var::Local(3), coalesce.clone())), + field_group(0x08, coalesce.clone()), + field_group(0x10, coalesce.clone()), + field_group(0x18, coalesce.clone()), + field_group(0x20, coalesce), + simple(Stmt::Eval(native( + "USE", + vec![local(0), local(1), local(2), local(3)], + ))), + ]; + 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("string local_0 = (string)(p0 ?? (object)Global_0);"), + "{text}" + ); + assert!( + text.contains("Cell local_1 = (Cell)(p0 ?? (object)Global_0);"), + "{text}" + ); + assert!( + text.contains("void* local_2 = (void*)(Cell)(p0 ?? (object)Global_0);"), + "{text}" + ); + assert!( + text.contains("object local_3 = p0 ?? (object)Global_0;"), + "{text}" + ); + assert!( + text.contains("p1.f_8 = (string)(p0 ?? (object)Global_0);"), + "{text}" + ); + assert!( + text.contains("p1.f_10 = (void*)(Cell)(p0 ?? (object)Global_0);"), + "{text}" + ); + assert!(text.contains("p1.f_18 = p0 ?? (object)Global_0;"), "{text}"); + assert!( + text.contains("p1.f_20 = (Cell)(p0 ?? (object)Global_0);"), + "{text}" + ); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("object-to-target casts read back"); +} + +#[test] +fn non_native_ref_out_unwraps_and_managed_ref_uses_addr_and_reads_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[ + (Var::Local(0), Kind::I32), + (Var::Local(1), Kind::Object("MyClass".to_owned())), + (Var::Local(2), Kind::I32), + ]); + h.locals = 3; + let script_call = Stmt::Eval(Expr::Call { + callee: Callee::Local { + at: 0x300, + name: "func_000300".to_owned(), + }, + args: vec![ + Expr::sugar(ExprSugar::Out, address(Var::Local(0), 0)), + Expr::sugar(ExprSugar::Ref, address(Var::Local(1), 0)), + ], + returns: Some(0), + }); + let native_call = Stmt::Eval(Expr::Call { + callee: Callee::Native { + namespace: Some("MISC".to_owned()), + name: "GET_VAL".to_owned(), + hash: 0x1234, + rva: 0, + }, + args: vec![Expr::sugar(ExprSugar::Out, address(Var::Local(2), 0))], + returns: Some(0), + }); + let body = vec![ + tree::Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: tree::Group::Out, + parts: vec![assign(Var::Local(0), int(0)), script_call], + })), + tree::Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: tree::Group::Out, + parts: vec![assign(Var::Local(2), int(0)), native_call], + })), + simple(Stmt::Eval(native( + "USE", + vec![local(0), local(1), local(2)], + ))), + ]; + 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("func_000300(&local_0, addr(ref local_1));"), + "{text}" + ); + assert!(text.contains("MISC.GET_VAL(out local_2);"), "{text}"); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("non-native ref/out unwrap and native out read back"); +} + +#[test] +fn captured_outer_local_uses_addr_ref_in_outer_method_and_reads_back() { + use crate::gta6::script::class::Method; + use crate::gta6::script::ir::VmType; + use crate::gta6::script::reparse; + let mut lambda_head = head(); + lambda_head.at = 0x200; + lambda_head.params = 1; + lambda_head.vars.insert( + Var::Param(1), + VarInfo { + name: Some("local_0".to_owned()), + kind: Kind::I32, + ..VarInfo::new(Width::Cell) + }, + ); + let lambda_fn = function_of( + lambda_head, + vec![tree::Stmt::Return(Some(Expr::Var(Var::Param(1))))], + ); + let mut h = kinds(&[ + (Var::Local(0), Kind::I32), + (Var::Local(1), Kind::I32), + (Var::Local(2), Kind::Object("System.Delegate".to_owned())), + ]); + h.locals = 3; + let bind = tree::Stmt::Sugar(Box::new(tree::Sugar::Group { + kind: tree::Group::Delegate, + parts: vec![ + assign( + Var::Local(2), + Expr::NewObject(VmType { + name: "System.Delegate".to_owned(), + byte_size: 32, + id: 9, + flags: 0, + }), + ), + Stmt::Eval(Expr::Call { + callee: Callee::Builtin { + path: "System.Delegate.Ctor".to_owned(), + ty: 9, + method: 0, + }, + args: vec![ + local(2), + int(0), + Expr::sugar( + ExprSugar::Lambda, + Expr::FunctionRef { + program: 0x1122_3344, + at: 0x200, + }, + ), + ], + returns: Some(0), + }), + ], + })); + let binder = function_of( + h, + vec![ + simple(assign(Var::Local(0), int(1))), + simple(assign(Var::Local(1), int(2))), + bind, + simple(Stmt::Eval(native( + "USE", + vec![ + address(Var::Local(0), 0), + address(Var::Local(1), 0), + local(2), + ], + ))), + ], + ); + let names = Names::default(); + let project = Project::default(); + let cx = Context::new(&names, &project, Options::default()); + let mut lambdas = Lambdas::new(); + lambdas.insert(0x200, &lambda_fn); + let sited = bound_in_place(&binder, &lambdas, &cx); + assert_eq!(sited.iter().copied().collect::>(), [0x200]); + let mut text = String::new(); + method_in( + &mut text, + &Method::free(binder.clone()), + None, + 0, + &cx, + &lambdas, + ); + assert!( + text.contains("USE(addr(ref local_0), &local_1, local_2);"), + "{text}" + ); + assert!( + text.contains("ScriptDelegate local_2 = () => local_0;"), + "{text}" + ); + reparse::agrees_source_binding( + &binder, &text, cx.options, &project, &lambdas, &sited, &names, + ) + .expect("captured outer local addr(ref ...) reads back"); +} + +#[test] +fn script_call_bool_params_align_after_wide_mismatch_and_read_back() { + use crate::gta6::script::project::{Param, Signature}; + use crate::gta6::script::reparse; + let mut project = Project::default(); + project.signatures.insert( + FunctionKey::new(0x1122_3344, 0x410), + Signature { + params: vec![ + Param { + kind: Kind::Vector, + cells: 2, + }, + Param { + kind: Kind::Bool, + cells: 1, + }, + Param { + kind: Kind::Bool, + cells: 1, + }, + Param { + kind: Kind::Bool, + cells: 1, + }, + ], + returns: 0, + result: Kind::Unknown, + }, + ); + let mut h = kinds(&[ + (Var::Param(0), Kind::Unknown), + (Var::Param(1), Kind::Unknown), + (Var::Param(2), Kind::I32), + ]); + h.params = 3; + let cmp = Expr::Binary { + op: BinOp::Eq, + at: Kind::I32, + l: Box::new(param(2)), + r: Box::new(int(0)), + }; + let call = Expr::Call { + callee: Callee::Local { + at: 0x410, + name: "func_000410".to_owned(), + }, + args: vec![param(0), param(1), int(1), param(2), cmp], + returns: Some(0), + }; + let f = function_of(h, vec![simple(Stmt::Eval(call))]); + let names = Names::default(); + let cx = Context::new(&names, &project, Options::default()); + let text = written_in(&f, &cx); + assert!( + text.contains("func_000410(p0, p1, true, (bool)(Cell)p2, p2 == 0);"), + "{text}" + ); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("bool param literals and casts read back"); +} + +#[test] +fn delegate_spelling_invoke_and_event_casts_read_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[ + (Var::Param(0), Kind::Object("System.Delegate".to_owned())), + (Var::Param(1), Kind::Unknown), + (Var::Param(2), Kind::Pointer), + (Var::Param(3), Kind::Object("System.Object".to_owned())), + ( + Var::Local(0), + Kind::Object("System.MulticastDelegate".to_owned()), + ), + ]); + h.params = 4; + h.locals = 1; + let combine = Expr::Call { + callee: Callee::Builtin { + path: "System.Delegate.Combine".to_owned(), + ty: 1, + method: 1, + }, + args: vec![param(0), param(3)], + returns: Some(1), + }; + let invoke_typed = intrinsic("invoke_delegate", vec![param(0), param(1)]); + let invoke_cell = intrinsic("invoke_delegate", vec![param(1), param(2)]); + let invoke_ptr = intrinsic("invoke_delegate", vec![param(2), param(2)]); + let invoke_obj = intrinsic("invoke_delegate", vec![param(3), param(1)]); + let f = function_of( + h, + vec![ + simple(assign(Var::Local(0), combine)), + simple(Stmt::Eval(invoke_typed)), + simple(Stmt::Eval(invoke_cell)), + simple(Stmt::Eval(invoke_ptr)), + simple(Stmt::Eval(invoke_obj)), + simple(Stmt::Eval(native("USE", vec![local(0)]))), + ], + ); + 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("ScriptDelegate p0"), "{text}"); + assert!( + text.contains("ScriptDelegate local_0 = System.Delegate.Combine(p0, p3);"), + "{text}" + ); + assert!(text.contains("p0(p1);"), "{text}"); + assert!( + text.contains("((ScriptDelegate)(object)p1)((Cell)p2);"), + "{text}" + ); + assert!( + text.contains("((ScriptDelegate)(object)(Cell)p2)((Cell)p2);"), + "{text}" + ); + assert!(text.contains("((ScriptDelegate)p3)(p1);"), "{text}"); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("ScriptDelegate spelling and invoke casts read back"); +} + +#[test] +fn foreach_cells_aggregate_over_concrete_collection_uses_var_and_reads_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[ + (Var::Param(0), Kind::Object("MyCollection".to_owned())), + (Var::Param(1), Kind::Object("System.Object".to_owned())), + (Var::Local(0), Kind::Aggregate(2)), + (Var::Local(1), Kind::Aggregate(2)), + (Var::Local(2), Kind::Aggregate(2)), + ]); + h.params = 2; + h.locals = 3; + h.vars.get_mut(&Var::Local(0)).unwrap().width = Width::Cells; + h.vars.get_mut(&Var::Local(1)).unwrap().width = Width::Cells; + h.vars.get_mut(&Var::Local(2)).unwrap().width = Width::Cells; + let mk_foreach = |source: Expr, target: Var, body: Vec| { + let enumerator = Var::Local(10); + tree::Stmt::Sugar(Box::new(tree::Sugar::Foreach { + setup: vec![assign( + enumerator, + Expr::Call { + callee: Callee::Virtual { + class: "MyCollection".to_owned(), + method: "GetEnumerator".to_owned(), + ty: "MyCollection".to_owned(), + slot: 1, + }, + args: vec![source], + returns: Some(1), + }, + )], + cond: Expr::Call { + callee: Callee::Virtual { + class: "IEnumerator".to_owned(), + method: "MoveNext".to_owned(), + ty: "IEnumerator".to_owned(), + slot: 2, + }, + args: vec![Expr::Var(enumerator)], + returns: Some(1), + }, + item: Box::new(assign( + target, + Expr::Call { + callee: Callee::Virtual { + class: "IEnumerator".to_owned(), + method: "get_Current".to_owned(), + ty: "IEnumerator".to_owned(), + slot: 3, + }, + args: vec![Expr::Var(enumerator)], + returns: Some(2), + }, + )), + body, + step: None, + after: Vec::new(), + })) + }; + let f = function_of( + h, + vec![ + mk_foreach( + param(0), + Var::Local(0), + vec![simple(Stmt::Eval(native("USE", vec![local(0)])))], + ), + mk_foreach( + param(0), + Var::Local(1), + vec![simple(Stmt::Eval(native( + "USE", + vec![Expr::Cell { + base: Box::new(local(1)), + index: 0, + }], + )))], + ), + mk_foreach( + param(1), + Var::Local(2), + vec![simple(Stmt::Eval(native("USE", vec![local(2)])))], + ), + ], + ); + 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("foreach (var local_0 in p0)"), "{text}"); + assert!(text.contains("foreach (Cells2 local_1 in p0)"), "{text}"); + assert!(text.contains("foreach (Cells2 local_2 in p1)"), "{text}"); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("foreach var and Cells2 read back"); +} + +#[test] +fn byte_offset_on_non_pointer_box_and_property_emits_byte_offset_and_reads_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[(Var::Param(0), Kind::Object("MyEnum".to_owned()))]); + h.params = 1; + let boxed = intrinsic("box", vec![param(0)]); + let prop = Expr::sugar( + ExprSugar::Property, + Expr::Call { + callee: Callee::Virtual { + class: "MyEnum".to_owned(), + method: "get_Current".to_owned(), + ty: "MyEnum".to_owned(), + slot: 1, + }, + args: vec![param(0)], + returns: Some(1), + }, + ); + let off_box = Expr::ByteOffset { + addr: Box::new(boxed), + offset: Box::new(int(8)), + }; + let off_prop = Expr::ByteOffset { + addr: Box::new(prop), + offset: Box::new(int(8)), + }; + let f = function_of( + h, + vec![simple(Stmt::Eval(native("USE", vec![off_box, off_prop])))], + ); + 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("USE(byte_offset(box(p0), 8), byte_offset(p0.Current, 8));"), + "{text}" + ); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("byte_offset on non-pointer calls reads back"); +} + +#[test] +fn large_unsigned_complement_and_unchecked_ulong_cast_read_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[ + (Var::Param(0), Kind::U64), + (Var::Param(1), Kind::U32), + (Var::Local(0), Kind::U64), + (Var::Local(1), Kind::U32), + (Var::Local(2), Kind::U64), + ]); + h.params = 2; + h.locals = 3; + let mask64 = Expr::Unary { + op: UnOp::BitNot, + e: Box::new(Expr::Const(Const { + bits: 0x200_0000_0000, + kind: Kind::I64, + })), + }; + let mask32 = Expr::Unary { + op: UnOp::BitNot, + e: Box::new(Expr::Const(Const { + bits: 0x8000_0000, + kind: Kind::U32, + })), + }; + let neg_const = Expr::Const(Const { + bits: (-5i64) as u64, + kind: Kind::I64, + }); + let f = function_of( + h, + vec![ + simple(assign( + Var::Local(0), + Expr::Binary { + op: BinOp::And, + at: Kind::U64, + l: Box::new(param(0)), + r: Box::new(mask64.clone()), + }, + )), + simple(assign( + Var::Local(1), + Expr::Binary { + op: BinOp::And, + at: Kind::U32, + l: Box::new(param(1)), + r: Box::new(mask32), + }, + )), + simple(assign( + Var::Local(2), + Expr::Binary { + op: BinOp::And, + at: Kind::U64, + l: Box::new(param(0)), + r: Box::new(neg_const), + }, + )), + simple(Stmt::Eval(native( + "USE", + vec![local(0), local(1), local(2)], + ))), + ], + ); + 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("p0 & ~0x20000000000UL;"), "{text}"); + assert!(text.contains("p1 & ~0x80000000U;"), "{text}"); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("large unsigned complement reads back"); + + // With UnsignedComplement off, cast_64 wraps `(ulong)~0x20000000000` in `unchecked(...)`. + let cx_no_comp = Context::new( + &names, + &project, + Options::default().without(Pass::UnsignedComplement), + ); + let text_no_comp = written_in(&f, &cx_no_comp); + assert!( + text_no_comp.contains("unchecked((ulong)~0x20000000000)") + || text_no_comp.contains("unchecked((ulong)~2199023255552)"), + "{text_no_comp}" + ); + reparse::agrees_source_with(&f, &text_no_comp, cx_no_comp.options, false, &project) + .expect("unchecked((ulong)~...) reads back"); +} + +#[test] +fn value_type_builtin_method_unwraps_addrof_receiver_and_reads_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[(Var::Param(0), Kind::I32), (Var::Local(0), Kind::I32)]); + h.params = 1; + h.locals = 1; + let call = Expr::sugar( + ExprSugar::Method, + Expr::Call { + callee: Callee::Builtin { + path: "System.Int32.GetHashCode".to_owned(), + ty: 1, + method: 2, + }, + args: vec![address(Var::Param(0), 0)], + returns: Some(1), + }, + ); + let f = function_of( + h, + vec![ + simple(assign(Var::Local(0), call)), + simple(Stmt::Eval(native("USE", vec![local(0)]))), + ], + ); + 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("int local_0 = p0.GetHashCode();"), "{text}"); + reparse::agrees_source_with(&f, &text, cx.options, false, &project) + .expect("value-type builtin method unwrap reads back"); +} + +#[test] +fn indexer_on_object_receiver_stays_method_call_and_reads_back() { + use crate::gta6::script::reparse; + let mut h = kinds(&[ + (Var::Param(0), Kind::Object("System.Object".to_owned())), + (Var::Param(1), Kind::I32), + (Var::Local(0), Kind::Unknown), + ]); + h.params = 2; + h.locals = 1; + let call = Expr::sugar( + ExprSugar::Property, + Expr::Call { + callee: Callee::Virtual { + class: "System.Object".to_owned(), + method: "get_Item".to_owned(), + ty: "System.Object".to_owned(), + slot: 3, + }, + args: vec![param(0), param(1)], + returns: Some(1), + }, + ); + let f = function_of( + h, + vec![ + simple(assign(Var::Local(0), call)), + simple(Stmt::Eval(native("USE", vec![local(0)]))), + ], + ); + 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("Cell local_0 = p0.get_Item(p1);"), "{text}"); + reparse::agrees_source_named(&f, &text, cx.options, &project, &names) + .expect("get_Item on object receiver reads back"); +} diff --git a/crates/io/or-io/src/gta6/script/project/layouts/flows.rs b/crates/io/or-io/src/gta6/script/project/layouts/flows.rs index b8573d59f..46221b6e3 100644 --- a/crates/io/or-io/src/gta6/script/project/layouts/flows.rs +++ b/crates/io/or-io/src/gta6/script/project/layouts/flows.rs @@ -81,8 +81,8 @@ enum Val { Of(TypeKey), /// Arrays of the script type's values of so many cells, or of its objects where none. Array(TypeKey, u32), - /// The address of a value held in place: in a frame, an element or an object's field, whose address a lending made. - Place, + /// The address of a value held in place: in a frame, an element or an object's field, whose address a lending made; holds its script value type when known. + Place(Option), /// Anything. Any, } @@ -97,7 +97,7 @@ impl Val { ty: of.to_string(), cells, }, - Val::None | Val::Place | Val::Any => return None, + Val::None | Val::Place(_) | Val::Any => return None, }; Some(Kind::Array(Box::new(element))) } @@ -110,7 +110,7 @@ fn join(project: &Project, a: Val, b: Val) -> Val { (Val::Any, _) | (_, Val::Any) => Val::Any, (Val::Of(a), Val::Of(b)) if a == b => Val::Of(a), (Val::Array(a, n), Val::Array(b, m)) if a == b && n == m => Val::Array(a, n), - (Val::Array(..) | Val::Place, _) | (_, Val::Array(..) | Val::Place) => Val::Any, + (Val::Array(..) | Val::Place(_), _) | (_, Val::Array(..) | Val::Place(_)) => Val::Any, (Val::Of(a), Val::Of(b)) => { // ⚠ Each side's bases are walked: an interface lies on no class's chain of bases, // yet the class is one. @@ -161,6 +161,8 @@ struct Pass { put: BTreeMap<(TypeKey, u32), BTreeSet>, /// What the stores through a base of no known type put at each offset, where what they put is known; `u32::MAX` for those at an offset no constant gives. blind_put: BTreeMap>, + /// The script class types stored into a value type's reference fields (for `holder` when reached through). + value_held: BTreeMap<(TypeKey, u32), BTreeSet>, } /// One reading of the flows against a settled project and what the fields hold so far. @@ -178,13 +180,18 @@ impl Reader<'_> { // may go through any instance of it. let object = |kind: &Kind| { let value = match kind { - Kind::Object(name) => TypeKey::of_name(name) - .and_then(|key| project.types.get(&key)) - .is_some_and(TypeFacts::is_value), - _ => false, + Kind::Object(name) => TypeKey::of_name(name).and_then(|key| { + project + .types + .get(&key) + .is_some_and(TypeFacts::is_value) + .then_some(key) + }), + _ => None, }; - if value { - return Val::Place; + if let Some(key) = value { + let script = (key.builtin().is_none() && !waits(key)).then_some(key); + return Val::Place(script); } let key = object_of(project, kind); let open = key @@ -223,7 +230,7 @@ impl Reader<'_> { } Origin::Field(of, offset) => match self.origin(function, of) { Val::None => Val::None, - Val::Any | Val::Array(..) | Val::Place => Val::Any, + Val::Any | Val::Array(..) | Val::Place(_) => Val::Any, Val::Of(ty) if project.types.get(&ty).is_some_and(|f| f.parameters > 0) => Val::Any, Val::Of(ty) => { let row = FieldFacts { @@ -264,9 +271,25 @@ impl Reader<'_> { let at = flow.offset; match (base, &flow.does) { (Val::None, _) => {} - // An array's elements are written as elements, through what no field is, and a - // value held in place in an object is reached only through an address lent. - (Val::Array(..) | Val::Place, _) => {} + // An array's elements are written as elements, through what no field is. + (Val::Array(..), _) => {} + // A value held in place is no class field (so never feeds `blind`), but a reference + // store into a known script value type records the stored class types for `holder`. + (Val::Place(Some(ty)), Does::Store(Some(values))) if at != u32::MAX => { + let row = FieldFacts { + offset: at, + bytes: 8, + kind: Kind::Unknown, + }; + if let Some(owner) = declarer(&self.project.types, ty, &row) { + for value in values { + if let Val::Of(rhs) = self.origin(&flow.function, value) { + pass.value_held.entry((owner, at)).or_default().insert(rhs); + } + } + } + } + (Val::Place(_), _) => {} // ⚠ It may write the field at its offset of any type: null there changes nothing, // an object of a type is one more every such field may hold. (Val::Any, Does::Store(values)) => match self.put(&flow.function, values) { @@ -384,7 +407,13 @@ fn open( true } -/// The least typing of the reference fields of `candidates`, the fields no call types, that every flow agrees with. +/// Resolved field kinds keyed by owning type and byte offset. +pub type FieldKinds = BTreeMap<(TypeKey, u32), Kind>; + +/// Class types observed stored into value-type reference fields, keyed by owning type and byte offset. +pub type ValueHeld = BTreeMap<(TypeKey, u32), BTreeSet>; + +/// The least typing of the reference fields of `candidates`, the fields no call types, that every flow agrees with, and the class types stored into value-type reference fields. // ⚠ Each field starts holding no object and takes in what each pass finds stored, so a pass // only ever widens what a field holds or shuts it: the passes end, and what they end on agrees // with every flow, read with the types it gives. @@ -394,7 +423,7 @@ pub fn solve( unread: &BTreeSet, called: &BTreeMap<(TypeKey, u32), TypeKey>, candidates: &BTreeSet<(TypeKey, u32)>, -) -> BTreeMap<(TypeKey, u32), Kind> { +) -> (FieldKinds, ValueHeld) { let mut held: BTreeMap<(TypeKey, u32), Val> = candidates.iter().map(|place| (*place, Val::None)).collect(); for _ in 0..PASSES { @@ -421,11 +450,12 @@ pub fn solve( next.insert(*place, value); } if next == held { - return (held.into_iter()) + let solved = (held.into_iter()) .filter_map(|(place, value)| Some((place, value.kind()?))) .collect(); + return (solved, pass.value_held); } held = next; } - BTreeMap::new() + (BTreeMap::new(), BTreeMap::new()) } diff --git a/crates/io/or-io/src/gta6/script/project/layouts/mod.rs b/crates/io/or-io/src/gta6/script/project/layouts/mod.rs index b011b3523..751afa78c 100644 --- a/crates/io/or-io/src/gta6/script/project/layouts/mod.rs +++ b/crates/io/or-io/src/gta6/script/project/layouts/mod.rs @@ -109,7 +109,7 @@ pub struct Rows { pub array_elems: BTreeMap<(TypeKey, u32), ArrayElem>, /// 8-byte fields with positive managed heap reference evidence (`StoreKind::Ref` of non-raw values, managed casts, `System.Object` uses), by `(base_type, offset)`. pub managed_refs: BTreeSet<(TypeKey, u32)>, - /// 8-byte fields whose loaded values are raw-dereferenced (`Load`/`Store`/`ByteOffset`/array/delegate/raw-ptr intrinsics) or that interact with `void*` (`Kind::Pointer`), by `(base_type, offset)`. + /// 8-byte fields whose loaded values are raw-dereferenced (`Load`/`Store`/`ByteOffset`/array/raw-ptr intrinsics) or that interact with `void*` (`Kind::Pointer`), by `(base_type, offset)`. pub raw_derefed: BTreeSet<(TypeKey, u32)>, } @@ -1011,6 +1011,8 @@ fn peel_ref(mut e: &Expr) -> &Expr { /// One reading of a function for the fields its accesses show. struct Seen<'a> { bases: &'a BTreeMap, + /// The variables that hold a script value type in place on the stack (reached via `AddrOf`), in a second reading; their types are among `values`. + value_locals: &'a BTreeMap, /// The variables that hold an array of values of a script value type, in a second reading, with that type; its type is among `values`. elements: &'a BTreeMap, /// The settled project of a second reading, whose fields of object types a base's loads go through; `None` in the first. @@ -1211,7 +1213,17 @@ impl Seen<'_> { fn reference_store(&mut self, addr: &Expr, offset: u32, value: &Expr) { if self.project.is_some() { let put = self.origins(value, 0); - self.flow(addr, offset, Does::Store(put)); + if let Some((key, at)) = self.value_local_place(addr, offset, 8) { + let function = FunctionKey::new(self.head.program, self.head.at); + self.flows.push(Flow { + function, + base: Origin::Typed(key), + offset: at, + does: Does::Store(put), + }); + } else { + self.flow(addr, offset, Does::Store(put)); + } } } @@ -1222,7 +1234,38 @@ impl Seen<'_> { } } - /// The type and the offset in it that an access of `bytes` bytes at `offset` from `addr` reaches, the fields loaded on the way, and whether it is a part of an array's element, where `addr` is a base of known type moved by constants, a reference loaded through fields the settled project types, or the address of such an element. + /// The script value type and byte offset reached directly through `AddrOf` of a stack value local (under constant `ByteOffset`s), where the access lies within that value's bytes and is not a whole-value copy. + fn value_local_place(&self, addr: &Expr, offset: u32, bytes: u32) -> Option<(TypeKey, u32)> { + let (mut addr, mut offset) = (addr, offset); + for _ in 0..NESTED { + let Expr::ByteOffset { + addr: inner, + offset: by, + } = addr + else { + break; + }; + let Expr::Const(c) = &**by else { + return None; + }; + let by = u32::try_from(c.bits).ok()?; + offset = offset.checked_add(by)?; + addr = &**inner; + } + let Expr::AddrOf { var, cell } = addr else { + return None; + }; + let key = *self.value_locals.get(var)?; + let at = cell.checked_mul(8)?.checked_add(offset)?; + let facts = self.project?.types.get(&key)?; + let end = u64::from(at) + u64::from(bytes); + let fits = bytes > 0 + && end <= u64::from(facts.byte_size) + && (bytes < facts.byte_size || (bytes == 8 && at == 0)); + fits.then_some((key, at)) + } + + /// The type and the offset in it that an access of `bytes` bytes at `offset` from `addr` reaches, the fields loaded on the way, and whether it is a part of an array's element or a stack value local, where `addr` is a base of known type moved by constants, a reference loaded through fields the settled project types, or the address of such an element or value local. fn place( &self, addr: &Expr, @@ -1252,9 +1295,37 @@ impl Seen<'_> { } // The offsets `addr` is loaded through, the last load first. let mut through: Vec = Vec::new(); - let var = loop { + let mut key = loop { match addr { - Expr::Var(var) => break var, + Expr::Var(var) => { + // ⚠ A copy of a field read through a base of known type, assigned once, is that field. + break match (self.bases.get(var), self.copies.get(var)) { + (Some(key), _) => *key, + (None, Some((base, at))) if through.len() < CHAIN => { + through.push(*at); + *self.bases.get(base)? + } + _ => return None, + }; + } + Expr::AddrOf { var, cell } => { + let key = *self.value_locals.get(var)?; + let facts = self.project?.types.get(&key)?; + if through.is_empty() { + let at = cell.checked_mul(8)?.checked_add(offset)?; + let end = u64::from(at) + u64::from(bytes); + let fits = bytes > 0 + && end <= u64::from(facts.byte_size) + && (bytes < facts.byte_size || (bytes == 8 && at == 0)); + return fits.then_some((key, at, Vec::new(), true)); + } + let first = through.last_mut()?; + *first = cell.checked_mul(8)?.checked_add(*first)?; + if u64::from(*first) + 8 > u64::from(facts.byte_size) { + return None; + } + break key; + } Expr::Load { ty: Scalar::U64, addr: under, @@ -1266,15 +1337,6 @@ impl Seen<'_> { _ => return None, } }; - // ⚠ A copy of a field read through a base of known type, assigned once, is that field. - let mut key = match (self.bases.get(var), self.copies.get(var)) { - (Some(key), _) => *key, - (None, Some((base, at))) if through.len() < CHAIN => { - through.push(*at); - *self.bases.get(base)? - } - _ => return None, - }; let mut links = Vec::with_capacity(through.len()); for (n, at) in through.iter().rev().enumerate() { let project = self.project?; @@ -2197,7 +2259,7 @@ impl Seen<'_> { if let Some(first) = args.first() { if name == "invoke_delegate" || name.starts_with("invoke_delegate<") { self.note_delegate_field(first); - self.mark_raw_deref(first); + self.mark_managed_ref(first); } else if let Some((scalar, is_set)) = array_scalar(name) { self.mark_raw_deref(first); if let Some(place) = self.single_field_place(first) { @@ -2364,6 +2426,7 @@ pub fn of_function(project: &mut Project, f: &cfg::Function) { f, &bases, &BTreeMap::new(), + &BTreeMap::new(), &BTreeSet::new(), &sets.frame, None, @@ -2406,6 +2469,23 @@ fn of_typed_function_with( bases.entry(*var).or_insert(key); } } + // Stack locals (and value parameters) the kinds pass types as a script value type in place: + // their fields lie from byte 0 via `AddrOf`; their address is taken to initialize or pass them, + // so `sets.frame.reaches` is not checked. + let mut value_locals = BTreeMap::new(); + for (var, info) in &f.head.vars { + let Kind::Value { ty, .. } = &info.kind else { + continue; + }; + let Some(key) = TypeKey::of_name(ty).filter(|key| key.builtin().is_none() && !waits(*key)) + else { + continue; + }; + if project.types.get(&key).is_some_and(TypeFacts::is_value) { + value_locals.insert(*var, key); + values.insert(key); + } + } // An array the kinds pass types as one of values of a script value type: each element's // fields lie from its first byte. let mut elements = BTreeMap::new(); @@ -2419,6 +2499,7 @@ fn of_typed_function_with( part, f, &bases, + &value_locals, &elements, &values, &sets.frame, @@ -3142,12 +3223,13 @@ fn prescan_vars(f: &cfg::Function, seen: &mut Seen<'_>, frame: &Frame) { } } -/// Adds the rows, the truths and the objects stored the accesses of `f` through `bases` and the elements of the arrays `elements` holds show; a base of a type in `values` points at a value held in place, and `settled`, where given, types the fields loaded below a base. +/// Adds the rows, the truths and the objects stored the accesses of `f` through `bases`, stack `value_locals` and the elements of the arrays `elements` holds show; a base of a type in `values` points at a value held in place, and `settled`, where given, types the fields loaded below a base. #[allow(clippy::too_many_arguments)] fn seen_through( project: &mut Project, f: &cfg::Function, bases: &BTreeMap, + value_locals: &BTreeMap, elements: &BTreeMap, values: &BTreeSet, frame: &Frame, @@ -3155,11 +3237,12 @@ fn seen_through( names: Option<&crate::gta6::script::Names>, ) { // ⚠ A second reading notes every reference store, through a base of no known type too. - if bases.is_empty() && elements.is_empty() && settled.is_none() { + if bases.is_empty() && value_locals.is_empty() && elements.is_empty() && settled.is_none() { return; } let mut seen = Seen { bases, + value_locals, elements, project: settled, names, @@ -3358,6 +3441,7 @@ fn unread_truths(part: &mut Project, f: &cfg::Function, project: &Project) { f, &bases, &BTreeMap::new(), + &BTreeMap::new(), &values, &sets.frame, Some(project), @@ -3902,7 +3986,10 @@ fn settle_core( note_array_elem(&mut elems_by_owner, (owner, *offset), *elem); } } - let solved = flows::solve(known, flows, unread, &called, &open); + let (solved, value_held) = flows::solve(known, flows, unread, &called, &open); + for (place, types) in value_held { + held.entry(place).or_default().extend(types); + } for (owner, fields) in &mut settled { for field in fields.iter_mut() { let place = (*owner, field.offset); diff --git a/crates/io/or-io/src/gta6/script/project/layouts/tests.rs b/crates/io/or-io/src/gta6/script/project/layouts/tests.rs index 5a305d3c0..b4c1e59ba 100644 --- a/crates/io/or-io/src/gta6/script/project/layouts/tests.rs +++ b/crates/io/or-io/src/gta6/script/project/layouts/tests.rs @@ -1621,3 +1621,270 @@ fn concrete_array_fields_settle_from_new_array_and_array_intrinsics_despite_blin assert_eq!(kind(0x18), Some(Kind::Array(Box::new(Kind::F32)))); assert_eq!(kind(0x20), Some(Kind::Pointer)); } + +#[test] +fn stack_value_local_enumerator_stores_record_held_type_and_resolve_f0() { + use crate::gta6::script::class::Role; + use crate::gta6::script::ir::VarInfo; + use crate::gta6::script::project::Member; + + const DICT: TypeKey = TypeKey(0x0A0A_0000_0000_0050); + const ENUM: TypeKey = TypeKey(0x0A0A_0000_0000_0051); + + let mut project = classes(); + project.types.insert( + DICT, + TypeFacts { + byte_size: 48, + base: Some(TypeKey(0x8000_0000)), + ..TypeFacts::default() + }, + ); + project.types.insert( + ENUM, + TypeFacts { + byte_size: 32, + flags: 0x04, + ..TypeFacts::default() + }, + ); + project.members.insert( + FunctionKey::new(PROGRAM, 0x40), + Member { + owner: DICT, + role: Role::Method, + is_static: false, + slot: None, + }, + ); + project.members.insert( + FunctionKey::new(PROGRAM, 0x50), + Member { + owner: ENUM, + role: Role::Method, + is_static: false, + slot: None, + }, + ); + + // `Dictionary.GetEnumerator`: allocates stack `Enumerator` local `local_0`, zeroes it, + // initializes `e.f_0 = this`, and returns the 32-byte struct value. + let addr_e = Expr::AddrOf { + var: Var::Local(0), + cell: 0, + }; + let mut get_enum = function( + 0x40, + vec![ + Stmt::ZeroBytes { + addr: addr_e.clone(), + bytes: 32, + }, + store(StoreKind::Ref, addr_e.clone(), 0, param(0)), + store(StoreKind::I32, addr_e.clone(), 8, int(1)), + ], + ); + get_enum.head.returns = Returns::Cells; + let mut e_info = VarInfo::new(Width::Cells); + e_info.kind = Kind::Value { + ty: ENUM.to_string(), + cells: 4, + }; + get_enum.head.vars.insert(Var::Local(0), e_info); + get_enum.cfg.blocks[0].term = Terminator::Return(Some(Expr::LoadBytes { + addr: Box::new(addr_e), + offset: 0, + bytes: 32, + })); + + // `Enumerator.MoveNext`: dereferences `(*this.f_0).f_18`. + let move_next = function( + 0x50, + vec![set( + Var::Local(0), + load(Scalar::I32, load(Scalar::U64, param(0), 0), 0x18), + )], + ); + + let project = read_thrice(project, &[get_enum, move_next]); + assert_eq!( + project.field(ENUM, 0).map(|f| f.kind.clone()), + Some(Kind::Object(DICT.to_string())) + ); + assert_eq!(project.field(ENUM, 8).map(|f| f.bytes), Some(4)); +} + +#[test] +fn value_type_constructor_flow_resolves_f0_after_param_is_typed_and_avoids_false_positives() { + use crate::gta6::script::class::Role; + use crate::gta6::script::project::{Member, Signature}; + + const DICT: TypeKey = TypeKey(0x0A0A_0000_0000_0060); + const OTHER: TypeKey = TypeKey(0x0A0A_0000_0000_0061); + const ENUM: TypeKey = TypeKey(0x0A0A_0000_0000_0062); + const UNREACHED: TypeKey = TypeKey(0x0A0A_0000_0000_0063); + const CONFLICT: TypeKey = TypeKey(0x0A0A_0000_0000_0064); + + let mut project = classes(); + for ty in [DICT, OTHER] { + project.types.insert( + ty, + TypeFacts { + byte_size: 48, + base: Some(TypeKey(0x8000_0000)), + ..TypeFacts::default() + }, + ); + } + for ty in [ENUM, UNREACHED, CONFLICT] { + project.types.insert( + ty, + TypeFacts { + byte_size: 32, + flags: 0x04, + ..TypeFacts::default() + }, + ); + } + let member = |owner: TypeKey| Member { + owner, + role: Role::Method, + is_static: false, + slot: None, + }; + project + .members + .insert(FunctionKey::new(PROGRAM, 0x40), member(ENUM)); + project + .members + .insert(FunctionKey::new(PROGRAM, 0x50), member(ENUM)); + project + .members + .insert(FunctionKey::new(PROGRAM, 0x60), member(UNREACHED)); + project + .members + .insert(FunctionKey::new(PROGRAM, 0x70), member(CONFLICT)); + project + .members + .insert(FunctionKey::new(PROGRAM, 0x80), member(CONFLICT)); + project + .members + .insert(FunctionKey::new(PROGRAM, 0x90), member(CONFLICT)); + + // `ENUM.Ctor(this, dict)`: stores `param(1)` before `param(1)`'s signature is typed. + let enum_ctor = function(0x40, vec![store(StoreKind::Ref, param(0), 0, param(1))]); + // `ENUM.MoveNext(this)`: reads `(*this.f_0).f_18`. + let enum_move = function( + 0x50, + vec![set( + Var::Local(0), + load(Scalar::I32, load(Scalar::U64, param(0), 0), 0x18), + )], + ); + // `UNREACHED.Ctor(this, dict)`: stores `param(1)`, but `f_0` is never dereferenced. + let unreached_ctor = function(0x60, vec![store(StoreKind::Ref, param(0), 0, param(1))]); + // `CONFLICT`: stores two unrelated classes into `f_0`, dereferenced at `0x18`. + let conflict_a = function(0x70, vec![store(StoreKind::Ref, param(0), 0, param(1))]); + let conflict_b = function(0x80, vec![store(StoreKind::Ref, param(0), 0, param(1))]); + let conflict_move = function( + 0x90, + vec![set( + Var::Local(0), + load(Scalar::I32, load(Scalar::U64, param(0), 0), 0x18), + )], + ); + + let mut project = read_thrice( + project, + &[ + enum_ctor, + enum_move, + unreached_ctor, + conflict_a, + conflict_b, + conflict_move, + ], + ); + assert_eq!( + project.field(ENUM, 0).map(|f| f.kind.clone()), + Some(Kind::Pointer) + ); + + let ctor_sig = |ty: TypeKey| Signature { + params: vec![ + Param { + kind: Kind::Pointer, + cells: 1, + }, + Param { + kind: Kind::Object(ty.to_string()), + cells: 1, + }, + ], + ..Signature::default() + }; + project + .signatures + .insert(FunctionKey::new(PROGRAM, 0x40), ctor_sig(DICT)); + project + .signatures + .insert(FunctionKey::new(PROGRAM, 0x60), ctor_sig(DICT)); + project + .signatures + .insert(FunctionKey::new(PROGRAM, 0x70), ctor_sig(DICT)); + project + .signatures + .insert(FunctionKey::new(PROGRAM, 0x80), ctor_sig(OTHER)); + + settle_again(&mut project); + + assert_eq!( + project.field(ENUM, 0).map(|f| f.kind.clone()), + Some(Kind::Object(DICT.to_string())) + ); + // Value-struct field never dereferenced stays `Kind::Pointer`. + assert_eq!( + project.field(UNREACHED, 0).map(|f| f.kind.clone()), + Some(Kind::Pointer) + ); + // Conflicting unrelated classes stored into `f_0` stay `Kind::Pointer`. + assert_eq!( + project.field(CONFLICT, 0).map(|f| f.kind.clone()), + Some(Kind::Pointer) + ); +} + +#[test] +fn invoke_delegate_does_not_mark_field_raw_dereferenced() { + let invoke = |arg: Expr| Expr::Call { + callee: Callee::Intrinsic { + name: "invoke_delegate".to_owned(), + ty: None, + wrapper: None, + }, + args: vec![arg], + returns: Some(0), + }; + let body = vec![ + set(Var::Local(0), made()), + // f_8: directly invoked via `invoke_delegate` -> `System.Delegate`, not `raw_derefed`. + store(StoreKind::Ref, local(0), 8, param(1)), + Stmt::Eval(invoke(load(Scalar::U64, local(0), 8))), + // f_10 and f_18: merged through a multi-assigned local `local_1`, then invoked via + // `invoke_delegate` -> neither is `raw_derefed`, so both promote to `System.Object`. + store(StoreKind::Ref, local(0), 0x10, param(1)), + store(StoreKind::Ref, local(0), 0x18, param(1)), + set(Var::Local(1), load(Scalar::U64, local(0), 0x10)), + set(Var::Local(1), load(Scalar::U64, local(0), 0x18)), + Stmt::Eval(invoke(local(1))), + ]; + let mut project = read_twice(classes(), &[function(0x40, body)]); + assert!(!project.rows.raw_derefed.contains(&(MADE, 8))); + assert!(!project.rows.raw_derefed.contains(&(MADE, 0x10))); + assert!(!project.rows.raw_derefed.contains(&(MADE, 0x18))); + apply_stated_fields(&mut project); + let kind = |offset: u32| project.field(MADE, offset).map(|f| f.kind.clone()); + assert_eq!(kind(8), Some(Kind::Object("System.Delegate".to_owned()))); + assert_eq!(kind(0x10), Some(Kind::Object("System.Object".to_owned()))); + assert_eq!(kind(0x18), Some(Kind::Object("System.Object".to_owned()))); +} diff --git a/crates/io/or-io/src/gta6/script/project/signatures/mod.rs b/crates/io/or-io/src/gta6/script/project/signatures/mod.rs index 838ed18b9..7ea12f906 100644 --- a/crates/io/or-io/src/gta6/script/project/signatures/mod.rs +++ b/crates/io/or-io/src/gta6/script/project/signatures/mod.rs @@ -156,6 +156,28 @@ pub fn of_function_read(project: &mut Project, f: &cfg::Function, first: FirstRe } } open.backs = truth_backs(f, &reader, &body); + } else if head.returns == Returns::Cells { + let found = returned_cells(f, project, &body, returns); + let waits = !found.from.is_empty() || found.kind.is_none(); + match (found.dead, waits) { + (true, _) => {} + (false, true) => { + open.live = true; + if !open.wide { + open.returned = found.from.iter().copied().collect(); + } else if !found.from.is_empty() { + let mut all: BTreeSet = open.returned.iter().copied().collect(); + all.extend(found.from.iter().copied()); + open.returned = all.into_iter().collect(); + } + result = found.kind.clone().unwrap_or(Kind::Unknown); + } + (false, false) => { + if let Some(kind) = found.kind { + result = kind; + } + } + } } let groups = body.groups(); @@ -1124,6 +1146,223 @@ fn returned(f: &cfg::Function, reader: &Reader<'_>) -> Found { found } +/// The cell count of a concrete multi-cell kind (`Vector`, `Handle`, or `Value` of 2+ cells). +pub(super) fn wide_cells_of(kind: &Kind) -> Option { + match kind { + Kind::Vector | Kind::Handle => Some(2), + Kind::Value { ty, cells } if *cells >= 2 && !ty.is_empty() => Some(*cells), + _ => None, + } +} + +/// The concrete multi-cell kind `head` states for `var` matching `want` cells (or any 2+ cells when `want == 0`). +fn var_wide_kind(head: &Head, var: Var, want: u32) -> Option { + if let Some(info) = head.vars.get(&var) { + if let Some(cells) = wide_cells_of(&info.kind) { + if want == 0 || cells == want { + return Some(info.kind.clone()); + } + } + } + if let Some(Some((ty, cells))) = head.value_types.get(&var) { + if ty.builtin().is_none() && *cells >= 2 && (want == 0 || *cells == want) { + return Some(Kind::Value { + ty: ty.to_string(), + cells: *cells, + }); + } + } + None +} + +/// The owner type of a non-static receiver for `own`, from `members` or a unique vtable slot owner in `project.types`. +fn receiver_owner(project: &Project, own: FunctionKey) -> Option { + if let Some(member) = project.members.get(&own).filter(|m| !m.is_static) { + return Some(member.owner); + } + let mut found: Option = None; + for (ty, facts) in &project.types { + if facts.slots.values().any(|f| *f == own) { + if found.is_some() { + return None; + } + found = Some(*ty); + } + } + found +} + +/// Unwraps constant `ByteOffset`s around `addr` into `offset`. +fn fold_byte_offset(mut addr: &Expr, offset: u32) -> (&Expr, Option) { + let mut at = Some(offset); + for _ in 0..8 { + let Expr::ByteOffset { + addr: inner, + offset: by, + } = handed(addr) + else { + break; + }; + let by = match handed(by) { + Expr::Const(c) => u32::try_from(c.bits).ok(), + _ => None, + }; + at = at.zip(by).and_then(|(a, b)| a.checked_add(b)); + addr = inner; + } + (addr, at) +} + +/// What a multi-cell expression evaluates to (`Vector`, `Handle`, or `Value` of matching cells). +#[allow(clippy::too_many_arguments)] +fn wide_expr( + e: &Expr, + head: &Head, + project: &Project, + owner: Option, + groups: &BTreeMap, + vars: &HashMap, + returns: u32, + depth: u32, +) -> Found { + if depth > MAX_DEPTH { + return Found::dead(); + } + let d = depth + 1; + match e { + Expr::Sugar { e: inner, .. } => { + wide_expr(inner, head, project, owner, groups, vars, returns, d) + } + Expr::Vector3(_) if returns == 0 || returns == 2 => Found::of(Kind::Vector), + Expr::GuidEmpty if returns == 0 || returns == 2 => Found::of(Kind::Handle), + Expr::ZeroSlots(cells) if *cells >= 2 && (returns == 0 || *cells == returns) => { + Found::default() + } + Expr::Select { then, els, .. } => { + let mut found = wide_expr(then, head, project, owner, groups, vars, returns, d); + found.join(&wide_expr( + els, head, project, owner, groups, vars, returns, d, + )); + found + } + Expr::Var(var) => { + if let Some(kind) = var_wide_kind(head, *var, returns) { + return Found::of(kind); + } + vars.get(var).cloned().unwrap_or_else(Found::dead) + } + Expr::Cells(items) => match run(items) { + Some((first, 2)) + if (returns == 0 || returns == 2) && groups.get(&first) == Some(&(2, true)) => + { + Found::of(Kind::Handle) + } + _ => Found::dead(), + }, + Expr::LoadBytes { + addr, + offset, + bytes, + } => { + let cells = bytes.div_ceil(8); + if cells < 2 || (returns != 0 && cells != returns) { + return Found::dead(); + } + let (base_addr, total_offset) = fold_byte_offset(addr, *offset); + match handed(base_addr) { + Expr::AddrOf { var, cell: 0 } if total_offset == Some(0) => { + var_wide_kind(head, *var, cells).map_or_else(Found::dead, Found::of) + } + Expr::Var(Var::Param(0)) => { + let Some((owner, at)) = owner.zip(total_offset) else { + return Found::dead(); + }; + let field = project + .field(owner, at) + .filter(|f| f.bytes == *bytes && wide_cells_of(&f.kind) == Some(cells)); + field.map_or_else(Found::dead, |f| Found::of(f.kind.clone())) + } + _ => Found::dead(), + } + } + Expr::Call { + callee, + returns: call_returns, + .. + } => { + let ok_cells = call_returns.is_none_or(|c| c >= 2 && (returns == 0 || c == returns)); + match (key_of(head.program, callee), callee) { + (Some(key), _) if ok_cells => Found { + from: BTreeSet::from([key]), + ..Found::default() + }, + (None, Callee::Intrinsic { name, .. }) + if name.starts_with("packed_vector_") + && *call_returns == Some(2) + && (returns == 0 || returns == 2) => + { + Found::of(Kind::Vector) + } + _ => Found::dead(), + } + } + _ => Found::dead(), + } +} + +/// What the cells a function of several returned cells hands back are, by its own code. +fn returned_cells(f: &cfg::Function, project: &Project, body: &Body, returns: u32) -> Found { + let head = &f.head; + let own = FunctionKey::new(head.program, head.at); + let groups = body.groups(); + let owner = receiver_owner(project, own); + let sealed = |var: Var| match var { + Var::Local(n) => body.lowest_local.is_none_or(|low| n < low), + Var::Value { .. } | Var::Stack { .. } => !body.addressed.contains(&var), + Var::Param(_) | Var::Global { .. } => false, + }; + let mut sets: Vec<(Var, &Expr)> = Vec::new(); + for stmt in f.cfg.blocks.iter().flat_map(|block| &block.stmts) { + match stmt { + Stmt::Assign { target, value } => sets.push((*target, value)), + Stmt::AssignMany { targets, values } => { + sets.extend(targets.iter().copied().zip(values)); + } + _ => {} + } + } + sets.retain(|(target, _)| sealed(*target)); + let mut vars: HashMap = HashMap::new(); + for (target, _) in &sets { + vars.entry(*target).or_default(); + } + let mut moving = true; + for _ in 0..ROUNDS { + moving = false; + for (target, value) in &sets { + let given = wide_expr(value, head, project, owner, &groups, &vars, returns, 0); + if let Some(held) = vars.get_mut(target) { + moving |= held.join(&given); + } + } + if !moving { + break; + } + } + if moving { + vars.clear(); + } + let mut found = Found::default(); + for block in &f.cfg.blocks { + if let Terminator::Return(Some(e)) = &block.term { + found.join(&wide_expr( + e, head, project, owner, &groups, &vars, returns, 0, + )); + } + } + found +} + /// The results a function of one returned cell hands on, where every `return` is zero, one, a truth, or such a result, and some `return` hands one on. // ⚠ What a variable returned holds counts only where nothing but its assignments writes it, as // the reader has it; a slot's result only as the call yields it, one cell. @@ -1516,7 +1755,7 @@ fn run(items: &[Expr]) -> Option<(u32, u32)> { /// What a function that waits on nothing returns, by its signature; one the project does not hold returns what nothing knows. fn stated(project: &Project, function: &FunctionKey) -> Found { match project.signatures.get(function) { - Some(held) if held.returns == 1 && held.result != Kind::Unknown => { + Some(held) if held.returns >= 1 && held.result != Kind::Unknown => { Found::of(held.result.clone()) } _ => Found::dead(), @@ -1604,10 +1843,17 @@ fn results( } if waits.live { let found = kinds.get(key).filter(|found| !found.dead && !unsettled); - let kind = found.and_then(|found| { - let kind = resolved(project, found).or_else(|| shared.read_as(key, found)); - let kind = kind.or_else(|| shared.line_read_as(key, found)); - kind.filter(|kind| holds(kind, found)) + let returns = project.signatures.get(key).map(|held| held.returns); + let kind = found.and_then(|found| match returns { + Some(1) => { + let kind = resolved(project, found).or_else(|| shared.read_as(key, found)); + let kind = kind.or_else(|| shared.line_read_as(key, found)); + kind.filter(|kind| wide_cells_of(kind).is_none() && holds(kind, found)) + } + Some(cells) if cells >= 2 => { + resolved(project, found).filter(|kind| wide_cells_of(kind) == Some(cells)) + } + _ => None, }); if let Some(held) = project.signatures.get_mut(key) { held.result = kind.unwrap_or(Kind::Unknown); diff --git a/crates/io/or-io/src/gta6/script/project/signatures/shared.rs b/crates/io/or-io/src/gta6/script/project/signatures/shared.rs index 3cfc7f6d0..433c1100c 100644 --- a/crates/io/or-io/src/gta6/script/project/signatures/shared.rs +++ b/crates/io/or-io/src/gta6/script/project/signatures/shared.rs @@ -5,8 +5,8 @@ use std::collections::{BTreeMap, BTreeSet}; use super::{ - holds, number, param_at, resolved, settled, Back, Found, Open, Slot, Usage, ANY, MAX_PARAMS, - ROUNDS, + holds, param_at, resolved, settled, wide_cells_of, Back, Found, Open, Slot, Usage, ANY, + MAX_PARAMS, ROUNDS, }; use crate::gta6::script::ir::{FunctionKey, Kind, TypeKey}; use crate::gta6::script::project::{Param, Project, Signature}; @@ -151,23 +151,24 @@ impl Shared { } } -/// Notes for each function a virtual slot holds the kind of the one cell every function of its line hands back, where all of them prove the same. +/// Notes for each function a virtual slot holds the kind every function of its line hands back, where all of them prove the same cell count and kind. // ⚠ A call through the slot reaches one function of the line, whichever type the object is: // one function that proves nothing, or another kind, and the call yields no kind. pub(super) fn slot_results(project: &mut Project, shared: &Shared) { - let mut agreed: BTreeMap> = BTreeMap::new(); + let mut agreed: BTreeMap> = BTreeMap::new(); for (member, root) in &shared.roots { let held = project.signatures.get(member); - let proved = held.filter(|held| settled(held) && held.returns == 1); - let kind = proved.map(|held| held.result.clone()); - let kind = kind.filter(|kind| *kind != Kind::Unknown); - let line = agreed.entry(*root).or_insert_with(|| kind.clone()); - if *line != kind { + let proved = held.filter(|held| settled(held) && held.returns >= 1); + let found = proved + .filter(|held| held.result != Kind::Unknown) + .map(|held| (held.returns, held.result.clone())); + let line = agreed.entry(*root).or_insert_with(|| found.clone()); + if *line != found { *line = None; } } for (member, root) in &shared.roots { - if let Some(Some(kind)) = agreed.get(root) { + if let Some(Some((_, kind))) = agreed.get(root) { project.slot_results.insert(*member, kind.clone()); } } @@ -725,15 +726,21 @@ pub(super) fn agreed( ) -> bool { let mut changed = false; for members in shared.families.values() { + let mut expected_returns: Option = None; let mut kind: Option = None; let mut constant: Vec<(FunctionKey, &Found)> = Vec::new(); let mut whole = true; for member in members { let held = project.signatures.get(member); - let Some(held) = held.filter(|held| settled(held) && held.returns == 1) else { + let Some(held) = held.filter(|held| settled(held) && held.returns >= 1) else { whole = false; break; }; + if expected_returns.is_some_and(|cells| cells != held.returns) { + whole = false; + break; + } + expected_returns = Some(held.returns); if held.result != Kind::Unknown { if kind.as_ref().is_some_and(|kind| *kind != held.result) { whole = false; @@ -750,10 +757,14 @@ pub(super) fn agreed( }; constant.push((*member, found)); } - let Some(kind) = kind.filter(|_| whole) else { + let (Some(returns), Some(kind)) = (expected_returns, kind.filter(|_| whole)) else { continue; }; - if !constant.iter().all(|(_, found)| holds(&kind, found)) { + let shape_ok = match returns { + 1 => wide_cells_of(&kind).is_none(), + cells => wide_cells_of(&kind) == Some(cells), + }; + if !shape_ok || !constant.iter().all(|(_, found)| holds(&kind, found)) { continue; } for (member, _) in constant { @@ -929,7 +940,7 @@ pub(super) fn passed(project: &mut Project, open: &BTreeMap, } } -/// Gives each parameter cell that some functions of a line type alike, and the rest leave untyped, that kind in all of them, where it is no integer. +/// Gives each parameter cell that some functions of a line type alike, and the rest leave untyped, that kind in all of them. // An override declares what the method it overrides declares; two kinds for one cell stay as each function has them. pub(super) fn overridden(project: &mut Project, shared: &Shared) { for members in shared.families.values() { @@ -945,9 +956,8 @@ pub(super) fn overridden(project: &mut Project, shared: &Shared) { wanted = true; continue; } - // Another kind, cells that are no parameter of one cell there, or an integer, - // whose sign each function's own reads say. - let theirs = stated(project, member, cell).filter(|kind| !number(kind)); + // Another kind or cells that are no parameter of one cell there. + let theirs = stated(project, member, cell); let differs = kind .as_ref() .is_some_and(|mine| theirs.as_ref() != Some(mine)); diff --git a/crates/io/or-io/src/gta6/script/project/signatures/tests.rs b/crates/io/or-io/src/gta6/script/project/signatures/tests.rs index 2b8a28f72..05c9a427b 100644 --- a/crates/io/or-io/src/gta6/script/project/signatures/tests.rs +++ b/crates/io/or-io/src/gta6/script/project/signatures/tests.rs @@ -496,3 +496,311 @@ fn what_a_function_whose_signature_is_not_kept_calls_is_read_as_anything() { assert_eq!(result(&lost, 0x10), Kind::Unknown); assert!(!lost.native_truths.contains(&5)); } + +#[test] +fn multi_cell_returns_infer_result_kind_and_propagate_through_calls_and_slots() { + use crate::gta6::script::cfg::{Block, Cfg, Function, Terminator}; + use crate::gta6::script::ir::{Callee, Const, Expr, Head, Returns, Stmt, Var, VarInfo, Width}; + use crate::gta6::script::project::{FieldFacts, Project, TypeFacts}; + + let kvp_ty = invented(0xE1); + let base_enum = invented(0xE2); + let derived_enum = invented(0xE3); + let kvp_kind = Kind::Value { + ty: kvp_ty.to_string(), + cells: 2, + }; + + let make_fn = |at: u32, params: u32, blocks: Vec| Function { + head: Head { + value_types: Default::default(), + program: 1, + at, + name: format!("func_{at:06X}"), + returns: Returns::Cells, + params, + locals: 4, + vars: BTreeMap::new(), + incomplete: None, + }, + cfg: Cfg { blocks }, + }; + + // 0x10: returns Vector3 (2 cells). + let f_vec = make_fn( + 0x10, + 0, + vec![Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::Vector3(Box::new([ + Expr::Const(Const::f32(1.0)), + Expr::Const(Const::f32(2.0)), + Expr::Const(Const::f32(3.0)), + ])))), + }], + ); + + // 0x20: returns GuidEmpty on one path and ZeroSlots(2) on another -> Kind::Handle. + let f_handle = make_fn( + 0x20, + 1, + vec![ + Block { + at: None, + stmts: Vec::new(), + term: Terminator::Branch { + cond: Expr::Var(Var::Param(0)), + then: 1, + els: 2, + }, + }, + Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::GuidEmpty)), + }, + Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::ZeroSlots(2))), + }, + ], + ); + + // 0x30: forwards 0x20's multi-cell return through an aggregate local -> inherits Kind::Handle. + let mut f_forward = make_fn( + 0x30, + 1, + vec![Block { + at: None, + stmts: vec![Stmt::Assign { + target: Var::Local(0), + value: Expr::Call { + callee: Callee::Local { + at: 0x20, + name: "func_000020".to_owned(), + }, + args: vec![Expr::Var(Var::Param(0))], + returns: Some(2), + }, + }], + term: Terminator::Return(Some(Expr::Var(Var::Local(0)))), + }], + ); + let mut agg_var = VarInfo::new(Width::Cells); + agg_var.kind = Kind::Aggregate(2); + f_forward.head.vars.insert(Var::Local(0), agg_var); + + // 0x38: directly forwards 0x20 with unspecified call return count (wide + live). + let f_direct_forward = make_fn( + 0x38, + 1, + vec![Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::Call { + callee: Callee::Local { + at: 0x20, + name: "func_000020".to_owned(), + }, + args: vec![Expr::Var(Var::Param(0))], + returns: None, + })), + }], + ); + + // 0x40: returns LoadBytes(&local_0, 0, 16) where local_0 is Kind::Value { kvp, cells: 2 }. + let mut f_struct = make_fn( + 0x40, + 0, + vec![Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::LoadBytes { + addr: Box::new(Expr::AddrOf { + var: Var::Local(0), + cell: 0, + }), + offset: 0, + bytes: 16, + })), + }], + ); + let mut kvp_var = VarInfo::new(Width::Cells); + kvp_var.kind = kvp_kind.clone(); + f_struct.head.vars.insert(Var::Local(0), kvp_var); + + // 0x50 (base stub) and 0x60 (derived `get_Current`) share virtual slot 4: + // base returns ZeroSlots(2), derived loads the 16-byte KVP field at offset 0x10 of `this`. + let f_base_cur = make_fn( + 0x50, + 1, + vec![Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::ZeroSlots(2))), + }], + ); + let f_derived_cur = make_fn( + 0x60, + 1, + vec![Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::LoadBytes { + addr: Box::new(Expr::Var(Var::Param(0))), + offset: 0x10, + bytes: 16, + })), + }], + ); + + // 0x70: conflicting Vector3 vs GuidEmpty -> stays Kind::Unknown. + let f_conflict = make_fn( + 0x70, + 1, + vec![ + Block { + at: None, + stmts: Vec::new(), + term: Terminator::Branch { + cond: Expr::Var(Var::Param(0)), + then: 1, + els: 2, + }, + }, + Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::Vector3(Box::new([ + Expr::Const(Const::f32(0.0)), + Expr::Const(Const::f32(0.0)), + Expr::Const(Const::f32(0.0)), + ])))), + }, + Block { + at: None, + stmts: Vec::new(), + term: Terminator::Return(Some(Expr::GuidEmpty)), + }, + ], + ); + + let mut project = Project::default(); + project.types.insert( + base_enum, + TypeFacts { + base: None, + slots: BTreeMap::from([(4, key(0x50))]), + ..TypeFacts::default() + }, + ); + project.types.insert( + derived_enum, + TypeFacts { + base: Some(base_enum), + byte_size: 32, + flags: 0x04, + slots: BTreeMap::from([(4, key(0x60))]), + ..TypeFacts::default() + }, + ); + project.fields.insert( + derived_enum, + vec![FieldFacts { + offset: 0x10, + bytes: 16, + kind: kvp_kind.clone(), + }], + ); + + for f in [ + &f_vec, + &f_handle, + &f_forward, + &f_direct_forward, + &f_struct, + &f_base_cur, + &f_derived_cur, + &f_conflict, + ] { + of_function(&mut project, f); + } + settle(&mut project); + + assert_eq!(result(&project, 0x10), Kind::Vector); + assert_eq!(result(&project, 0x20), Kind::Handle); + assert_eq!(result(&project, 0x30), Kind::Handle); + assert_eq!(result(&project, 0x38), Kind::Handle); + assert_eq!(result(&project, 0x40), kvp_kind); + assert_eq!(result(&project, 0x50), kvp_kind); + assert_eq!(result(&project, 0x60), kvp_kind); + assert_eq!(result(&project, 0x70), Kind::Unknown); + assert_eq!(project.slot_result(base_enum, 4), Some(&kvp_kind)); + assert_eq!(project.slot_result(derived_enum, 4), Some(&kvp_kind)); +} + +#[test] +fn overridden_unifies_agreed_numeric_slot_parameters_and_leaves_conflicts_unknown() { + let functions = [ + // Slot family 1: empty base stub + override reading p1 as `int`. + function("void", 0x10, 2, "return;"), + function( + "void", + 0x20, + 2, + "if (((as_i32(p1) < as_i32(5)))) { Native.DEMO.USE(1); } return;", + ), + // Slot family 2: empty base stub + override reading p1 as `uint`. + function("void", 0x30, 2, "return;"), + function( + "void", + 0x40, + 2, + "if (((as_u32(p1) < as_u32(5)))) { Native.DEMO.USE(1); } return;", + ), + // Slot family 3: empty base stub + two overrides disagreeing (`int` vs `uint`). + function("void", 0x50, 2, "return;"), + function( + "void", + 0x60, + 2, + "if (((as_i32(p1) < as_i32(5)))) { Native.DEMO.USE(1); } return;", + ), + function( + "void", + 0x70, + 2, + "if (((as_u32(p1) < as_u32(5)))) { Native.DEMO.USE(1); } return;", + ), + ]; + let mut project = parts_of(&[listing(1, &functions)]); + project.types.insert(invented(0xF1), fills(None, 0x10)); + project + .types + .insert(invented(0xF2), fills(Some(invented(0xF1)), 0x20)); + project.types.insert(invented(0xF3), fills(None, 0x30)); + project + .types + .insert(invented(0xF4), fills(Some(invented(0xF3)), 0x40)); + project.types.insert(invented(0xF5), fills(None, 0x50)); + project + .types + .insert(invented(0xF6), fills(Some(invented(0xF5)), 0x60)); + project + .types + .insert(invented(0xF7), fills(Some(invented(0xF5)), 0x70)); + settle(&mut project); + + // Agreed `int` propagates to the empty base stub. + assert_eq!(param(&project, 0x10, 1), Kind::I32); + assert_eq!(param(&project, 0x20, 1), Kind::I32); + // Agreed `uint` propagates to the empty base stub. + assert_eq!(param(&project, 0x30, 1), Kind::U32); + assert_eq!(param(&project, 0x40, 1), Kind::U32); + // Disagreement (`int` vs `uint`) leaves the base stub `Unknown` and each override intact. + assert_eq!(param(&project, 0x50, 1), Kind::Unknown); + assert_eq!(param(&project, 0x60, 1), Kind::I32); + assert_eq!(param(&project, 0x70, 1), Kind::U32); +} 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 aa0195ad8..f2004a18d 100644 --- a/crates/io/or-io/src/gta6/script/reparse/mod.rs +++ b/crates/io/or-io/src/gta6/script/reparse/mod.rs @@ -2617,7 +2617,7 @@ fn takes(taken: &Stmt, asked: Option<&Expr>) -> bool { } /// The call that fills the variables the statements before it only made zero, where `parts` are those and it: `F(out T x)`. -fn filled(parts: &[Stmt]) -> Option<&Stmt> { +fn filled(parts: &[Stmt], native_only: bool) -> Option<&Stmt> { let (call, zeroed) = parts.split_last()?; if zeroed.is_empty() { return None; @@ -2627,7 +2627,7 @@ fn filled(parts: &[Stmt]) -> Option<&Stmt> { return None; }; let empty = is_zero(value) || matches!(under_wide(value), Expr::ZeroSlots(_)); - if !empty || !fills(call, *target) { + if !empty || !fills(call, *target, native_only) { return None; } } @@ -2635,14 +2635,28 @@ fn filled(parts: &[Stmt]) -> Option<&Stmt> { } /// Whether `call` hands the address of `var` to a parameter its callee only fills. -fn fills(call: &Stmt, var: Var) -> bool { +fn fills(call: &Stmt, var: Var, native_only: bool) -> bool { + let handed = Expr::AddrOf { var, cell: 0 }; let mut found = false; call.each_expr(&mut |top| { top.walk(&mut |node| { - found |= matches!( - node, - Expr::Sugar { kind: ExprSugar::Out, e: held } if **held == Expr::AddrOf { var, cell: 0 } - ); + if native_only { + if let Expr::Call { + callee: Callee::Native { .. }, + args, + .. + } = node + { + found |= args.iter().any(|arg| { + matches!(arg, Expr::Sugar { kind: ExprSugar::Out, e } if **e == handed) + }); + } + } else { + found |= matches!( + node, + Expr::Sugar { kind: ExprSugar::Out, e: held } if **held == handed + ); + } }); }); found @@ -3602,7 +3616,14 @@ impl Held<'_> { Expr::ByteOffset { addr, offset } => match &**offset { Expr::Const(c) if c.bits == 0 => self.sk(addr, d)?, Expr::Const(c) if c.bits <= u64::from(u32::MAX) => { - Sk::Op("&", vec![self.place(addr, c.bits as u32, false, d)?]) + let addr_of = Sk::Op("&", vec![self.place(addr, c.bits as u32, false, d)?]); + if self.sharp() { + let called = + call("byte_offset", vec![self.sk(addr, d)?, self.sk(offset, d)?]); + Sk::Op(EITHER, vec![addr_of, called]) + } else { + addr_of + } } _ => call("byte_offset", vec![self.sk(addr, d)?, self.sk(offset, d)?]), }, @@ -3835,10 +3856,18 @@ impl Held<'_> { } // The rest the source level writes as the form of old does, a method by the name the // printer writes it under. - (ExprSugar::Method, Expr::Call { callee, args, .. }) if !args.is_empty() => called( - member(self.sk(&args[0], d)?, &self.called_name(callee)), - self.list(&args[1..], d)?, - ), + (ExprSugar::Method, Expr::Call { callee, args, .. }) if !args.is_empty() => { + let receiver = match under_wide(&args[0]) { + Expr::AddrOf { var, cell: 0 } if super::print::is_value_builtin(callee) => { + Sk::Name(self.var(*var)) + } + _ => self.sk(&args[0], d)?, + }; + called( + member(receiver, &self.called_name(callee)), + self.list(&args[1..], d)?, + ) + } // A static property of the runtime's own types, by the type that declares it. ( ExprSugar::Property, @@ -4789,7 +4818,7 @@ impl Held<'_> { } if let tree::Group::Out = kind { let call = match self.on(Pass::RefOut) { - true => filled(parts), + true => filled(parts, self.sharp()), false => None, }; return self.simples(call.map_or(parts, std::slice::from_ref), out, d);