Constrain and solve import params

No reporting yet
This commit is contained in:
Agus Zubiaga 2024-06-27 18:27:33 -03:00
parent c541dd5747
commit 5ec4b042bb
No known key found for this signature in database
18 changed files with 238 additions and 26 deletions

View file

@ -602,7 +602,8 @@ impl Constraints {
| Constraint::Exhaustive { .. }
| Constraint::Resolve(..)
| Constraint::IngestedFile(..)
| Constraint::CheckCycle(..) => false,
| Constraint::CheckCycle(..)
| Constraint::ImportParams(..) => false,
}
}
@ -685,6 +686,15 @@ impl Constraints {
) -> Constraint {
Constraint::IngestedFile(type_index, file_path, bytes)
}
pub fn import_params(
&mut self,
type_index: TypeOrVar,
module_id: ModuleId,
region: Region,
) -> Constraint {
Constraint::ImportParams(type_index, module_id, region)
}
}
roc_error_macros::assert_sizeof_default!(Constraint, 3 * 8);
@ -787,6 +797,7 @@ pub enum Constraint {
CheckCycle(Index<Cycle>, IllegalCycleMark),
IngestedFile(TypeOrVar, Box<PathBuf>, Arc<Vec<u8>>),
ImportParams(TypeOrVar, ModuleId, Region),
}
#[derive(Debug, Clone, Copy, Default)]
@ -865,6 +876,9 @@ impl std::fmt::Debug for Constraint {
Self::IngestedFile(arg0, arg1, arg2) => {
write!(f, "IngestedFile({arg0:?}, {arg1:?}, {arg2:?})")
}
Self::ImportParams(arg0, arg1, arg2) => {
write!(f, "ImportParams({arg0:?}, {arg1:?}, {arg2:?})")
}
}
}
}

View file

@ -297,9 +297,11 @@ fn deep_copy_expr_help<C: CopyEnv>(env: &mut C, copied: &mut Vec<Variable>, expr
params: *params,
var: sub!(*var),
},
ImportParams(loc_expr, module_id) => {
ImportParams(Box::new(loc_expr.map(|e| go_help!(e))), *module_id)
}
ImportParams(loc_expr, var, module_id) => ImportParams(
Box::new(loc_expr.map(|e| go_help!(e))),
sub!(*var),
*module_id,
),
&AbilityMember(sym, specialization, specialization_var) => {
AbilityMember(sym, specialization, sub!(specialization_var))
}

View file

