Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 106 additions & 16 deletions codegen/src/semantic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -488,22 +488,29 @@ fn compile_lookup(
name: name.clone(),
fields: fields.iter().map(|field| field.name.clone()).collect(),
};
let cases = lookup
.definition
let cases = enum_type
.values
.iter()
.map(|case| RecordLookupCase {
member: case.key.clone(),
values: fields
.map(|member| {
let case = lookup
.definition
.values
.iter()
.map(|field| {
let value = case.value[&field.name];
Number {
value,
lexeme: format!("{value:?}"),
}
})
.collect(),
.find(|case| case.key == member.name)
.expect("validated lookup covers every enum member exactly once");
RecordLookupCase {
member: member.name.clone(),
values: fields
.iter()
.map(|field| {
let value = case.value[&field.name];
Number {
value,
lexeme: format!("{value:?}"),
}
})
.collect(),
}
})
.collect();
Ok((
Expand Down Expand Up @@ -729,12 +736,12 @@ mod tests {
use crate::{
formula::parse,
model::{
RawExpression, RawFunction, RawInput, RawInputType, RawVariable, RawVariableValue,
SourceLocation,
EnumDefinition, LookupDefinition, Outputs, Parameter, RawExpression, RawFunction,
RawInput, RawInputType, RawLookup, RawVariable, RawVariableValue, SourceLocation,
},
};

use super::{BinaryOp, Expr, compile};
use super::{BinaryOp, Expr, VariableValue, compile};

fn expression(path: &str, source: &str) -> RawExpression {
RawExpression {
Expand Down Expand Up @@ -798,6 +805,89 @@ mod tests {
));
}

#[test]
fn lookup_cases_follow_enum_order() {
let mut enum_type: EnumDefinition = serde_yaml::from_str(
r#"
type: enum
description: Example enum.
values:
- name: first
value: first
- name: second
value: second
"#,
)
.unwrap();
enum_type.name = "ExampleEnum".into();

let mut lookup_definition: LookupDefinition = serde_yaml::from_str(
r##"
type: lookup
input:
$ref: "#/$defs/ExampleEnum"
output:
$ref: "#/$defs/ExampleRecord"
values:
- key: second
value:
value: 2.0
- key: first
value:
value: 1.0
"##,
)
.unwrap();
lookup_definition.name = "ExampleLookup".into();
lookup_definition.input_type = Some(enum_type.clone());
lookup_definition.output_type = Some(Outputs::Record {
name: "ExampleRecord".into(),
fields: vec![Parameter {
name: "value".into(),
unit: "1".into(),
domain: None,
description: "Example value.".into(),
}],
});

let raw = RawFunction {
specification_path: PathBuf::from("specs/functions/example.md"),
name: "example".into(),
inputs: vec![RawInput {
name: "kind".into(),
value_type: RawInputType::Enum(enum_type),
}],
variables: vec![RawVariable {
name: "row".into(),
value: RawVariableValue::Lookup(RawLookup {
implementation_path: "implementation.variables[0].lookup".into(),
key: "kind".into(),
definition: lookup_definition,
}),
}],
};
let compiled = compile(&raw).unwrap();
let VariableValue::RecordLookup(lookup) = &compiled.variables[0].value else {
panic!("expected record lookup");
};
assert_eq!(
lookup
.cases
.iter()
.map(|case| case.member.as_str())
.collect::<Vec<_>>(),
["first", "second"]
);
assert_eq!(
lookup
.cases
.iter()
.map(|case| case.values[0].value)
.collect::<Vec<_>>(),
[1.0, 2.0]
);
}

#[test]
fn rejects_unknown_forward_and_self_references_with_expression_paths() {
for (source, expected) in [
Expand Down
124 changes: 47 additions & 77 deletions codegen/src/targets/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,13 +85,10 @@ fn c_header(slug: &str, functions: &[&CompiledFunction]) -> Result<String> {
if requires_pow4(functions) {
writer.write("#include <ptfkit/detail/power.h>\n");
}
if requires_record_literal(functions) {
writer.write("#include <ptfkit/detail/record.h>\n");
}
if requires_math(functions) {
if requires_math(functions) || requires_lookup(functions) {
writer.write("#include <math.h>\n");
}
if requires_pow4(functions) || requires_math(functions) {
if requires_pow4(functions) || requires_math(functions) || requires_lookup(functions) {
writer.blank_line();
}
let first = functions
Expand Down Expand Up @@ -147,17 +144,14 @@ fn c_header(slug: &str, functions: &[&CompiledFunction]) -> Result<String> {
fn cpp_module(slug: &str, functions: &[&CompiledFunction]) -> Result<String> {
let mut writer = Writer::new();
writer.write(format_args!("{HEADER}\n\n"));
if requires_pow4(functions) || requires_math(functions) || requires_cpp_unreachable(functions) {
if requires_pow4(functions) || requires_math(functions) {
writer.write("module;\n");
if requires_pow4(functions) {
writer.write("#include <ptfkit/detail/power.h>\n");
}
if requires_math(functions) {
writer.write("#include <cmath>\n");
}
if requires_cpp_unreachable(functions) {
writer.write("#include <utility>\n");
}
writer.blank_line();
}
writer.write(format_args!("export module ptfkit.{slug};\n\n"));
Expand Down Expand Up @@ -363,19 +357,10 @@ impl NativeFunction<'_> {
}
Output::Scalar => writer.line(format_args!("return {output_name};")),
Output::Struct(fields) if matches!(self.dialect, NativeDialect::C) => {
writer.line("#ifdef __cplusplus");
writer.write(format_args!("return {}{{", self.result));
writer.write(format_args!("{} result = {{", self.result));
render_values(writer, fields);
writer.line("};");
writer.line("#else");
writer.line(format_args!("return ({}) {{", self.result));
writer.indented(|writer| {
for field in fields {
writer.line(format_args!(".{field} = {field},"));
}
});
writer.line("};");
writer.line("#endif");
writer.line("return result;");
}
Output::Struct(fields) => {
writer.write(format_args!("return {}{{", self.result));
Expand All @@ -396,7 +381,7 @@ impl NativeFunction<'_> {
};
writer.line(format_args!(
"const {result} {name} = {}({key});",
record_lookup_function_name(lookup, self.dialect)
record_lookup_function_name(lookup)
));
}
}
Expand All @@ -414,7 +399,7 @@ fn lookup_definitions<'a>(functions: &[&'a CompiledFunction]) -> Vec<&'a RecordL
.collect()
}

fn record_lookup_function_name(lookup: &RecordLookup, _dialect: NativeDialect) -> String {
fn record_lookup_function_name(lookup: &RecordLookup) -> String {
format!(
"{}_from_{}",
c_result_name(&lookup.output.name),
Expand Down Expand Up @@ -442,65 +427,56 @@ fn render_record_lookup_helper(
}
writer.line(format_args!(
"{result} {}({enum_name} value) {{",
record_lookup_function_name(lookup, dialect)
record_lookup_function_name(lookup)
));
writer.indented(|writer| {
writer.line("switch (value) {");
match dialect {
NativeDialect::C => writer.line(format_args!("static const {result} table[] = {{")),
NativeDialect::Cpp => {
writer.line(format_args!("static constexpr {result} table[] = {{"))
}
}
writer.indented(|writer| {
for case in &lookup.cases {
let member = match dialect {
NativeDialect::C => c_enum_member(slug, &lookup.enum_name, &case.member),
NativeDialect::Cpp => format!(
"{}::{}",
lookup.enum_name,
case.member.to_case(Case::Pascal)
),
};
writer.line(format_args!("case {member}:"));
writer.write("{");
render_lookup_values(writer, &case.values);
writer.line("},");
}
});
writer.line("};");
match dialect {
NativeDialect::C => {
writer.line("const unsigned index = (unsigned)value;");
writer.line("if (index < sizeof(table) / sizeof(table[0])) {");
writer.indented(|writer| {
writer.write("return ");
render_record_literal(writer, &result, &case.values, dialect);
writer.line(";");
writer.line("return table[index];");
});
}
writer.line("default:");
writer.indented(|writer| match dialect {
NativeDialect::C => {
let nan_values = std::iter::repeat_n("NAN", lookup.output.fields.len())
.collect::<Vec<_>>()
.join(", ");
writer.line(format_args!(
"return PTFKIT_RECORD_LITERAL({result}, {nan_values});"
));
writer.line("}");
writer.write(format_args!("const {result} fallback = {{"));
for index in 0..lookup.output.fields.len() {
if index > 0 {
writer.write(", ");
}
writer.write("NAN");
}
NativeDialect::Cpp => writer.line("std::unreachable();"),
});
});
writer.line("}");
writer.line("};");
writer.line("return fallback;");
}
NativeDialect::Cpp => {
writer.line("return table[static_cast<unsigned>(value)];");
}
}
});
writer.line("}");
}

fn render_record_literal(
writer: &mut Writer,
result: &str,
values: &[crate::semantic::Number],
dialect: NativeDialect,
) {
match dialect {
NativeDialect::C => writer.write(format_args!("PTFKIT_RECORD_LITERAL({result}, ")),
NativeDialect::Cpp => writer.write(format_args!("{result}{{")),
}
fn render_lookup_values(writer: &mut Writer, values: &[crate::semantic::Number]) {
for (index, value) in values.iter().enumerate() {
if index > 0 {
writer.write(", ");
}
writer.write(c::float_literal(&value.lexeme));
}
writer.write(match dialect {
NativeDialect::C => ")",
NativeDialect::Cpp => "}",
});
}

fn render_values(writer: &mut Writer, values: &[String]) {
Expand Down Expand Up @@ -756,38 +732,32 @@ fn requires_math(functions: &[&CompiledFunction]) -> bool {
.ir
.variables
.iter()
.any(|variable| match &variable.value {
VariableValue::Number(expression) => c::requires_math(expression),
VariableValue::RecordLookup(_) => true,
})
.filter_map(|variable| variable.value.as_number())
.any(c::requires_math)
})
}

fn requires_pow4(functions: &[&CompiledFunction]) -> bool {
fn requires_lookup(functions: &[&CompiledFunction]) -> bool {
functions.iter().any(|function| {
function
.ir
.variables
.iter()
.filter_map(|variable| variable.value.as_number())
.any(c::requires_pow4)
.any(|variable| matches!(variable.value, VariableValue::RecordLookup(_)))
})
}

fn requires_record_literal(functions: &[&CompiledFunction]) -> bool {
fn requires_pow4(functions: &[&CompiledFunction]) -> bool {
functions.iter().any(|function| {
function
.ir
.variables
.iter()
.any(|variable| matches!(variable.value, VariableValue::RecordLookup(_)))
.filter_map(|variable| variable.value.as_number())
.any(c::requires_pow4)
})
}

fn requires_cpp_unreachable(functions: &[&CompiledFunction]) -> bool {
requires_record_literal(functions)
}

fn c_test(slug: &str, functions: &[&CompiledFunction]) -> Result<String> {
c_compatibility_test(slug, functions)
}
Expand Down
Loading