Skip to content

Commit 9460260

Browse files
committed
improve prev PR
1 parent 9fe6f6d commit 9460260

9 files changed

Lines changed: 296 additions & 14 deletions

File tree

‎src/men-sharp-codegen/src/generator.rs‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1731,6 +1731,12 @@ impl<'a, 'ast> Generator<'a, 'ast> {
17311731
}
17321732
if bindings.is_empty() && !self.field_units_done.contains(&class) {
17331733
self.field_units_in_progress.push(class);
1734+
// every static field of the class with initializer code gets its
1735+
// slot now, not only the ones some body happened to read: a
1736+
// unit is the whole class, and a field's initializer may read
1737+
// a field nobody else does (`S3 = S2 + 1`), which must already
1738+
// hold its value — textual order below, over the full set
1739+
self.materialize_static_fields(class);
17341740
let mut fields: Vec<(SymbolId, FileId, usize)> = self
17351741
.static_init
17361742
.iter()
@@ -1765,6 +1771,44 @@ impl<'a, 'ast> Generator<'a, 'ast> {
17651771
}
17661772
}
17671773

1774+
/// Slots for the static fields of a (non-generic) class whose
1775+
/// initializers run as code, so that `emit_type_unit` sees the class's
1776+
/// complete field list. Shared statics were registered by the prologue;
1777+
/// a generic class's statics live in the registry, not in slots.
1778+
fn materialize_static_fields(&mut self, class: SymbolId) {
1779+
if !self.type_parameter_chain(class).is_empty() {
1780+
return;
1781+
}
1782+
let members = self.declarations.table.symbol(class).members.clone();
1783+
for field in members {
1784+
let symbol = self.declarations.table.symbol(field);
1785+
if !symbol.is_static || symbol.kind != SymbolKind::Field {
1786+
continue;
1787+
}
1788+
let Some(site) = symbol.declarations.first() else {
1789+
continue;
1790+
};
1791+
let SyntaxRef::Field { declarator, .. } = &site.syntax else {
1792+
continue;
1793+
};
1794+
let Some(InitializerValue::Expression(expression)) = &declarator.initializer else {
1795+
continue;
1796+
};
1797+
if self.static_storage(field) != StaticStorage::Local {
1798+
continue;
1799+
}
1800+
let ty = match self.signatures.members.get(&field) {
1801+
Some(MemberSignature::Field(ty)) => ty.clone(),
1802+
_ => continue,
1803+
};
1804+
let udon_type = self.heap_type(&ty);
1805+
if literal_heap_init(expression, &udon_type).is_some() {
1806+
continue;
1807+
}
1808+
self.ensure_static(field, false);
1809+
}
1810+
}
1811+
17681812
/// A class met while the static initializer is being emitted — by a
17691813
/// field initializer's expression, through a static of the class or a
17701814
/// use of it — is initialized right there, ahead of what met it. Only

