Skip to content

Commit 2626aed

Browse files
committed
impl C# execution on field init for private
1 parent 76604d5 commit 2626aed

7 files changed

Lines changed: 297 additions & 1 deletion

File tree

‎src/men-sharp-asm/src/lib.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ pub mod world;
1313
pub use emulator::{Alone, DelayedEvent, Due, Emulator, EmulatorError, Peers, Value};
1414
pub use program::{
1515
AssembleError, Assembled, DataId, DataSymbol, EntryPoint, HALT_ADDRESS, HeapInit, LabelId,
16-
Layout, NetworkCallable, Op, Program, Resolved, SourceMark, SourceMarkKind, Target, UdonType,
16+
Layout, NetworkCallable, Op, Program, ProxyInit, Resolved, SourceMark, SourceMarkKind, Target,
17+
UdonType,
1718
};
1819
pub use world::World;
1920

‎src/men-sharp-asm/src/program.rs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,20 @@ pub struct Program {
233233
/// The `[NetworkCallable]` events: what the runtime needs to carry
234234
/// their arguments over the network (see `generator::network`).
235235
pub network_callables: Vec<NetworkCallable>,
236+
/// Fields whose initializer Udon cannot run (`new VRCUrl("...")` — a
237+
/// constructor with no extern): the Unity importer constructs the proxy,
238+
/// which runs the initializer in real C#, and bakes the field's value
239+
/// into the heap default. See `generator`'s proxy-baking.
240+
pub proxy_initialized: Vec<ProxyInit>,
241+
}
242+
243+
/// One field the Unity importer fills from a constructed proxy instance.
244+
#[derive(Debug, Clone)]
245+
pub struct ProxyInit {
246+
/// The heap symbol to write (`static_UrlPriv_url`).
247+
pub symbol: String,
248+
/// The C# field on the proxy to read (`url`).
249+
pub field: String,
236250
}
237251

238252
/// One network-callable event: the variables its arguments arrive in, by
@@ -706,6 +720,20 @@ impl Program {
706720
}
707721
out.push_str("\n ]");
708722
}
723+
if !self.proxy_initialized.is_empty() {
724+
out.push_str(",\n \"proxyInitialized\": [");
725+
for (index, entry) in self.proxy_initialized.iter().enumerate() {
726+
if index > 0 {
727+
out.push(',');
728+
}
729+
out.push_str("\n {\"symbol\": ");
730+
write_json_string(&mut out, &entry.symbol);
731+
out.push_str(", \"field\": ");
732+
write_json_string(&mut out, &entry.field);
733+
out.push('}');
734+
}
735+
out.push_str("\n ]");
736+
}
709737
// address → source position, in address order; a position repeats
710738
// at most once in a row
711739
out.push_str(",\n \"lines\": [");

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1543,6 +1543,10 @@ impl<'a, 'ast> Generator<'a, 'ast> {
15431543
};
15441544
let span = declarator.span.clone();
15451545
let shared = self.static_storage(field) == StaticStorage::Shared;
1546+
// owned, so the `symbol` borrow of `self.declarations` does not
1547+
// outlive the `&mut self` emission below
1548+
let field_name = symbol.name.to_string();
1549+
let field_is_static = symbol.is_static;
15461550