@ -209,7 +209,7 @@ fn expr<'a>(c: &Ctx, p: EPrec, f: &'a Arena<'a>, e: &'a Expr) -> DocBuilder<'a,
Var(sym, _) | ParamsVar { symbol: sym, .. } | AbilityMember(sym, _, _) => {
pp_sym(c, f, *sym)
}
ImportParams(loc_expr, _) => expr(c, p, f, &loc_expr.value),
ImportParams(loc_expr, _, _) => expr(c, p, f, &loc_expr.value),
When {
loc_cond, branches, ..
} => maybe_paren!(

View file

@ -2422,7 +2422,7 @@ fn canonicalize_pending_value_def<'a>(
let loc_expr = Loc::at(
loc_pattern.region,
Expr::ImportParams(Box::new(loc_record), module_id),
Expr::ImportParams(Box::new(loc_record), var_store.fresh(), module_id),
);
let def = single_can_def(

View file

@ -184,7 +184,7 @@ pub enum Expr {
},
/// Module params expression in import
ImportParams(Box<Loc<Expr>>, ModuleId),
ImportParams(Box<Loc<Expr>>, Variable, ModuleId),
/// The "crash" keyword
Crash {
@ -338,7 +338,7 @@ impl Expr {
Self::RecordAccessor(data) => Category::Accessor(data.field.clone()),
Self::TupleAccess { index, .. } => Category::TupleAccess(*index),
Self::RecordUpdate { .. } => Category::Record,
Self::ImportParams(loc_expr, _) => loc_expr.value.category(),
Self::ImportParams(loc_expr, _, _) => loc_expr.value.category(),
Self::Tag {
name, arguments, ..
} => Category::TagApply {
@ -2225,9 +2225,9 @@ pub fn inline_calls(var_store: &mut VarStore, expr: Expr) -> Expr {
);
}
ImportParams(loc_expr, module_id) => {
ImportParams(loc_expr, var, module_id) => {
let loc_expr = Loc::at(loc_expr.region, inline_calls(var_store, loc_expr.value));
ImportParams(Box::new(loc_expr), module_id)
ImportParams(Box::new(loc_expr), var, module_id)
}
RecordAccess {
@ -3242,7 +3242,7 @@ pub(crate) fn get_lookup_symbols(expr: &Expr) -> Vec<ExpectLookup> {
Expr::Tuple { elems, .. } => {
stack.extend(elems.iter().map(|(_, elem)| &elem.value));
}
Expr::ImportParams(loc_expr, _) => {
Expr::ImportParams(loc_expr, _, _) => {
stack.push(&loc_expr.value);
}
Expr::Expect {

View file

@ -1254,7 +1254,7 @@ fn fix_values_captured_in_closure_expr(
}
}
ImportParams(loc_expr, _) => {
ImportParams(loc_expr, _, _) => {
fix_values_captured_in_closure_expr(
&mut loc_expr.value,
no_capture_symbols,

View file

@ -318,7 +318,7 @@ pub fn walk_expr<V: Visitor>(visitor: &mut V, expr: &Expr, var: Variable) {
.iter()
.for_each(|(var, elem)| visitor.visit_expr(&elem.value, elem.region, *var)),
Expr::EmptyRecord => { /* terminal */ }
Expr::ImportParams(expr, _) => visitor.visit_expr(&expr.value, expr.region, var),
Expr::ImportParams(expr, _, _) => visitor.visit_expr(&expr.value, expr.region, var),
Expr::RecordAccess {
field_var,
loc_expr,

View file

@ -580,9 +580,24 @@ pub fn constrain_expr(
constraints.and_constraint([store_expected, lookup_constr])
}
ImportParams(params, module_id) => {
// todo(agus): constrain
Constraint::True
ImportParams(params, var, module_id) => {
let index = constraints.push_variable(*var);
let expected_params = constraints.push_expected_type(Expected::ForReason(
Reason::ImportParams(*module_id),
index,
params.region,
));
let expr_con = constrain_expr(
types,
constraints,
env,
params.region,
&params.value,
expected_params,
);
let params_con = constraints.import_params(index, *module_id, params.region);
let expr_and_params = constraints.and_constraint([expr_con, params_con]);
constraints.exists([*var], expr_and_params)
}
&AbilityMember(symbol, specialization_id, specialization_var) => {
// Save the expectation in the `specialization_var` so we know what to specialize, then
@ -4098,7 +4113,7 @@ fn is_generalizable_expr(mut expr: &Expr) -> bool {
return true;
}
OpaqueRef { argument, .. } => expr = &argument.1.value,
ImportParams(loc_expr, _) => expr = &loc_expr.value,
ImportParams(loc_expr, _, _) => expr = &loc_expr.value,
Str(_)
| IngestedFile(..)
| List { .. }

View file

@ -75,14 +75,16 @@ fn constrain_params(
let pattern_constraints = constraints.and_constraint(state.constraints);
constraints.let_constraint(
let cons = constraints.let_constraint(
[],
state.vars,
state.headers,
pattern_constraints,
constraint,
Generalizable(true),
)
);
constraints.exists([*pattern_var], cons)
}
fn constrain_symbols_from_requires(

View file

@ -52,6 +52,7 @@ pub fn infer_expr(
derived_module,
function_kind: FunctionKind::LambdaSet,
params_pattern: None,
module_params_vars: Default::default(),
#[cfg(debug_assertions)]
checkmate: None,
};

View file

@ -340,6 +340,21 @@ fn start_phase<'a>(
None
};
let mut module_params_vars = Vec::with_capacity(available_modules.len());
for (module_id, _) in available_modules.iter() {
if let Some((_, _, pat)) = state.module_cache.param_patterns.get(module_id) {
match pat.value {
roc_can::pattern::Pattern::RecordDestructure { whole_var, .. } => {
module_params_vars.push((*module_id, whole_var));
}
_ => {
internal_error!("Module params can only be records");
}
}
}
}
BuildTask::solve_module(
module,
ident_ids,
@ -351,6 +366,7 @@ fn start_phase<'a>(
pending_derives,
var_store,
available_modules,
module_params_vars,
&state.exposed_types,
dep_idents,
declarations,
@ -905,6 +921,7 @@ enum BuildTask<'a> {
dep_idents: IdentIdsByModule,
cached_subs: CachedTypeState,
derived_module: SharedDerivedModule,
module_params_vars: Vec<(ModuleId, Variable)>,
#[cfg(debug_assertions)]
checkmate: Option<roc_checkmate::Collector>,
@ -4301,6 +4318,7 @@ impl<'a> BuildTask<'a> {
pending_derives: PendingDerives,
var_store: VarStore,
imported_modules: MutMap<ModuleId, Region>,
module_params_vars: Vec<(ModuleId, Variable)>,
exposed_types: &ExposedByModule,
dep_idents: IdentIdsByModule,
declarations: Declarations,
@ -4329,6 +4347,7 @@ impl<'a> BuildTask<'a> {
module_timing,
cached_subs,
derived_module,
module_params_vars,
#[cfg(debug_assertions)]
checkmate,
@ -4597,6 +4616,7 @@ struct SolveResult {
#[allow(clippy::complexity)]
fn run_solve_solve(
exposed_for_module: ExposedForModule,
original_param_vars: Vec<(ModuleId, Variable)>,
mut types: Types,
mut constraints: Constraints,
constraint: ConstraintSoa,
@ -4623,7 +4643,7 @@ fn run_solve_solve(
let mut subs = Subs::new_from_varstore(var_store);
let (import_variables, abilities_store) = add_imports(
let (mut import_variables, abilities_store) = add_imports(
module.module_id,
&mut constraints,
&mut subs,
@ -4634,6 +4654,31 @@ fn run_solve_solve(
&mut imported_flex_vars,
);
let mut imported_param_vars = HashMap::with_capacity(original_param_vars.len());
for (module_id, params_var) in original_param_vars.iter() {
let ExposedModuleTypes {
exposed_types_storage_subs: exposed_types,
resolved_implementations: _,
} = exposed_for_module
.exposed_by_module
.get(&module_id)
.unwrap();
let copied_import = exposed_types
.storage_subs
.export_variable_to(&mut subs, *params_var);
let copied_import_var = extend_imports_data_with_copied_import(
copied_import,
&mut import_variables,
&mut imported_rigid_vars,
&mut imported_flex_vars,
);
imported_param_vars.insert(*module_id, copied_import_var);
}
let actual_constraint = constraints.let_import_constraint(
imported_rigid_vars,
imported_flex_vars,
@ -4662,6 +4707,7 @@ fn run_solve_solve(
#[cfg(debug_assertions)]
checkmate,
params_pattern: params_pattern.map(|(_, _, pattern)| pattern.value),
module_params_vars: imported_param_vars,
};
let solve_output = roc_solve::module::run_solve(
@ -4726,6 +4772,7 @@ fn run_solve<'a>(
ident_ids: IdentIds,
mut module_timing: ModuleTiming,
exposed_for_module: ExposedForModule,
module_params_vars: Vec<(ModuleId, Variable)>,
types: Types,
constraints: Constraints,
constraint: ConstraintSoa,
@ -4746,6 +4793,11 @@ fn run_solve<'a>(
// TODO remove when we write builtins in roc
let aliases = module.aliases.clone();
let opt_params_var = match module.params_pattern {
Some((params_var, _, _)) => Some(params_var),
None => None,
};
let mut module = module;
let loc_expects = std::mem::take(&mut module.loc_expects);
let loc_dbgs = std::mem::take(&mut module.loc_dbgs);
@ -4756,6 +4808,7 @@ fn run_solve<'a>(
match cached_types.lock().remove(&module_id) {
None => run_solve_solve(
exposed_for_module,
module_params_vars,
types,
constraints,
constraint,
@ -4787,6 +4840,7 @@ fn run_solve<'a>(
} else {
run_solve_solve(
exposed_for_module,
module_params_vars,
types,
constraints,
constraint,
@ -4817,6 +4871,7 @@ fn run_solve<'a>(
module_id,
&mut solved_subs,
&exposed_vars_by_symbol,
opt_params_var,
&solved_implementations,
&abilities_store,
);
@ -6202,6 +6257,7 @@ fn run_task<'a>(
dep_idents,
cached_subs,
derived_module,
module_params_vars,
#[cfg(debug_assertions)]
checkmate,
@ -6210,6 +6266,7 @@ fn run_task<'a>(
ident_ids,
module_timing,
exposed_for_module,
module_params_vars,
types,
constraints,
constraint,

View file

@ -1564,7 +1564,7 @@ fn cannot_use_original_name_if_imported_with_alias() {
}
#[test]
fn import_module_params_no_warn() {
fn module_params_checks() {
let modules = vec![
(
"Api.roc",
@ -1590,10 +1590,73 @@ fn import_module_params_no_warn() {
),
];
let result = multiple_modules("module_params_typecheck", modules);
let result = multiple_modules("module_params_checks", modules);
assert!(result.is_ok());
}
#[test]
fn module_params_optional() {
let modules = vec![
(
"Api.roc",
indoc!(
r#"
module { key, exp ? "default" } -> [url]
url = "example.com/$(key)?exp=$(exp)"
"#
),
),
(
"Main.roc",
indoc!(
r#"
module [example]
import Api { key: "abcdef" }
example = Api.url
"#
),
),
];
let result = multiple_modules("module_params_optional", modules);
assert!(result.is_ok())
}
#[test]
#[should_panic]
fn module_params_typecheck_fail() {
let modules = vec![
(
"Api.roc",
indoc!(
r#"
module { key } -> [url]
url = "example.com/$(key)"
"#
),
),
(
"Main.roc",
indoc!(
r#"
module [example]
import Api { key: 123 }
example = Api.url
"#
),
),
];
multiple_modules("module_params_typecheck", modules).unwrap_err();
// todo(agus): test reporting
}
#[test]
fn issue_2863_module_type_does_not_exist() {
let modules = vec![

View file

@ -4425,7 +4425,7 @@ pub fn with_hole<'a>(
ParamsVar { .. } => {
todo!("agus: handle params var")
}
ImportParams(loc_expr, _) => with_hole(
ImportParams(loc_expr, _, _) => with_hole(
env,
loc_expr.value,
variable,

View file

@ -1,3 +1,5 @@
use std::collections::HashMap;
use crate::solve::RunSolveOutput;
use crate::FunctionKind;
use crate::{aliases::Aliases, solve};
@ -81,8 +83,9 @@ pub struct SolveConfig<'a> {
/// The checkmate collector for this module.
pub checkmate: Option<roc_checkmate::Collector>,
/// Module params pattern
/// Module params
pub params_pattern: Option<roc_can::pattern::Pattern>,
pub module_params_vars: HashMap<ModuleId, Variable>,
}
pub struct SolveOutput {
@ -147,6 +150,7 @@ pub fn exposed_types_storage_subs(
home: ModuleId,
solved_subs: &mut Solved<Subs>,
exposed_vars_by_symbol: &[(Symbol, Variable)],
params_var: Option<Variable>,
solved_implementations: &ResolvedImplementations,
abilities_store: &AbilitiesStore,
) -> ExposedTypesStorageSubs {
@ -159,6 +163,10 @@ pub fn exposed_types_storage_subs(
stored_vars_by_symbol.insert(*symbol, new_var);
}
if let Some(params_var) = params_var {
storage_subs.import_variable_from(subs, params_var);
}
let mut stored_specialization_lambda_set_vars =
VecMap::with_capacity(solved_implementations.len());

View file

@ -1,3 +1,5 @@
use std::collections::HashMap;
use crate::ability::{
resolve_ability_specialization, type_implementing_specialization, AbilityImplError,
CheckedDerives, ObligationCache, PendingDerivesTable, Resolved,
@ -20,7 +22,7 @@ use roc_debug_flags::dbg_do;
#[cfg(debug_assertions)]
use roc_debug_flags::ROC_VERIFY_RIGID_LET_GENERALIZED;
use roc_error_macros::internal_error;
use roc_module::symbol::Symbol;
use roc_module::symbol::{ModuleId, Symbol};
use roc_problem::can::CycleEntry;
use roc_region::all::Loc;
use roc_solve_problem::TypeError;
@ -130,6 +132,7 @@ fn run_help(
derived_module,
function_kind,
params_pattern,
module_params_vars,
..
} = config;
@ -183,6 +186,7 @@ fn run_help(
&mut obligation_cache,
&mut awaiting_specializations,
params_pattern,
module_params_vars,
);
RunSolveOutput {
@ -241,6 +245,7 @@ fn solve(
obligation_cache: &mut ObligationCache,
awaiting_specializations: &mut AwaitingSpecializations,
params_pattern: Option<roc_can::pattern::Pattern>,
module_params_vars: HashMap<ModuleId, Variable>,
) -> State {
let scope = Scope::new(params_pattern);
@ -1396,6 +1401,48 @@ fn solve(
}
}
}
ImportParams(type_index, module_id, _region) => {
let actual = either_type_index_to_var(
env,
rank,
problems,
abilities_store,
obligation_cache,
&mut can_types,
aliases,
*type_index,
);
let expected = module_params_vars
.get(module_id)
// todo(agus): Module has no params? handle
.unwrap();
match unify(
&mut env.uenv(),
actual,
*expected,
UnificationMode::EQ,
Polarity::OF_VALUE,
) {
Success {
vars,
must_implement_ability: _,
lambda_sets_to_specialize: _,
extra_metadata: _,
} => {
env.introduce(rank, &vars);
state
}
Failure(vars, _actual_type, _expected_type, _) => {
env.introduce(rank, &vars);
todo!("agus: reporting")
}
}
}
};
}

View file

@ -439,6 +439,7 @@ fn check_derived_typechecks_and_golden(
exposed_by_module: &exposed_for_module.exposed_by_module,
derived_module: Default::default(),
params_pattern: None,
module_params_vars: Default::default(),
#[cfg(debug_assertions)]
checkmate: None,

View file

@ -11,7 +11,7 @@ use roc_error_macros::internal_error;
use roc_module::called_via::CalledVia;
use roc_module::ident::{ForeignSymbol, Lowercase, TagName};
use roc_module::low_level::LowLevel;
use roc_module::symbol::{Interns, Symbol};
use roc_module::symbol::{Interns, ModuleId, Symbol};
use roc_region::all::{Loc, Region};
use std::fmt;
use std::fmt::Write;
@ -3424,6 +3424,7 @@ pub enum Reason {
def_region: Region,
},
CrashArg,
ImportParams(ModuleId),
}
#[derive(PartialEq, Eq, Debug, Clone)]