‎src/men-sharp-compiler/tests/codegen.rs‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16216,3 +16216,141 @@ fn compound_constants_use_boolean_locals_without_converting_bool_to_int() {
1621616216
};
1621716217
assert!(messages.is_empty(), "{messages:?}");
1621816218
}
16219+
16220+
#[test]
16221+
fn chained_constants_are_evaluated_once_per_field() {
16222+
// `S1 = S0 + 1; S2 = S1 + 1; ...` in another file, and a chain declared
16223+
// below its use: each field is bound once, whatever the chain length,
16224+
// and its value survives a narrowing compound assignment.
16225+
let mut chain = String::from("public static class Chain { public const int S0 = 0;");
16226+
for index in 1..40 {
16227+
chain.push_str(&format!(" public const int S{index} = S{} + 1;", index - 1));
16228+
}
16229+
chain.push('}');
16230+
let mut sources = vec![
16231+
SourceCode::new(
16232+
"caller.cs",
16233+
r#"
16234+
using MenSharp;
16235+
public class Probe : MenSharpBehaviour {
16236+
public void Interact() {
16237+
byte b = 0; b += Chain.S39; b += Local.L29;
16238+
uint u = 0; u += Chain.S39;
16239+
int x = Chain.S39 * 2;
16240+
}
16241+
public static class Local {
16242+
public const int L0 = 0; public const int L1 = L0 + 1; public const int L2 = L1 + 1;
16243+
public const int L3 = L2 + 1; public const int L4 = L3 + 1; public const int L5 = L4 + 1;
16244+
public const int L6 = L5 + 1; public const int L7 = L6 + 1; public const int L8 = L7 + 1;
16245+
public const int L9 = L8 + 1; public const int L10 = L9 + 1; public const int L11 = L10 + 1;
16246+
public const int L12 = L11 + 1; public const int L13 = L12 + 1; public const int L14 = L13 + 1;
16247+
public const int L15 = L14 + 1; public const int L16 = L15 + 1; public const int L17 = L16 + 1;
16248+
public const int L18 = L17 + 1; public const int L19 = L18 + 1; public const int L20 = L19 + 1;
16249+
public const int L21 = L20 + 1; public const int L22 = L21 + 1; public const int L23 = L22 + 1;
16250+
public const int L24 = L23 + 1; public const int L25 = L24 + 1; public const int L26 = L25 + 1;
16251+
public const int L27 = L26 + 1; public const int L28 = L27 + 1; public const int L29 = L28 + 1;
16252+
}
16253+
}
16254+
"#,
16255+
),
16256+
SourceCode::new("chain.cs", chain),
16257+
];
16258+
sources.extend(Compiler::corlib_sources());
16259+
let Some(dir) = dotnet_shared_dir() else {
16260+
return;
16261+
};
16262+
let compiler = Compiler::new(CompilerSettings::default()).unwrap();
16263+
let bytes = vec![std::fs::read(dir.join("System.Private.CoreLib.dll")).unwrap()];
16264+
let references = compiler.load_references(&bytes).unwrap();
16265+
let files = compiler.parse(sources);
16266+
let declarations = compiler.collect_declarations(&files);
16267+
let signatures = compiler.resolve_signatures(&declarations, &references);
16268+
let started = std::time::Instant::now();
16269+
let bodies = compiler.check_bodies(&declarations, &signatures, &references);
16270+
assert!(bodies.errors.is_empty(), "{:#?}", bodies.errors);
16271+
assert!(
16272+
started.elapsed() < std::time::Duration::from_secs(5),
16273+
"constant chains must not be re-evaluated per reference"
16274+
);
16275+
}
16276+
16277+
#[test]
16278+
fn cyclic_constants_across_classes_are_rejected_without_looping() {
16279+
// The memo's in-progress set catches a cycle through two classes in
16280+
// two files; both fields are then non-constant.
16281+
let mut sources = vec![
16282+
SourceCode::new(
16283+
"caller.cs",
16284+
r#"
16285+
using MenSharp;
16286+
public class Probe : MenSharpBehaviour {
16287+
public void Interact() { byte b = 0; b += Left.K; b += Right.L; }
16288+
}
16289+
public static class Left { public const int K = Right.L + 1; }
16290+
"#,
16291+
),
16292+
SourceCode::new(
16293+
"right.cs",
16294+
"public static class Right { public const int L = Left.K + 1; }",
16295+
),
16296+
];
16297+
sources.extend(Compiler::corlib_sources());
16298+
let Some(dir) = dotnet_shared_dir() else {
16299+
return;
16300+
};
16301+
let compiler = Compiler::new(CompilerSettings::default()).unwrap();
16302+
let bytes = vec![std::fs::read(dir.join("System.Private.CoreLib.dll")).unwrap()];
16303+
let references = compiler.load_references(&bytes).unwrap();
16304+
let files = compiler.parse(sources);
16305+
let declarations = compiler.collect_declarations(&files);
16306+
let signatures = compiler.resolve_signatures(&declarations, &references);
16307+
let bodies = compiler.check_bodies(&declarations, &signatures, &references);
16308+
let mismatches = bodies
16309+
.errors
16310+
.iter()
16311+
.filter(|error| {
16312+
matches!(
16313+
error.kind,
16314+
men_sharp_semantics::SemanticErrorKind::TypeMismatch { .. }
16315+
)
16316+
})
16317+
.count();
16318+
assert_eq!(mismatches, 2, "{:#?}", bodies.errors);
16319+
}
16320+
16321+
#[test]
16322+
fn chained_constants_initialize_in_declaration_order() {
16323+
// `S3 = S2 + 1` is initializer code (not a baked literal), so the class's
16324+
// unit must create and run every field's initializer in textual order —
16325+
// not only the fields a body read, which put S3 before S2 and gave 1
16326+
let Some(emulator) = run_behaviour(
16327+
r#"
16328+
using MenSharp;
16329+
public class Probe : MenSharpBehaviour {
16330+
public int a; public int b; public int c;
16331+
public void Interact() {
16332+
a = Chain.S3;
16333+
b = Chain.S3 * 2;
16334+
c = Chain.T3;
16335+
}
16336+
}
16337+
public static class Chain {
16338+
public const int S0 = 0;
16339+
public const int S1 = S0 + 1;
16340+
public const int S2 = S1 + 1;
16341+
public const int S3 = S2 + 1;
16342+
public static int T0 = 10;
16343+
public static int T1 = T0 + 1;
16344+
public static int T2 = T1 + 1;
16345+
public static int T3 = T2 + 1;
16346+
}
16347+
"#,
16348+
"Probe",
16349+
"_interact",
16350+
) else {
16351+
return;
16352+
};
16353+
assert_eq!(int_of(&emulator, "a"), 3);
16354+
assert_eq!(int_of(&emulator, "b"), 6);
16355+
assert_eq!(int_of(&emulator, "c"), 13);
16356+
}

