Skip to content

Commit 632feef

Browse files
committed
impl enum calc
1 parent 91bb926 commit 632feef

7 files changed

Lines changed: 314 additions & 13 deletions

File tree

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

Lines changed: 187 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,24 +1145,37 @@ impl<'a, 'ast> Generator<'a, 'ast> {
11451145
id: men_sharp_semantics::ExternalTypeId,
11461146
span: Range<usize>,
11471147
) -> DataId {
1148+
let int32 = self.corlib_type("Int32");
1149+
let index = self.convert(ctx, source, from, &int32, span.clone());
1150+
self.box_external_enum(ctx, index, to, id, span)
1151+
.unwrap_or(source)
1152+
}
1153+
1154+
/// The enum's value table (see convert_to_external_enum) and its length,
1155+
/// or `None` (reported) for an enum the table cannot cover.
1156+
fn external_enum_table(
1157+
&mut self,
1158+
ctx: &mut Ctx<'ast>,
1159+
ty: &Type,
1160+
id: men_sharp_semantics::ExternalTypeId,
1161+
span: Range<usize>,
1162+
) -> Option<(DataId, u64)> {
11481163
// a negative member (TextureFormat keeps its retired formats as
11491164
// -127) has no place in the array: a number naming one throws
11501165
let highest = self.external.enum_values(id).into_iter().max();
11511166
let length = highest
11521167
.map(|highest| (highest.max(0) as u64 + 1).next_power_of_two())
11531168
.filter(|&length| length <= 4096);
1154-
let display = self.describe_type(to);
11551169
let Some(length) = length else {
1170+
let display = self.describe_type(ty);
11561171
self.error(
11571172
ctx,
11581173
Message::key("codegen.a_number_cannot_be_turned_into_a_display")
11591174
.arg("display", display),
11601175
span,
11611176
);
1162-
return source;
1177+
return None;
11631178
};
1164-
let int32 = self.corlib_type("Int32");
1165-
let index = self.convert(ctx, source, from, &int32, span.clone());
11661179
let dotnet_type = self.external_type_display_name(id).to_string();
11671180
let table = self.constant(
11681181
"SystemArray",
@@ -1172,6 +1185,22 @@ impl<'a, 'ast> Generator<'a, 'ast> {
11721185
length: length as u32,
11731186
},
11741187
);
1188+
Some((table, length))
1189+
}
1190+
1191+
/// An Int32 slot as the boxed value of the external enum `ty`, through
1192+
/// the enum's value table; out of the table's range, an
1193+
/// InvalidCastException.
1194+
fn box_external_enum(
1195+
&mut self,
1196+
ctx: &mut Ctx<'ast>,
1197+
index: DataId,
1198+
ty: &Type,
1199+
id: men_sharp_semantics::ExternalTypeId,
1200+
span: Range<usize>,
1201+
) -> Option<DataId> {
1202+
let (table, length) = self.external_enum_table(ctx, ty, id, span.clone())?;
1203+
let display = self.describe_type(ty);
11751204
let zero = self.int_constant(0);
11761205
let limit = self.int_constant(length as i32);
11771206
let below = self.temp("SystemBoolean");
@@ -1192,7 +1221,7 @@ impl<'a, 'ast> Generator<'a, 'ast> {
11921221
let valid = self.fresh_label("enum_cast_valid");
11931222
self.jump_if(below, invalid);
11941223
self.jump_if(beyond, invalid);
1195-
let udon_type = self.heap_type(to);
1224+
let udon_type = self.heap_type(ty);
11961225
let out = self.temp(&udon_type);
11971226
self.call_extern(
11981227
ctx,
@@ -1213,7 +1242,82 @@ impl<'a, 'ast> Generator<'a, 'ast> {
12131242
span,
12141243
);
12151244
self.program.code.push(Op::Label(valid));
1216-
out
1245+
Some(out)
1246+
}
1247+
1248+
/// An operand of an operator on an external enum as an Int32: the boxed
1249+
/// enum unboxed, or a number converted.
1250+
fn enum_operand_as_int32(
1251+
&mut self,
1252+
ctx: &mut Ctx<'ast>,
1253+
(slot, ty): (DataId, &Type),
1254+
span: Range<usize>,
1255+
) -> DataId {
1256+
if self.external_enum(ty).is_some() {
1257+
let out = self.temp("SystemInt32");
1258+
self.call_extern(
1259+
ctx,
1260+
"SystemConvert.__ToInt32__SystemObject__SystemInt32",
1261+
&[slot, out],
1262+
span,
1263+
);
1264+
return out;
1265+
}
1266+
let int32 = self.corlib_type("Int32");
1267+
self.convert(ctx, slot, ty, &int32, span)
1268+
}
1269+
1270+
/// `flags | Flag.B`, `format + 1`, `(flags & Flag.B) != 0`, `a - b`: an
1271+
/// operator with an external enum on a side, computed on the
1272+
/// underlying Int32 — and, when the result is the enum, boxed back
1273+
/// through its value table (see convert_to_external_enum). One rule
1274+
/// for every operator, so no operation can leave an Int32 in an
1275+
/// enum-typed slot.
1276+
#[allow(clippy::too_many_arguments)]
1277+
fn external_enum_operator(
1278+
&mut self,
1279+
ctx: &mut Ctx<'ast>,
1280+
operator: BinaryOperator,
1281+
name: &str,
1282+
left: (DataId, &Type),
1283+
right: (DataId, &Type),
1284+
result_type: &Type,
1285+
span: Range<usize>,
1286+
) -> Option<DataId> {
1287+
use BinaryOperator::*;
1288+
let operands = [
1289+
self.enum_operand_as_int32(ctx, left, span.clone()),
1290+
self.enum_operand_as_int32(ctx, right, span.clone()),
1291+
];
1292+
let comparison = matches!(
1293+
operator,
1294+
Equal | NotEqual | LessThan | GreaterThan | LessThanEqual | GreaterThanEqual
1295+
);
1296+
let extern_result = if comparison {
1297+
"SystemBoolean"
1298+
} else {
1299+
"SystemInt32"
1300+
};
1301+
let signature = format!("SystemInt32.__{name}__SystemInt32_SystemInt32__{extern_result}");
1302+
if !self.nodes.has_signature(&signature) {
1303+
self.error(
1304+
ctx,
1305+
Message::key("codegen.operator_name_is_not_available_on_udon").arg("name", name),
1306+
span,
1307+
);
1308+
return None;
1309+
}
1310+
let out = self.temp(extern_result);
1311+
self.call_extern(
1312+
ctx,
1313+
&signature,
1314+
&[operands[0], operands[1], out],
1315+
span.clone(),
1316+
);
1317+
if let Some(id) = self.external_enum(result_type) {
1318+
return self.box_external_enum(ctx, out, result_type, id, span);
1319+
}
1320+
Some(out)
12171321
}
12181322

12191323
/// The `op_Implicit` that turns `from` into `to`, applied — with
@@ -1566,6 +1670,29 @@ impl<'a, 'ast> Generator<'a, 'ast> {
15661670
result_type.clone()
15671671
};
15681672

1673+
// an external enum under an arithmetic or bitwise operator, or
1674+
// against a number: on the underlying Int32, boxed back when the
1675+
// result is the enum
1676+
let left_enum = self.external_enum(left.1);
1677+
let right_enum = self.external_enum(right.1);
1678+
let same_enum_comparison = left_enum.is_some()
1679+
&& left_enum == right_enum
1680+
&& matches!(
1681+
operator,
1682+
Equal | NotEqual | LessThan | GreaterThan | LessThanEqual | GreaterThanEqual
1683+
);
1684+
if (left_enum.is_some() || right_enum.is_some()) && !same_enum_comparison {
1685+
return self.external_enum_operator(
1686+
ctx,
1687+
operator,
1688+
name,
1689+
left,
1690+
right,
1691+
result_type,
1692+
span,
1693+
);
1694+
}
1695+
15691696
// an external enum is a boxed value: `==`/`!=` go through
15701697
// Object.Equals (value equality for same-type enums, where
15711698
// op_Equality would compare boxes), orderings through the
@@ -2002,6 +2129,56 @@ impl<'a, 'ast> Generator<'a, 'ast> {
20022129
Some(out)
20032130
}
20042131
UnaryOperator::Plus => Some(operand),
2132+
// `~x`: Udon has no complement extern, but xor with all ones is
2133+
// the same thing. On an external enum the result is boxed back
2134+
// through its value table, so the complement is taken within
2135+
// the bits the table covers — which is all `flags & ~Flag.A`
2136+
// ever looks at
2137+
UnaryOperator::BitwiseNot => {
2138+
if let Some(id) = self.external_enum(operand_type) {
2139+
let (_, length) =
2140+
self.external_enum_table(ctx, operand_type, id, span.clone())?;
2141+
let value =
2142+
self.enum_operand_as_int32(ctx, (operand, operand_type), span.clone());
2143+
let mask = self.int_constant(length as i32 - 1);
2144+
let flipped = self.temp("SystemInt32");
2145+
self.call_extern(
2146+
ctx,
2147+
"SystemInt32.__op_LogicalXor__SystemInt32_SystemInt32__SystemInt32",
2148+
&[value, mask, flipped],
2149+
span.clone(),
2150+
);
2151+
return self.box_external_enum(ctx, flipped, operand_type, id, span);
2152+
}
2153+
let name = if self.source_enum(result_type).is_some() {
2154+
"SystemInt32".to_string()
2155+
} else {
2156+
self.extern_type_name(result_type)?
2157+
};
2158+
let ones = match name.as_str() {
2159+
"SystemInt32" => self.int_constant(-1),
2160+
"SystemInt64" => self.constant("SystemInt64", "-1", HeapInit::Int64(-1)),
2161+
"SystemUInt32" => {
2162+
self.constant("SystemUInt32", "4294967295", HeapInit::UInt32(u32::MAX))
2163+
}
2164+
_ => {
2165+
self.error(
2166+
ctx,
2167+
Message::key("codegen.this_operator_is_not_supported_by_the"),
2168+
span,
2169+
);
2170+
return None;
2171+
}
2172+
};
2173+
let out = self.temp(&name);
2174+
self.call_extern(
2175+
ctx,
2176+
&format!("{name}.__op_LogicalXor__{name}_{name}__{name}"),
2177+
&[operand, ones, out],
2178+
span,
2179+
);
2180+
Some(out)
2181+
}
20052182
_ => {
20062183
self.error(
20072184
ctx,
@@ -2036,7 +2213,10 @@ impl<'a, 'ast> Generator<'a, 'ast> {
20362213
}
20372214
}
20382215
match unary.operator.value {
2039-
UnaryOperator::Not | UnaryOperator::Minus | UnaryOperator::Plus => {
2216+
UnaryOperator::Not
2217+
| UnaryOperator::Minus
2218+
| UnaryOperator::Plus
2219+
| UnaryOperator::BitwiseNot => {
20402220
let operand = self.lower_expression(ctx, operand_expression)?;
20412221
let operand_type = self.type_of(ctx, operand_expression);
20422222
let result_type = self.type_of(ctx, whole);

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12206,3 +12206,68 @@ fn a_number_cast_to_an_external_enum_is_the_boxed_enum_value() {
1220612206
"caught: the number is outside what Udon can hold as a System.StringSplitOptions (0 to 3)"
1220712207
);
1220812208
}
12209+
12210+
#[test]
12211+
fn operators_on_an_external_enum_compute_on_the_int_and_box_the_result() {
12212+
// one rule for every operator with an external enum on a side: the
12213+
// underlying Int32 does the work, and a result that is the enum goes
12214+
// back through its value table — `|`, `&`, `~`, `+ 1`, `++`, `- other`,
12215+
// and the literal 0 C# lets stand for the enum's zero
12216+
let Some(emulator) = run(
12217+
r#"
12218+
using System;
12219+
namespace Game
12220+
{
12221+
public class Program
12222+
{
12223+
public static int combined;
12224+
public static int cleared;
12225+
public static int next;
12226+
public static int stepped;
12227+
public static int difference;
12228+
public static bool hasTrim;
12229+
public static bool noneIsZero;
12230+
public static bool ordered;
12231+
public static int plainComplement;
12232+
public static void Main()
12233+
{
12234+
StringSplitOptions both = StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries;
12235+
combined = (int)both;
12236+
cleared = (int)(both & ~StringSplitOptions.TrimEntries);
12237+
next = (int)(StringSplitOptions.None + 1);
12238+
StringSplitOptions walker = StringSplitOptions.None;
12239+
walker++;
12240+
walker += 1;
12241+
stepped = (int)walker;
12242+
difference = StringSplitOptions.TrimEntries - StringSplitOptions.RemoveEmptyEntries;
12243+
hasTrim = (both & StringSplitOptions.TrimEntries) != 0;
12244+
noneIsZero = StringSplitOptions.None == 0;
12245+
ordered = StringSplitOptions.RemoveEmptyEntries < StringSplitOptions.TrimEntries;
12246+
plainComplement = ~5;
12247+
}
12248+
}
12249+
}
12250+
"#,
12251+
"Main",
12252+
) else {
12253+
return;
12254+
};
12255+
assert_eq!(int_of(&emulator, "combined"), 3);
12256+
assert_eq!(int_of(&emulator, "cleared"), 1);
12257+
assert_eq!(int_of(&emulator, "next"), 1);
12258+
assert_eq!(int_of(&emulator, "stepped"), 2);
12259+
assert_eq!(int_of(&emulator, "difference"), 1);
12260+
assert!(matches!(
12261+
emulator.value_of("hasTrim"),
12262+
Some(Value::Boolean(true))
12263+
));
12264+
assert!(matches!(
12265+
emulator.value_of("noneIsZero"),
12266+
Some(Value::Boolean(true))
12267+
));
12268+
assert!(matches!(
12269+
emulator.value_of("ordered"),
12270+
Some(Value::Boolean(true))
12271+
));
12272+
assert_eq!(int_of(&emulator, "plainComplement"), -6);
12273+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ fn bool_literal(expression: &Expression) -> Option<bool> {
8989
/// The value of an integer literal, as an enum member initializer is
9090
/// allowed to be. Anything else is `None`: the member is then a case of
9191
/// its own, which is right unless it aliases another.
92-
fn integer_literal_value(expression: &Expression) -> Option<i64> {
92+
pub(super) fn integer_literal_value(expression: &Expression) -> Option<i64> {
9393
let Expression::Primary(primary) = expression else {
9494
return None;
9595
};

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,11 +84,18 @@ impl<'a, 'ast> Checker<'a, 'ast> {
8484
AssignmentOperator::RightShift => BinaryOperator::RightShift,
8585
_ => BinaryOperator::UnsignedRightShift,
8686
};
87+
let zero_literal = assignment
88+
.value
89+
.as_ref()
90+
.ok()
91+
.and_then(super::exhaustive::integer_literal_value)
92+
== Some(0);
8793
let result = self.binary_type(
8894
operator,
8995
target.clone(),
9096
value_type,
9197
literal,
98+
zero_literal,
9299
assignment.span.clone(),
93100
Some(EntityID::from(*assignment)),
94101
);
@@ -158,18 +165,21 @@ impl<'a, 'ast> Checker<'a, 'ast> {
158165
}
159166
Expression::Binary(binary) => {
160167
let left = self.check_expression(&binary.left);
161-
let (right, literal) = match &binary.right {
168+
let (right, literal, zero_literal) = match &binary.right {
162169
Ok(right) => (
163170
self.check_expression(right),
164171
Self::is_integer_literal(right) || Self::is_integer_literal(&binary.left),
172+
super::exhaustive::integer_literal_value(right) == Some(0)
173+
|| super::exhaustive::integer_literal_value(&binary.left) == Some(0),
165174
),
166-
Err(()) => (Type::Error, false),
175+
Err(()) => (Type::Error, false, false),
167176
};
168177
self.binary_type(
169178
binary.operator.value,
170179
left,
171180
right,
172181
literal,
182+
zero_literal,
173183
binary.span.clone(),
174184
Some(EntityID::from(*binary)),
175185
)

0 commit comments

Comments
 (0)