Thread down environment module from cli down to the type-checker

We simply provide a flag with a free-form output which acts as
  the module to lookup in the 'env' folder. The strategy is to replace
  the environment module name on-the-fly when a user tries to import
  'env'.

  If the environment isn't found, an 'UnknownModule' error is raised
  (which I will slightly adjust in a following commits to something more
  related to environment)

  There are few important consequences to this design which may not seem
  immediately obvious:

  1. We parse and type-check every env modules, even if they aren't
     used. This ensures that code doesn't break with a compilation error
     simply because people forgot to type-check a given env.

     Note that compilation could still fail because the env module
     itself could provide an invalid API. So it only prevents each
     modules to be independently wrong when taken in isolation.

  2. Technically, this also means that one can import env modules in
     other env modules by their names. I don't know if it's a good or
     bad idea at this point but it doesn't really do any wrong;
     dependencies and cycles are handlded all-the-same.
This commit is contained in:
KtorZ 2024-08-04 10:27:32 +02:00
parent c9d0da0c22
commit fbe2f82582
No known key found for this signature in database
GPG Key ID: 33173CB6F77F4277
16 changed files with 73 additions and 63 deletions

View File

@ -21,6 +21,9 @@ pub const BACKPASS_VARIABLE: &str = "_backpass";
pub const CAPTURE_VARIABLE: &str = "_capture"; pub const CAPTURE_VARIABLE: &str = "_capture";
pub const PIPE_VARIABLE: &str = "_pipe"; pub const PIPE_VARIABLE: &str = "_pipe";
pub const ENV_MODULE: &str = "env";
pub const DEFAULT_ENV_MODULE: &str = "default";
pub type TypedModule = Module<TypeInfo, TypedDefinition>; pub type TypedModule = Module<TypeInfo, TypedDefinition>;
pub type UntypedModule = Module<(), UntypedDefinition>; pub type UntypedModule = Module<(), UntypedDefinition>;

View File

@ -49,6 +49,7 @@ macro_rules! aiken_fn {
$module_types, $module_types,
$crate::ast::Tracing::silent(), $crate::ast::Tracing::silent(),
&mut warnings, &mut warnings,
None,
) )
.unwrap(); .unwrap();

View File

@ -38,6 +38,7 @@ fn check_module(
&module_types, &module_types,
Tracing::All(TraceLevel::Verbose), Tracing::All(TraceLevel::Verbose),
&mut warnings, &mut warnings,
None,
) )
.expect("extra dependency did not compile"); .expect("extra dependency did not compile");
module_types.insert(package.clone(), typed_module.type_info.clone()); module_types.insert(package.clone(), typed_module.type_info.clone());
@ -50,6 +51,7 @@ fn check_module(
&module_types, &module_types,
tracing, tracing,
&mut warnings, &mut warnings,
None,
); );
result result

View File

