Skip to content

Commit

Permalink
Nix the global TYPE_ENGINE (FuelLabs#3353)
Browse files Browse the repository at this point in the history
  • Loading branch information
Centril authored Nov 22, 2022
1 parent de22d2b commit fe6b76e
Show file tree
Hide file tree
Showing 107 changed files with 4,305 additions and 2,374 deletions.
23 changes: 22 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 7 additions & 7 deletions forc-pkg/src/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
sync::Arc,
};

use sway_core::{language::parsed::TreeType, parse};
use sway_core::{language::parsed::TreeType, parse_tree_type};
pub use sway_types::ConfigTimeConstant;
use sway_utils::constants;

Expand Down Expand Up @@ -277,14 +277,14 @@ impl PackageManifestFile {
/// Parse and return the associated project's program type.
pub fn program_type(&self) -> Result<TreeType> {
let entry_string = self.entry_string()?;
let parse_res = parse(entry_string, None);
match parse_res.value {
Some(parse_program) => Ok(parse_program.kind),
None => bail!(parsing_failed(&self.project.name, parse_res.errors)),
}
let parse_res = parse_tree_type(entry_string);
parse_res
.value
.ok_or_else(|| parsing_failed(&self.project.name, parse_res.errors))
}

/// Given the current directory and expected program type, determines whether the correct program type is present.
/// Given the current directory and expected program type,
/// determines whether the correct program type is present.
pub fn check_program_type(&self, expected_types: Vec<TreeType>) -> Result<()> {
let parsed_type = self.program_type()?;
if !expected_types.contains(&parsed_type) {
Expand Down
66 changes: 50 additions & 16 deletions forc-pkg/src/pkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ use std::{
path::{Path, PathBuf},
str::FromStr,
};
use sway_core::fuel_prelude::{
fuel_crypto,
fuel_tx::{self, Contract, ContractId, StorageSlot},
use sway_core::{
fuel_prelude::{
fuel_crypto,
fuel_tx::{self, Contract, ContractId, StorageSlot},
},
TypeEngine,
};
use sway_core::{
language::{
Expand Down Expand Up @@ -2094,8 +2097,9 @@ pub fn dependency_namespace(
graph: &Graph,
node: NodeIx,
constants: BTreeMap<String, ConfigTimeConstant>,
type_engine: &TypeEngine,
) -> Result<namespace::Module, vec1::Vec1<CompileError>> {
let mut namespace = namespace::Module::default_with_constants(constants)?;
let mut namespace = namespace::Module::default_with_constants(type_engine, constants)?;

// Add direct dependencies.
let mut core_added = false;
Expand Down Expand Up @@ -2126,7 +2130,7 @@ pub fn dependency_namespace(
public: true,
};
constants.insert(contract_dep_constant_name.to_string(), contract_id_constant);
namespace::Module::default_with_constants(constants)?
namespace::Module::default_with_constants(type_engine, constants)?
}
};
namespace.insert_submodule(dep_name, dep_namespace);
Expand All @@ -2144,10 +2148,18 @@ pub fn dependency_namespace(
}
}

namespace.star_import_with_reexports(&[CORE, PRELUDE].map(Ident::new_no_span), &[]);
namespace.star_import_with_reexports(
&[CORE, PRELUDE].map(Ident::new_no_span),
&[],
type_engine,
);

if has_std_dep(graph, node) {
namespace.star_import_with_reexports(&[STD, PRELUDE].map(Ident::new_no_span), &[]);
namespace.star_import_with_reexports(
&[STD, PRELUDE].map(Ident::new_no_span),
&[],
type_engine,
);
}

Ok(namespace)
Expand Down Expand Up @@ -2207,14 +2219,16 @@ fn find_core_dep(graph: &Graph, node: NodeIx) -> Option<NodeIx> {

/// Compiles the package to an AST.
pub fn compile_ast(
type_engine: &TypeEngine,
manifest: &PackageManifestFile,
build_profile: &BuildProfile,
namespace: namespace::Module,
) -> Result<CompileResult<ty::TyProgram>> {
let source = manifest.entry_string()?;
let sway_build_config =
sway_build_config(manifest.dir(), &manifest.entry_path(), build_profile)?;
let ast_res = sway_core::compile_to_ast(source, namespace, Some(&sway_build_config));
let ast_res =
sway_core::compile_to_ast(type_engine, source, namespace, Some(&sway_build_config));
Ok(ast_res)
}

Expand All @@ -2241,6 +2255,7 @@ pub fn compile(
manifest: &PackageManifestFile,
build_profile: &BuildProfile,
namespace: namespace::Module,
type_engine: &TypeEngine,
source_map: &mut SourceMap,
) -> Result<(BuiltPackage, namespace::Root)> {
// Time the given expression and print the result if `build_config.time_phases` is true.
Expand Down Expand Up @@ -2275,7 +2290,7 @@ pub fn compile(
// First, compile to an AST. We'll update the namespace and check for JSON ABI output.
let ast_res = time_expr!(
"compile to ast",
compile_ast(manifest, build_profile, namespace,)?
compile_ast(type_engine, manifest, build_profile, namespace)?
);
let typed_program = match ast_res.value.as_ref() {
None => return fail(&ast_res.warnings, &ast_res.errors),
Expand All @@ -2289,7 +2304,7 @@ pub fn compile(
let mut types = vec![];
let json_abi_program = time_expr!(
"generate JSON ABI program",
typed_program.generate_json_abi_program(&mut types)
typed_program.generate_json_abi_program(type_engine, &mut types)
);

let storage_slots = typed_program.storage_slots.clone();
Expand All @@ -2303,7 +2318,7 @@ pub fn compile(

let asm_res = time_expr!(
"compile ast to asm",
sway_core::ast_to_asm(ast_res, &sway_build_config)
sway_core::ast_to_asm(type_engine, ast_res, &sway_build_config)
);
let entries = asm_res
.value
Expand Down Expand Up @@ -2507,6 +2522,7 @@ pub fn build(
.flat_map(|output_node| plan.node_deps(*output_node))
.collect();

let type_engine = TypeEngine::default();
let mut lib_namespace_map = Default::default();
let mut compiled_contract_deps = HashMap::new();
for &node in plan
Expand All @@ -2524,14 +2540,22 @@ pub fn build(
&plan.graph,
node,
constants,
&type_engine,
) {
Ok(o) => o,
Err(errs) => {
print_on_failure(profile.terse, &[], &errs);
bail!("Failed to compile {}", pkg.name);
}
};
let res = compile(pkg, manifest, profile, dep_namespace, &mut source_map)?;
let res = compile(
pkg,
manifest,
profile,
dep_namespace,
&type_engine,
&mut source_map,
)?;
let (mut built_package, namespace) = res;
// If the current node is a contract dependency, collect the contract_id
if plan
Expand Down Expand Up @@ -2681,7 +2705,11 @@ type ParseAndTypedPrograms = CompileResult<(ParseProgram, Option<ty::TyProgram>)
/// Compile the entire forc package and return the parse and typed programs
/// of the dependancies and project.
/// The final item in the returned vector is the project.
pub fn check(plan: &BuildPlan, terse_mode: bool) -> anyhow::Result<Vec<ParseAndTypedPrograms>> {
pub fn check(
plan: &BuildPlan,
terse_mode: bool,
type_engine: &TypeEngine,
) -> anyhow::Result<Vec<ParseAndTypedPrograms>> {
//TODO remove once type engine isn't global anymore.
sway_core::clear_lazy_statics();
let mut lib_namespace_map = Default::default();
Expand All @@ -2700,13 +2728,14 @@ pub fn check(plan: &BuildPlan, terse_mode: bool) -> anyhow::Result<Vec<ParseAndT
&plan.graph,
node,
constants,
type_engine,
)
.expect("failed to create dependency namespace");
let CompileResult {
value,
mut warnings,
mut errors,
} = parse(manifest, terse_mode)?;
} = parse(manifest, terse_mode, type_engine)?;

let parse_program = match value {
None => {
Expand All @@ -2716,7 +2745,7 @@ pub fn check(plan: &BuildPlan, terse_mode: bool) -> anyhow::Result<Vec<ParseAndT
Some(program) => program,
};

let ast_result = sway_core::parsed_to_ast(&parse_program, dep_namespace);
let ast_result = sway_core::parsed_to_ast(type_engine, &parse_program, dep_namespace);
warnings.extend(ast_result.warnings);
errors.extend(ast_result.errors);

Expand Down Expand Up @@ -2750,14 +2779,19 @@ pub fn check(plan: &BuildPlan, terse_mode: bool) -> anyhow::Result<Vec<ParseAndT
pub fn parse(
manifest: &PackageManifestFile,
terse_mode: bool,
type_engine: &TypeEngine,
) -> anyhow::Result<CompileResult<ParseProgram>> {
let profile = BuildProfile {
terse: terse_mode,
..BuildProfile::debug()
};
let source = manifest.entry_string()?;
let sway_build_config = sway_build_config(manifest.dir(), &manifest.entry_path(), &profile)?;
Ok(sway_core::parse(source, Some(&sway_build_config)))
Ok(sway_core::parse(
source,
type_engine,
Some(&sway_build_config),
))
}

/// Attempt to find a `Forc.toml` with the given project name within the given directory.
Expand Down
5 changes: 3 additions & 2 deletions forc-plugins/forc-doc/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ use sway_core::{
};
use sway_types::Spanned;

#[derive(Eq, PartialEq, Debug)]
// TODO: See if there's a way we can use the TyDeclarations directly
//
/// The type of [TyDeclaration] documented by the [Descriptor].
#[derive(Debug)]
pub(crate) enum DescriptorType {
Struct(TyStructDeclaration),
Enum(TyEnumDeclaration),
Expand All @@ -24,6 +24,7 @@ pub(crate) enum DescriptorType {
Function(TyFunctionDeclaration),
Const(Box<TyConstantDeclaration>),
}

impl DescriptorType {
/// Converts the [DescriptorType] to a `&str` name for HTML file name creation.
pub fn as_str(&self) -> &'static str {
Expand All @@ -41,7 +42,6 @@ impl DescriptorType {
}
}

#[derive(Eq, PartialEq)]
/// Used in deciding whether or not a [Declaration] is documentable.
pub(crate) enum Descriptor {
Documentable {
Expand All @@ -52,6 +52,7 @@ pub(crate) enum Descriptor {
},
NonDocumentable,
}

impl Descriptor {
pub(crate) fn from_typed_decl(d: &TyDeclaration, module_prefix: Vec<String>) -> Result<Self> {
use TyDeclaration::*;
Expand Down
4 changes: 3 additions & 1 deletion forc-plugins/forc-doc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::{
process::Command as Process,
{fs, path::PathBuf},
};
use sway_core::TypeEngine;

use crate::{
doc::{Document, Documentation},
Expand Down Expand Up @@ -54,7 +55,8 @@ pub fn main() -> Result<()> {
let lock_path = manifest.lock_path()?;
let plan =
pkg::BuildPlan::from_lock_and_manifests(&lock_path, &member_manifests, locked, offline)?;
let compilation = pkg::check(&plan, silent)?
let type_engine = TypeEngine::default();
let compilation = pkg::check(&plan, silent, &type_engine)?
.pop()
.expect("there is guaranteed to be at least one elem in the vector");
let raw_docs: Documentation = Document::from_ty_program(&compilation, no_deps)?;
Expand Down
4 changes: 3 additions & 1 deletion forc/src/cli/commands/check.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::ops::forc_check;
use anyhow::Result;
use clap::Parser;
use sway_core::TypeEngine;

/// Check the current or target project and all of its dependencies for errors.
///
Expand All @@ -25,7 +26,8 @@ pub struct Command {
}

pub(crate) fn exec(command: Command) -> Result<()> {
let res = forc_check::check(command)?;
let type_engine = TypeEngine::default();
let res = forc_check::check(command, &type_engine)?;
if !res.is_ok() {
anyhow::bail!("unable to type check");
}
Expand Down
9 changes: 6 additions & 3 deletions forc/src/ops/forc_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ use anyhow::Result;
use forc_pkg::{self as pkg};
use pkg::manifest::ManifestFile;
use std::path::PathBuf;
use sway_core::{language::ty, CompileResult};
use sway_core::{language::ty, CompileResult, TypeEngine};

pub fn check(command: CheckCommand) -> Result<CompileResult<ty::TyProgram>> {
pub fn check(
command: CheckCommand,
type_engine: &TypeEngine,
) -> Result<CompileResult<ty::TyProgram>> {
let CheckCommand {
path,
offline_mode: offline,
Expand All @@ -24,7 +27,7 @@ pub fn check(command: CheckCommand) -> Result<CompileResult<ty::TyProgram>> {
let plan =
pkg::BuildPlan::from_lock_and_manifests(&lock_path, &member_manifests, locked, offline)?;

let mut v = pkg::check(&plan, terse_mode)?;
let mut v = pkg::check(&plan, terse_mode, type_engine)?;
let res = v
.pop()
.expect("there is guaranteed to be at least one elem in the vector")
Expand Down
1 change: 1 addition & 0 deletions sway-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ derivative = "2.2.0"
dirs = "3.0"
either = "1.6"
fuel-vm = { version = "0.22", features = ["serde"] }
hashbrown = "0.13.1"
hex = { version = "0.4", optional = true }
im = "15.0"
itertools = "0.10"
Expand Down
Loading

0 comments on commit fe6b76e

Please sign in to comment.