Skip to content

Commit 5734291

Browse files
committed
impl static generics
1 parent 7fceb45 commit 5734291

5 files changed

Lines changed: 140 additions & 16 deletions

File tree

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

Lines changed: 56 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,13 +1867,15 @@ impl<'a, 'ast> Generator<'a, 'ast> {
18671867

18681868
/// The place a generic class's static field is read and written at: its
18691869
/// entry in the shared array's registry, found by the closed type's key or
1870-
/// appended (with the field's default) the first time any program asks.
1871-
/// The registry is two parallel arrays — keys and values — kept in the two
1872-
/// slots the layout reserves past the plain shared statics.
1870+
/// appended the first time any program asks — with the field's initializer
1871+
/// value (a constant literal) or its default. The registry is two parallel
1872+
/// arrays — keys and values — kept in the two slots the layout reserves
1873+
/// past the plain shared statics.
18731874
fn generic_static_place(
18741875
&mut self,
18751876
ctx: &Ctx<'ast>,
18761877
field: SymbolId,
1878+
declaring: &Type,
18771879
key: &str,
18781880
ty: Type,
18791881
span: Range<usize>,
@@ -1887,24 +1889,49 @@ impl<'a, 'ast> Generator<'a, 'ast> {
18871889
);
18881890
return Place::Error;
18891891
}
1890-
// an initializer would have to run once per closed type, which nothing
1891-
// models yet; leaving it out would make `= 5` silently read 0, so this
1892-
// is an error rather than a wrong value
1893-
let has_initializer = self
1892+
1893+
// the closed type's arguments bind the class's own type parameters
1894+
// (`Cache<int>` gives T = int), so a field typed or initialized in
1895+
// terms of T resolves to the concrete type
1896+
let class = self.declarations.table.symbol(field).parent;
1897+
let class_bindings: Vec<(SymbolId, Type)> = match (class, declaring) {
1898+
(Some(class), Type::Named { arguments, .. }) => self
1899+
.declarations
1900+
.table
1901+
.symbol(class)
1902+
.type_parameters
1903+
.iter()
1904+
.copied()
1905+
.zip(arguments.iter().cloned())
1906+
.collect(),
1907+
_ => Vec::new(),
1908+
};
1909+
let ty = self.substitute(&ty, &class_bindings);
1910+
1911+
// the initializer, if any. Only a constant literal is supported: a
1912+
// computed one (`= new List<T>()`, a call) would have to run once per
1913+
// closed type with a real call frame, which the inline append has not.
1914+
// A literal bakes to a heap value with no code, so it is safe here.
1915+
let written = self
18941916
.declarations
18951917
.table
18961918
.symbol(field)
18971919
.declarations
18981920
.first()
1899-
.is_some_and(|site| {
1900-
matches!(&site.syntax, SyntaxRef::Field { declarator, .. }
1901-
if declarator.initializer.is_some())
1921+
.and_then(|site| match site.syntax {
1922+
SyntaxRef::Field { declarator, .. } => declarator.initializer.as_ref(),
1923+
_ => None,
19021924
});
1903-
if has_initializer {
1925+
let udon = self.heap_type(&ty);
1926+
let literal_init = match written {
1927+
Some(InitializerValue::Expression(expression)) => literal_heap_init(expression, &udon),
1928+
_ => None,
1929+
};
1930+
if written.is_some() && literal_init.is_none() {
19041931
self.error(
19051932
ctx,
1906-
"a static field of a generic class cannot have an initializer yet (its value \
1907-
would have to be built once per closed type); leave it default"
1933+
"a static field of a generic class can only be initialized with a constant \
1934+
literal (= 5, = \"text\", = true); a computed initializer is not supported yet"
19081935
.to_string(),
19091936
span,
19101937
);
@@ -1965,8 +1992,22 @@ impl<'a, 'ast> Generator<'a, 'ast> {
19651992
span.clone(),
19661993
);
19671994
let new_keys = self.grow_object_array(ctx, keys, length, grown, key_constant, span.clone());
1968-
let default = self.default_value(&ty);
1969-
let new_values = self.grow_object_array(ctx, values, length, grown, default, span.clone());
1995+
// the field's initial value: its constant-literal initializer, baked to
1996+
// a heap slot with no code (safe to place directly), or its default
1997+
let tail = match literal_init {
1998+
Some(init) => {
1999+
let serial = self.program.data.len();
2000+
self.program.add_data(DataSymbol {
2001+
name: format!("__gstatic_init_{serial}"),
2002+
udon_type: udon.clone(),
2003+
init,
2004+
export: false,
2005+
sync: None,
2006+
})
2007+
}
2008+
None => self.default_value(&ty),
2009+
};
2010+
let new_values = self.grow_object_array(ctx, values, length, grown, tail, span.clone());
19702011
self.set_element(ctx, array, keys_index, new_keys, span.clone());
19712012
self.set_element(ctx, array, values_index, new_values, span.clone());
19722013
self.copy(new_values, values);

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2625,7 +2625,14 @@ impl<'a, 'ast> Generator<'a, 'ast> {
26252625
if self.static_storage(symbol) == StaticStorage::Shared
26262626
&& let Some(key) = self.generic_static_key(&declaring, symbol)
26272627
{
2628-
return self.generic_static_place(ctx, symbol, &key, member_type, span);
2628+
return self.generic_static_place(
2629+
ctx,
2630+
symbol,
2631+
&declaring,
2632+
&key,
2633+
member_type,
2634+
span,
2635+
);
26292636
}
26302637
self.static_place(ctx, symbol, false, member_type, span)
26312638
}

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -842,6 +842,68 @@ fn a_generic_static_reached_through_a_type_parameter_is_tracked() {
842842
assert_eq!(int_of(&emulator, "b"), 1);
843843
}
844844

845+
#[test]
846+
fn a_generic_static_takes_its_constant_initializer_per_closed_type() {
847+
let Some(emulator) = run_behaviour(
848+
r#"
849+
using MenSharp;
850+
851+
public static class Cache<T> { public static int Count = 5; }
852+
853+
public class Probe : MenSharpBehaviour
854+
{
855+
public int a;
856+
public int b;
857+
public int c;
858+
public void Interact()
859+
{
860+
a = Cache<int>.Count; // initialized to 5
861+
Cache<int>.Count += 100;
862+
b = Cache<int>.Count; // 105
863+
c = Cache<string>.Count; // its own 5, untouched
864+
}
865+
}
866+
"#,
867+
"Probe",
868+
"_interact",
869+
) else {
870+
panic!("no emulator");
871+
};
872+
assert_eq!(int_of(&emulator, "a"), 5);
873+
assert_eq!(int_of(&emulator, "b"), 105);
874+
assert_eq!(int_of(&emulator, "c"), 5);
875+
}
876+
877+
#[test]
878+
fn a_generic_static_with_a_computed_initializer_is_rejected() {
879+
let mut sources = vec![SourceCode::new(
880+
"test.cs",
881+
r#"
882+
using MenSharp;
883+
using System.Text;
884+
885+
public static class Cache<T> { public static StringBuilder B = new StringBuilder(); }
886+
887+
public class Probe : MenSharpBehaviour
888+
{
889+
public void Interact() { Cache<int>.B.Append("x"); }
890+
}
891+
"#,
892+
)];
893+
sources.extend(Compiler::corlib_sources());
894+
let Some(program) = compile_behaviour(sources, "Probe") else {
895+
return; // no dotnet reference assemblies available
896+
};
897+
assert!(
898+
program.output.errors.iter().any(|error| error
899+
.message
900+
.to_string()
901+
.contains("can only be initialized with a constant literal")),
902+
"expected the computed-initializer error, got: {:#?}",
903+
program.output.errors
904+
);
905+
}
906+
845907
#[test]
846908
fn behaviour_instance_fields_become_public_variables() {
847909
let Some(emulator) = run_behaviour(

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,12 +97,19 @@ public void RunShared()
9797
public int genericString;
9898
public int genericMine;
9999

100+
public int genericSeededInt;
101+
public int genericSeededString;
102+
100103
public void GenericStatics()
101104
{
102105
GenericCache<int>.Count++;
103106
GenericCache<string>.Count += 10;
104107
genericInt = GenericCache<int>.Count;
105108
genericString = GenericCache<string>.Count;
109+
// each closed type takes its own constant initializer (7)
110+
GenericCache<int>.Seeded += 1;
111+
genericSeededInt = GenericCache<int>.Seeded; // 8
112+
genericSeededString = GenericCache<string>.Seeded; // 7, untouched
106113
}
107114

108115
public void BumpGeneric()
@@ -148,4 +155,7 @@ public async void RunAsync()
148155
public static class GenericCache<T>
149156
{
150157
public static int Count;
158+
// a constant-literal initializer: one per closed type (int and string
159+
// each start at 7), baked with no code
160+
public static int Seeded = 7;
151161
}

‎tests/unity-project/Assets/Tests/Editor/MenSharpIntegrationTests.cs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,10 @@ public IEnumerator GeneratedProgramsExecuteInTheSdkUdonVm()
204204
smoke.RunProgram("GenericStatics");
205205
Assert.AreEqual(1, smoke.GetProgramVariable("genericInt"));
206206
Assert.AreEqual(10, smoke.GetProgramVariable("genericString"));
207+
// constant-literal initializer, one per closed type: <int> seeded 7 → 8,
208+
// <string> its own 7
209+
Assert.AreEqual(8, smoke.GetProgramVariable("genericSeededInt"));
210+
Assert.AreEqual(7, smoke.GetProgramVariable("genericSeededString"));
207211
smoke.RunProgram("BumpGeneric");
208212
second.RunProgram("BumpGeneric");
209213
smoke.RunProgram("BumpGeneric");

0 commit comments

Comments
 (0)