@ -7,7 +7,7 @@ use super::{
}; };
use crate::{ use crate::{
ast::{ ast::{
Annotation, CallArg, DataType, Definition, Function, ModuleConstant, ModuleKind, self, Annotation, CallArg, DataType, Definition, Function, ModuleConstant, ModuleKind,
RecordConstructor, RecordConstructorArg, Span, TypeAlias, TypedDefinition, TypedFunction, RecordConstructor, RecordConstructorArg, Span, TypeAlias, TypedDefinition, TypedFunction,
TypedPattern, UnqualifiedImport, UntypedArg, UntypedDefinition, UntypedFunction, Use, TypedPattern, UnqualifiedImport, UntypedArg, UntypedDefinition, UntypedFunction, Use,
Validator, PIPE_VARIABLE, Validator, PIPE_VARIABLE,
@ -80,11 +80,33 @@ pub struct Environment<'a> {
/// A mapping from known annotations to their resolved type. /// A mapping from known annotations to their resolved type.
pub annotations: HashMap<Annotation, Rc<Type>>, pub annotations: HashMap<Annotation, Rc<Type>>,
/// The user-defined target environment referred to as the module 'env'.
pub target_env: Option<&'a str>,
/// Warnings /// Warnings
pub warnings: &'a mut Vec<Warning>, pub warnings: &'a mut Vec<Warning>,
} }
impl<'a> Environment<'a> { impl<'a> Environment<'a> {
pub fn find_module(&self, fragments: &[String], location: Span) -> Result<&'a TypeInfo, Error> {
let mut name = fragments.join("/");
if name == ast::ENV_MODULE {
name = self
.target_env
.unwrap_or(ast::DEFAULT_ENV_MODULE)
.to_string()
}
self.importable_modules
.get(&name)
.ok_or_else(|| Error::UnknownModule {
location,
name,
imported_modules: self.imported_modules.keys().cloned().collect(),
})
}
pub fn close_scope(&mut self, data: ScopeResetData) { pub fn close_scope(&mut self, data: ScopeResetData) {
let unused = self let unused = self
.entity_usages .entity_usages
@ -705,6 +727,7 @@ impl<'a> Environment<'a> {
current_kind: &'a ModuleKind, current_kind: &'a ModuleKind,
importable_modules: &'a HashMap<String, TypeInfo>, importable_modules: &'a HashMap<String, TypeInfo>,
warnings: &'a mut Vec<Warning>, warnings: &'a mut Vec<Warning>,
target_env: Option<&'a str>,
) -> Self { ) -> Self {
let prelude = importable_modules let prelude = importable_modules
.get("aiken") .get("aiken")
@ -731,6 +754,7 @@ impl<'a> Environment<'a> {
annotations: HashMap::new(), annotations: HashMap::new(),
warnings, warnings,
entity_usages: vec![HashMap::new()], entity_usages: vec![HashMap::new()],
target_env,
} }
} }
@ -772,17 +796,7 @@ impl<'a> Environment<'a> {
location, location,
package: _, package: _,
}) => { }) => {
let name = module.join("/"); let module_info = self.find_module(module, *location)?;
// Find imported module
let module_info =
self.importable_modules
.get(&name)
.ok_or_else(|| Error::UnknownModule {
location: *location,
name: name.clone(),
imported_modules: self.imported_modules.keys().cloned().collect(),
})?;
if module_info.kind.is_validator() if module_info.kind.is_validator()
&& (self.current_kind.is_lib() && (self.current_kind.is_lib()
@ -791,7 +805,7 @@ impl<'a> Environment<'a> {
{ {
return Err(Error::ValidatorImported { return Err(Error::ValidatorImported {
location: *location, location: *location,
name, name: module.join("/"),
}); });
} }

View File

@ -19,6 +19,7 @@ use crate::{
use std::{borrow::Borrow, collections::HashMap, ops::Deref, rc::Rc}; use std::{borrow::Borrow, collections::HashMap, ops::Deref, rc::Rc};
impl UntypedModule { impl UntypedModule {
#[allow(clippy::too_many_arguments)]
pub fn infer( pub fn infer(
mut self, mut self,
id_gen: &IdGenerator, id_gen: &IdGenerator,
@ -27,11 +28,12 @@ impl UntypedModule {
modules: &HashMap<String, TypeInfo>, modules: &HashMap<String, TypeInfo>,
tracing: Tracing, tracing: Tracing,
warnings: &mut Vec<Warning>, warnings: &mut Vec<Warning>,
env: Option<&str>,
) -> Result<TypedModule, Error> { ) -> Result<TypedModule, Error> {
let module_name = self.name.clone(); let module_name = self.name.clone();
let docs = std::mem::take(&mut self.docs); let docs = std::mem::take(&mut self.docs);
let mut environment = let mut environment =
Environment::new(id_gen.clone(), &module_name, &kind, modules, warnings); Environment::new(id_gen.clone(), &module_name, &kind, modules, warnings, env);
let mut type_names = HashMap::with_capacity(self.definitions.len()); let mut type_names = HashMap::with_capacity(self.definitions.len());
let mut value_names = HashMap::with_capacity(self.definitions.len()); let mut value_names = HashMap::with_capacity(self.definitions.len());
@ -574,18 +576,7 @@ fn infer_definition(
unqualified, unqualified,
package: _, package: _,
}) => { }) => {
let name = module.join("/"); let module_info = environment.find_module(&module, location)?;
// Find imported module
let module_info =
environment
.importable_modules
.get(&name)
.ok_or_else(|| Error::UnknownModule {
location,
name,
imported_modules: environment.imported_modules.keys().cloned().collect(),
})?;
Ok(Definition::Use(Use { Ok(Definition::Use(Use {
location, location,

View File

@ -40,6 +40,7 @@ impl LspProject {
u32::default(), u32::default(),
PropertyTest::DEFAULT_MAX_SUCCESS, PropertyTest::DEFAULT_MAX_SUCCESS,
Tracing::silent(), Tracing::silent(),
None,
); );
self.project.restore(checkpoint); self.project.restore(checkpoint);

View File

@ -32,7 +32,7 @@ use crate::{
}; };
use aiken_lang::{ use aiken_lang::{
ast::{ ast::{
DataTypeKey, Definition, FunctionAccessKey, ModuleKind, Tracing, TypedDataType, self, DataTypeKey, Definition, FunctionAccessKey, ModuleKind, Tracing, TypedDataType,
TypedFunction, TypedFunction,
}, },
builtins, builtins,
@ -65,8 +65,6 @@ use uplc::{
PlutusData, PlutusData,
}; };
const DEFAULT_ENV_MODULE: &str = "default";
#[derive(Debug)] #[derive(Debug)]
pub struct Source { pub struct Source {
pub path: PathBuf, pub path: PathBuf,
@ -186,10 +184,16 @@ where
self.defined_modules = checkpoint.defined_modules; self.defined_modules = checkpoint.defined_modules;
} }
pub fn build(&mut self, uplc: bool, tracing: Tracing) -> Result<(), Vec<Error>> { pub fn build(
&mut self,
uplc: bool,
tracing: Tracing,
env: Option<String>,
) -> Result<(), Vec<Error>> {
let options = Options { let options = Options {
code_gen_mode: CodeGenMode::Build(uplc), code_gen_mode: CodeGenMode::Build(uplc),
tracing, tracing,
env,
}; };
self.compile(options) self.compile(options)
@ -211,7 +215,7 @@ where
let mut modules = self.parse_sources(self.config.name.clone())?; let mut modules = self.parse_sources(self.config.name.clone())?;
self.type_check(&mut modules, Tracing::silent(), false)?; self.type_check(&mut modules, Tracing::silent(), None, false)?;
let destination = destination.unwrap_or_else(|| self.root.join("docs")); let destination = destination.unwrap_or_else(|| self.root.join("docs"));
@ -252,9 +256,11 @@ where
seed: u32, seed: u32,
property_max_success: usize, property_max_success: usize,
tracing: Tracing, tracing: Tracing,
env: Option<String>,
) -> Result<(), Vec<Error>> { ) -> Result<(), Vec<Error>> {
let options = Options { let options = Options {
tracing, tracing,
env,
code_gen_mode: if skip_tests { code_gen_mode: if skip_tests {
CodeGenMode::NoOp CodeGenMode::NoOp
} else { } else {
@ -307,7 +313,7 @@ where
let mut modules = self.parse_sources(self.config.name.clone())?; let mut modules = self.parse_sources(self.config.name.clone())?;
self.type_check(&mut modules, options.tracing, true)?; self.type_check(&mut modules, options.tracing, options.env.as_deref(), true)?;
match options.code_gen_mode { match options.code_gen_mode {
CodeGenMode::Build(uplc_dump) => { CodeGenMode::Build(uplc_dump) => {
@ -725,6 +731,7 @@ where
&mut self, &mut self,
modules: &mut ParsedModules, modules: &mut ParsedModules,
tracing: Tracing, tracing: Tracing,
env: Option<&str>,
validate_module_name: bool, validate_module_name: bool,
) -> Result<(), Vec<Error>> { ) -> Result<(), Vec<Error>> {
let our_modules: BTreeSet<String> = modules.keys().cloned().collect(); let our_modules: BTreeSet<String> = modules.keys().cloned().collect();
@ -737,6 +744,7 @@ where
&self.id_gen, &self.id_gen,
&self.config.name.to_string(), &self.config.name.to_string(),
tracing, tracing,
env,
validate_module_name, validate_module_name,
&mut self.module_sources, &mut self.module_sources,
&mut self.module_types, &mut self.module_types,
@ -905,7 +913,7 @@ where
} }
if keep { if keep {
if self.module_name(dir, &path).as_str() == DEFAULT_ENV_MODULE { if self.module_name(dir, &path).as_str() == ast::DEFAULT_ENV_MODULE {
has_default = Some(true); has_default = Some(true);
} }
self.add_module(path, dir, kind) self.add_module(path, dir, kind)

View File

@ -51,6 +51,7 @@ impl ParsedModule {
id_gen: &IdGenerator, id_gen: &IdGenerator,
package: &str, package: &str,
tracing: Tracing, tracing: Tracing,
env: Option<&str>,
validate_module_name: bool, validate_module_name: bool,
module_sources: &mut HashMap<String, (String, LineNumbers)>, module_sources: &mut HashMap<String, (String, LineNumbers)>,
module_types: &mut HashMap<String, TypeInfo>, module_types: &mut HashMap<String, TypeInfo>,
@ -68,6 +69,7 @@ impl ParsedModule {
module_types, module_types,
tracing, tracing,
&mut warnings, &mut warnings,
env,
) )
.map_err(|error| Error::Type { .map_err(|error| Error::Type {
path: self.path.clone(), path: self.path.clone(),

View File

@ -3,6 +3,7 @@ use aiken_lang::ast::Tracing;
pub struct Options { pub struct Options {
pub code_gen_mode: CodeGenMode, pub code_gen_mode: CodeGenMode,
pub tracing: Tracing, pub tracing: Tracing,
pub env: Option<String>,
} }
impl Default for Options { impl Default for Options {
@ -10,6 +11,7 @@ impl Default for Options {
Self { Self {
code_gen_mode: CodeGenMode::NoOp, code_gen_mode: CodeGenMode::NoOp,
tracing: Tracing::silent(), tracing: Tracing::silent(),
env: None,
} }
} }
} }

View File

@ -1314,6 +1314,7 @@ mod test {
&module_types, &module_types,
Tracing::All(TraceLevel::Verbose), Tracing::All(TraceLevel::Verbose),
&mut warnings, &mut warnings,
None,
) )
.expect("Failed to type-check module."); .expect("Failed to type-check module.");

View File

@ -99,6 +99,7 @@ impl TestProject {
&self.module_types, &self.module_types,
Tracing::All(TraceLevel::Verbose), Tracing::All(TraceLevel::Verbose),
&mut warnings, &mut warnings,
None,
) )
.expect("Failed to type-check module"); .expect("Failed to type-check module");

View File

@ -1,4 +1,3 @@
use aiken_lang::ast::Tracing;
use aiken_project::watch::with_project; use aiken_project::watch::with_project;
use std::path::PathBuf; use std::path::PathBuf;
@ -20,10 +19,6 @@ pub struct Args {
#[clap(long)] #[clap(long)]
delegated_to: Option<String>, delegated_to: Option<String>,
/// Force the project to be rebuilt, otherwise relies on existing artifacts (i.e. plutus.json)
#[clap(long)]
rebuild: bool,
/// Output the address for mainnet (this command defaults to testnet) /// Output the address for mainnet (this command defaults to testnet)
#[clap(long)] #[clap(long)]
mainnet: bool, mainnet: bool,
@ -35,15 +30,10 @@ pub fn exec(
module, module,
validator, validator,
delegated_to, delegated_to,
rebuild,
mainnet, mainnet,
}: Args, }: Args,
) -> miette::Result<()> { ) -> miette::Result<()> {
with_project(directory.as_deref(), false, |p| { with_project(directory.as_deref(), false, |p| {
if rebuild {
p.build(false, Tracing::silent())?;
}
let title = module.as_ref().map(|m| { let title = module.as_ref().map(|m| {
format!( format!(
"{m}{}", "{m}{}",

View File

@ -1,4 +1,3 @@
use aiken_lang::ast::Tracing;
use aiken_project::watch::with_project; use aiken_project::watch::with_project;
use std::path::PathBuf; use std::path::PathBuf;
@ -15,10 +14,6 @@ pub struct Args {
/// Name of the validator within the module. Optional if there's only one validator /// Name of the validator within the module. Optional if there's only one validator
#[clap(short, long)] #[clap(short, long)]
validator: Option<String>, validator: Option<String>,
/// Force the project to be rebuilt, otherwise relies on existing artifacts (i.e. plutus.json)
#[clap(long)]
rebuild: bool,
} }
pub fn exec( pub fn exec(
@ -26,14 +21,9 @@ pub fn exec(
directory, directory,
module, module,
validator, validator,
rebuild,
}: Args, }: Args,
) -> miette::Result<()> { ) -> miette::Result<()> {
with_project(directory.as_deref(), false, |p| { with_project(directory.as_deref(), false, |p| {
if rebuild {
p.build(false, Tracing::silent())?;
}
let title = module.as_ref().map(|m| { let title = module.as_ref().map(|m| {
format!( format!(
"{m}{}", "{m}{}",

View File

@ -1,4 +1,3 @@
use aiken_lang::ast::Tracing;
use aiken_project::watch::with_project; use aiken_project::watch::with_project;
use std::path::PathBuf; use std::path::PathBuf;
@ -15,10 +14,6 @@ pub struct Args {
/// Name of the validator within the module. Optional if there's only one validator /// Name of the validator within the module. Optional if there's only one validator
#[clap(short, long)] #[clap(short, long)]
validator: Option<String>, validator: Option<String>,
/// Force the project to be rebuilt, otherwise relies on existing artifacts (i.e. plutus.json)
#[clap(long)]
rebuild: bool,
} }
pub fn exec( pub fn exec(
@ -26,14 +21,9 @@ pub fn exec(
directory, directory,
module, module,
validator, validator,
rebuild,
}: Args, }: Args,
) -> miette::Result<()> { ) -> miette::Result<()> {
with_project(directory.as_deref(), false, |p| { with_project(directory.as_deref(), false, |p| {
if rebuild {
p.build(false, Tracing::silent())?;
}
let title = module.as_ref().map(|m| { let title = module.as_ref().map(|m| {
format!( format!(
"{m}{}", "{m}{}",

View File

@ -21,6 +21,10 @@ pub struct Args {
#[clap(short, long)] #[clap(short, long)]
uplc: bool, uplc: bool,
/// Environment to build against.
#[clap(long)]
env: Option<String>,
/// Filter traces to be included in the generated program(s). /// Filter traces to be included in the generated program(s).
/// ///
/// - user-defined: /// - user-defined:
@ -63,6 +67,7 @@ pub fn exec(
uplc, uplc,
filter_traces, filter_traces,
trace_level, trace_level,
env,
}: Args, }: Args,
) -> miette::Result<()> { ) -> miette::Result<()> {
let result = if watch { let result = if watch {
@ -73,6 +78,7 @@ pub fn exec(
Some(filter_traces) => filter_traces(trace_level), Some(filter_traces) => filter_traces(trace_level),
None => Tracing::All(trace_level), None => Tracing::All(trace_level),
}, },
env.clone(),
) )
}) })
} else { } else {
@ -83,6 +89,7 @@ pub fn exec(
Some(filter_traces) => filter_traces(trace_level), Some(filter_traces) => filter_traces(trace_level),
None => Tracing::All(trace_level), None => Tracing::All(trace_level),
}, },
env.clone(),
) )
}) })
}; };

View File

@ -48,6 +48,10 @@ pub struct Args {
#[clap(short, long)] #[clap(short, long)]
exact_match: bool, exact_match: bool,
/// Environment to build against.
#[clap(long)]
env: Option<String>,
/// Filter traces to be included in the generated program(s). /// Filter traces to be included in the generated program(s).
/// ///
/// - user-defined: /// - user-defined:
@ -95,6 +99,7 @@ pub fn exec(
trace_level, trace_level,
seed, seed,
max_success, max_success,
env,
}: Args, }: Args,
) -> miette::Result<()> { ) -> miette::Result<()> {
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
@ -114,6 +119,7 @@ pub fn exec(
Some(filter_traces) => filter_traces(trace_level), Some(filter_traces) => filter_traces(trace_level),
None => Tracing::All(trace_level), None => Tracing::All(trace_level),
}, },
env.clone(),
) )
}) })
} else { } else {
@ -129,6 +135,7 @@ pub fn exec(
Some(filter_traces) => filter_traces(trace_level), Some(filter_traces) => filter_traces(trace_level),
None => Tracing::All(trace_level), None => Tracing::All(trace_level),
}, },
env.clone(),
) )
}) })
}; };