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 51 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 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
8df8f4b
prepend_module_path(vec[]) is the same as current_mod_path()
jjcnn Sep 16, 2024
285bf01
Merge branch 'master' of github.com:FuelLabs/sway into jjcnn/move-ext…
jjcnn Sep 16, 2024
6b2e03c
Add enum name to enum variant paths
jjcnn Oct 4, 2024
35f0ba4
Partial merge of master
jjcnn Oct 11, 2024
eb34879
Merge finalized
jjcnn Oct 11, 2024
7ec3af9
Fixed resolution of enum names
jjcnn Oct 15, 2024
512ce8a
Renamed CallPathType::Resolved to CallPathType::Full
jjcnn Oct 15, 2024
6185867
Make CallPath::to_fullpath work on all cloneable suffixes
jjcnn Oct 18, 2024
2a4ffe4
Temporary save
jjcnn Oct 18, 2024
1c2b602
Fix visibility check for method applications within the same module
jjcnn Oct 18, 2024
f4fffc8
Fix mod path for abis
jjcnn Oct 20, 2024
a1740d6
Merge
jjcnn Oct 21, 2024
ecce5d7
Fix resolution of enum variant paths
jjcnn Oct 22, 2024
eda97db
Fix resolution of absolute and relative paths for modules
jjcnn Oct 22, 2024
64c98ba
Add comment about module paths during path resolution
jjcnn Oct 22, 2024
f799d08
Merge
jjcnn Oct 24, 2024
6d50867
Merge
jjcnn Oct 24, 2024
e521b9d
Fix privacy check for module paths
jjcnn Oct 29, 2024
246b25c
Fix privacy check for module paths
jjcnn Oct 29, 2024
3667762
Merge
jjcnn Oct 29, 2024
57afd26
Merge
jjcnn Nov 27, 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 @@ -40,7 +40,7 @@ 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,
Expand All @@ -49,7 +49,7 @@ use sway_core::{
use sway_core::{set_bytecode_configurables_offset, PrintAsm, PrintIr};
use sway_error::{error::CompileError, handler::Handler, warning::CompileWarning};
use sway_features::ExperimentalFeatures;
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 @@ -181,7 +181,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 @@ -1569,9 +1569,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 @@ -1585,7 +1582,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 @@ -1596,30 +1593,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 @@ -1630,17 +1622,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 @@ -1651,51 +1636,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 @@ -1755,7 +1718,7 @@ pub fn compile(
pkg: &PackageDescriptor,
profile: &BuildProfile,
engines: &Engines,
namespace: &mut namespace::Root,
namespace: namespace::Root,
source_map: &mut SourceMap,
experimental: ExperimentalFeatures,
) -> Result<CompiledPackage> {
Expand Down Expand Up @@ -1980,7 +1943,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 @@ -2488,7 +2451,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 @@ -2505,7 +2468,7 @@ pub fn build(
&descriptor,
&profile,
&engines,
&mut dep_namespace,
dep_namespace,
&mut source_map,
experimental,
)?;
Expand Down Expand Up @@ -2553,7 +2516,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 @@ -2579,7 +2542,7 @@ pub fn build(
&descriptor,
&profile,
&engines,
&mut dep_namespace,
dep_namespace,
&mut source_map,
experimental,
)?;
Expand Down Expand Up @@ -2659,7 +2622,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 @@ -2690,7 +2653,7 @@ pub fn check(
&handler,
engines,
input,
&mut dep_namespace,
dep_namespace,
Some(&build_config),
&pkg.name,
retrigger_compilation.clone(),
Expand All @@ -2714,12 +2677,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 @@ -2728,7 +2691,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 @@ -166,7 +166,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 @@ -176,7 +176,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 @@ -189,7 +189,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 @@ -200,7 +200,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