‎src/men-sharp-semantics/src/semantics/check.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,10 @@
4040
//! share).
4141
4242
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
43+
use std::cell::RefCell;
4344
use std::collections::BTreeSet;
4445
use std::ops::Range;
46+
use std::rc::Rc;
4547

4648
mod calls;
4749
mod checker;
@@ -508,8 +510,13 @@ struct LocalFunctionEntry<'ast> {
508510

509511
struct Checker<'a, 'ast> {
510512
resolver: Resolver<'a, 'ast>,
511-
/// Bounds recursive const-field binding as well as value evaluation.
513+
/// Bounds the nesting of one constant expression's operators; field
514+
/// recursion is bounded by [`ConstantCache`] instead.
512515
constant_depth: usize,
516+
/// Values of source `const` fields, shared with the checkers spun up to
517+
/// bind initializers not checked yet, so a chain of constants is
518+
/// evaluated once per field rather than once per reference.
519+
constant_cache: Rc<RefCell<ConstantCache>>,
513520
signatures: &'a Signatures,
514521
scopes: Vec<NamespaceScope<'ast>>,
515522
type_stack: Vec<SymbolId>,
@@ -621,6 +628,15 @@ fn type_parameter_leaves(ty: &Type) -> usize {
621628
}
622629
}
623630

631+
/// Memo of source `const` field values. `in_progress` holds the fields
632+
/// whose initializers are being evaluated up the call stack: meeting one
633+
/// again is a cycle, which makes the field non-constant.
634+
#[derive(Default)]
635+
struct ConstantCache {
636+
values: HashMap<SymbolId, Option<i128>>,
637+
in_progress: HashSet<SymbolId>,
638+
}
639+
624640
impl<'a, 'ast> Checker<'a, 'ast> {
625641
fn for_file(
626642
declarations: &'a Declarations<'ast>,
@@ -638,6 +654,7 @@ impl<'a, 'ast> Checker<'a, 'ast> {
638654
},
639655
signatures,
640656
constant_depth: 64,
657+
constant_cache: Rc::new(RefCell::new(ConstantCache::default())),
641658
scopes: Vec::new(),
642659
type_stack: Vec::new(),
643660
locals: Vec::new(),

‎src/men-sharp-semantics/src/semantics/check/checker.rs‎

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -489,17 +489,40 @@ impl<'a, 'ast> Checker<'a, 'ast> {
489489
})
490490
}
491491

