Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement new builder syntax alongside old one #6883

Merged
merged 4 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
219 changes: 204 additions & 15 deletions crates/compiler/can/src/desugar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use roc_module::called_via::{BinOp, CalledVia};
use roc_module::ident::ModuleName;
use roc_parse::ast::Expr::{self, *};
use roc_parse::ast::{
AssignedField, Collection, ModuleImportParams, Pattern, RecordBuilderField, StrLiteral,
AssignedField, Collection, ModuleImportParams, OldRecordBuilderField, Pattern, StrLiteral,
StrSegment, ValueDef, WhenBranch,
};
use roc_region::all::{LineInfo, Loc, Region};
Expand Down Expand Up @@ -300,8 +300,11 @@ pub fn desugar_expr<'a>(
| MalformedClosure
| MalformedSuffixed(..)
| PrecedenceConflict { .. }
| MultipleRecordBuilders { .. }
| UnappliedRecordBuilder { .. }
| MultipleOldRecordBuilders(_)
| UnappliedOldRecordBuilder(_)
| EmptyNewRecordBuilder(_)
| SingleFieldNewRecordBuilder(_)
| OptionalFieldInNewRecordBuilder { .. }
| Tag(_)
| OpaqueRef(_)
| Crash => loc_expr,
Expand Down Expand Up @@ -485,10 +488,196 @@ pub fn desugar_expr<'a>(
}
}
}
RecordBuilder(_) => arena.alloc(Loc {
value: UnappliedRecordBuilder(loc_expr),
OldRecordBuilder(_) => arena.alloc(Loc {
value: UnappliedOldRecordBuilder(loc_expr),
region: loc_expr.region,
}),
NewRecordBuilder { mapper, fields } => {
// NOTE the `mapper` is always a `Var { .. }`, we only desugar it to get rid of
// any spaces before/after
let new_mapper = desugar_expr(arena, mapper, src, line_info, module_path);

if fields.is_empty() {
return arena.alloc(Loc {
value: EmptyNewRecordBuilder(loc_expr),
region: loc_expr.region,
});
} else if fields.len() == 1 {
return arena.alloc(Loc {
value: SingleFieldNewRecordBuilder(loc_expr),
region: loc_expr.region,
});
}

let mut field_names = vec![];
let mut field_vals = vec![];
smores56 marked this conversation as resolved.
Show resolved Hide resolved

for field in fields.items {
match desugar_field(arena, &field.value, src, line_info, module_path) {
AssignedField::RequiredValue(loc_name, _, loc_val) => {
field_names.push(loc_name);
field_vals.push(loc_val);
}
AssignedField::LabelOnly(loc_name) => {
field_names.push(loc_name);
field_vals.push(arena.alloc(Loc {
region: loc_name.region,
value: Expr::Var {
module_name: "",
ident: loc_name.value,
},
}));
}
AssignedField::OptionalValue(loc_name, _, loc_val) => {
return arena.alloc(Loc {
region: loc_expr.region,
value: OptionalFieldInNewRecordBuilder(arena.alloc(loc_name), loc_val),
});
}
AssignedField::SpaceBefore(_, _) | AssignedField::SpaceAfter(_, _) => {
unreachable!("Should have been desugared in `desugar_field`")
}
AssignedField::Malformed(_name) => {}
}
}

let closure_arg_from_field = |field: Loc<&'a str>| Loc {
region: field.region,
value: Pattern::Identifier {
ident: arena.alloc_str(&format!("#{}", field.value)),
},
};

let combiner_closure = arena.alloc(Loc::at_zero(Closure(
arena.alloc_slice_copy(&[
Loc::at_zero(Pattern::Identifier {
ident: "#record_builder_closure_arg_a",
}),
Loc::at_zero(Pattern::Identifier {
ident: "#record_builder_closure_arg_b",
}),
]),
arena.alloc(Loc::at_zero(Tuple(Collection::with_items(
Vec::from_iter_in(
[
&*arena.alloc(Loc::at_zero(Expr::Var {
module_name: "",
ident: "#record_builder_closure_arg_a",
})),
&*arena.alloc(Loc::at_zero(Expr::Var {
module_name: "",
ident: "#record_builder_closure_arg_b",
})),
],
arena,
)
.into_bump_slice(),
)))),
)));
smores56 marked this conversation as resolved.
Show resolved Hide resolved

let closure_args = {
if field_names.len() <= 2 {
arena.alloc_slice_copy(&[
closure_arg_from_field(field_names[0]),
closure_arg_from_field(field_names[1]),
])
smores56 marked this conversation as resolved.
Show resolved Hide resolved
} else {
let second_to_last_arg =
closure_arg_from_field(field_names[field_names.len() - 2]);
let last_arg = closure_arg_from_field(field_names[field_names.len() - 1]);

let mut second_arg = Pattern::Tuple(Collection::with_items(
arena.alloc_slice_copy(&[second_to_last_arg, last_arg]),
));
for index in (1..(field_names.len() - 2)).rev() {
second_arg =
Pattern::Tuple(Collection::with_items(arena.alloc_slice_copy(&[
closure_arg_from_field(field_names[index]),
Loc::at_zero(second_arg),
])));
}

arena.alloc_slice_copy(&[
closure_arg_from_field(field_names[0]),
Loc::at_zero(second_arg),
])
}
};

let record_val = Record(Collection::with_items(
Vec::from_iter_in(
field_names.iter().map(|field_name| {
Loc::at(
field_name.region,
AssignedField::RequiredValue(
Loc::at(field_name.region, field_name.value),
&[],
arena.alloc(Loc::at_zero(Expr::Var {
smores56 marked this conversation as resolved.
Show resolved Hide resolved
module_name: "",
ident: arena.alloc_str(&format!("#{}", field_name.value)),
})),
),
)
}),
arena,
)
.into_bump_slice(),
));

let record_combiner_closure = arena.alloc(Loc {
region: loc_expr.region,
value: Closure(closure_args, arena.alloc(Loc::at_zero(record_val))),
});

if field_names.len() == 2 {
return arena.alloc(Loc {
region: loc_expr.region,
value: Apply(
new_mapper,
arena.alloc_slice_copy(&[
field_vals[0],
field_vals[1],
record_combiner_closure,
]),
CalledVia::NewRecordBuilder,
),
});
}

let mut inner_combined = arena.alloc(Loc {
region: loc_expr.region,
value: Apply(
new_mapper,
arena.alloc_slice_copy(&[
field_vals[field_names.len() - 2],
field_vals[field_names.len() - 1],
combiner_closure,
]),
CalledVia::NewRecordBuilder,
),
});

for index in (1..(field_names.len() - 2)).rev() {
inner_combined = arena.alloc(Loc::at_zero(Apply(
new_mapper,
arena.alloc_slice_copy(&[field_vals[index], inner_combined, combiner_closure]),
CalledVia::NewRecordBuilder,
)));
}

arena.alloc(Loc {
region: loc_expr.region,
value: Apply(
new_mapper,
arena.alloc_slice_copy(&[
field_vals[0],
inner_combined,
record_combiner_closure,
]),
CalledVia::NewRecordBuilder,
),
})
}
BinOps(lefts, right) => desugar_bin_ops(
arena,
loc_expr.region,
Expand All @@ -513,10 +702,10 @@ pub fn desugar_expr<'a>(
let mut current = loc_arg.value;
let arg = loop {
match current {
RecordBuilder(fields) => {
OldRecordBuilder(fields) => {
if builder_apply_exprs.is_some() {
return arena.alloc(Loc {
value: MultipleRecordBuilders(loc_expr),
value: MultipleOldRecordBuilders(loc_expr),
region: loc_expr.region,
});
}
Expand Down Expand Up @@ -557,7 +746,7 @@ pub fn desugar_expr<'a>(
let args = std::slice::from_ref(arena.alloc(apply));

apply = arena.alloc(Loc {
value: Apply(desugared_expr, args, CalledVia::RecordBuilder),
value: Apply(desugared_expr, args, CalledVia::OldRecordBuilder),
region: loc_expr.region,
});
}
Expand Down Expand Up @@ -1015,7 +1204,7 @@ struct RecordBuilderArg<'a> {
fn record_builder_arg<'a>(
smores56 marked this conversation as resolved.
Show resolved Hide resolved
arena: &'a Bump,
region: Region,
fields: Collection<'a, Loc<RecordBuilderField<'a>>>,
fields: Collection<'a, Loc<OldRecordBuilderField<'a>>>,
) -> RecordBuilderArg<'a> {
let mut record_fields = Vec::with_capacity_in(fields.len(), arena);
let mut apply_exprs = Vec::with_capacity_in(fields.len(), arena);
Expand All @@ -1028,10 +1217,10 @@ fn record_builder_arg<'a>(

let new_field = loop {
match current {
RecordBuilderField::Value(label, spaces, expr) => {
OldRecordBuilderField::Value(label, spaces, expr) => {
break AssignedField::RequiredValue(label, spaces, expr)
}
RecordBuilderField::ApplyValue(label, _, _, expr) => {
OldRecordBuilderField::ApplyValue(label, _, _, expr) => {
apply_field_names.push(label);
apply_exprs.push(expr);

Expand All @@ -1045,14 +1234,14 @@ fn record_builder_arg<'a>(

break AssignedField::RequiredValue(label, &[], var);
}
RecordBuilderField::LabelOnly(label) => break AssignedField::LabelOnly(label),
RecordBuilderField::SpaceBefore(sub_field, _) => {
OldRecordBuilderField::LabelOnly(label) => break AssignedField::LabelOnly(label),
OldRecordBuilderField::SpaceBefore(sub_field, _) => {
current = *sub_field;
}
RecordBuilderField::SpaceAfter(sub_field, _) => {
OldRecordBuilderField::SpaceAfter(sub_field, _) => {
current = *sub_field;
}
RecordBuilderField::Malformed(malformed) => {
OldRecordBuilderField::Malformed(malformed) => {
break AssignedField::Malformed(malformed)
}
}
Expand Down
Loading