Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Refactor the module structure of the namespace module #6291

Draft
wants to merge 30 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
8aa2e55
Make module name mandatory and private
jjcnn Jul 15, 2024
aa9fec4
Merge branch 'master' of github.com:FuelLabs/sway into jjcnn/encapsul…
jjcnn Jul 15, 2024
158dfd9
Encapsulate visiblity and span fiels of Module
jjcnn Jul 16, 2024
9c301f2
Merge branch 'master' into jjcnn/encapsulate-namespace-module
jjcnn Jul 16, 2024
b87dcd1
Fix sway-core tests
jjcnn Jul 16, 2024
329fecb
clippy; fmt
jjcnn Jul 16, 2024
19ecf89
Save game
jjcnn Jul 21, 2024
d7061c1
Rebase
jjcnn Jul 22, 2024
960b2b5
Namespace module builds, interface defined
jjcnn Jul 22, 2024
74ca425
Change to new namespace interface
jjcnn Jul 23, 2024
3f802bb
Merge branch 'master' of github.com:FuelLabs/sway into jjcnn/move-ext…
jjcnn Jul 25, 2024
428996a
Change externals to be packages rather than modules
jjcnn Jul 29, 2024
1b06988
forc-pkg and sway-lsp usage of namespace module updated
jjcnn Jul 31, 2024
fcf2644
Updated test harness
jjcnn Aug 1, 2024
20863df
Merge branch 'master' of github.com:FuelLabs/sway into jjcnn/move-ext…
jjcnn Aug 1, 2024
d463cf8
Simplify compilation of core during testing
jjcnn Aug 1, 2024
93aab4d
Ensure the preludes are imported into all modules
jjcnn Aug 2, 2024
a63db83
Root module is not visited before its submodules
jjcnn Aug 2, 2024
3fc997f
Remove SubmoduleNamespace
jjcnn Aug 6, 2024
a76a1ee
Rename is_absolute to is_relative_to_package_root, convert relative p…
jjcnn Aug 7, 2024
019c089
Pop submodule when done typechecking it
jjcnn Aug 7, 2024
3a45380
Fix various path issues
jjcnn Aug 12, 2024
e6bbc60
Fix require_module
jjcnn Aug 13, 2024
4f80b55
Fix resolution of ambiguous paths
jjcnn Aug 15, 2024
a17290e
Merge
jjcnn Aug 16, 2024
c028199
Changed CallPath.is_absolute to CallPath.callpath_type
jjcnn Aug 16, 2024
cacbd4e
Merge
jjcnn Sep 3, 2024
51a673c
Fix path in shadow check in asm blocks
jjcnn Sep 5, 2024
b2b2893
Merge
jjcnn Sep 13, 2024
b1ec95c
Do not require core as external
jjcnn Sep 13, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 47 additions & 84 deletions forc-pkg/src/pkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ use sway_core::{
fuel_crypto,
fuel_tx::{self, Contract, ContractId, StorageSlot},
},
language::{parsed::TreeType, Visibility},
language::parsed::TreeType,
semantic_analysis::namespace,
source_map::SourceMap,
transform::AttributeKind,
write_dwarf, BuildTarget, Engines, FinalizedEntry, LspConfig,
};
use sway_core::{PrintAsm, PrintIr};
use sway_error::{error::CompileError, handler::Handler, warning::CompileWarning};
use sway_types::constants::{CORE, PRELUDE, STD};
use sway_types::constants::{CORE, STD};
use sway_types::{Ident, Span, Spanned};
use sway_utils::{constants, time_expr, PerformanceData, PerformanceMetric};
use tracing::{debug, info};
Expand Down Expand Up @@ -183,7 +183,7 @@ pub struct CompiledPackage {
pub program_abi: ProgramABI,
pub storage_slots: Vec<StorageSlot>,
pub bytecode: BuiltPackageBytecode,
pub root_module: namespace::Module,
pub root_module: namespace::Root,
pub warnings: Vec<CompileWarning>,
pub metrics: PerformanceData,
}
Expand Down Expand Up @@ -1572,9 +1572,6 @@ pub fn sway_build_config(
Ok(build_config)
}

