Skip to content

Commit 9fe6f6d

Browse files
authored
Merge pull request #9 from ureishi/fix-constant-expression-evaluation
fix constant expression evaluation
2 parents b962edc + ac0fede commit 9fe6f6d

6 files changed

Lines changed: 378 additions & 290 deletions

File tree

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

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16065,3 +16065,154 @@ fn static_field_initializers_are_part_of_their_classs_initialization() {
1606516065
};
1606616066
assert_eq!(int_of(&emulator, "x"), 11);
1606716067
}
16068+
16069+
#[test]
16070+
fn compound_constants_keep_types_and_declaration_scope() {
16071+
// The RHS must be evaluated in its declaration's scope, with its real
16072+
// signedness and width, even before that initializer has been checked.
16073+
for expression in [
16074+
"Other.N + 1",
16075+
"sizeof(System.Int32)",
16076+
"(int)(0xffffffffu >> 31)",
16077+
"(int)(0xffffffffffffffffUL >> 63)",
16078+
"(int)(((long)1 << 32) >> 32)",
16079+
"(int)(~0xfffffffeu)",
16080+
"(int)(~0xfffffffffffffffeUL)",
16081+
"true ? 1 : 2",
16082+
"Other.Flag && Other.N == 2 ? 1 : 2",
16083+
] {
16084+
for target in ["sbyte", "byte", "short", "ushort", "uint", "ulong"] {
16085+
for before in [true, false] {
16086+
let constant = format!("const int K = {expression};");
16087+
let method = format!("public void Interact() {{ {target} b = 1; b += K; }}");
16088+
let body = if before {
16089+
format!("{constant} {method}")
16090+
} else {
16091+
format!("{method} {constant}")
16092+
};
16093+
let source = format!(
16094+
"using MenSharp; public class Probe : MenSharpBehaviour {{ {body} }}
16095+
public class Other {{ public const int N = 2; public const bool Flag = true; }}"
16096+
);
16097+
let Some(messages) = codegen_messages(&source, "Probe") else {
16098+
return;
16099+
};
16100+
assert!(
16101+
messages.is_empty(),
16102+
"{target}: {expression}, before={before}: {messages:?}"
16103+
);
16104+
}
16105+
}
16106+
}
16107+
}
16108+
16109+
#[test]
16110+
fn compound_constants_resolve_aliases_in_the_declaring_file() {
16111+
// The caller has a different alias and a shadowing constant: neither
16112+
// may change a constant declared in another file or a nested type.
16113+
let mut sources = vec![
16114+
SourceCode::new(
16115+
"caller.cs",
16116+
r#"
16117+
using MenSharp;
16118+
using Number = System.Int64;
16119+
public class Probe : MenSharpBehaviour {
16120+
const int N = 1000;
16121+
public void Interact() { byte b = 0; b += Values.Outer.Inner.K; }
16122+
}
16123+
"#,
16124+
),
16125+
SourceCode::new(
16126+
"values.cs",
16127+
r#"
16128+
namespace Values {
16129+
using Number = System.Int32;
16130+
public class Outer {
16131+
public const int N = 2;
16132+
public class Inner { public const int K = Outer.N + sizeof(Number); }
16133+
}
16134+
}
16135+
"#,
16136+
),
16137+
];
16138+
sources.extend(Compiler::corlib_sources());
16139+
let Some(dir) = dotnet_shared_dir() else {
16140+
return;
16141+
};
16142+
let compiler = Compiler::new(CompilerSettings::default()).unwrap();
16143+
let bytes = vec![std::fs::read(dir.join("System.Private.CoreLib.dll")).unwrap()];
16144+
let references = compiler.load_references(&bytes).unwrap();
16145+
let files = compiler.parse(sources);
16146+
let declarations = compiler.collect_declarations(&files);
16147+
let signatures = compiler.resolve_signatures(&declarations, &references);
16148+
let bodies = compiler.check_bodies(&declarations, &signatures, &references);
16149+
assert!(bodies.errors.is_empty(), "{:#?}", bodies.errors);
16150+
}
16151+
16152+
#[test]
16153+
fn compound_constants_do_not_admit_nonconstants_or_out_of_range_values() {
16154+
// A selected branch fitting byte does not make a nonconstant expression
16155+
// constant. Cycles must also terminate instead of recursively rebinding.
16156+
for declaration in [
16157+
"const int K = true ? 256 : 1;",
16158+
"const int K = false ? 1 : -1;",
16159+
"const int K = (int)(0xffffffffu >> 23);",
16160+
"static readonly int K = 1;",
16161+
"const bool K = true;",
16162+
"static int X = 1; const int K = true ? 1 : X;",
16163+
"const int K = L; const int L = K;",
16164+
] {
16165+
let mut sources = vec![SourceCode::new(
16166+
"test.cs",
16167+
format!(
16168+
"using MenSharp; public class Probe : MenSharpBehaviour {{
16169+
public void Interact() {{ byte b = 0; b += K; }} {declaration}
16170+
}}"
16171+
),
16172+
)];
16173+
sources.extend(Compiler::corlib_sources());
16174+
let Some(dir) = dotnet_shared_dir() else {
16175+
return;
16176+
};
16177+
let compiler = Compiler::new(CompilerSettings::default()).unwrap();
16178+
let bytes = vec![std::fs::read(dir.join("System.Private.CoreLib.dll")).unwrap()];
16179+
let references = compiler.load_references(&bytes).unwrap();
16180+
let files = compiler.parse(sources);
16181+
let declarations = compiler.collect_declarations(&files);
16182+
let signatures = compiler.resolve_signatures(&declarations, &references);
16183+
let bodies = compiler.check_bodies(&declarations, &signatures, &references);
16184+
assert!(
16185+
bodies.errors.iter().any(|error| matches!(
16186+
error.kind,
16187+
men_sharp_semantics::SemanticErrorKind::TypeMismatch { .. }
16188+
| men_sharp_semantics::SemanticErrorKind::InvalidOperator { .. }
16189+
)),
16190+
"{declaration}: {:#?}",
16191+
bodies.errors
16192+
);
16193+
}
16194+
}
16195+
16196+
#[test]
16197+
fn compound_constants_use_boolean_locals_without_converting_bool_to_int() {
16198+
// A const bool may select an integral constant, but the bool itself
16199+
// must never be accepted as an integral constant conversion.
16200+
let Some(messages) = codegen_messages(
16201+
r#"
16202+
using MenSharp;
16203+
public class Probe : MenSharpBehaviour {
16204+
public void Interact() {
16205+
const bool flag = true;
16206+
const bool other = !flag;
16207+
const int step = flag && !other ? 1 : 2;
16208+
byte b = 0;
16209+
b += step;
16210+
}
16211+
}
16212+
"#,
16213+
"Probe",
16214+
) else {
16215+
return;
16216+
};
16217+
assert!(messages.is_empty(), "{messages:?}");
16218+
}

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

