Skip to content

Commit

Permalink
Store source in an Arc<str> (FuelLabs#483)
Browse files Browse the repository at this point in the history
* make fields of Ident private

* Make Ident<'sc> not hold a &'sc str

* rename Ident::primary_name to Ident::as_str

* impl fmt::Display for Ident

* use Idents in warnings, rather than str

* use Idents in CompileError rather than &str

* switch to static spans

* remove pest dependency from forc and sway-server

* use Arc-based pest from github

* fix clippy lints

* remove remaining unused 'sc lifetimes

* run rustfmt
  • Loading branch information
canndrew authored Jan 5, 2022
1 parent 9ce8ef1 commit ff6f914
Show file tree
Hide file tree
Showing 103 changed files with 2,501 additions and 2,702 deletions.
365 changes: 147 additions & 218 deletions Cargo.lock

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions core_lang/src/parse_tree/expression/match_condition.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use super::Expression;

#[derive(Debug, Clone)]
pub(crate) enum MatchCondition {
CatchAll,
Expression(Box<Expression>),
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use super::*;
use crate::semantic_analysis::ast_node::TypedCodeBlock;
use either::Either;

#[allow(dead_code)]
#[derive(Clone, Debug)]
pub(crate) struct TypedMatchBranch {
condition: TypedMatchCondition,
result: Either<TypedCodeBlock, TypedExpression>,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use crate::semantic_analysis::TypedExpression;

#[allow(dead_code)]
#[derive(Clone, Debug)]
pub(crate) enum TypedMatchCondition {
CatchAll,
Expression(Box<TypedExpression>),
}
25 changes: 25 additions & 0 deletions core_lang/src/semantic_analysis/type_check_arguments.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use crate::build_config::BuildConfig;
use crate::control_flow_analysis::ControlFlowGraph;
use crate::parse_tree::declaration::Purity;
use crate::semantic_analysis::{ast_node::Mode, Namespace};
use crate::type_engine::*;

use std::collections::{HashMap, HashSet};
pub struct TypeCheckArguments<'a, T> {
pub(crate) checkee: T,
pub(crate) namespace: &'a mut Namespace,
pub(crate) crate_namespace: Option<&'a Namespace>,
pub(crate) return_type_annotation: TypeId,
pub(crate) help_text: &'static str,
pub(crate) self_type: TypeId,
pub(crate) build_config: &'a BuildConfig,
pub(crate) dead_code_graph: &'a mut ControlFlowGraph,
pub(crate) mode: Mode,
pub(crate) dependency_graph: &'a mut HashMap<String, HashSet<String>>,
pub(crate) opts: TCOpts,
}

#[derive(Default, Clone, Copy)]
pub struct TCOpts {
pub(crate) purity: Purity,
}
1 change: 0 additions & 1 deletion forc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ fuel-tx = "0.1"
fuel-vm = "0.1"
futures = "0.3"
hex = "0.4.3"
pest = { version = "3.0", package = "fuel-pest" }
prettydiff = "0.4.0"
reqwest = { version = "0.11.4", features = ["json"] }
semver = "1.0.3"
Expand Down
2 changes: 1 addition & 1 deletion forc/src/cli/commands/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(crate) fn exec(command: Command) -> Result<(), String> {
// Cargo args setup
let mut args: Vec<String> = vec!["test".into()];
if let Some(name) = command.test_name {
args.push(name)
args.push(name);
};
args.push("--color".into());
args.push("always".into());
Expand Down
26 changes: 11 additions & 15 deletions forc/src/ops/forc_abi_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use sway_core::{BuildConfig, CompileAstResult, Namespace, TreeType, TypedParseTree};

pub fn build(command: JsonAbiCommand) -> Result<Value, String> {
Expand Down Expand Up @@ -128,11 +129,11 @@ pub fn build(command: JsonAbiCommand) -> Result<Value, String> {

/// Takes a dependency and returns a namespace of exported things from that dependency
/// trait implementations are included as well
fn compile_dependency_lib<'source, 'manifest>(
fn compile_dependency_lib<'manifest>(
project_file_path: &Path,
dependency_name: &'manifest str,
dependency_lib: &mut Dependency,
namespace: &mut Namespace<'source>,
namespace: &mut Namespace,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
offline_mode: bool,
Expand Down Expand Up @@ -235,14 +236,14 @@ fn compile_dependency_lib<'source, 'manifest>(
Ok(json_abi)
}

fn compile_library<'source>(
source: &'source str,
fn compile_library(
source: Arc<str>,
proj_name: &str,
namespace: &Namespace<'source>,
namespace: &Namespace,
build_config: BuildConfig,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
) -> Result<(Namespace<'source>, Vec<Function>), String> {
) -> Result<(Namespace, Vec<Function>), String> {
let res = sway_core::compile_to_ast(source, namespace, &build_config, dependency_graph);
match res {
CompileAstResult::Success {
Expand All @@ -253,12 +254,7 @@ fn compile_library<'source>(
let errors = vec![];
match tree_type {
TreeType::Library { name } => {
print_on_success(
silent_mode,
proj_name,
warnings,
TreeType::Library { name: name.clone() },
);
print_on_success(silent_mode, proj_name, warnings, TreeType::Library { name });
let json_abi = generate_json_abi(&Some(*parse_tree.clone()));
Ok((parse_tree.into_namespace(), json_abi))
}
Expand All @@ -275,10 +271,10 @@ fn compile_library<'source>(
}
}

fn compile<'source>(
source: &'source str,
fn compile(
source: Arc<str>,
proj_name: &str,
namespace: &Namespace<'source>,
namespace: &Namespace,
build_config: BuildConfig,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
Expand Down
29 changes: 15 additions & 14 deletions forc/src/ops/forc_build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{
};
use std::fs::File;
use std::io::Write;
use std::sync::Arc;
use sway_core::{FinalizedAsm, TreeType};
use sway_utils::{constants, find_manifest_dir};

Expand Down Expand Up @@ -105,11 +106,11 @@ pub fn build(command: BuildCommand) -> Result<Vec<u8>, String> {

/// Takes a dependency and returns a namespace of exported things from that dependency
/// trait implementations are included as well
fn compile_dependency_lib<'source, 'manifest>(
fn compile_dependency_lib<'manifest>(
project_file_path: &Path,
dependency_name: &'manifest str,
dependency_lib: &mut Dependency,
namespace: &mut Namespace<'source>,
namespace: &mut Namespace,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
offline_mode: bool,
Expand Down Expand Up @@ -232,14 +233,14 @@ fn compile_dependency_lib<'source, 'manifest>(
Ok(())
}

fn compile_library<'source>(
source: &'source str,
fn compile_library(
source: Arc<str>,
proj_name: &str,
namespace: &Namespace<'source>,
namespace: &Namespace,
build_config: BuildConfig,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
) -> Result<Namespace<'source>, String> {
) -> Result<Namespace, String> {
let res = sway_core::compile_to_asm(source, namespace, build_config, dependency_graph);
match res {
CompilationResult::Library {
Expand All @@ -263,10 +264,10 @@ fn compile_library<'source>(
}
}

fn compile<'source>(
source: &'source str,
fn compile(
source: Arc<str>,
proj_name: &str,
namespace: &Namespace<'source>,
namespace: &Namespace,
build_config: BuildConfig,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
Expand All @@ -283,19 +284,19 @@ fn compile<'source>(
}
BytecodeCompilationResult::Failure { errors, warnings } => {
print_on_failure(silent_mode, warnings, errors);
return Err(format!("Failed to compile {}", proj_name));
Err(format!("Failed to compile {}", proj_name))
}
}
}

fn compile_to_asm<'sc>(
source: &'sc str,
fn compile_to_asm(
source: Arc<str>,
proj_name: &str,
namespace: &Namespace<'sc>,
namespace: &Namespace,
build_config: BuildConfig,
dependency_graph: &mut HashMap<String, HashSet<String>>,
silent_mode: bool,
) -> Result<FinalizedAsm<'sc>, String> {
) -> Result<FinalizedAsm, String> {
let res = sway_core::compile_to_asm(source, namespace, build_config, dependency_graph);
match res {
CompilationResult::Success { asm, warnings } => {
Expand Down
7 changes: 4 additions & 3 deletions forc/src/ops/forc_fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::cli::{BuildCommand, FormatCommand};
use crate::ops::forc_build;
use crate::utils::helpers::{println_green, println_red};
use prettydiff::{basic::DiffOp, diff_lines};
use std::{fmt, fs, io, path::Path};
use std::{fmt, fs, io, path::Path, sync::Arc};
use sway_fmt::get_formatted_data;
use sway_utils::{find_manifest_dir, get_sway_files};

Expand Down Expand Up @@ -36,10 +36,11 @@ fn format_after_build(command: FormatCommand) -> Result<(), FormatError> {
for file in files {
if let Ok(file_content) = fs::read_to_string(&file) {
// todo: get tab_size from Manifest file
match get_formatted_data(&file_content, 4) {
let file_content: Arc<str> = Arc::from(file_content);
match get_formatted_data(file_content.clone(), 4) {
Ok((_, formatted_content)) => {
if command.check {
if file_content != formatted_content {
if *file_content != *formatted_content {
let changeset = diff_lines(&file_content, &formatted_content);

println!("\n{:?}\n", file);
Expand Down
13 changes: 5 additions & 8 deletions forc/src/utils/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::ffi::OsStr;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::str;
use std::sync::Arc;
use sway_core::{CompileError, CompileWarning, TreeType};
use sway_utils::constants;
use termcolor::{self, Color as TermColor, ColorChoice, ColorSpec, StandardStream, WriteColor};
Expand Down Expand Up @@ -55,10 +56,7 @@ pub fn read_manifest(manifest_dir: &Path) -> Result<Manifest, String> {
}
}

pub fn get_main_file(
manifest_of_dep: &Manifest,
manifest_dir: &Path,
) -> Result<&'static mut String, String> {
pub fn get_main_file(manifest_of_dep: &Manifest, manifest_dir: &Path) -> Result<Arc<str>, String> {
let main_path = {
let mut code_dir = PathBuf::from(manifest_dir);
code_dir.push(constants::SRC_DIR);
Expand All @@ -68,16 +66,15 @@ pub fn get_main_file(

// some hackery to get around lifetimes for now, until the AST returns a non-lifetime-bound AST
let main_file = std::fs::read_to_string(&main_path).map_err(|e| e.to_string())?;
let main_file = Box::new(main_file);
let main_file: &'static mut String = Box::leak(main_file);
let main_file = Arc::from(main_file);
Ok(main_file)
}

pub fn print_on_success<'sc>(
pub fn print_on_success(
silent_mode: bool,
proj_name: &str,
warnings: Vec<CompileWarning>,
tree_type: TreeType<'sc>,
tree_type: TreeType,
) {
let type_str = match tree_type {
TreeType::Script {} => "script",
Expand Down
4 changes: 2 additions & 2 deletions forc/src/utils/manifest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,14 @@ fn default_url() -> String {
fn try_parse() {
println!(
"{:#?}",
toml::from_str::<Manifest>(&super::defaults::default_manifest("test_proj".into())).unwrap()
toml::from_str::<Manifest>(&super::defaults::default_manifest("test_proj")).unwrap()
)
}

#[test]
fn test_print_tx_inputs() {
let mut default_manifest: Manifest =
toml::from_str::<Manifest>(&super::defaults::default_manifest("test_proj".into())).unwrap();
toml::from_str::<Manifest>(&super::defaults::default_manifest("test_proj")).unwrap();

let input1 = TxInput {
contract_id: Some(
Expand Down
4 changes: 2 additions & 2 deletions sway-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ fuel-vm = "0.1"
hex = { version = "0.4", optional = true }
lazy_static = "1.4"
line-col = "0.2"
pest = { version = "3.0", package = "fuel-pest" }
pest_derive = "2.0"
pest = { git = "https://github.com/canndrew/pest", rev = "51f47bbaccea15458ad6ac3cd5421d6c9f4f6279" }
pest_derive = { git = "https://github.com/canndrew/pest", rev = "51f47bbaccea15458ad6ac3cd5421d6c9f4f6279" }
petgraph = "0.5"
sha2 = "0.9"
smallvec = "1.7"
Expand Down
6 changes: 3 additions & 3 deletions sway-core/src/asm_generation/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::error::*;
/// Checks for disallowed opcodes in non-contract code.
/// i.e., if this is a script or predicate, we can't use certain contract opcodes.
/// See https://github.com/FuelLabs/sway/issues/350 for details.
pub fn check_invalid_opcodes<'sc>(asm: &FinalizedAsm<'sc>) -> CompileResult<'sc, ()> {
pub fn check_invalid_opcodes(asm: &FinalizedAsm) -> CompileResult<()> {
match asm {
FinalizedAsm::ContractAbi { .. } | FinalizedAsm::Library => ok((), vec![], vec![]),
FinalizedAsm::ScriptMain {
Expand All @@ -23,10 +23,10 @@ pub fn check_invalid_opcodes<'sc>(asm: &FinalizedAsm<'sc>) -> CompileResult<'sc,

/// Checks if an opcode is one that can only be executed from within a contract. If so, throw an
/// error.
fn check_for_contract_opcodes<'sc>(ops: &[AllocatedOp<'sc>]) -> CompileResult<'sc, ()> {
fn check_for_contract_opcodes(ops: &[AllocatedOp]) -> CompileResult<()> {
use AllocatedOpcode::*;
let default_span = crate::Span {
span: pest::Span::new("no span found for opcode", 0, 1).unwrap(),
span: pest::Span::new("no span found for opcode".into(), 0, 1).unwrap(),
path: None,
};
let mut errors = vec![];
Expand Down
8 changes: 4 additions & 4 deletions sway-core/src/asm_generation/declaration/const_decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ use crate::{

/// Provisions a register to put a value in, and then adds the assembly used to initialize the
/// value to the end of the buffer.
pub(crate) fn convert_constant_decl_to_asm<'sc>(
const_decl: &TypedConstantDeclaration<'sc>,
namespace: &mut AsmNamespace<'sc>,
pub(crate) fn convert_constant_decl_to_asm(
const_decl: &TypedConstantDeclaration,
namespace: &mut AsmNamespace,
register_sequencer: &mut RegisterSequencer,
) -> CompileResult<'sc, Vec<Op<'sc>>> {
) -> CompileResult<Vec<Op>> {
let val_register = register_sequencer.next();
let initialization = convert_expression_to_asm(
&const_decl.value,
Expand Down
6 changes: 3 additions & 3 deletions sway-core/src/asm_generation/declaration/fn_decl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ use crate::{
TypedFunctionDeclaration,
};

pub(crate) fn convert_fn_decl_to_asm<'sc>(
_decl: &TypedFunctionDeclaration<'sc>,
pub(crate) fn convert_fn_decl_to_asm(
_decl: &TypedFunctionDeclaration,
_namespace: &mut AsmNamespace,
_register_sequencer: &mut RegisterSequencer,
) -> CompileResult<'sc, Vec<Op<'sc>>> {
) -> CompileResult<Vec<Op>> {
// for now, we inline all functions as a shortcut.
ok(vec![], vec![], vec![])
}
10 changes: 5 additions & 5 deletions sway-core/src/asm_generation/declaration/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ pub(crate) use fn_decl::convert_fn_decl_to_asm;
pub(crate) use reassignment::convert_reassignment_to_asm;
pub(crate) use var_decl::convert_variable_decl_to_asm;

pub(crate) fn convert_decl_to_asm<'sc>(
decl: &TypedDeclaration<'sc>,
namespace: &mut AsmNamespace<'sc>,
pub(crate) fn convert_decl_to_asm(
decl: &TypedDeclaration,
namespace: &mut AsmNamespace,
register_sequencer: &mut RegisterSequencer,
) -> CompileResult<'sc, Vec<Op<'sc>>> {
) -> CompileResult<Vec<Op>> {
match decl {
// For an enum declaration, we don't generate any asm.
TypedDeclaration::EnumDeclaration(_) => ok(vec![], vec![], vec![]),
Expand All @@ -42,7 +42,7 @@ pub(crate) fn convert_decl_to_asm<'sc>(
vec![],
vec![CompileError::Unimplemented(
"ASM generation has not yet been implemented for this declaration variant.",
decl.span().clone(),
decl.span(),
)],
),
}
Expand Down
Loading

0 comments on commit ff6f914

Please sign in to comment.