use std::collections::{BTreeMap, BTreeSet};
use bumpalo::Bump;
use nash_ast::{
Alias as CanAlias, Binop as CanBinop, Ctor as CanCtor, CtorOpts, Decls, Export, Exports,
Module as CanModule, ModuleName, PackageName, Union as CanUnion,
};
use nash_region::{Located, Region};
use nash_source::{
Alias as SourceAlias, Ctor as SourceCtor, CtorArgs as SourceCtorArgs, Exposed, Exposing, Infix,
Module as SourceModule, Privacy, Type as SourceType, Union as SourceUnion,
Value as SourceValue,
};
use crate::accumulate;
use crate::environment::{self, Env, dups};
use crate::error::{DuplicatePatternContext, VarKind};
use crate::expression;
use crate::kinds;
use crate::pattern;
use crate::scc;
use crate::types;
use crate::warning::{Warning, WarningContext};
use crate::{Error, Interface};
#[derive(Clone, Copy, Debug, Default)]
pub struct Context<'a, 'i> {
pub package: Option<PackageName<'a>>,
pub interfaces: Option<&'i BTreeMap<&'a str, Interface<'a>>>,
}
#[derive(Debug)]
pub struct CanResult<'a> {
pub tables: environment::Tables<'a>,
pub module: CanModule<'a>,
pub warnings: Vec<Warning<'a>>,
}
pub fn canonicalize<'a>(
bump: &'a Bump,
context: Context<'a, '_>,
module: &SourceModule<'a>,
) -> Result<CanResult<'a>, Vec<Error<'a>>> {
let mut interfaces = context.interfaces.cloned().unwrap_or_default();
interfaces
.entry("Primitive")
.or_insert_with(|| kinds::primitive_interface(bump));
interfaces
.entry("Builtin")
.or_insert_with(|| kinds::builtin_interface(bump));
let context = Context {
package: context.package,
interfaces: Some(&interfaces),
};
let name = module
.name
.ok_or_else(|| vec![Error::MissingModuleHeader])?;
let home = ModuleName {
package: context.package,
name: name.value,
};
let mut env =
environment::foreign::create_initial_env(bump, home, context.interfaces, module.imports)?;
environment::local::add_union_types(&mut env, module.unions, module.aliases)?;
for union in module.unions {
check_union_free_vars(bump, union)?;
}
let pre_aliases = canonicalize_aliases(bump, &mut env, module.aliases)?;
environment::local::add_vars(&mut env, module.values)?;
if let nash_ast::ModuleKind::Validator(region) = module.kind
&& !module
.values
.iter()
.any(|value| value.value.name.value == "main")
{
return Err(vec![Error::ValidatorMissingMain {
region,
module: home.name,
}]);
}
let pre_unions = canonicalize_unions(bump, &env, module.unions)?;
let mut kind_env = kinds::KindEnv::from_interfaces(context.interfaces);
let schemes = kinds::infer_declarations(bump, &mut kind_env, home, &pre_unions, &pre_aliases)?;
env.kinds = kind_env.clone();
let unions = bump.alloc_slice_fill_iter(pre_unions.iter().map(|u| {
&*bump.alloc(Located::at(
u.source.region,
CanUnion {
name: u.name,
parameters: u.parameters,
ctors: u.ctors,
alternatives: u.alternatives,
options: u.options,
kind: schemes.kind(u.name.value),
context: schemes.context(u.name.value),
},
))
}));
let aliases = bump.alloc_slice_fill_iter(pre_aliases.iter().map(|a| {
&*bump.alloc(Located::at(
a.source.region,
CanAlias {
name: a.name,
parameters: a.parameters,
typ: a.typ,
kind: schemes.kind(a.name.value),
context: schemes.context(a.name.value),
},
))
}));
environment::local::add_ctors(bump, &mut env, module.unions, unions, aliases)?;
let mut warnings = Vec::new();
let traits = crate::traits::canonicalize(bump, &mut env, &mut kind_env, module, &mut warnings)?;
environment::local::check_binops(&env, module.binops)?;
let impls = crate::impls::canonicalize(bump, &env, &kind_env, module.impls, &mut warnings)?;
let decls = canonicalize_decls(bump, &env, module.values, &mut warnings)?;
let mut test_env = env.clone();
if let Some(tests) = module.tests {
let defaults = crate::defaults::test_imports(bump, home, context.interfaces);
environment::foreign::add_imports(bump, &mut test_env, context.interfaces, &defaults)?;
environment::foreign::add_imports(bump, &mut test_env, context.interfaces, tests.imports)?;
for (name, info) in &env.types {
if matches!(info, environment::Info::Specific(owner, _) if *owner == home) {
test_env.types.insert(name, info.clone());
}
}
for (name, info) in &env.ctors {
if matches!(info, environment::Info::Specific(owner, _) if *owner == home) {
test_env.ctors.insert(name, info.clone());
}
}
for (name, info) in &env.traits {
if matches!(info, environment::Info::Specific(owner, _) if *owner == home) {
test_env.traits.insert(name, info.clone());
}
}
for (name, var) in &env.vars {
if matches!(
var,
environment::Var::TopLevel(_)
| environment::Var::Method {
local_region: Some(_),
..
}
) {
test_env.vars.insert(name, var.clone());
}
}
}
let tests = canonicalize_tests(bump, &test_env, module.tests, &mut warnings)?;
let binops = canonicalize_binops(bump, &env, module.binops);
let exports = canonicalize_exports(bump, module)?;
if matches!(module.kind, nash_ast::ModuleKind::Validator(_))
&& matches!(&exports, Exports::Explicit(items) if !items.iter().any(|e| matches!(e.value, Export::Value("main"))))
{
return Err(vec![Error::ValidatorMainNotExposed {
region: module.exports.region,
module: home.name,
}]);
}
let can_module = CanModule {
tests,
traits,
impls,
kind: module.kind,
name: env.home,
exports,
docs: module.docs,
decls,
unions,
aliases,
binops,
};
let used_modules = collect_used_modules(&can_module);
for import in module
.imports
.iter()
.chain(module.tests.into_iter().flat_map(|t| t.imports.iter()))
{
let module_name = import.import.value;
if !used_modules.contains(module_name) {
warnings.push(Warning::UnusedImport {
region: import.import.region,
module_name,
});
}
}
let mut tables = crate::impls::tables(bump, context.interfaces, &can_module, &kind_env)?;
tables.fields = environment::visible_fields(bump, &env);
tables.test_fields = environment::visible_fields(bump, &test_env);
Ok(CanResult {
tables,
module: can_module,
warnings,
})
}
fn canonicalize_tests<'a>(
bump: &'a Bump,
env: &Env<'a>,
tests: Option<&nash_source::Tests<'a>>,
warnings: &mut Vec<Warning<'a>>,
) -> Result<&'a [nash_ast::Test<'a>], Vec<Error<'a>>> {
let Some(tests) = tests else {
return Ok(&[]);
};
dups::detect(
tests
.tests
.iter()
.map(|t| (t.value.name.value, t.value.name.region)),
|name, first, second| Error::DuplicateTest {
name,
first,
second,
},
)?;
let empty = BTreeMap::new();
let base = environment::Scope::new(env, None, &empty)?;
let mut result = Vec::new();
for test in tests.tests {
let (binders, block) = match test.value.body {
nash_source::TestBody::Unit(body) => (&[][..], body),
nash_source::TestBody::Prop { binders, body } => (binders, body),
};
let patterns: Vec<_> = binders.iter().map(|b| b.value.pattern).collect();
let (patterns, bindings) =
pattern::verify_all(bump, env, DuplicatePatternContext::Destruct, &patterns)?;
let mut can_binders = Vec::new();
for (binder, pattern) in binders.iter().zip(patterns) {
let generator = expression::canonicalize_expr(
bump,
&base,
binder.value.generator,
&mut expression::FreeLocals::new(),
warnings,
)?;
can_binders.push(nash_ast::ViaBinder { pattern, generator });
}
let scope = base.add_locals(&bindings)?;
let mut free = expression::FreeLocals::new();
let body = expression::canonicalize_test_block(
bump,
&scope,
block.stmts,
block.last,
&mut free,
warnings,
)?;
expression::verify_bindings(WarningContext::Def, &bindings, free, warnings);
result.push(nash_ast::Test {
region: test.region,
name: test.value.name,
expect: test.value.expect,
budget: test.value.budget,
binders: bump.alloc_slice_fill_iter(can_binders),
body,
});
}
Ok(bump.alloc_slice_fill_iter(result))
}
fn canonicalize_decls<'a>(
bump: &'a Bump,
env: &Env<'a>,
values: &'a [&'a Located<SourceValue<'a>>],
warnings: &mut Vec<Warning<'a>>,
) -> Result<&'a Decls<'a>, Vec<Error<'a>>> {
if values.is_empty() {
return Ok(bump.alloc(Decls::Empty));
}
let mut errors = Vec::new();
let mut nodes: Vec<NodeOne<'a>> = Vec::with_capacity(values.len());
for value in values {
match to_node_one(bump, env, value, None, warnings) {
Ok(node) => nodes.push(node),
Err(errs) => errors.extend(errs),
}
}
if !errors.is_empty() {
return Err(errors);
}
let top_level_names: BTreeSet<&str> = nodes.iter().map(|n| n.name).collect();
let scc_nodes: Vec<scc::Node<'_, NodeOne<'a>>> = nodes
.into_iter()
.map(|node| {
let deps: Vec<&str> = node
.free_locals
.keys()
.filter(|k| top_level_names.contains(*k))
.copied()
.collect();
scc::Node {
key: node.name,
value: node,
deps,
}
})
.collect();
let phase1_sccs = scc::strongly_connected_components(scc_nodes);
let mut decls: &'a Decls<'a> = bump.alloc(Decls::Empty);
for scc_group in phase1_sccs.into_iter().rev() {
match scc_group {
scc::Scc::Acyclic(node) => {
decls = bump.alloc(Decls::Declare {
definition: node.def,
next: decls,
});
}
scc::Scc::Cyclic(group) => {
let group_names: BTreeSet<&str> = group.iter().map(|n| n.name).collect();
let phase2_nodes: Vec<scc::Node<'_, &NodeOne<'a>>> = group
.iter()
.map(|node| {
let deps = if node.has_args {
vec![] } else {
node.free_locals
.iter()
.filter(|(k, uses)| group_names.contains(*k) && uses.direct > 0)
.map(|(k, _)| *k)
.collect()
};
scc::Node {
key: node.name,
value: node,
deps,
}
})
.collect();
let phase2_sccs = scc::strongly_connected_components(phase2_nodes);
let mut rec_defs: Vec<&'a nash_ast::Def<'a>> = Vec::new();
let mut cycle_errors: Vec<Error<'a>> = Vec::new();
for sub_scc in phase2_sccs {
match sub_scc {
scc::Scc::Acyclic(node) => {
rec_defs.push(node.def);
}
scc::Scc::Cyclic(bad_nodes) => {
let def_name = match bad_nodes[0].def {
nash_ast::Def::Def { name, .. }
| nash_ast::Def::TypedDef { name, .. } => name,
};
cycle_errors.push(Error::RecursiveDecl {
name: def_name,
others: bump
.alloc_slice_fill_iter(bad_nodes[1..].iter().map(|n| n.name)),
});
}
}
}
if !cycle_errors.is_empty() {
return Err(cycle_errors);
}
if let Some((first, rest)) = rec_defs.split_first() {
decls = bump.alloc(Decls::DeclareRec {
definition: first,
following: bump.alloc_slice_fill_iter(rest.iter().copied()),
next: decls,
});
}
}
}
}
Ok(decls)
}
struct NodeOne<'a> {
def: &'a nash_ast::Def<'a>,
name: &'a str,
has_args: bool,
free_locals: expression::FreeLocals<'a>,
}
enum TopLevelDefBuilder<'a> {
Typed {
context: &'a [nash_ast::Pred<'a>],
annotation: &'a Located<nash_ast::Type<'a>>,
free_vars: nash_ast::FreeVars<'a>,
args: &'a [nash_ast::TypedPattern<'a>],
typ: &'a Located<nash_ast::Type<'a>>,
},
Untyped {
args: &'a [&'a Located<nash_ast::Pattern<'a>>],
},
}
fn to_node_one<'a>(
bump: &'a Bump,
env: &Env<'a>,
value: &'a Located<SourceValue<'a>>,
known_annotation: Option<&'a nash_ast::Annotation<'a>>,
warnings: &mut Vec<Warning<'a>>,
) -> Result<NodeOne<'a>, Vec<Error<'a>>> {
let src = &value.value;
if let Some(attribute) = src.attributes.first() {
return Err(vec![Error::Unsupported {
feature: "attributes",
region: attribute.name.region,
}]);
}
let annotation = match known_annotation {
Some(annotation) => Some(annotation),
None => src
.annotation
.map(|ann| types::to_annotation(bump, env, ann))
.transpose()?,
};
let annotation = match (known_annotation, annotation) {
(None, Some(annotation)) => Some(kinds::check_annotation(
bump,
&env.kinds,
src.name.value,
annotation,
)?),
(_, annotation) => annotation,
};
let (builder, arg_bindings) = if let Some(annotation) = annotation {
let mut bound: Vec<(&'a str, Region)> = Vec::new();
let (typed_args, result_type) = expression::gather_typed_args(
bump,
env,
src.name.value,
src.arguments,
annotation.typ,
&mut bound,
)?;
let arg_bindings =
pattern::detect_duplicates(DuplicatePatternContext::FuncArgs(src.name.value), bound)?;
(
TopLevelDefBuilder::Typed {
context: annotation.context,
annotation: annotation.typ,
free_vars: annotation.free_vars,
args: bump.alloc_slice_fill_iter(typed_args),
typ: result_type,
},
arg_bindings,
)
} else {
let (can_args, arg_bindings) = pattern::verify_all(
bump,
env,
DuplicatePatternContext::FuncArgs(src.name.value),
src.arguments,
)?;
(
TopLevelDefBuilder::Untyped {
args: bump.alloc_slice_fill_iter(can_args),
},
arg_bindings,
)
};
let body_env = crate::environment::Scope::new(env, None, &arg_bindings)?;
let mut free_locals = expression::FreeLocals::new();
let can_body =
expression::canonicalize_expr(bump, &body_env, src.body, &mut free_locals, warnings)?;
let outer_free = expression::verify_bindings(
WarningContext::Pattern,
&arg_bindings,
free_locals,
warnings,
);
let def = match builder {
TopLevelDefBuilder::Typed {
context,
annotation,
free_vars,
args,
typ,
} => bump.alloc(nash_ast::Def::TypedDef {
context,
annotation,
name: src.name,
free_vars,
args,
body: can_body,
typ,
}),
TopLevelDefBuilder::Untyped { args } => bump.alloc(nash_ast::Def::Def {
name: src.name,
args,
body: can_body,
}),
};
Ok(NodeOne {
def,
name: src.name.value,
has_args: !src.arguments.is_empty(),
free_locals: outer_free,
})
}
#[derive(Clone, Copy)]
pub(crate) struct PreUnion<'a> {
pub source: &'a Located<SourceUnion<'a>>,
pub name: &'a Located<&'a str>,
pub parameters: &'a [&'a str],
pub ctors: &'a [&'a CanCtor<'a>],
pub context: &'a [nash_ast::Pred<'a>],
pub alternatives: u16,
pub options: CtorOpts,
}
#[derive(Clone, Copy)]
pub(crate) struct PreAlias<'a> {
pub source: &'a Located<SourceAlias<'a>>,
pub name: &'a Located<&'a str>,
pub parameters: &'a [&'a str],
pub typ: &'a Located<nash_ast::Type<'a>>,
pub context: &'a [nash_ast::Pred<'a>],
}
fn canonicalize_unions<'a>(
bump: &'a Bump,
env: &Env<'a>,
unions: &'a [&'a Located<SourceUnion<'a>>],
) -> Result<Vec<PreUnion<'a>>, Vec<Error<'a>>> {
accumulate::try_all(
unions
.iter()
.map(|union| canonicalize_union(bump, env, union)),
)
}
fn ctor_arg_types<'a>(
bump: &'a Bump,
ctor: &'a SourceCtor<'a>,
) -> &'a [&'a Located<SourceType<'a>>] {
match &ctor.arguments {
SourceCtorArgs::Positional(args) => args,
SourceCtorArgs::Labeled(fields) => {
bump.alloc_slice_fill_iter(fields.iter().map(|(_, typ)| *typ))
}
}
}
fn canonicalize_union<'a>(
bump: &'a Bump,
env: &Env<'a>,
source_union: &'a Located<SourceUnion<'a>>,
) -> Result<PreUnion<'a>, Vec<Error<'a>>> {
let union = &source_union.value;
if let Some(attribute) = union.attributes.first() {
return Err(vec![Error::Unsupported {
feature: "attributes",
region: attribute.name.region,
}]);
}
let parameters =
bump.alloc_slice_fill_iter(union.arguments.iter().copied().map(|arg| arg.name.value));
let ctors = canonicalize_ctors(bump, env, union.ctors)?;
let mut context = parameter_repr_predicates(bump, union.arguments);
for ctor in union.ctors {
for typ in ctor_arg_types(bump, ctor) {
context.extend(types::repr_predicates(bump, env, typ)?);
}
}
let context = bump.alloc_slice_fill_iter(context);
let alternatives = union
.ctors
.len()
.try_into()
.expect("union alternatives exceed u16");
let options = if union.ctors.len() == 1 && ctor_arg_types(bump, union.ctors[0]).len() == 1 {
CtorOpts::Unbox
} else if union
.ctors
.iter()
.all(|ctor| ctor_arg_types(bump, ctor).is_empty())
{
CtorOpts::Enum
} else {
CtorOpts::Normal
};
Ok(PreUnion {
source: source_union,
context,
name: union.name,
parameters,
ctors,
alternatives,
options,
})
}
fn canonicalize_ctors<'a>(
bump: &'a Bump,
env: &Env<'a>,
ctors: &'a [&'a SourceCtor<'a>],
) -> Result<&'a [&'a CanCtor<'a>], Vec<Error<'a>>> {
accumulate::try_all_alloc_ref(
bump,
ctors.iter().copied().enumerate().map(|(index, ctor)| {
let source_arguments = ctor_arg_types(bump, ctor);
if matches!(&ctor.arguments, SourceCtorArgs::Positional(_))
&& let Some(record) = source_arguments
.iter()
.find(|arg| matches!(arg.value.unannotated(), SourceType::Record(_)))
{
return Err(vec![Error::Unsupported {
feature: "anonymous record constructor arguments",
region: record.region,
}]);
}
let labels = match &ctor.arguments {
SourceCtorArgs::Positional(_) => None,
SourceCtorArgs::Labeled(fields) => {
dups::detect(
fields.iter().map(|(name, _)| (name.value, name.region)),
|name, first, second| Error::DuplicateField {
name,
first,
second,
},
)?;
Some(&*bump.alloc_slice_fill_iter(fields.iter().map(|(name, _)| name.value)))
}
};
let arguments = types::canonicalize_type_arguments(bump, env, source_arguments)?;
Ok(&*bump.alloc(CanCtor {
labels,
name: ctor.name.value,
index: index.try_into().expect("constructor index exceeds u16"),
arity: source_arguments
.len()
.try_into()
.expect("constructor arity exceeds u16"),
arguments,
}))
}),
)
}
fn canonicalize_aliases<'a>(
bump: &'a Bump,
env: &mut Env<'a>,
source_aliases: &'a [&'a Located<SourceAlias<'a>>],
) -> Result<Vec<PreAlias<'a>>, Vec<Error<'a>>> {
let alias_names: BTreeSet<&str> = source_aliases.iter().map(|a| a.value.name.value).collect();
let scc_nodes: Vec<scc::Node<'_, &'a Located<SourceAlias<'a>>>> = source_aliases
.iter()
.map(|&alias| {
let mut deps = Vec::new();
collect_type_edges(&alias.value.typ.value, &alias_names, &mut deps);
deps.reverse();
scc::Node {
key: alias.value.name.value,
value: alias,
deps,
}
})
.collect();
let sccs = scc::strongly_connected_components(scc_nodes);
let mut results: BTreeMap<&str, PreAlias> = BTreeMap::new();
for component in sccs {
match component {
scc::Scc::Acyclic(source) => {
check_alias_free_vars(bump, source)?;
let alias = canonicalize_single_alias(bump, env, source)?;
environment::local::add_alias_type(
env,
alias.name.value,
alias.parameters,
alias.typ,
);
results.insert(source.value.name.value, alias);
}
scc::Scc::Cyclic(cycle) => {
let first = &cycle[0];
check_alias_free_vars(bump, first)?;
return Err(vec![Error::RecursiveAlias {
region: first.value.name.region,
name: first.value.name.value,
args: bump
.alloc_slice_fill_iter(first.value.arguments.iter().map(|a| a.name.value)),
typ: first.value.typ,
others: bump
.alloc_slice_fill_iter(cycle[1..].iter().map(|a| a.value.name.value)),
}]);
}
}
}
Ok(source_aliases
.iter()
.map(|a| {
*results
.get(a.value.name.value)
.expect("all acyclic aliases inserted into results")
})
.collect())
}
fn canonicalize_single_alias<'a>(
bump: &'a Bump,
env: &Env<'a>,
source_alias: &'a Located<SourceAlias<'a>>,
) -> Result<PreAlias<'a>, Vec<Error<'a>>> {
let alias = &source_alias.value;
if let Some(attribute) = alias.attributes.first() {
return Err(vec![Error::Unsupported {
feature: "attributes",
region: attribute.name.region,
}]);
}
let parameters =
bump.alloc_slice_fill_iter(alias.arguments.iter().copied().map(|arg| arg.name.value));
let typ = types::canonicalize_alias_body(bump, env, alias.typ)?;
let mut context = parameter_repr_predicates(bump, alias.arguments);
context.extend(types::alias_repr_predicates(bump, env, alias.typ)?);
let can_alias = PreAlias {
context: bump.alloc_slice_fill_iter(context),
source: source_alias,
name: alias.name,
parameters,
typ,
};
Ok(can_alias)
}
fn check_union_free_vars<'a>(
bump: &'a Bump,
union: &'a Located<SourceUnion<'a>>,
) -> Result<(), Vec<Error<'a>>> {
let u = &union.value;
dups::detect(
u.arguments
.iter()
.rev()
.map(|a| (a.name.value, a.name.region)),
|arg_name, first, second| Error::DuplicateUnionArg {
type_name: u.name.value,
arg_name,
first,
second,
},
)?;
let bound: BTreeSet<&str> = u.arguments.iter().map(|a| a.name.value).collect();
let mut free_vars: BTreeMap<&str, Region> = BTreeMap::new();
for ctor in u.ctors.iter().rev() {
for arg in ctor_arg_types(bump, ctor) {
collect_free_type_vars(arg, &mut free_vars);
}
}
let unbound: Vec<(&str, Region)> = free_vars
.into_iter()
.filter(|(name, _)| !bound.contains(name))
.collect();
if unbound.is_empty() {
Ok(())
} else {
let args = bump.alloc_slice_fill_iter(u.arguments.iter().map(|a| a.name.value));
let (first_unbound, rest_unbound) = unbound
.split_first()
.expect("unbound is non-empty: guarded by is_empty check");
Err(vec![Error::TypeVarsUnboundInUnion {
region: union.region,
name: u.name.value,
args,
unbound: *first_unbound,
more_unbound: bump.alloc_slice_fill_iter(rest_unbound.iter().copied()),
}])
}
}
fn check_alias_free_vars<'a>(
bump: &'a Bump,
alias: &'a Located<SourceAlias<'a>>,
) -> Result<(), Vec<Error<'a>>> {
let a = &alias.value;
dups::detect(
a.arguments
.iter()
.rev()
.map(|arg| (arg.name.value, arg.name.region)),
|arg_name, first, second| Error::DuplicateAliasArg {
type_name: a.name.value,
arg_name,
first,
second,
},
)?;
let bound: BTreeSet<&str> = a.arguments.iter().map(|arg| arg.name.value).collect();
let mut free_vars: BTreeMap<&str, Region> = BTreeMap::new();
collect_free_type_vars(a.typ, &mut free_vars);
let unused: BTreeMap<&str, Region> = a
.arguments
.iter()
.filter(|arg| !free_vars.contains_key(arg.name.value))
.map(|arg| (arg.name.value, arg.name.region))
.collect();
let unbound: Vec<(&str, Region)> = free_vars
.into_iter()
.filter(|(name, _)| !bound.contains(name))
.collect();
if unused.is_empty() && unbound.is_empty() {
Ok(())
} else {
let args = bump.alloc_slice_fill_iter(a.arguments.iter().map(|arg| arg.name.value));
Err(vec![Error::TypeVarsMessedUpInAlias {
region: alias.region,
name: a.name.value,
args,
unused: bump.alloc_slice_fill_iter(unused),
unbound: bump.alloc_slice_fill_iter(unbound),
}])
}
}
fn collect_type_edges<'a>(
typ: &SourceType<'a>,
alias_names: &BTreeSet<&'a str>,
edges: &mut Vec<&'a str>,
) {
match typ {
SourceType::Repr { typ, .. } => collect_type_edges(&typ.value, alias_names, edges),
SourceType::Lambda { from, to } => {
collect_type_edges(&from.value, alias_names, edges);
collect_type_edges(&to.value, alias_names, edges);
}
SourceType::Var(_) => {}
SourceType::VarApp { args, .. } => {
for arg in *args {
collect_type_edges(&arg.value, alias_names, edges);
}
}
SourceType::Type { name, args, .. } => {
if alias_names.contains(name) {
edges.push(name);
}
for arg in *args {
collect_type_edges(&arg.value, alias_names, edges);
}
}
SourceType::TypeQual { args, .. } => {
for arg in *args {
collect_type_edges(&arg.value, alias_names, edges);
}
}
SourceType::Record(fields) => {
for field in *fields {
collect_type_edges(&field.typ.value, alias_names, edges);
}
}
SourceType::Unit => {}
SourceType::Tuple {
first,
second,
rest,
} => {
collect_type_edges(&first.value, alias_names, edges);
collect_type_edges(&second.value, alias_names, edges);
for r in *rest {
collect_type_edges(&r.value, alias_names, edges);
}
}
}
}
fn collect_free_type_vars<'a>(typ: &Located<SourceType<'a>>, vars: &mut BTreeMap<&'a str, Region>) {
match &typ.value {
SourceType::Repr { typ, .. } => collect_free_type_vars(typ, vars),
SourceType::Var(name) => {
vars.insert(name, typ.region);
}
SourceType::VarApp { name, region, args } => {
vars.insert(name, *region);
for arg in *args {
collect_free_type_vars(arg, vars);
}
}
SourceType::Lambda { from, to } => {
collect_free_type_vars(from, vars);
collect_free_type_vars(to, vars);
}
SourceType::Type { args, .. } | SourceType::TypeQual { args, .. } => {
for arg in *args {
collect_free_type_vars(arg, vars);
}
}
SourceType::Record(fields) => {
for field in *fields {
collect_free_type_vars(field.typ, vars);
}
}
SourceType::Unit => {}
SourceType::Tuple {
first,
second,
rest,
} => {
collect_free_type_vars(first, vars);
collect_free_type_vars(second, vars);
for r in *rest {
collect_free_type_vars(r, vars);
}
}
}
}
fn canonicalize_exports<'a>(
bump: &'a Bump,
module: &SourceModule<'a>,
) -> Result<Exports<'a>, Vec<Error<'a>>> {
match module.exports.value {
Exposing::Open => Ok(Exports::Everything(module.exports.region)),
Exposing::Explicit(exposed) => {
let value_names: BTreeSet<&str> =
module.values.iter().map(|v| v.value.name.value).collect();
let union_names: BTreeSet<&str> =
module.unions.iter().map(|u| u.value.name.value).collect();
let alias_names: BTreeSet<&str> =
module.aliases.iter().map(|a| a.value.name.value).collect();
let trait_names: BTreeSet<&str> =
module.traits.iter().map(|t| t.value.name.value).collect();
let binop_names: BTreeSet<&str> = module.binops.iter().map(|b| b.value.op).collect();
let mut resolved: Vec<(&'a str, Region, Export<'a>)> = Vec::new();
let mut errors: Vec<Error<'a>> = Vec::new();
for item in exposed {
match item {
Exposed::Lower(name) => {
if value_names.contains(name.value) {
resolved.push((name.value, name.region, Export::Value(name.value)));
} else {
errors.push(Error::ExportNotFound {
region: name.region,
kind: VarKind::BadVar,
name: name.value,
suggestions: bump
.alloc_slice_fill_iter(value_names.iter().copied()),
});
}
}
Exposed::Operator { region, op } => {
if binop_names.contains(*op) {
resolved.push((op, *region, Export::Binop(op)));
} else {
errors.push(Error::ExportNotFound {
region: *region,
kind: VarKind::BadOp,
name: op,
suggestions: bump
.alloc_slice_fill_iter(binop_names.iter().copied()),
});
}
}
Exposed::Upper { name, privacy } | Exposed::LowerType { name, privacy } => {
if trait_names.contains(name.value) {
match privacy {
Privacy::Private => resolved.push((
name.value,
name.region,
Export::Trait(name.value),
)),
Privacy::Public(region) => errors.push(Error::ExportOpenTrait {
region: *region,
name: name.value,
}),
}
continue;
}
match privacy {
Privacy::Public(dot_dot_region) => {
if union_names.contains(name.value) {
resolved.push((
name.value,
name.region,
Export::UnionOpen(name.value),
));
} else if alias_names.contains(name.value) {
errors.push(Error::ExportOpenAlias {
region: *dot_dot_region,
name: name.value,
});
} else {
errors.push(Error::ExportNotFound {
region: name.region,
kind: VarKind::BadType,
name: name.value,
suggestions: type_suggestions(
bump,
&union_names,
&alias_names,
),
});
}
}
Privacy::Private => {
if union_names.contains(name.value) {
resolved.push((
name.value,
name.region,
Export::UnionClosed(name.value),
));
} else if alias_names.contains(name.value) {
resolved.push((
name.value,
name.region,
Export::Alias(name.value),
));
} else {
errors.push(Error::ExportNotFound {
region: name.region,
kind: VarKind::BadType,
name: name.value,
suggestions: type_suggestions(
bump,
&union_names,
&alias_names,
),
});
}
}
}
}
}
}
if !errors.is_empty() {
return Err(errors);
}
let mut occurrences: BTreeMap<&'a str, Vec<(Region, Export<'a>)>> = BTreeMap::new();
for (name, region, export) in resolved {
occurrences.entry(name).or_default().push((region, export));
}
let mut exports: Vec<&'a Located<Export<'a>>> = Vec::new();
let mut dup_errors: Vec<Error<'a>> = Vec::new();
for (name, entries) in occurrences {
if entries.len() > 1 {
dup_errors.push(Error::ExportDuplicate {
name,
first: entries[0].0,
second: entries[1].0,
});
} else {
let (region, export) = entries.into_iter().next().expect("one entry");
exports.push(bump.alloc(Located::at(region, export)));
}
}
if !dup_errors.is_empty() {
return Err(dup_errors);
}
Ok(Exports::Explicit(bump.alloc_slice_fill_iter(exports)))
}
}
}
fn type_suggestions<'a>(
bump: &'a Bump,
union_names: &BTreeSet<&'a str>,
alias_names: &BTreeSet<&'a str>,
) -> &'a [&'a str] {
let names: Vec<&'a str> = union_names
.iter()
.chain(alias_names.iter())
.copied()
.collect();
bump.alloc_slice_fill_iter(names)
}
fn canonicalize_binops<'a>(
bump: &'a Bump,
env: &Env<'a>,
binops: &'a [&'a Located<Infix<'a>>],
) -> &'a [&'a Located<CanBinop<'a>>] {
bump.alloc_slice_fill_iter(binops.iter().copied().map(|binop| {
let (home, annotation) = match env.vars.get(binop.value.name) {
Some(environment::Var::TopLevel(_)) => (env.home, None),
Some(environment::Var::Foreign(home, annotation)) => (*home, Some(*annotation)),
Some(environment::Var::Method {
trait_, annotation, ..
}) => (trait_.home, Some(*annotation)),
_ => unreachable!("check_binops validates every backing function"),
};
&*bump.alloc(Located::at(
binop.region,
CanBinop {
symbol: binop.value.op,
associativity: binop.value.associativity,
precedence: binop.value.precedence,
function: nash_ast::QualifiedName {
home,
name: binop.value.name,
},
annotation,
},
))
}))
}
fn collect_used_modules<'a>(module: &CanModule<'a>) -> BTreeSet<&'a str> {
let mut used = BTreeSet::new();
let home = module.name;
for test in module.tests {
collect_from_expr(&test.body.value, home, &mut used);
for binder in test.binders {
collect_from_expr(&binder.generator.value, home, &mut used);
collect_from_pattern(&binder.pattern.value, home, &mut used);
}
}
for binop in module.binops {
add_if_foreign(home, binop.value.function.home, &mut used);
}
collect_from_decls(module.decls, home, &mut used);
for impl_ in module.impls {
add_if_foreign(home, impl_.value.trait_.home, &mut used);
for head in impl_.value.heads {
let mut pending = vec![&head.value];
while let Some(head) = pending.pop() {
if let nash_ast::Head::Named { reference, .. } = head {
add_if_foreign(home, reference.home, &mut used);
}
pending.extend(nash_ast::head::children(head));
}
}
for predicate in impl_.value.context {
collect_from_predicate(predicate, home, &mut used);
}
for method in impl_.value.methods {
collect_from_def(method, home, &mut used);
}
}
for trait_ in module.traits {
for predicate in trait_.value.supers {
collect_from_predicate(predicate, home, &mut used);
}
for method in trait_.value.methods {
collect_from_type(&method.annotation.typ.value, home, &mut used);
for predicate in method.annotation.context {
collect_from_predicate(predicate, home, &mut used);
}
if let Some(default) = method.default {
collect_from_def(default, home, &mut used);
}
}
}
for union in module.unions {
for ctor in union.value.ctors {
for arg in ctor.arguments {
collect_from_type(&arg.value, home, &mut used);
}
}
}
for alias in module.aliases {
collect_from_type(&alias.value.typ.value, home, &mut used);
}
used
}
fn add_if_foreign<'a>(
home: ModuleName<'a>,
reference_home: ModuleName<'a>,
used: &mut BTreeSet<&'a str>,
) {
if reference_home != home {
used.insert(reference_home.name);
}
}
fn collect_from_decls<'a>(decls: &Decls<'a>, home: ModuleName<'a>, used: &mut BTreeSet<&'a str>) {
match decls {
Decls::Declare { definition, next } => {
collect_from_def(definition, home, used);
collect_from_decls(next, home, used);
}
Decls::DeclareRec {
definition,
following,
next,
} => {
collect_from_def(definition, home, used);
for def in *following {
collect_from_def(def, home, used);
}
collect_from_decls(next, home, used);
}
Decls::Empty => {}
}
}
fn collect_from_def<'a>(
def: &nash_ast::Def<'a>,
home: ModuleName<'a>,
used: &mut BTreeSet<&'a str>,
) {
match def {
nash_ast::Def::Def { body, args, .. } => {
for arg in *args {
collect_from_pattern(&arg.value, home, used);
}
collect_from_expr(&body.value, home, used);
}
nash_ast::Def::TypedDef {
context,
annotation,
args,
body,
typ,
..
} => {
for predicate in *context {
collect_from_predicate(predicate, home, used);
}
for arg in *args {
collect_from_pattern(&arg.pattern.value, home, used);
collect_from_type(&arg.typ.value, home, used);
}
collect_from_expr(&body.value, home, used);
collect_from_type(&annotation.value, home, used);
collect_from_type(&typ.value, home, used);
}
}
}
fn collect_from_expr<'a>(
expr: &nash_ast::Expr<'a>,
home: ModuleName<'a>,
used: &mut BTreeSet<&'a str>,
) {
use nash_ast::Expr::*;
match expr {
Assert(inner) | Comptime(inner) => collect_from_expr(&inner.value, home, used),
Fail(message) | Todo(message) => {
if let Some(message) = message {
collect_from_expr(&message.value, home, used);
}
}
Trace { message, body } => {
collect_from_expr(&message.value, home, used);
collect_from_expr(&body.value, home, used);
}
VarLocal(_) | Accessor(_) => {}
Bool(_) => {
add_if_foreign(home, nash_ast::primitives::primitive_home(), used);
add_if_foreign(home, nash_ast::primitives::literal_home(), used);
}
Str(_) | Bytes(_) | Int(_) | Unit => {
add_if_foreign(home, nash_ast::primitives::literal_home(), used);
}
VarTopLevel(q) => add_if_foreign(home, q.home, used),
VarForeign { reference, .. } => add_if_foreign(home, reference.home, used),
VarMethod { trait_, .. } => add_if_foreign(home, trait_.home, used),
VarConstructor {
reference,
annotation,
..
} => {
add_if_foreign(home, reference.home, used);
collect_from_type(&annotation.typ.value, home, used);
}
VarOperator { operator_home, .. } => {
add_if_foreign(home, *operator_home, used);
}
Binop {
operator_home,
left,
right,
..
} => {
add_if_foreign(home, *operator_home, used);
collect_from_expr(&left.value, home, used);
collect_from_expr(&right.value, home, used);
}
List(items) => {
for item in *items {
collect_from_expr(&item.value, home, used);
}
}
Lambda { parameters, body } => {
for p in *parameters {
collect_from_pattern(&p.value, home, used);
}
collect_from_expr(&body.value, home, used);
}
Call {
function,
arguments,
} => {
collect_from_expr(&function.value, home, used);
for a in *arguments {
collect_from_expr(&a.value, home, used);
}
}
If {
branches,
final_else,
} => {
for b in *branches {
collect_from_expr(&b.condition.value, home, used);
collect_from_expr(&b.then_branch.value, home, used);
}
collect_from_expr(&final_else.value, home, used);
}
Let { definition, body } => {
collect_from_def(definition, home, used);
collect_from_expr(&body.value, home, used);
}
LetRec { definitions, body } => {
for d in *definitions {
collect_from_def(d, home, used);
}
collect_from_expr(&body.value, home, used);
}
LetDestruct {
pattern,
value,
body,
} => {
collect_from_pattern(&pattern.value, home, used);
collect_from_expr(&value.value, home, used);
collect_from_expr(&body.value, home, used);
}
Case {
scrutinee,
branches,
} => {
collect_from_expr(&scrutinee.value, home, used);
for b in *branches {
collect_from_pattern(&b.pattern.value, home, used);
collect_from_expr(&b.body.value, home, used);
}
}
Access { record, .. } => collect_from_expr(&record.value, home, used),
Update { base, fields, .. } => {
collect_from_expr(&base.value, home, used);
for f in *fields {
collect_from_expr(&f.value.value, home, used);
}
}
Record {
alias,
annotation,
fields,
} => {
add_if_foreign(home, alias.home, used);
collect_from_type(&annotation.typ.value, home, used);
for f in *fields {
collect_from_expr(&f.value.value, home, used);
}
}
Tuple {
first,
second,
rest,
} => {
collect_from_expr(&first.value, home, used);
collect_from_expr(&second.value, home, used);
for r in *rest {
collect_from_expr(&r.value, home, used);
}
}
}
}
fn collect_from_pattern<'a>(
pat: &nash_ast::Pattern<'a>,
home: ModuleName<'a>,
used: &mut BTreeSet<&'a str>,
) {
use nash_ast::Pattern::*;
match pat {
Anything | Var(_) | Unit | Record(_) => {}
Str(_) | Bytes(_) | Int(_) => {
add_if_foreign(home, nash_ast::primitives::literal_home(), used);
add_if_foreign(
home,
nash_ast::ModuleName {
package: Some(nash_ast::primitives::BASE),
name: "Eq",
},
used,
);
}
Bool { .. } => {
add_if_foreign(home, nash_ast::primitives::primitive_home(), used);
}
Constructor(ctor) => {
add_if_foreign(home, ctor.reference.home, used);
for arg in ctor.arguments {
collect_from_type(&arg.typ.value, home, used);
collect_from_pattern(&arg.pattern.value, home, used);
}
}
Alias { pattern, .. } => collect_from_pattern(&pattern.value, home, used),
Pair { first, second } => {
collect_from_pattern(&first.value, home, used);
collect_from_pattern(&second.value, home, used);
}
Tuple {
first,
second,
rest,
} => {
collect_from_pattern(&first.value, home, used);
collect_from_pattern(&second.value, home, used);
for r in *rest {
collect_from_pattern(&r.value, home, used);
}
}
List(items) => {
for item in *items {
collect_from_pattern(&item.value, home, used);
}
}
Cons { head, tail } => {
collect_from_pattern(&head.value, home, used);
collect_from_pattern(&tail.value, home, used);
}
}
}
fn collect_from_type<'a>(
typ: &nash_ast::Type<'a>,
home: ModuleName<'a>,
used: &mut BTreeSet<&'a str>,
) {
use nash_ast::Type::*;
match typ {
App { head, args } => {
collect_from_type(&head.value, home, used);
for arg in *args {
collect_from_type(&arg.value, home, used);
}
}
Var(_) => {}
Lambda { from, to } => {
collect_from_type(&from.value, home, used);
collect_from_type(&to.value, home, used);
}
Named { reference, args } => {
add_if_foreign(home, reference.home, used);
for a in *args {
collect_from_type(&a.value, home, used);
}
}
Record { fields, .. } => {
for f in *fields {
collect_from_type(&f.typ.value, home, used);
}
}
Tuple {
first,
second,
rest,
} => {
collect_from_type(&first.value, home, used);
collect_from_type(&second.value, home, used);
for r in *rest {
collect_from_type(&r.value, home, used);
}
}
Alias {
reference,
arguments,
target,
..
} => {
add_if_foreign(home, reference.home, used);
for a in *arguments {
collect_from_type(&a.typ.value, home, used);
}
match target {
nash_ast::AliasType::Open(t) | nash_ast::AliasType::Filled { typ: t, .. } => {
collect_from_type(&t.value, home, used);
}
}
}
}
}
pub(crate) fn canonicalize_typed_value<'a>(
bump: &'a Bump,
env: &Env<'a>,
definition: &'a Located<nash_source::Def<'a>>,
annotation: &'a nash_ast::Annotation<'a>,
warnings: &mut Vec<Warning<'a>>,
) -> Result<&'a nash_ast::Def<'a>, Vec<Error<'a>>> {
let nash_source::Def::Define {
name, args, body, ..
} = &definition.value
else {
unreachable!("trait defaults are named definitions")
};
let value = bump.alloc(Located::at(
definition.region,
SourceValue {
docs: None,
name,
arguments: args,
body,
annotation: None,
attributes: &[],
},
));
Ok(to_node_one(bump, env, value, Some(annotation), warnings)?.def)
}
fn collect_from_predicate<'a>(
predicate: &nash_ast::Pred<'a>,
home: ModuleName<'a>,
used: &mut BTreeSet<&'a str>,
) {
if let Some(trait_) = predicate.trait_ref() {
add_if_foreign(home, trait_.home, used);
}
for argument in predicate.types() {
collect_from_type(&argument.value, home, used);
}
}
fn parameter_repr_predicates<'a>(
bump: &'a Bump,
parameters: &'a [&'a nash_source::TypeParam<'a>],
) -> Vec<nash_ast::Pred<'a>> {
parameters
.iter()
.filter_map(|parameter| {
parameter.repr.map(|repr| nash_ast::Pred::Implied {
trait_: types::repr_trait(repr.value).qualified(),
args: bump.alloc_slice_copy(&[&*bump.alloc(Located::at(
parameter.name.region,
nash_ast::Type::Var(parameter.name.value),
))]),
})
})
.collect()
}
#[cfg(test)]
mod tests {
fn test_constructor_kind<'a>(bump: &'a bumpalo::Bump, arity: usize) -> &'a nash_ast::Kind<'a> {
(0..arity).fold(&nash_ast::Kind::Type, |result, _| {
bump.alloc(nash_ast::Kind::Arrow(&nash_ast::Kind::Type, result))
})
}
use std::collections::BTreeMap;
use bumpalo::Bump;
use indoc::indoc;
use nash_ast::{
Associativity, Ctor as CanCtor, CtorOpts, Module as CanModule, ModuleName, PackageName,
Precedence, Type as CanType,
};
use nash_region::{Located, Region};
use crate::snapshot_support::{errors as render_errors, warnings as render_warnings};
use nash_can::{
AliasVisibility, InterfaceAlias, InterfaceBinop, InterfaceUnion, InterfaceValue,
UnionVisibility,
};
use nash_can::{Context, canonicalize};
use nash_can::{Error, Interface};
fn parse_and_canonicalize<'a>(
bump: &'a Bump,
input: &str,
context: Context<'a, '_>,
) -> Result<CanModule<'a>, Vec<Error<'a>>> {
let src = bump.alloc_str(input);
let mut parser = nash_parse::Parser::new(bump, src);
let module = parser.module().expect("expected successful parse");
canonicalize(bump, context, &module).map(|r| r.module)
}
macro_rules! assert_module_snapshot {
(@output $input:expr, $module:expr) => {{
insta::with_settings!({description => $input, omit_expression => true}, {
insta::assert_debug_snapshot!($module);
});
}};
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let result = parse_and_canonicalize(&bump, input, Context::default())
.expect("expected successful canonicalization");
assert_module_snapshot!(@output format!("Code:\n\n{}", input), result);
}};
}
macro_rules! assert_module_error_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let result = parse_and_canonicalize(&bump, input, Context::default())
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}};
}
macro_rules! assert_interface_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let can_module = parse_and_canonicalize(&bump, input, Context::default())
.expect("expected successful canonicalization");
let annotations = mock_annotations(&bump, &can_module);
let result = nash_can::from_module(&bump, &can_module, &annotations);
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}};
}
#[test]
fn record_type_outside_alias_errors() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f : { x : int } -> int
f r = r.x
"#
);
}
#[test]
fn nested_record_type_in_alias_errors() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias outer = { inner : { x : int } }
"#
);
}
#[test]
fn record_type_in_transparent_alias_errors() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias wrapped = list { x : int }
"#
);
}
#[test]
fn alias_record_fields_sorted_by_name() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias point = { z : int, a : int }
"#
);
}
#[test]
fn record_literal_no_alias_error() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
value = { x = () }
"#
);
}
#[test]
fn record_literal_ambiguous_error() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias first = { x : unit }
type alias second = { x : unit }
value = { x = () }
"#
);
}
#[test]
fn record_literal_fields_in_wire_order() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias point = { z : unit, a : unit }
value = { a = (), z = () }
"#
);
}
fn var_type<'a>(bump: &'a Bump, name: &'a str) -> &'a Located<CanType<'a>> {
bump.alloc(Located::at(Region::zero(), CanType::Var(name)))
}
fn test_annotation<'a>(bump: &'a Bump) -> &'a nash_ast::Annotation<'a> {
bump.alloc(nash_ast::Annotation {
context: &[],
free_vars: bump.alloc_slice_fill_iter(["a"]),
typ: var_type(bump, "a"),
})
}
fn mock_annotations<'a>(bump: &'a Bump, module: &CanModule<'a>) -> nash_can::Annotations<'a> {
fn walk<'a>(
decls: &nash_ast::Decls<'a>,
bump: &'a Bump,
out: &mut nash_can::Annotations<'a>,
) {
match decls {
nash_ast::Decls::Declare { definition, next } => {
add(definition, bump, out);
walk(next, bump, out);
}
nash_ast::Decls::DeclareRec {
definition,
following,
next,
} => {
add(definition, bump, out);
for def in *following {
add(def, bump, out);
}
walk(next, bump, out);
}
nash_ast::Decls::Empty => {}
}
}
fn add<'a>(def: &nash_ast::Def<'a>, bump: &'a Bump, out: &mut nash_can::Annotations<'a>) {
let name = match def {
nash_ast::Def::Def { name, .. } | nash_ast::Def::TypedDef { name, .. } => {
name.value
}
};
out.insert(name, test_annotation(bump));
}
let mut annotations = nash_can::Annotations::new();
walk(module.decls, bump, &mut annotations);
annotations
}
fn union_interface<'a>(
bump: &'a Bump,
module_name: &'a str,
union_name: &'a str,
parameters: &'a [&'a str],
) -> Interface<'a> {
Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: module_name,
},
values: &[],
aliases: &[],
unions: bump.alloc_slice_fill_iter([InterfaceUnion {
context: &[],
kind: test_constructor_kind(bump, parameters.len()),
name: union_name,
parameters,
ctors: &[],
alternatives: 0,
options: CtorOpts::Normal,
visibility: UnionVisibility::Open,
}]),
binops: &[],
}
}
fn alias_interface<'a>(
bump: &'a Bump,
module_name: &'a str,
alias_name: &'a str,
parameters: &'a [&'a str],
typ: &'a Located<CanType<'a>>,
) -> Interface<'a> {
Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: module_name,
},
values: &[],
aliases: bump.alloc_slice_fill_iter([InterfaceAlias {
context: &[],
kind: test_constructor_kind(bump, parameters.len()),
name: alias_name,
parameters,
typ,
visibility: AliasVisibility::Public,
}]),
unions: &[],
binops: &[],
}
}
#[test]
fn module_shell_header_only() {
assert_module_snapshot!("module Main exposing (..)\n");
}
#[test]
fn validator_missing_main() {
assert_module_error_snapshot!("validator module Foo exposing (main)\n\nx = 1\n");
}
#[test]
fn validator_main_not_exposed() {
assert_module_error_snapshot!(
"validator module Foo exposing (x)\n\nx = 1\n\nmain c = ()\n"
);
}
#[test]
fn validator_main_explicitly_exposed() {
assert_module_snapshot!("validator module Foo exposing (main)\n\nmain ctx = ()\n");
}
#[test]
fn validator_module_kind_is_preserved() {
assert_module_snapshot!("validator module Main exposing (..)\n\nmain = 1\n");
}
#[test]
fn module_shell_with_infix_metadata() {
assert_module_snapshot!(
r#"
module Main exposing ((|>))
infix left 6 (|>) = apR
apR x f = f x
"#
);
}
#[test]
fn module_shell_with_enum_union() {
assert_module_snapshot!(
r#"
module Main exposing (Bool(..))
type Bool
= True
| False
"#
);
}
#[test]
fn module_shell_with_aliases_and_unions() {
assert_module_snapshot!(
r#"
module Main exposing (type pair, Maybe(..))
type alias pair 'a 'b = ('a, 'b)
type Maybe 'a
= Just 'a
| Nothing
"#
);
}
#[test]
fn module_shell_with_local_named_types() {
assert_module_snapshot!(
r#"
module Main exposing (type pair, type wrappedPair, WrappedMaybe, Maybe(..))
type alias pair 'a 'b = ('a, 'b)
type alias wrappedPair 'a 'b = pair 'a 'b
type alias WrappedMaybe 'a = Maybe 'a
type Maybe 'a
= Just 'a
| Nothing
"#
);
}
#[test]
fn module_shell_with_self_qualified_named_types() {
assert_module_snapshot!(
r#"
module Main exposing (Maybe(..), Wrapped)
type alias Wrapped 'a = Main.Maybe 'a
type Maybe 'a
= Just 'a
| Nothing
"#
);
}
#[test]
fn module_shell_reports_unresolved_named_types() {
assert_module_error_snapshot!(
r#"
module Main exposing (Wrapped)
type alias Wrapped = Missing
"#
);
}
#[test]
fn module_shell_reports_unresolved_qualified_named_types() {
assert_module_error_snapshot!(
r#"
module Main exposing (Wrapped)
type alias Wrapped = Missing.Maybe
"#
);
}
#[test]
fn module_shell_reports_missing_imported_interfaces() {
assert_module_error_snapshot!(
r#"
module Main exposing (Wrapped)
import Outcome
type alias Wrapped 'e 'a = Outcome.Outcome 'e 'a
"#
);
}
#[test]
fn module_shell_reports_ambiguous_open_imported_types() {
let input = indoc!(
r#"
module Main exposing (Wrapped)
import Maybe exposing (..)
import Option exposing (..)
type alias Wrapped 'a = Maybe 'a
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["a"]);
let interfaces = BTreeMap::from([
(
"Maybe",
union_interface(&bump, "Maybe", "Maybe", parameters),
),
(
"Option",
union_interface(&bump, "Option", "Maybe", parameters),
),
]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn module_shell_reports_ambiguous_explicit_and_open_imported_types() {
let input = indoc!(
r#"
module Main exposing (Wrapped)
import Maybe exposing (Maybe)
import Option exposing (..)
type alias Wrapped 'a = Maybe 'a
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["a"]);
let interfaces = BTreeMap::from([
(
"Maybe",
union_interface(&bump, "Maybe", "Maybe", parameters),
),
(
"Option",
union_interface(&bump, "Option", "Maybe", parameters),
),
]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn module_shell_reports_ambiguous_qualified_imported_types() {
let input = indoc!(
r#"
module Main exposing (Wrapped)
import Json.Decode as Decode
import Html.Decode as Decode
type alias Wrapped 'msg = Decode.Decoder 'msg
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["msg"]);
let interfaces = BTreeMap::from([
(
"Json.Decode",
alias_interface(
&bump,
"Json.Decode",
"Decoder",
parameters,
var_type(&bump, "msg"),
),
),
(
"Html.Decode",
alias_interface(
&bump,
"Html.Decode",
"Decoder",
parameters,
var_type(&bump, "msg"),
),
),
]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn module_shell_rejects_constructor_as_alias_body() {
assert_module_error_snapshot!(
r#"
module Main exposing (Wrapped, Maybe(..))
type alias Wrapped = Maybe
type Maybe 'a
= Just 'a
| Nothing
"#
);
}
#[test]
fn module_shell_reports_missing_exported_values() {
assert_module_error_snapshot!("module Main exposing (main)\n");
}
#[test]
fn module_shell_reports_missing_exported_operators() {
assert_module_error_snapshot!("module Main exposing ((|>))\n");
}
#[test]
fn module_shell_reports_ambiguous_imported_types_with_multiple_modules() {
let input = indoc!(
r#"
module Main exposing (Wrapped)
import Maybe exposing (..)
import Option exposing (..)
import Choice exposing (..)
type alias Wrapped 'a = Maybe 'a
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["a"]);
let interfaces = BTreeMap::from([
(
"Maybe",
union_interface(&bump, "Maybe", "Maybe", parameters),
),
(
"Option",
union_interface(&bump, "Option", "Maybe", parameters),
),
(
"Choice",
union_interface(&bump, "Choice", "Maybe", parameters),
),
]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn module_shell_with_imported_exposed_union_types() {
let input = indoc!(
r#"
module Main exposing (Wrapped)
import Maybe exposing (Maybe)
type alias Wrapped 'a = Maybe 'a
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["a"]);
let interfaces = BTreeMap::from([(
"Maybe",
union_interface(&bump, "Maybe", "Maybe", parameters),
)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn module_shell_with_imported_qualified_union_types() {
let input = indoc!(
r#"
module Main exposing (Wrapped)
import Outcome
type alias Wrapped 'e 'a = Outcome.Outcome 'e 'a
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["e", "a"]);
let interfaces = BTreeMap::from([(
"Outcome",
union_interface(&bump, "Outcome", "Outcome", parameters),
)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn module_shell_with_imported_aliased_alias_types() {
let input = indoc!(
r#"
module Main exposing (Decoder)
import Json.Decode as Decode
type alias Decoder 'msg = Decode.Decoder 'msg
"#
);
let bump = Bump::new();
let parameters = bump.alloc_slice_fill_iter(["msg"]);
let interfaces = BTreeMap::from([(
"Json.Decode",
alias_interface(
&bump,
"Json.Decode",
"Decoder",
parameters,
var_type(&bump, "msg"),
),
)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn module_shell_requires_explicit_header() {
assert_module_error_snapshot!("main = 42\n");
}
#[test]
fn module_shell_keeps_package_context() {
let input = indoc!("module Json.Decode exposing (..)\n");
let bump = Bump::new();
let context = Context {
package: Some(PackageName {
author: "nash",
project: "compiler",
}),
interfaces: None,
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn module_shell_reports_unresolved_exported_upper_names() {
assert_module_error_snapshot!("module Main exposing (Missing)\n");
}
#[test]
fn module_shell_reports_export_open_alias() {
assert_module_error_snapshot!(
r#"
module Main exposing (Pair(..))
type alias Pair 'a = 'a
"#
);
}
#[test]
fn interface_from_module_empty() {
assert_interface_snapshot!("module Main exposing (..)\n");
}
#[test]
fn interface_from_module_open_exports() {
assert_interface_snapshot!(
r#"
module Main exposing (..)
type alias pair 'a 'b = ('a, 'b)
type Maybe 'a
= Just 'a
| Nothing
"#
);
}
#[test]
fn interface_from_module_open_union() {
assert_interface_snapshot!(
r#"
module Main exposing (Bool(..))
type Bool
= True
| False
"#
);
}
#[test]
fn interface_from_module_closed_union() {
assert_interface_snapshot!(
r#"
module Main exposing (Bool)
type Bool
= True
| False
"#
);
}
#[test]
fn interface_from_module_mixed_visibility() {
assert_interface_snapshot!(
r#"
module Main exposing (PublicAlias)
type alias PublicAlias 'a = 'a
type alias PrivateAlias 'a = 'a
type PrivateUnion
= Foo
| Bar
"#
);
}
#[test]
fn interface_from_module_with_binops() {
assert_interface_snapshot!(
r#"
module Main exposing ((|>))
infix left 6 (|>) = apR
apR x f = f x
"#
);
}
#[test]
fn builtin_bool_patterns_count_as_import_uses() {
let bump = Bump::new();
let module = nash_parse::Parser::new(
&bump,
"module Main exposing (..)\nimport Primitive exposing (type bool(..))\nignore flag =\n case flag of\n False -> ()\n True -> ()\n",
).module().unwrap();
let interfaces = BTreeMap::from([("Builtin", nash_can::kinds::builtin_interface(&bump))]);
let result = canonicalize(
&bump,
Context {
package: None,
interfaces: Some(&interfaces),
},
&module,
)
.unwrap();
assert!(result.warnings.is_empty(), "{:?}", result.warnings);
}
#[test]
fn to_public_union_open_passes_through() {
let union = InterfaceUnion {
context: &[],
kind: &nash_ast::Kind::Type,
name: "Bool",
parameters: &[],
ctors: &[],
alternatives: 2,
options: CtorOpts::Enum,
visibility: UnionVisibility::Open,
};
let public = union.to_public().unwrap();
assert_eq!(public.name, union.name);
assert_eq!(public.parameters, union.parameters);
assert_eq!(public.alternatives, union.alternatives);
assert!(std::ptr::eq(public.ctors, union.ctors));
}
#[test]
fn to_public_union_closed_strips_ctors() {
let bump = Bump::new();
let ctor: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "True",
index: 0,
arity: 0,
arguments: &[],
});
let union = InterfaceUnion {
context: &[],
kind: &nash_ast::Kind::Type,
name: "Bool",
parameters: &[],
ctors: bump.alloc_slice_fill_iter([ctor]),
alternatives: 2,
options: CtorOpts::Enum,
visibility: UnionVisibility::Closed,
};
assert!(union.to_public().unwrap().ctors.is_empty());
}
#[test]
fn to_public_union_private_returns_none() {
let union = InterfaceUnion {
context: &[],
kind: &nash_ast::Kind::Type,
name: "Internal",
parameters: &[],
ctors: &[],
alternatives: 0,
options: CtorOpts::Normal,
visibility: UnionVisibility::Private,
};
assert!(union.to_public().is_none());
}
#[test]
fn to_public_alias_public_passes_through() {
let bump = Bump::new();
let typ = bump.alloc(Located::at(Region::zero(), CanType::unit()));
let alias = InterfaceAlias {
context: &[],
kind: test_constructor_kind(&bump, 2),
name: "Pair",
parameters: &["a", "b"],
typ,
visibility: AliasVisibility::Public,
};
let public = alias.to_public().unwrap();
assert_eq!(public.name, alias.name);
assert_eq!(public.parameters, alias.parameters);
assert!(std::ptr::eq(public.typ, alias.typ));
}
#[test]
fn to_public_alias_private_returns_none() {
let bump = Bump::new();
let typ = bump.alloc(Located::at(Region::zero(), CanType::unit()));
let alias = InterfaceAlias {
context: &[],
kind: &nash_ast::Kind::Type,
name: "Internal",
parameters: &[],
typ,
visibility: AliasVisibility::Private,
};
assert!(alias.to_public().is_none());
}
#[test]
fn duplicate_type_alias_and_union() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Foo = Int
type Foo
= Bar
"#
);
}
#[test]
fn duplicate_type_two_aliases() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Foo = Int
type alias Foo = String
"#
);
}
#[test]
fn duplicate_value_decl() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
foo = 1
foo = 2
"#
);
}
#[test]
fn duplicate_binop() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
infix left 6 (|>) = apR
infix left 6 (|>) = apR2
apR x f = f x
apR2 x f = f x
"#
);
}
#[test]
fn record_type_duplicate_field() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias R = { x : Int, x : String }
"#
);
}
#[test]
fn recursive_alias_self() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Loop = Loop
"#
);
}
#[test]
fn recursive_alias_cycle() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias A = B
type alias B = A
"#
);
}
#[test]
fn union_unbound_type_var() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type MyType 'a
= MyTag 'b
"#
);
}
#[test]
fn alias_unused_type_param() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Phantom 'a = Int
"#
);
}
#[test]
fn alias_unbound_type_var() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Bad = List 'a
"#
);
}
#[test]
fn union_duplicate_type_param() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type Bad 'a 'a
= Foo
"#
);
}
#[test]
fn alias_duplicate_type_param() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Bad 'a 'a = 'a
"#
);
}
#[test]
fn multiple_duplicate_types_all_reported() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Foo = Int
type alias Foo = String
type alias Bar = Int
type alias Bar = String
"#
);
}
#[test]
fn record_multiple_duplicate_fields_all_reported() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias R = { x : Int, x : String, y : Int, y : String }
"#
);
}
#[test]
fn duplicate_export() {
assert_module_error_snapshot!(
r#"
module Main exposing (Foo, Foo)
type alias Foo = Int
"#
);
}
fn parse_and_canonicalize_with_warnings<'a>(
bump: &'a Bump,
input: &str,
context: Context<'a, '_>,
) -> Result<(CanModule<'a>, Vec<nash_can::Warning<'a>>), Vec<Error<'a>>> {
let src = bump.alloc_str(input);
let mut parser = nash_parse::Parser::new(bump, src);
let module = parser.module().expect("expected successful parse");
canonicalize(bump, context, &module).map(|r| (r.module, r.warnings))
}
macro_rules! assert_module_warning_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let (_, warnings) =
parse_and_canonicalize_with_warnings(&bump, input, Context::default())
.expect("expected successful canonicalization");
assert!(!warnings.is_empty(), "expected warnings but got none");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_warnings(input, &warnings));
});
}};
}
#[test]
fn simple_value() {
assert_module_snapshot!(
r#"
module Main exposing (..)
x = 42
"#
);
}
#[test]
fn function_def() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f a b = a
"#
);
}
#[test]
fn lambda_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = \x -> x
"#
);
}
#[test]
fn let_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f =
let
x = 1
in
x
"#
);
}
#[test]
fn if_then_else() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f x = if x then 1 else 2
"#
);
}
#[test]
fn record_literal() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias point = { x : int, y : int }
f = { x = 1, y = 2 }
"#
);
}
#[test]
fn record_update() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f r = { r | x = 1 }
"#
);
}
#[test]
fn list_literal() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = [ 1, 2, 3 ]
"#
);
}
#[test]
fn accessor_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = .name
"#
);
}
#[test]
fn field_access() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f r = r.name
"#
);
}
#[test]
fn case_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f x =
case x of
1 -> "one"
_ -> "other"
"#
);
}
#[test]
fn string_literal() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = "hello"
"#
);
}
#[test]
fn negation_requires_core_num() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
trait Num 'a where
negate : 'a -> 'a
f x = -x
"#
);
}
#[test]
fn function_call() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f x = g x
g y = y
"#
);
}
#[test]
fn tuple_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = ( 1, 2, 3 )
"#
);
}
#[test]
fn unit_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = ()
"#
);
}
#[test]
fn let_recursive_function() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f =
let
go x = go x
in
go 1
"#
);
}
#[test]
fn nested_let() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f =
let
x = 1
y = 2
in
x
"#
);
}
#[test]
fn not_found_var() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f = nonexistent
"#
);
}
#[test]
fn recursive_let_value() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f =
let
x = x
in
x
"#
);
}
#[test]
fn scope_recovery_between_case_branches() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f outer =
case outer of
first -> missing
second -> first
"#
);
}
#[test]
fn scope_recovery_after_rejected_shadowing() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f outer =
case outer of
outer -> outer
next -> unknown
"#
);
}
#[test]
fn scope_siblings_reuse_binding_names() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f outer =
case outer of
(first, value) -> value
(second, value) -> value
"#
);
}
#[test]
fn shadowing_local() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f x =
let
x = 1
in
x
"#
);
}
#[test]
fn duplicate_let_bindings() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f =
let
x = 1
x = 2
in
x
"#
);
}
#[test]
fn tuple_four_in_expr() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = ( 1, 2, 3, 4 )
"#
);
}
#[test]
fn duplicate_record_fields_in_expr() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f = { x = 1, x = 2 }
"#
);
}
#[test]
fn unused_lambda_arg() {
assert_module_warning_snapshot!(
r#"
module Main exposing (..)
f = \x -> 1
"#
);
}
#[test]
fn unused_let_binding() {
assert_module_warning_snapshot!(
r#"
module Main exposing (..)
f =
let
x = 1
in
2
"#
);
}
#[test]
fn mutual_recursion_functions() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f x = g x
g x = f x
"#
);
}
#[test]
fn self_recursive_function() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f x = f x
"#
);
}
#[test]
fn mixed_recursive_and_non_recursive() {
assert_module_snapshot!(
r#"
module Main exposing (..)
x = 1
f a = g a
g a = f a
y = 2
"#
);
}
#[test]
fn dependency_ordering() {
assert_module_snapshot!(
r#"
module Main exposing (..)
b = a
a = 1
"#
);
}
#[test]
fn value_and_function_in_cycle() {
assert_module_snapshot!(
r#"
module Main exposing (..)
x = f 1
f a = x
"#
);
}
#[test]
fn recursive_decl_self_reference() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
x = x
"#
);
}
#[test]
fn recursive_decl_mutual_values() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
x = y
y = x
"#
);
}
fn value_interface<'a>(
bump: &'a Bump,
module_name: &'a str,
val_name: &'a str,
) -> Interface<'a> {
Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: module_name,
},
values: bump.alloc_slice_fill_iter([nash_can::InterfaceValue {
name: val_name,
annotation: test_annotation(bump),
}]),
aliases: &[],
unions: &[],
binops: &[],
}
}
#[test]
fn unused_import_warning() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo
x = 1
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let (_, warnings) = parse_and_canonicalize_with_warnings(&bump, input, context)
.expect("expected successful canonicalization");
assert!(!warnings.is_empty(), "expected warnings but got none");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_warnings(input, &warnings));
});
}
#[test]
fn used_import_no_warning() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo
x = Foo.bar
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let (_, warnings) = parse_and_canonicalize_with_warnings(&bump, input, context)
.expect("expected successful canonicalization");
assert!(
warnings.is_empty(),
"expected no warnings but got: {warnings:?}"
);
}
fn maybe_with_ctors_interface<'a>(bump: &'a Bump) -> Interface<'a> {
let just_arg = bump.alloc(Located::at(Region::zero(), CanType::Var("a")));
let just_ctor: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "Just",
index: 0,
arity: 1,
arguments: bump.alloc_slice_fill_iter([&*just_arg]),
});
let nothing_ctor: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "Nothing",
index: 1,
arity: 0,
arguments: &[],
});
Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "Maybe",
},
values: &[],
aliases: &[],
unions: bump.alloc_slice_fill_iter([InterfaceUnion {
context: &[],
kind: test_constructor_kind(bump, 1),
name: "Maybe",
parameters: bump.alloc_slice_fill_iter(["a"]),
ctors: bump.alloc_slice_fill_iter([just_ctor, nothing_ctor]),
alternatives: 2,
options: CtorOpts::Normal,
visibility: UnionVisibility::Open,
}]),
binops: &[],
}
}
fn basics_with_binops_interface<'a>(bump: &'a Bump) -> Interface<'a> {
Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "Basics",
},
values: bump.alloc_slice_fill_iter([
InterfaceValue {
name: "add",
annotation: test_annotation(bump),
},
InterfaceValue {
name: "sub",
annotation: test_annotation(bump),
},
InterfaceValue {
name: "mul",
annotation: test_annotation(bump),
},
InterfaceValue {
name: "apR",
annotation: test_annotation(bump),
},
InterfaceValue {
name: "apL",
annotation: test_annotation(bump),
},
]),
aliases: &[],
unions: &[],
binops: bump.alloc_slice_fill_iter([
InterfaceBinop {
symbol: "+",
annotation: test_annotation(bump),
associativity: Associativity::Left,
precedence: Precedence(6),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "Basics",
},
name: "add",
},
},
InterfaceBinop {
symbol: "-",
annotation: test_annotation(bump),
associativity: Associativity::Left,
precedence: Precedence(6),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "Basics",
},
name: "sub",
},
},
InterfaceBinop {
symbol: "*",
annotation: test_annotation(bump),
associativity: Associativity::Left,
precedence: Precedence(7),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "Basics",
},
name: "mul",
},
},
InterfaceBinop {
symbol: "|>",
annotation: test_annotation(bump),
associativity: Associativity::Left,
precedence: Precedence(0),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "Basics",
},
name: "apR",
},
},
InterfaceBinop {
symbol: "<|",
annotation: test_annotation(bump),
associativity: Associativity::Right,
precedence: Precedence(0),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "Basics",
},
name: "apL",
},
},
]),
}
}
#[test]
fn constructor_in_expression() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe(..))
x = Just
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn record_ctor_in_expression() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias Pair 'a 'b = { first : 'a, second : 'b }
p = Pair
"#
);
}
#[test]
fn op_as_value() {
let input = indoc!(
r#"
module Main exposing (..)
import Basics exposing (..)
x = (+)
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn binop_expression() {
let input = indoc!(
r#"
module Main exposing (..)
import Basics exposing (..)
x a b = a + b
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn binop_multi_precedence() {
let input = indoc!(
r#"
module Main exposing (..)
import Basics exposing (..)
x a b c = a + b * c
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn binop_right_assoc() {
let input = indoc!(
r#"
module Main exposing (..)
import Basics exposing (..)
x a b c = a <| b <| c
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn typed_def_top_level() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f : 'a -> 'a
f x = x
"#
);
}
#[test]
fn typed_def_in_let() {
assert_module_snapshot!(
r#"
module Main exposing (..)
g =
let
f : 'a -> 'a
f x = x
in
f 1
"#
);
}
#[test]
fn let_destruct() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f =
let
(a, b) = (1, 2)
in
a
"#
);
}
#[test]
fn let_mutual_recursion() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f =
let
go x = stop x
stop x = go x
in
go 1
"#
);
}
#[test]
fn foreign_var_unqualified() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo exposing (bar)
x = bar
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn not_found_var_qualified() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo
x = Foo.nonexistent
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn underscore_prefix_no_warning() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f = \_ -> 1
"#
);
}
#[test]
fn chained_if_else_if() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f x =
if x then
1
else if x then
2
else
3
"#
);
}
#[test]
fn update_missing_record_var() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f = { nonexistent | x = 1 }
"#
);
}
#[test]
fn case_with_ctor_patterns() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe(..))
f x =
case x of
Just y -> y
Nothing -> 0
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn not_found_binop() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
x = (+)
"#
);
}
#[test]
fn ambiguous_var() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo exposing (..)
import Bar exposing (..)
x = baz
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([
("Foo", value_interface(&bump, "Foo", "baz")),
("Bar", value_interface(&bump, "Bar", "baz")),
]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn ambiguous_ctor_in_expr() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe(..))
import Option exposing (Option(..))
x = Just
"#
);
let bump = Bump::new();
let just_arg = bump.alloc(Located::at(Region::zero(), CanType::Var("a")));
let just_ctor: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "Just",
index: 0,
arity: 1,
arguments: bump.alloc_slice_fill_iter([&*just_arg]),
});
let nothing_ctor: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "Nothing",
index: 1,
arity: 0,
arguments: &[],
});
let maybe_interface = Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "Maybe",
},
values: &[],
aliases: &[],
unions: bump.alloc_slice_fill_iter([InterfaceUnion {
context: &[],
kind: test_constructor_kind(&bump, 1),
name: "Maybe",
parameters: bump.alloc_slice_fill_iter(["a"]),
ctors: bump.alloc_slice_fill_iter([just_ctor, nothing_ctor]),
alternatives: 2,
options: CtorOpts::Normal,
visibility: UnionVisibility::Open,
}]),
binops: &[],
};
let just_arg2 = bump.alloc(Located::at(Region::zero(), CanType::Var("a")));
let just_ctor2: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "Just",
index: 0,
arity: 1,
arguments: bump.alloc_slice_fill_iter([&*just_arg2]),
});
let none_ctor: &CanCtor = bump.alloc(CanCtor {
labels: None,
name: "None",
index: 1,
arity: 0,
arguments: &[],
});
let option_interface = Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "Option",
},
values: &[],
aliases: &[],
unions: bump.alloc_slice_fill_iter([InterfaceUnion {
context: &[],
kind: test_constructor_kind(&bump, 1),
name: "Option",
parameters: bump.alloc_slice_fill_iter(["a"]),
ctors: bump.alloc_slice_fill_iter([just_ctor2, none_ctor]),
alternatives: 2,
options: CtorOpts::Normal,
visibility: UnionVisibility::Open,
}]),
binops: &[],
};
let interfaces = BTreeMap::from([("Maybe", maybe_interface), ("Option", option_interface)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn ambiguous_binop() {
let input = indoc!(
r#"
module Main exposing (..)
import Basics exposing (..)
import MyMath exposing (..)
x a b = a + b
"#
);
let bump = Bump::new();
let basics = basics_with_binops_interface(&bump);
let mymath = Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "MyMath",
},
values: &[],
aliases: &[],
unions: &[],
binops: bump.alloc_slice_fill_iter([InterfaceBinop {
symbol: "+",
annotation: test_annotation(&bump),
associativity: Associativity::Left,
precedence: Precedence(6),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "MyMath",
},
name: "myAdd",
},
}]),
};
let interfaces = BTreeMap::from([("Basics", basics), ("MyMath", mymath)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn binop_non_assoc_conflict() {
let input = indoc!(
r#"
module Main exposing (..)
import Basics exposing (..)
x a b c = a == b == c
"#
);
let bump = Bump::new();
let basics = Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "Basics",
},
values: bump.alloc_slice_fill_iter([InterfaceValue {
name: "eq",
annotation: test_annotation(&bump),
}]),
aliases: &[],
unions: &[],
binops: bump.alloc_slice_fill_iter([InterfaceBinop {
symbol: "==",
annotation: test_annotation(&bump),
associativity: Associativity::None,
precedence: Precedence(4),
function: nash_ast::QualifiedName {
home: ModuleName {
package: None,
name: "Basics",
},
name: "eq",
},
}]),
};
let interfaces = BTreeMap::from([("Basics", basics)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn annotation_too_short() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f : a
f x = x
"#
);
}
#[test]
fn duplicate_field_in_update() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f r = { r | x = 1, x = 2 }
"#
);
}
#[test]
fn duplicate_pattern_lambda_args() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f = \x x -> x
"#
);
}
#[test]
fn duplicate_pattern_func_args() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f x x = x
"#
);
}
#[test]
fn duplicate_pattern_destruct() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f =
let
(x, x) = (1, 2)
in
x
"#
);
}
#[test]
fn let_mutual_recursion_values_error() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
f =
let
a = b
b = a
in
a
"#
);
}
#[test]
fn shadowing_toplevel() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
x = 1
f =
let
x = 2
in
x
"#
);
}
#[test]
fn unused_func_arg_warning() {
assert_module_warning_snapshot!(
r#"
module Main exposing (..)
f x = 42
"#
);
}
#[test]
fn unused_case_branch_var() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe(..))
f x =
case x of
Just y -> 1
Nothing -> 0
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let (_, warnings) = parse_and_canonicalize_with_warnings(&bump, input, context)
.expect("expected successful canonicalization");
assert!(!warnings.is_empty(), "expected warnings but got none");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_warnings(input, &warnings));
});
}
#[test]
fn duplicate_ctor_error() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Point 'a = { x : 'a, y : 'a }
type Shape 'a
= Point 'a 'a
| Circle 'a
"#
);
}
#[test]
fn ctor_opts_unbox() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type Wrap 'a
= Wrap 'a
"#
);
}
#[test]
fn multiple_unbound_union_vars() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type Foo
= Bar a b
"#
);
}
#[test]
fn alias_both_unused_and_unbound() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
type alias Bad 'a = 'b
"#
);
}
#[test]
fn export_explicit_value() {
assert_module_snapshot!(
r#"
module Main exposing (foo)
foo = 42
"#
);
}
#[test]
fn infix_right_associativity() {
assert_module_snapshot!(
r#"
module Main exposing ((<|))
infix right 0 (<|) = apL
apL f x = f x
"#
);
}
#[test]
fn infix_non_associativity() {
assert_module_snapshot!(
r#"
module Main exposing ((==))
infix non 4 (==) = eq
eq a b = a
"#
);
}
#[test]
fn local_record_alias_ctor() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias Point 'a = { x : 'a, y : 'a }
p = Point
"#
);
}
#[test]
fn interface_non_exported_binop() {
assert_interface_snapshot!(
r#"
module Main exposing (foo)
infix left 6 (|>) = apR
apR x f = f x
foo = 42
"#
);
}
#[test]
fn import_exposing_not_found_value() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo exposing (nonexistent)
x = 1
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn import_exposing_not_found_type() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo exposing (Nonexistent)
x = 1
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn import_exposing_not_found_op() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo exposing ((+))
x = 1
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Foo", value_interface(&bump, "Foo", "bar"))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn import_ctor_by_name() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Just)
x = 1
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn import_open_alias() {
let input = indoc!(
r#"
module Main exposing (..)
import Foo exposing (MyAlias(..))
x = 1
"#
);
let bump = Bump::new();
let alias_type = bump.alloc(Located::at(Region::zero(), CanType::Var("a")));
let foo = Interface {
impls: &[],
traits: &[],
home: ModuleName {
package: None,
name: "Foo",
},
values: &[],
aliases: bump.alloc_slice_fill_iter([InterfaceAlias {
context: &[],
kind: test_constructor_kind(&bump, 1),
name: "MyAlias",
parameters: bump.alloc_slice_fill_iter(["a"]),
typ: alias_type,
visibility: AliasVisibility::Public,
}]),
unions: &[],
binops: &[],
};
let interfaces = BTreeMap::from([("Foo", foo)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn collect_from_def_typed() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe)
f : Maybe 'a -> Maybe 'a
f x = x
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let (_, warnings) = parse_and_canonicalize_with_warnings(&bump, input, context)
.expect("expected successful canonicalization");
assert!(
warnings.is_empty(),
"expected no warnings but got: {warnings:?}"
);
}
fn maybe_interface_with_visibility<'a>(
bump: &'a Bump,
visibility: UnionVisibility,
) -> Interface<'a> {
let base = maybe_with_ctors_interface(bump);
Interface {
impls: &[],
traits: &[],
unions: bump.alloc_slice_fill_iter([InterfaceUnion {
visibility,
..base.unions[0]
}]),
..base
}
}
#[test]
fn closed_union_does_not_leak_ctors() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe(..))
x = Just
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([(
"Maybe",
maybe_interface_with_visibility(&bump, UnionVisibility::Closed),
)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn private_union_not_importable() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe)
x = 1
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([(
"Maybe",
maybe_interface_with_visibility(&bump, UnionVisibility::Private),
)]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect_err("expected canonicalization error");
insta::with_settings!({info => &"diagnostic",
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_snapshot!(render_errors(input, &result));
});
}
#[test]
fn aliased_import_exposes_ctors_unqualified() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe as M exposing (Maybe(..))
x = Just
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn let_destruct_self_reference_is_recursive() {
assert_module_error_snapshot!(
r#"
module Main exposing (..)
main = let (a, b) = (a, 1) in b
"#
);
}
#[test]
fn let_destruct_ctor_pattern_binds_names() {
let input = indoc!(
r#"
module Main exposing (..)
import Maybe exposing (Maybe(..))
f w = let (Just x) = w in x
"#
);
let bump = Bump::new();
let interfaces = BTreeMap::from([("Maybe", maybe_with_ctors_interface(&bump))]);
let context = Context {
package: None,
interfaces: Some(&interfaces),
};
let result = parse_and_canonicalize(&bump, input, context)
.expect("expected successful canonicalization");
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn let_destruct_list_pattern_binds_names() {
assert_module_snapshot!(
r#"
module Main exposing (..)
f w = let [a, b] = w in a
"#
);
}
#[test]
fn let_destruct_local_ctor_pattern_binds_names() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type Wrap 'a
= Wrap 'a
f w = let (Wrap x) = w in x
"#
);
}
#[test]
fn binop_function_must_be_top_level() {
assert_module_error_snapshot!(
r#"
module Main exposing ((|>))
infix left 6 (|>) = missing
"#
);
}
#[test]
fn typed_def_through_parameterized_alias() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias transform 'a = 'a -> 'a
f : transform (List 'b)
f x = x
"#
);
}
#[test]
fn anonymous_record_constructor_argument_unsupported() {
assert_module_error_snapshot!("module Main exposing (..)\n\ntype D = D int { x : int }\n");
}
#[test]
fn little_type_open_export() {
assert_interface_snapshot!(
"module Main exposing (type option(..))\n\ntype option 'a = Some 'a | None\n"
);
}
#[test]
fn unknown_trait_in_context() {
assert_module_error_snapshot!(
"module Main exposing (..)\n\nid : Eq 'a => 'a -> 'a\nid x = x\n"
);
}
#[test]
fn keyword_children_retain_import_uses_and_local_dependencies() {
let bump = Bump::new();
let source = bump.alloc_str("module Main exposing (..)\nimport Primitive exposing (..)\nimport Builtin exposing (..)\nf message x = trace message (comptime (addInteger x x))\ncheck = assert True\nstop message = fail message\nlater message = todo message\nrecur x = comptime (recur x)\n");
let parsed = nash_parse::Parser::new(&bump, source).module().unwrap();
let interfaces = std::collections::BTreeMap::from([(
"Builtin",
nash_can::kinds::builtin_interface(&bump),
)]);
let result = canonicalize(
&bump,
Context {
package: None,
interfaces: Some(&interfaces),
},
&parsed,
)
.unwrap();
assert_module_snapshot!(@output &*source, result.module);
assert!(result.warnings.is_empty(), "{:?}", result.warnings);
assert!(super::collect_used_modules(&result.module).contains("Builtin"));
let mut decls = result.module.decls;
let mut recursive = false;
loop {
match decls {
nash_ast::Decls::Declare { next, .. } => decls = next,
nash_ast::Decls::DeclareRec { next, .. } => {
recursive = true;
decls = next;
}
nash_ast::Decls::Empty => break,
}
}
assert!(
recursive,
"a dependency through comptime still forms a recursive group"
);
}
#[test]
fn keyword_expressions_preserve_children_and_source_regions() {
let bump = Bump::new();
let source =
"module Main exposing (..)\nvalue message body = trace message (comptime body)\n";
let module = parse_and_canonicalize(&bump, source, Context::default()).unwrap();
assert_module_snapshot!(@output source, module);
let nash_ast::Decls::Declare { definition, .. } = module.decls else {
panic!("definition")
};
let nash_ast::Def::Def { body, .. } = definition else {
panic!("untyped")
};
let nash_ast::Expr::Trace {
message,
body: inner,
} = body.value
else {
panic!("trace")
};
assert_eq!(body.region.start.column, 22);
assert_eq!(message.region.start.column, 28);
assert!(matches!(message.value, nash_ast::Expr::VarLocal("message")));
let nash_ast::Expr::Comptime(value) = inner.value else {
panic!("comptime")
};
assert!(matches!(value.value, nash_ast::Expr::VarLocal("body")));
assert!(value.region.start.column > inner.region.start.column);
}
#[test]
fn macro_call_unsupported() {
assert_module_error_snapshot!("module Main exposing (..)\n\nvalue = json!(1)\n");
}
#[test]
fn nested_right_operator_sections() {
let input =
"module Main exposing (..)\n\nimport Basics exposing (..)\n\nsection = (+ ((+ 1) 2))\n";
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let result = parse_and_canonicalize(
&bump,
input,
Context {
package: None,
interfaces: Some(&interfaces),
},
)
.expect("expected successful canonicalization");
insta::with_settings!({description => input, omit_expression => true}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn nested_left_operator_sections() {
let input =
"module Main exposing (..)\n\nimport Basics exposing (..)\n\nsection = (((1 +) 2) +)\n";
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let result = parse_and_canonicalize(
&bump,
input,
Context {
package: None,
interfaces: Some(&interfaces),
},
)
.expect("expected successful canonicalization");
insta::with_settings!({description => input, omit_expression => true}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn right_operator_section() {
let input = "module Main exposing (..)\n\nimport Basics exposing (..)\n\nsection = (+ 5)\n";
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let result = parse_and_canonicalize(
&bump,
input,
Context {
package: None,
interfaces: Some(&interfaces),
},
)
.expect("expected successful canonicalization");
insta::with_settings!({description => input, omit_expression => true}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn left_operator_section() {
let input = "module Main exposing (..)\n\nimport Basics exposing (..)\n\nsection = (5 +)\n";
let bump = Bump::new();
let interfaces = BTreeMap::from([("Basics", basics_with_binops_interface(&bump))]);
let result = parse_and_canonicalize(
&bump,
input,
Context {
package: None,
interfaces: Some(&interfaces),
},
)
.expect("expected successful canonicalization");
insta::with_settings!({description => input, omit_expression => true}, {
insta::assert_debug_snapshot!(result);
});
}
#[test]
fn attributes_unsupported() {
assert_module_error_snapshot!("module Main exposing (..)\n\n@inline\nvalue = 1\n");
}
#[test]
fn unknown_trait_in_impl() {
assert_module_error_snapshot!(
"module Main exposing (..)\n\nimpl Eq int where\n eq a b = true\n"
);
}
#[test]
fn builtin_types_resolve_qualified_without_import() {
assert_module_snapshot!(
"module Main exposing (..)\n\nidentity : Primitive.list Primitive.unit -> list unit\nidentity x = x\n"
);
}
#[test]
fn unit_syntax_is_named_builtin_type() {
let bump = Bump::new();
let result = parse_and_canonicalize(
&bump,
"module Main exposing (..)\n\nidentity : () -> unit\nidentity x = x\n",
Context {
package: None,
interfaces: None,
},
)
.expect("unit annotation canonicalizes");
let (nash_ast::Decls::Declare { definition, .. }
| nash_ast::Decls::DeclareRec { definition, .. }) = result.decls
else {
panic!("expected declaration group")
};
let nash_ast::Def::TypedDef { annotation, .. } = definition else {
panic!("expected typed definition")
};
let nash_ast::Type::Lambda { from, to } = annotation.value else {
panic!("expected function")
};
for typ in [from, to] {
assert!(
matches!(typ.value, nash_ast::Type::Named { reference, args } if reference.home == nash_ast::primitives::primitive_home() && reference.name == "unit" && args.is_empty())
);
}
}
#[test]
fn labeled_ctor_construction_in_wire_order() {
assert_module_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit, a : unit }\nbuild first second = Packet { a = second, z = first }\n"
);
}
#[test]
fn labeled_ctor_missing_field_error() {
assert_module_error_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit, a : unit }\nmain = Packet { a = () }\n"
);
}
#[test]
fn labeled_ctor_extra_field_error() {
assert_module_error_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit }\nmain = Packet { z = (), a = () }\n"
);
}
#[test]
fn ctor_duplicate_label_error() {
assert_module_error_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit, z : unit }\n"
);
}
#[test]
fn labeled_ctor_pattern_in_wire_order() {
assert_module_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit, a : unit }\nget (Packet { a }) = a\n"
);
}
#[test]
fn labeled_ctor_pattern_unknown_field_error() {
assert_module_error_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit }\nget (Packet { a }) = a\n"
);
}
#[test]
fn labeled_ctor_pattern_duplicate_field_error() {
assert_module_error_snapshot!(
"module Main exposing (..)\ntype packet = Packet { z : unit }\nget (Packet { z, z }) = z\n"
);
}
#[test]
fn labeled_ctor_twins_require_equal_label_order() {
assert_module_error_snapshot!(
"module Main exposing (..)\ntype Box = Box { z : Int, a : Int }\ntype box = Box { a : int, z : int }\n"
);
}
}