/// The name of the constant holding the contract's id.
pub const CONTRACT_ID_CONSTANT_NAME: &str = "CONTRACT_ID";

/// Builds the dependency namespace for the package at the given node index within the graph.
///
/// This function is designed to be called for each node in order of compilation.
Expand All @@ -1588,7 +1585,7 @@ pub const CONTRACT_ID_CONSTANT_NAME: &str = "CONTRACT_ID";
/// `contract_id_value` should only be Some when producing the `dependency_namespace` for a contract with tests enabled.
/// This allows us to provide a contract's `CONTRACT_ID` constant to its own unit tests.
pub fn dependency_namespace(
lib_namespace_map: &HashMap<NodeIx, namespace::Module>,
lib_namespace_map: &HashMap<NodeIx, namespace::Root>,
compiled_contract_deps: &CompiledContractDeps,
graph: &Graph,
node: NodeIx,
Expand All @@ -1599,30 +1596,25 @@ pub fn dependency_namespace(
// TODO: Clean this up when config-time constants v1 are removed.
let node_idx = &graph[node];
let name = Ident::new_no_span(node_idx.name.clone());
let mut root_module = if let Some(contract_id_value) = contract_id_value {
namespace::default_with_contract_id(
engines,
name.clone(),
Visibility::Public,
contract_id_value,
experimental,
)?
} else {
namespace::Module::new(name, Visibility::Public, None)
};

let mut root_namespace =
if let Some(contract_id_value) = contract_id_value {
namespace::namespace_with_contract_id(engines, name.clone(), contract_id_value, experimental)?
} else {
namespace::namespace_without_contract_id(name.clone())
};

// Add direct dependencies.
let mut core_added = false;
for edge in graph.edges_directed(node, Direction::Outgoing) {
let dep_node = edge.target();
let dep_name = kebab_to_snake_case(&edge.weight().name);
let dep_edge = edge.weight();
let mut dep_namespace = match dep_edge.kind {
let dep_namespace = match dep_edge.kind {
DepKind::Library => lib_namespace_map
.get(&dep_node)
.cloned()
.expect("no namespace module")
.read(engines, Clone::clone),
.expect("no root module")
.clone(),
DepKind::Contract { salt } => {
let dep_contract_id = compiled_contract_deps
.get(&dep_node)
Expand All @@ -1633,17 +1625,10 @@ pub fn dependency_namespace(
let contract_id_value = format!("0x{dep_contract_id}");
let node_idx = &graph[dep_node];
let name = Ident::new_no_span(node_idx.name.clone());
namespace::default_with_contract_id(
engines,
name.clone(),
Visibility::Private,
contract_id_value,
experimental,
)?
namespace::namespace_with_contract_id(engines, name.clone(), contract_id_value, experimental)?
}
};
dep_namespace.is_external = true;
root_module.insert_submodule(dep_name, dep_namespace);
root_namespace.add_external(dep_name, dep_namespace);
let dep = &graph[dep_node];
if dep.name == CORE {
core_added = true;
Expand All @@ -1654,51 +1639,29 @@ pub fn dependency_namespace(
if !core_added {
if let Some(core_node) = find_core_dep(graph, node) {
let core_namespace = &lib_namespace_map[&core_node];
root_module.insert_submodule(CORE.to_string(), core_namespace.clone());
core_added = true;
root_namespace.add_external(CORE.to_string(), core_namespace.clone());
// core_added = true;
}
}

let mut root = namespace::Root::from(root_module);

if core_added {
let _ = root.star_import(
&Handler::default(),
engines,
&[CORE, PRELUDE].map(|s| Ident::new_no_span(s.into())),
&[],
Visibility::Private,
);
}

if has_std_dep(graph, node) {
let _ = root.star_import(
&Handler::default(),
engines,
&[STD, PRELUDE].map(|s| Ident::new_no_span(s.into())),
&[],
Visibility::Private,
);
}

Ok(root)
Ok(root_namespace)
}

/// Find the `std` dependency, if it is a direct one, of the given node.
fn has_std_dep(graph: &Graph, node: NodeIx) -> bool {
// If we are `std`, do nothing.
let pkg = &graph[node];
if pkg.name == STD {
return false;
}

// If we have `std` as a direct dep, use it.
graph.edges_directed(node, Direction::Outgoing).any(|edge| {
let dep_node = edge.target();
let dep = &graph[dep_node];
matches!(&dep.name[..], STD)
})
}
///// Find the `std` dependency, if it is a direct one, of the given node.
//fn has_std_dep(graph: &Graph, node: NodeIx) -> bool {
// // If we are `std`, do nothing.
// let pkg = &graph[node];
// if pkg.name == STD {
// return false;
// }
//
// // If we have `std` as a direct dep, use it.
// graph.edges_directed(node, Direction::Outgoing).any(|edge| {
// let dep_node = edge.target();
// let dep = &graph[dep_node];
// matches!(&dep.name[..], STD)
// })
//}

/// Find the `core` dependency (whether direct or transitive) for the given node if it exists.
fn find_core_dep(graph: &Graph, node: NodeIx) -> Option<NodeIx> {
Expand Down Expand Up @@ -1758,7 +1721,7 @@ pub fn compile(
pkg: &PackageDescriptor,
profile: &BuildProfile,
engines: &Engines,
namespace: &mut namespace::Root,
namespace: namespace::Root,
source_map: &mut SourceMap,
) -> Result<CompiledPackage> {
let mut metrics = PerformanceData::default();
Expand Down Expand Up @@ -1953,7 +1916,7 @@ pub fn compile(
storage_slots,
tree_type,
bytecode,
root_module: namespace.root_module().clone(),
root_module: namespace.root().clone(),
warnings,
metrics,
};
Expand Down Expand Up @@ -2380,7 +2343,7 @@ pub fn build(

// `ContractIdConst` is a None here since we do not yet have a
// contract ID value at this point.
let mut dep_namespace = match dependency_namespace(
let dep_namespace = match dependency_namespace(
&lib_namespace_map,
&compiled_contract_deps,
plan.graph(),
Expand All @@ -2397,7 +2360,7 @@ pub fn build(
&descriptor,
&profile,
&engines,
&mut dep_namespace,
dep_namespace,
&mut source_map,
)?;

Expand Down Expand Up @@ -2444,7 +2407,7 @@ pub fn build(
};

// Note that the contract ID value here is only Some if tests are enabled.
let mut dep_namespace = match dependency_namespace(
let dep_namespace = match dependency_namespace(
&lib_namespace_map,
&compiled_contract_deps,
plan.graph(),
Expand All @@ -2470,7 +2433,7 @@ pub fn build(
&descriptor,
&profile,
&engines,
&mut dep_namespace,
dep_namespace,
&mut source_map,
)?;

Expand Down Expand Up @@ -2541,7 +2504,7 @@ pub fn check(
let contract_id_value =
(idx == plan.compilation_order.len() - 1).then(|| DUMMY_CONTRACT_ID.to_string());

let mut dep_namespace = dependency_namespace(
let dep_namespace = dependency_namespace(
&lib_namespace_map,
&compiled_contract_deps,
&plan.graph,
Expand Down Expand Up @@ -2572,7 +2535,7 @@ pub fn check(
&handler,
engines,
input,
&mut dep_namespace,
dep_namespace,
Some(&build_config),
&pkg.name,
retrigger_compilation.clone(),
Expand All @@ -2595,12 +2558,12 @@ pub fn check(

if let Ok(typed_program) = programs.typed.as_ref() {
if let TreeType::Library = typed_program.kind.tree_type() {
let mut module = typed_program
let mut lib_root = typed_program
.root
.namespace
.program_id(engines)
.read(engines, |m| m.clone());
module.set_span(
.clone()
.root();
lib_root.add_span_to_root_module(
Span::new(
manifest.entry_string()?,
0,
Expand All @@ -2609,7 +2572,7 @@ pub fn check(
)
.unwrap(),
);
lib_namespace_map.insert(node, module);
lib_namespace_map.insert(node, lib_root);
}
source_map.insert_dependency(manifest.dir());
} else {
Expand Down
18 changes: 10 additions & 8 deletions sway-core/src/abi_generation/fuel_abi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,16 @@ pub struct AbiContext<'a> {
}

impl<'a> AbiContext<'a> {
fn to_str_context(&self, engines: &Engines, abi_full: bool) -> AbiStrContext {
fn to_str_context(
&self,
abi_full: bool,
) -> AbiStrContext {
AbiStrContext {
program_name: self
.program
.root
.namespace
.program_id(engines)
.read(engines, |m| m.name().to_string()),
.current_package_name().to_string(),
abi_with_callpaths: self.abi_with_callpaths,
abi_with_fully_specified_types: abi_full,
abi_root_type_without_generic_type_parameters: !abi_full,
Expand All @@ -50,8 +52,8 @@ impl TypeId {
.program
.root
.namespace
.program_id(engines)
.read(engines, |m| m.name().clone().as_str().to_string()),
.current_package_name()
.to_string(),
abi_with_callpaths: true,
abi_with_fully_specified_types: true,
abi_root_type_without_generic_type_parameters: false,
Expand Down Expand Up @@ -382,7 +384,7 @@ fn generate_concrete_type_declaration(
let type_metadata_decl = program_abi::TypeMetadataDeclaration {
metadata_type_id: MetadataTypeId(type_id.index()),
type_field: type_id.get_abi_type_str(
&ctx.to_str_context(engines, false),
&ctx.to_str_context(false),
engines,
resolved_type_id,
),
Expand Down Expand Up @@ -476,7 +478,7 @@ fn generate_type_metadata_declaration(
let type_metadata_decl = program_abi::TypeMetadataDeclaration {
metadata_type_id: MetadataTypeId(type_id.index()),
type_field: type_id.get_abi_type_str(
&ctx.to_str_context(engines, false),
&ctx.to_str_context(false),
engines,
resolved_type_id,
),
Expand Down Expand Up @@ -1249,7 +1251,7 @@ impl TypeParameter {
let type_parameter = program_abi::TypeMetadataDeclaration {
metadata_type_id: type_id.clone(),
type_field: self.initial_type_id.get_abi_type_str(
&ctx.to_str_context(engines, false),
&ctx.to_str_context(false),
engines,
self.type_id,
),
Expand Down
6 changes: 3 additions & 3 deletions sway-core/src/control_flow_analysis/dead_code_analysis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
self, ConfigurableDecl, ConstantDecl, FunctionDecl, ProjectionKind, StructDecl,
TraitDecl, TyAstNode, TyAstNodeContent, TyDecl, TyImplItem, TypeAliasDecl,
},
CallPath, Visibility,
CallPath, CallPathType, Visibility,
},
transform::{self, AttributesMap},
type_system::TypeInfo,
Expand Down Expand Up @@ -857,7 +857,7 @@ fn connect_trait_declaration(
CallPath {
prefixes: vec![],
suffix: decl.name.clone(),
is_absolute: false,
callpath_type: CallPathType::Ambiguous,
},
TraitNamespaceEntry {
trait_idx: entry_node,
Expand All @@ -881,7 +881,7 @@ fn connect_abi_declaration(
CallPath {
prefixes: vec![],
suffix: decl.name.clone(),
is_absolute: false,
callpath_type: CallPathType::Ambiguous,
},
TraitNamespaceEntry {
trait_idx: entry_node,
Expand Down
8 changes: 4 additions & 4 deletions sway-core/src/ir_generation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ pub fn compile_program<'eng>(
engines,
&mut ctx,
entry_function,
root.namespace.module(engines),
root.namespace.current_module(),
&logged_types,
&messages_types,
&test_fns,
Expand All @@ -180,7 +180,7 @@ pub fn compile_program<'eng>(
engines,
&mut ctx,
entry_function,
root.namespace.module(engines),
root.namespace.current_module(),
&logged_types,
&messages_types,
&test_fns,
Expand All @@ -193,7 +193,7 @@ pub fn compile_program<'eng>(
&mut ctx,
entry_function.as_ref(),
abi_entries,
root.namespace.module(engines),
root.namespace.current_module(),
declarations,
&logged_types,
&messages_types,
Expand All @@ -204,7 +204,7 @@ pub fn compile_program<'eng>(
ty::TyProgramKind::Library { .. } => compile::compile_library(
engines,
&mut ctx,
root.namespace.module(engines),
root.namespace.current_module(),
&logged_types,
&messages_types,
&test_fns,
Expand Down
Loading
Loading