Lines changed: 86 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -337,75 +337,7 @@ pub fn check_file(
337337
) -> BodyCheck {
338338
let file = &declarations.files[file_index];
339339

340-
let mut checker = Checker {
341-
resolver: Resolver {
342-
declarations,
343-
external,
344-
file: file.file,
345-
out: Signatures::default(),
346-
},
347-
signatures,
348-
scopes: Vec::new(),
349-
type_stack: Vec::new(),
350-
locals: Vec::new(),
351-
this_type: None,
352-
static_context: true,
353-
return_type: Type::Void,
354-
lambda_probe_returns: None,
355-
lambda_stack: Vec::new(),
356-
current_member: None,
357-
captures: HashMap::default(),
358-
captured_locals: HashMap::default(),
359-
capture_types: HashMap::default(),
360-
local_functions: HashMap::default(),
361-
local_calls: HashMap::default(),
362-
declared_names: HashMap::default(),
363-
static_local_functions: HashSet::default(),
364-
local_order: 0,
365-
local_function_order: HashMap::default(),
366-
expression_types: HashMap::default(),
367-
numeric_promotions: HashMap::default(),
368-
attribute_types: HashMap::default(),
369-
targets: HashMap::default(),
370-
pattern_inputs: HashMap::default(),
371-
enumerations: HashMap::default(),
372-
disposals: HashMap::default(),
373-
constructor_chains: HashMap::default(),
374-
catch_depth: 0,
375-
in_async: false,
376-
awaits: HashMap::default(),
377-
iterator_element: None,
378-
yield_seen: false,
379-
value_return_seen: false,
380-
guarded_depth: 0,
381-
catch_depth_for_yield: 0,
382-
finally_depth: 0,
383-
iterators: HashSet::default(),
384-
};
385-
386-
// rebuild the same file scope signature resolution used
387-
checker.scopes.push(NamespaceScope {
388-
path: Vec::new(),
389-
symbol: Some(declarations.table.root()),
390-
usings: Vec::new(),
391-
});
392-
let mut root_usings = Vec::new();
393-
for (_, using) in declarations.global_usings() {
394-
if let Some(resolved) = checker.resolve_using(using) {
395-
root_usings.push(resolved);
396-
}
397-
}
398-
for using in &file.usings {
399-
if using.global.is_none()
400-
&& let Some(resolved) = checker.resolve_using(using)
401-
{
402-
root_usings.push(resolved);
403-
}
404-
}
405-
// using-target resolution errors were already reported by the resolve phase;
406-
// this rebuild must not duplicate them
407-
checker.resolver.out.errors.clear();
408-
checker.scopes[0].usings = root_usings;
340+
let mut checker = Checker::for_file(declarations, signatures, external, file_index);
409341

410342
checker.walk_nodes(&file.members);
411343
checker.close_captures();
@@ -576,6 +508,8 @@ struct LocalFunctionEntry<'ast> {
576508

577509
struct Checker<'a, 'ast> {
578510
resolver: Resolver<'a, 'ast>,
511+
/// Bounds recursive const-field binding as well as value evaluation.
512+
constant_depth: usize,
579513
signatures: &'a Signatures,
580514
scopes: Vec<NamespaceScope<'ast>>,
581515
type_stack: Vec<SymbolId>,
@@ -686,3 +620,86 @@ fn type_parameter_leaves(ty: &Type) -> usize {
686620
_ => 0,
687621
}
688622
}
623+
624+
impl<'a, 'ast> Checker<'a, 'ast> {
625+
fn for_file(
626+
declarations: &'a Declarations<'ast>,
627+
signatures: &'a Signatures,
628+
external: &'a dyn ExternalTypes,
629+
file_index: usize,
630+
) -> Self {
631+
let file = &declarations.files[file_index];
632+
let mut checker = Checker {
633+
resolver: Resolver {
634+
declarations,
635+
external,
636+
file: file.file,
637+
out: Signatures::default(),
638+
},
639+
signatures,
640+
constant_depth: 64,
641+
scopes: Vec::new(),
642+
type_stack: Vec::new(),
643+
locals: Vec::new(),
644+
this_type: None,
645+
static_context: true,
646+
return_type: Type::Void,
647+
lambda_probe_returns: None,
648+
lambda_stack: Vec::new(),
649+
current_member: None,
650+
captures: HashMap::default(),
651+
captured_locals: HashMap::default(),
652+
capture_types: HashMap::default(),
653+
local_functions: HashMap::default(),
654+
local_calls: HashMap::default(),
655+
declared_names: HashMap::default(),
656+
static_local_functions: HashSet::default(),
657+
local_order: 0,
658+
local_function_order: HashMap::default(),
659+
expression_types: HashMap::default(),
660+
numeric_promotions: HashMap::default(),
661+
attribute_types: HashMap::default(),
662+
targets: HashMap::default(),
663+
pattern_inputs: HashMap::default(),
664+
enumerations: HashMap::default(),
665+
disposals: HashMap::default(),
666+
constructor_chains: HashMap::default(),
667+
catch_depth: 0,
668+
in_async: false,
669+
awaits: HashMap::default(),
670+
iterator_element: None,
671+
yield_seen: false,
672+
value_return_seen: false,
673+
guarded_depth: 0,
674+
catch_depth_for_yield: 0,
675+
finally_depth: 0,
676+
iterators: HashSet::default(),
677+
};
678+
679+
// rebuild the same file scope signature resolution used
680+
checker.scopes.push(NamespaceScope {
681+
path: Vec::new(),
682+
symbol: Some(declarations.table.root()),
683+
usings: Vec::new(),
684+
});
685+
let mut root_usings = Vec::new();
686+
for (_, using) in declarations.global_usings() {
687+
if let Some(resolved) = checker.resolve_using(using) {
688+
root_usings.push(resolved);
689+
}
690+
}
691+
for using in &file.usings {
692+
if using.global.is_none()
693+
&& let Some(resolved) = checker.resolve_using(using)
694+
{
695+
root_usings.push(resolved);
696+
}
697+
}
698+
// using-target resolution errors were already reported by the resolve phase;
699+
// this rebuild must not duplicate them
700+
checker.resolver.out.errors.clear();
701+
checker.scopes[0].usings = root_usings;
702+
703+
checker
704+
}
705+
}

0 commit comments

Comments
 (0)