15471551
let mut ctx = Ctx {
15481552
key: FunctionKey {
@@ -1563,6 +1567,21 @@ impl<'a, 'ast> Generator<'a, 'ast> {
15631567
iterator_state: None,
15641568
};
15651569
// a shared field is initialized by the program that made the array
1570+
// an instance field of an external type whose initializer Udon cannot
1571+
// run (`new VRCUrl("...")`: no constructor extern) is filled by the
1572+
// Unity importer instead, which constructs the proxy — real C#, where
1573+
// the initializer runs — and bakes the field's value. So the emission
1574+
// is speculative: if it reports an error and the field can be baked
1575+
// from the proxy, the emitted code and the error are both rolled back
1576+
// and the field is recorded for proxy-baking. (Not for statics, whose
1577+
// value has no proxy field, nor user types, whose heap form is M#'s
1578+
// own object[] the proxy's C# object would not match.)
1579+
let bakeable = !field_is_static
1580+
&& !shared
1581+
&& self.is_entry_member(field)
1582+
&& self.is_proxy_bakeable_type(&ty);
1583+
let checkpoint = bakeable.then_some((self.errors.len(), self.program.code.len()));
1584+
15661585
let guard = shared.then(|| self.begin_owner_guard());
15671586
let place = if shared {
15681587
self.static_place(&ctx, field, false, ty.clone(), span.clone())
@@ -1585,6 +1604,20 @@ impl<'a, 'ast> Generator<'a, 'ast> {
15851604
if let Some(skip) = guard {
15861605
self.end_owner_guard(skip);
15871606
}
1607+
if let Some((errors, code)) = checkpoint
1608+
&& self.errors.len() > errors
1609+
{
1610+
// roll the failed emission back and hand the field to the proxy
1611+
self.errors.truncate(errors);
1612+
self.program.code.truncate(code);
1613+
let slot = self.statics[&field];
1614+
self.program
1615+
.proxy_initialized
1616+
.push(men_sharp_asm::ProxyInit {
1617+
symbol: self.program.data[slot.0].name.clone(),
1618+
field: field_name,
1619+
});
1620+
}
15881621
}
15891622

15901623
// ------------------------------------------------------ shared statics
@@ -3791,6 +3824,27 @@ impl<'a, 'ast> Generator<'a, 'ast> {
37913824
|| self.has_attribute(member, "SerializeField")
37923825
}
37933826

3827+
/// A field whose value the Unity importer can read from a proxy instance
3828+
/// and write straight into the Udon heap: an external type (VRCUrl, a
3829+
/// primitive, a string, an engine struct) or an array of one. Not a user
3830+
/// type — its heap form is M#'s own `object[]`, which the proxy's plain
3831+
/// C# object would not match — and not a jagged or multi-dimensional
3832+
/// array, which Unity does not serialize as one value either.
3833+
fn is_proxy_bakeable_type(&self, ty: &Type) -> bool {
3834+
match ty {
3835+
Type::Array { element, rank } => {
3836+
*rank == 1
3837+
&& !matches!(**element, Type::Array { .. })
3838+
&& self.is_proxy_bakeable_type(element)
3839+
}
3840+
Type::Named {
3841+
target: TypeTarget::External(_),
3842+
..
3843+
} => true,
3844+
_ => false,
3845+
}
3846+
}
3847+
37943848
/// Is an attribute of this name (with or without the `Attribute` suffix)
37953849
/// written on the member? By spelling, like every attribute here.
37963850
fn has_attribute(&self, member: SymbolId, name: &str) -> bool {

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

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12390,3 +12390,84 @@ fn a_private_field_initializer_still_runs() {
1239012390
assert_eq!(int_of(&emulator, "length"), 3);
1239112391
assert_eq!(int_of(&emulator, "first"), 4);
1239212392
}
12393+
12394+
fn compile_behaviour_with_corlib(
12395+
source: &str,
12396+
class_path: &str,
12397+
) -> Option<men_sharp_compiler::UdonBehaviourProgram> {
12398+
let mut sources = vec![SourceCode::new("test.cs", source)];
12399+
sources.extend(Compiler::corlib_sources());
12400+
compile_behaviour(sources, class_path)
12401+
}
12402+
12403+
#[test]
12404+
fn a_field_initializer_udon_cannot_run_is_left_to_the_proxy() {
12405+
// `new CultureInfo("en")` has no constructor extern (Udon exposes the
12406+
// type but not its ctor), so Udon cannot build it. Rather than an error,
12407+
// the field is recorded for the Unity importer to fill from a
12408+
// constructed proxy — real C#, where the initializer runs — like
12409+
// UdonSharp. The emitted code and the error are both rolled back.
12410+
let Some(program) = compile_behaviour_with_corlib(
12411+
r#"
12412+
using MenSharp;
12413+
using System.Globalization;
12414+
public class Thing : MenSharpBehaviour
12415+
{
12416+
private CultureInfo culture = new CultureInfo("en-US");
12417+
public bool hasCulture;
12418+
public void Interact() { hasCulture = culture != null; }
12419+
}
12420+
"#,
12421+
"Thing",
12422+
) else {
12423+
return;
12424+
};
12425+
assert!(
12426+
program.output.errors.is_empty(),
12427+
"{:#?}",
12428+
program.output.errors
12429+
);
12430+
let uasm = program.output.program.to_uasm().unwrap();
12431+
assert!(!uasm.contains("CultureInfo.__ctor"), "{uasm}");
12432+
let proxy = &program.output.program.proxy_initialized;
12433+
assert_eq!(proxy.len(), 1, "{proxy:?}");
12434+
assert_eq!(proxy[0].field, "culture");
12435+
assert!(proxy[0].symbol.contains("culture"), "{}", proxy[0].symbol);
12436+
}
12437+
12438+
#[test]
12439+
fn an_initializer_udon_can_run_is_not_handed_to_the_proxy() {
12440+
// the flip side: an external-typed field whose initializer Udon *can*
12441+
// build (StringBuilder's `(string)` constructor is an extern) still
12442+
// emits as code, not handed to the proxy
12443+
let Some(program) = compile_behaviour_with_corlib(
12444+
r#"
12445+
using MenSharp;
12446+
using System.Text;
12447+
public class Thing : MenSharpBehaviour
12448+
{
12449+
private StringBuilder builder = new StringBuilder("start");
12450+
public int length;
12451+
public void Interact() { length = builder.Length; }
12452+
}
12453+
"#,
12454+
"Thing",
12455+
) else {
12456+
return;
12457+
};
12458+
assert!(
12459+
program.output.errors.is_empty(),
12460+
"{:#?}",
12461+
program.output.errors
12462+
);
12463+
assert!(
12464+
program.output.program.proxy_initialized.is_empty(),
12465+
"{:?}",
12466+
program.output.program.proxy_initialized
12467+
);
12468+
let uasm = program.output.program.to_uasm().unwrap();
12469+
assert!(
12470+
uasm.contains("SystemTextStringBuilder.__ctor__SystemString"),
12471+
"{uasm}"
12472+
);
12473+
}

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ public void Scale()
7171
public void CountItems() { itemsLength = items.Length; }
7272
public void ScaleOne() { oneProduct = one * 0.92f; }
7373

74+
// a private field Udon cannot construct: the importer runs the C#
75+
// initializer on the proxy and bakes the VRCUrl into the heap default
76+
private VRC.SDKBase.VRCUrl url = new VRC.SDKBase.VRCUrl("https://example.com/baked");
77+
public string urlText;
78+
public void ReadUrl() { urlText = url.Get(); }
79+
7480
const string greeting = "Hello";
7581
public string greeted;
7682
public void Greet()

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,11 @@ public IEnumerator GeneratedProgramsExecuteInTheSdkUdonVm()
143143
smoke.RunProgram("Scale");
144144
Assert.AreEqual(1f, smoke.GetProgramVariable("scaled"));
145145

146+
// a private field whose initializer Udon cannot run (new VRCUrl):
147+
// the importer baked the value from the constructed proxy
148+
smoke.RunProgram("ReadUrl");
149+
Assert.AreEqual("https://example.com/baked", smoke.GetProgramVariable("urlText"));
150+
146151
// a public array initializer must not overwrite the inspector value
147152
smoke.RunProgram("CountItems");
148153
Assert.AreEqual(1, smoke.GetProgramVariable("itemsLength"));

‎unity/io.tesca.mensharp/Editor/MenSharpProgramAsset.cs‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -402,10 +402,118 @@ public void ApplyMenSharpMeta()
402402
current.Heap.SetHeapVariable(address, value, declared ?? value.GetType());
403403
}
404404

405+
ApplyProxyInitializers(current, meta, name);
406+
405407
// the caller (RefreshProgram) stores the patched heap so the runtime
406408
// loads the same state
407409
}
408410

411+
/// Fills the fields whose initializer Udon cannot run. Like UdonSharp:
412+
/// construct the proxy behaviour (its C# field initializers run — this is
413+
/// where `new VRCUrl("...")` happens), read the field by reflection, and
414+
/// write the value into the heap default. Runs in the editor, on the
415+
/// world author's own code; the built world ships only the baked value.
416+
private static void ApplyProxyInitializers(IUdonProgram current, MenSharpMeta meta, string classPath)
417+
{
418+
if (meta.proxyInitialized == null || meta.proxyInitialized.Length == 0)
419+
{
420+
return;
421+
}
422+
Type proxyType = FindProxyType(classPath);
423+
if (proxyType == null)
424+
{
425+
Debug.LogWarning(
426+
"MenSharp: could not find the C# behaviour to read field initializers from; "
427+
+ "some fields will keep their default value.");
428+
return;
429+
}
430+
// AddComponent on a throwaway GameObject runs the field initializers
431+
// the way Unity allows — `new`ing a MonoBehaviour would run them too,
432+
// but logs a native "not allowed" warning the managed log handler
433+
// cannot intercept. Hidden and not saved, destroyed straight after.
434+
var probe = new GameObject("__MenSharpProxyProbe") { hideFlags = HideFlags.HideAndDontSave };
435+
try
436+
{
437+
Component instance;
438+
try
439+
{
440+
instance = probe.AddComponent(proxyType);
441+
}
442+
catch (Exception error)
443+
{
444+
Debug.LogWarning(
445+
$"MenSharp: could not construct {proxyType.Name} to read its field "
446+
+ $"initializers ({error.Message}); those fields keep their default value.");
447+
return;
448+
}
449+
foreach (MenSharpProxyInit init in meta.proxyInitialized)
450+
{
451+
if (!current.SymbolTable.HasAddressForSymbol(init.symbol))
452+
{
453+
continue;
454+
}
455+
FieldInfo field = FindField(proxyType, init.field);
456+
if (field == null)
457+
{
458+
continue;
459+
}
460+
object value = field.GetValue(instance);
461+
if (value == null)
462+
{
463+
continue;
464+
}
465+
uint address = current.SymbolTable.GetAddressFromSymbol(init.symbol);
466+
Type declared = current.Heap.GetHeapVariableType(address);
467+
current.Heap.SetHeapVariable(address, value, declared ?? field.FieldType);
468+
}
469+
}
470+
finally
471+
{
472+
UnityEngine.Object.DestroyImmediate(probe);
473+
}
474+
}
475+
476+
/// The behaviour type this program was compiled from, by its class path
477+
/// — the full name the compiler names the asset after (reflection spells
478+
/// nesting with '+', the asset with '.').
479+
private static Type FindProxyType(string classPath)
480+
{
481+
foreach (Type type in
482+
UnityEditor.TypeCache.GetTypesDerivedFrom<MenSharp.MenSharpBehaviour>())
483+
{
484+
if (type.IsAbstract || type.IsGenericTypeDefinition)
485+
{
486+
continue;
487+
}
488+
string fullName = (type.FullName ?? type.Name).Replace('+', '.');
489+
if (fullName == classPath || type.Name == classPath)
490+
{
491+
return type;
492+
}
493+
}
494+
return null;
495+
}
496+
497+
/// A field by name, private ones on base classes included (GetField does
498+
/// not return a base class's private fields).
499+
private static FieldInfo FindField(Type type, string name)
500+
{
501+
for (Type current = type;
502+
current != null && current != typeof(MenSharp.MenSharpBehaviour);
503+
current = current.BaseType)
504+
{
505+
FieldInfo field = current.GetField(
506+
name,
507+
BindingFlags.Public | BindingFlags.NonPublic
508+
| BindingFlags.Instance | BindingFlags.DeclaredOnly);
509+
if (field != null)
510+
{
511+
return field;
512+
}
513+
}
514+
return null;
515+
}
516+
409517
private static object Decode(MenSharpHeapEntry entry)
410518
{
411519
switch (entry.kind)
@@ -518,6 +626,19 @@ public class MenSharpMeta
518626
/// arguments over the network — the variable each argument arrives in
519627
/// and its type. Handed to the SDK when the program is stored.
520628
public MenSharpNetworkCallable[] networkCallable;
629+
/// Fields whose C# initializer Udon cannot run (`new VRCUrl("...")`): the
630+
/// importer constructs the proxy, whose initializer runs in real C#, and
631+
/// bakes the field's value into the heap. Same idea as UdonSharp.
632+
public MenSharpProxyInit[] proxyInitialized;
633+
}
634+
635+
[Serializable]
636+
public class MenSharpProxyInit
637+
{
638+
/// The heap symbol to write.
639+
public string symbol;
640+
/// The C# field on the proxy behaviour to read.
641+
public string field;
521642
}
522643

523644
[Serializable]

0 commit comments

Comments
 (0)