492-
/// Bind an as-yet unchecked initializer in its own file/type scope.
493-
/// Reusing the normal checker preserves aliases, qualified names and
494-
/// integer promotion; a structural evaluator used to guess these from
495-
/// syntax and made constant conversion depend on declaration order.
492+
/// The value of a source `const` field, memoised per field. A cycle
493+
/// (`const int K = L; const int L = K;`) is caught by the in-progress
494+
/// set, so each field costs one evaluation however many references
495+
/// or nesting levels lead to it.
496496
fn source_const_value(&self, field: SymbolId, depth: usize) -> Option<i128> {
497497
if depth == 0 {
498498
return None;
499499
}
500+
{
501+
let mut cache = self.constant_cache.borrow_mut();
502+
if let Some(value) = cache.values.get(&field) {
503+
return *value;
504+
}
505+
if !cache.in_progress.insert(field) {
506+
return None;
507+
}
508+
}
509+
let value = self.evaluate_source_const(field);
510+
let mut cache = self.constant_cache.borrow_mut();
511+
cache.in_progress.remove(&field);
512+
cache.values.insert(field, value);
513+
value
514+
}
515+
516+
/// Bind an as-yet unchecked initializer in its own file/type scope.
517+
/// Reusing the normal checker preserves aliases, qualified names and
518+
/// integer promotion; a structural evaluator used to guess these from
519+
/// syntax and made constant conversion depend on declaration order.
520+
/// The initializer gets a full operator-depth budget of its own: field
521+
/// recursion is bounded by the cache, not by the depth.
522+
fn evaluate_source_const(&self, field: SymbolId) -> Option<i128> {
500523
let value = self.const_initializer(field)?;
501524
if self.expression_types.contains_key(&EntityID::from(value)) {
502-
return self.constant_value_inner(value, depth);
525+
return self.constant_value_inner(value, self.constant_depth);
503526
}
504527
let declarations = self.resolver.declarations;
505528
let file = declarations.table.symbol(field).declarations.first()?.file;
@@ -509,13 +532,13 @@ impl<'a, 'ast> Checker<'a, 'ast> {
509532
.position(|candidate| candidate.file == file)?;
510533
let mut checker =
511534
Self::for_file(declarations, self.signatures, self.resolver.external, index);
512-
checker.constant_depth = depth - 1;
535+
checker.constant_cache = self.constant_cache.clone();
513536
if !checker.bind_constant_nodes(&declarations.files[index].members, field)
514537
|| !checker.resolver.out.errors.is_empty()
515538
{
516539
return None;
517540
}
518-
checker.constant_value_inner(value, depth - 1)
541+
checker.constant_value_inner(value, self.constant_depth)
519542
}
520543

521544
fn sizeof_constant(&self, target: &men_sharp_parser::ast::TypeRef<'ast, 'ast>) -> Option<i32> {

‎src/men-sharp-semantics/src/semantics/check/expressions.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -265,12 +265,12 @@ impl<'a, 'ast> Checker<'a, 'ast> {
265265
use crate::types::conversions::NumericKind::*;
266266
let system = self.system();
267267
let pair = (system.numeric_kind(&ty), system.numeric_kind(other));
268-
let fits = self.integer_constant(expression).is_some_and(|v| v >= 0);
269-
if fits
270-
&& matches!(
271-
pair,
272-
(Some(Int32), Some(UInt32 | UInt64)) | (Some(Int64), Some(UInt64))
273-
)
268+
// evaluate the constant only for a pair it could promote:
269+
// a const field costs a lookup or, once, an evaluation
270+
if matches!(
271+
pair,
272+
(Some(Int32), Some(UInt32 | UInt64)) | (Some(Int64), Some(UInt64))
273+
) && self.integer_constant(expression).is_some_and(|v| v >= 0)
274274
{
275275
other.clone()
276276
} else {

‎tests/unity-project/Assets/MenSharp/MenSharpRuntimeSmoke.cs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -416,6 +416,16 @@ public void FieldInitializerOrder()
416416
initializerTrace = SmokeInitReader.Value;
417417
}
418418

419+
public byte chainedConstant;
420+
421+
public void ChainedConstants()
422+
{
423+
// a 30-link constant chain from another file narrows into a byte
424+
byte b = 0;
425+
b += SmokeConstants.S29;
426+
chainedConstant = b;
427+
}
428+
419429
public void GenericStaticConstructors()
420430
{
421431
nestedGenericValue = SmokeOuter<int>.Inner.Value;
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// A chain of constants in its own file: every link is bound in this
2+
// file's scope, once, when a behaviour first narrows one of them.
3+
public static class SmokeConstants
4+
{
5+
public const int S0 = 0;
6+
public const int S1 = S0 + 1;
7+
public const int S2 = S1 + 1;
8+
public const int S3 = S2 + 1;
9+
public const int S4 = S3 + 1;
10+
public const int S5 = S4 + 1;
11+
public const int S6 = S5 + 1;
12+
public const int S7 = S6 + 1;
13+
public const int S8 = S7 + 1;
14+
public const int S9 = S8 + 1;
15+
public const int S10 = S9 + 1;
16+
public const int S11 = S10 + 1;
17+
public const int S12 = S11 + 1;
18+
public const int S13 = S12 + 1;
19+
public const int S14 = S13 + 1;
20+
public const int S15 = S14 + 1;
21+
public const int S16 = S15 + 1;
22+
public const int S17 = S16 + 1;
23+
public const int S18 = S17 + 1;
24+
public const int S19 = S18 + 1;
25+
public const int S20 = S19 + 1;
26+
public const int S21 = S20 + 1;
27+
public const int S22 = S21 + 1;
28+
public const int S23 = S22 + 1;
29+
public const int S24 = S23 + 1;
30+
public const int S25 = S24 + 1;
31+
public const int S26 = S25 + 1;
32+
public const int S27 = S26 + 1;
33+
public const int S28 = S27 + 1;
34+
public const int S29 = S28 + 1;
35+
}

‎tests/unity-project/Assets/MenSharp/SmokeConstants.cs.meta‎

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)