Skip to content

Commit

Permalink
New encoding fixes (#5745)
Browse files Browse the repository at this point in the history
## Description

This PR contains three fixes:

1 - Fix to partial monomorphization. The fix was just removing a
"quick-fix" that was merged and it is not needed anymore after
#5684;
2 - To play safe, `compile_fn_call` cache will not be used for
autogenerated code;
3 - `experimental-new-encoding` was not being copied in all cases.

Two other small changes are:

1 - `Buffer` struct does not offer a generic `push` anymore, because
this function was extremely deceiving for primitive datatypes which have
memory layouts very different from the encoding memory layout (u16, u32
etc...);
2 - Changing name of one test to make the test more obvious and easier
to run just one specific test.

## Checklist

- [ ] I have linked to any relevant issues.
- [ ] I have commented my code, particularly in hard-to-understand
areas.
- [ ] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] I have added tests that prove my fix is effective or that my
feature works.
- [ ] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [ ] I have done my best to ensure that my PR adheres to [the Fuel Labs
Code Review
Standards](https://github.com/FuelLabs/rfcs/blob/master/text/code-standards/external-contributors.md).
- [ ] I have requested a review from the relevant team or maintainers.
  • Loading branch information
xunilrj authored Mar 20, 2024
1 parent 9e51eeb commit 98cdaac
Show file tree
Hide file tree
Showing 43 changed files with 532 additions and 134 deletions.
6 changes: 4 additions & 2 deletions sway-core/src/build_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ impl BuildConfig {
time_phases: false,
metrics_outfile: None,
optimization_level: OptLevel::Opt0,
experimental: ExperimentalFlags::default(),
experimental: ExperimentalFlags {
new_encoding: false,
},
lsp_mode: None,
}
}
Expand Down Expand Up @@ -203,7 +205,7 @@ impl BuildConfig {
}
}

#[derive(Debug, Default, Clone, Copy)]
#[derive(Debug, Clone, Copy)]
pub struct ExperimentalFlags {
pub new_encoding: bool,
}
Expand Down
7 changes: 6 additions & 1 deletion sway-core/src/ir_generation/const_eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,12 @@ mod tests {
fn assert_is_constant(is_constant: bool, prefix: &str, expr: &str) {
let engines = Engines::default();
let handler = Handler::default();
let mut context = Context::new(engines.se(), sway_ir::ExperimentalFlags::default());
let mut context = Context::new(
engines.se(),
sway_ir::ExperimentalFlags {
new_encoding: false,
},
);
let mut md_mgr = MetadataManager::default();
let core_lib = namespace::Root::from(namespace::Module {
name: Some(sway_types::Ident::new_no_span(
Expand Down
16 changes: 13 additions & 3 deletions sway-core/src/ir_generation/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1823,7 +1823,18 @@ impl<'eng> FnCompiler<'eng> {
// args and type parameters. It's using the Sway types rather than IR types, which would
// be more accurate but also more fiddly.

let (fn_key, item) = if !callee.span().as_str().is_empty() {
let no_span = callee.span().as_str().is_empty();
let is_autogenerated = if let Some(s) = callee.span.source_id() {
context
.source_engine
.get_path(s)
.starts_with("<autogenerated>")
} else {
false
};
let (fn_key, item) = if no_span || is_autogenerated {
(None, None)
} else {
let fn_key = (
callee.span(),
callee
Expand All @@ -1833,12 +1844,11 @@ impl<'eng> FnCompiler<'eng> {
.collect(),
callee.type_parameters.iter().map(|tp| tp.type_id).collect(),
);

(
Some(fn_key.clone()),
self.recreated_fns.get(&fn_key).copied(),
)
} else {
(None, None)
};

let new_callee = match item {
Expand Down
18 changes: 15 additions & 3 deletions sway-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,14 @@ pub fn parse(
config: Option<&BuildConfig>,
) -> Result<(lexed::LexedProgram, parsed::ParseProgram), ErrorEmitted> {
match config {
None => parse_in_memory(handler, engines, input),
None => parse_in_memory(
handler,
engines,
input,
ExperimentalFlags {
new_encoding: false,
},
),
// When a `BuildConfig` is given,
// the module source may declare `dep`s that must be parsed from other files.
Some(config) => parse_module_tree(
Expand Down Expand Up @@ -190,14 +197,15 @@ fn parse_in_memory(
handler: &Handler,
engines: &Engines,
src: Arc<str>,
experimental: ExperimentalFlags,
) -> Result<(lexed::LexedProgram, parsed::ParseProgram), ErrorEmitted> {
let mut hasher = DefaultHasher::new();
src.hash(&mut hasher);
let hash = hasher.finish();
let module = sway_parse::parse_file(handler, src, None)?;

let (kind, tree) = to_parsed_lang::convert_parse_tree(
&mut to_parsed_lang::Context::default(),
&mut to_parsed_lang::Context::new(BuildTarget::EVM, experimental),
handler,
engines,
module.value.clone(),
Expand Down Expand Up @@ -481,7 +489,11 @@ pub fn parsed_to_ast(
package_name: &str,
retrigger_compilation: Option<Arc<AtomicBool>>,
) -> Result<ty::TyProgram, ErrorEmitted> {
let experimental = build_config.map(|x| x.experimental).unwrap_or_default();
let experimental = build_config
.map(|x| x.experimental)
.unwrap_or(ExperimentalFlags {
new_encoding: false,
});
let lsp_config = build_config.map(|x| x.lsp_mode.clone()).unwrap_or_default();

// Build the dependency graph for the submodules.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,6 @@ pub(crate) fn monomorphize_method_application(
type_binding.as_mut().unwrap().type_arguments.to_vec_mut(),
)?;
let mut method = (*decl_engine.get_function(fn_ref)).clone();
method.is_trait_method_dummy = false;

// Unify method type parameters with implementing type type parameters.
if let Some(implementing_for_typeid) = method.implementing_for_typeid {
Expand Down
2 changes: 1 addition & 1 deletion sway-core/src/semantic_analysis/namespace/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl Module {
let attributes = Default::default();
// convert to const decl
let const_decl_id = to_parsed_lang::item_const_to_constant_declaration(
&mut to_parsed_lang::Context::default(),
&mut to_parsed_lang::Context::new(crate::BuildTarget::EVM, experimental),
handler,
engines,
const_item,
Expand Down
7 changes: 6 additions & 1 deletion sway-core/src/semantic_analysis/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,12 @@ impl TyProgram {
build_config: Option<&BuildConfig>,
module_eval_order: ModuleEvaluationOrder,
) -> Result<Self, ErrorEmitted> {
let experimental = build_config.map(|x| x.experimental).unwrap_or_default();
let experimental =
build_config
.map(|x| x.experimental)
.unwrap_or(crate::ExperimentalFlags {
new_encoding: false,
});

let mut namespace = Namespace::init_root(initial_namespace);
let mut ctx = TypeCheckContext::from_root(&mut namespace, engines, experimental)
Expand Down
7 changes: 5 additions & 2 deletions sway-core/src/transform/to_parsed_lang/context.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::{build_config::ExperimentalFlags, language::parsed::TreeType, BuildTarget};

#[derive(Default)]
pub struct Context {
pub experimental: ExperimentalFlags,

Expand Down Expand Up @@ -30,7 +29,11 @@ impl Context {
Self {
build_target,
experimental,
..Default::default()
module_has_configurable_block: std::default::Default::default(),
destructured_struct_unique_suffix: std::default::Default::default(),
destructured_tuple_unique_suffix: std::default::Default::default(),
match_expression_matched_value_unique_suffix: std::default::Default::default(),
program_type: std::default::Default::default(),
}
}

Expand Down
8 changes: 7 additions & 1 deletion sway-ir/src/bin/opt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ fn main() -> Result<(), anyhow::Error> {
let source_engine = SourceEngine::default();

// Parse it. XXX Improve this error message too.
let mut ir = sway_ir::parser::parse(&input_str, &source_engine, ExperimentalFlags::default())?;
let mut ir = sway_ir::parser::parse(
&input_str,
&source_engine,
ExperimentalFlags {
new_encoding: false,
},
)?;

// Perform optimisation passes in order.
let mut passes = PassGroup::default();
Expand Down
2 changes: 1 addition & 1 deletion sway-ir/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub struct Context<'eng> {
pub experimental: ExperimentalFlags,
}

#[derive(Copy, Clone, Default)]
#[derive(Copy, Clone)]
pub struct ExperimentalFlags {
pub new_encoding: bool,
}
Expand Down
7 changes: 6 additions & 1 deletion sway-ir/src/irtype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,7 +944,12 @@ mod tests {
static SOURCE_ENGINE: Lazy<SourceEngine> = Lazy::new(SourceEngine::default);

fn create_context() -> Context<'static> {
Context::new(&SOURCE_ENGINE, ExperimentalFlags::default())
Context::new(
&SOURCE_ENGINE,
ExperimentalFlags {
new_encoding: false,
},
)
}

/// Creates sample types that are not aggregates and do not point to
Expand Down
4 changes: 3 additions & 1 deletion sway-ir/src/optimize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ pub mod tests {
"
),
&source_engine,
ExperimentalFlags::default(),
ExperimentalFlags {
new_encoding: false,
},
)
.unwrap();

Expand Down
16 changes: 11 additions & 5 deletions sway-ir/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ fn run_tests<F: Fn(&str, &mut Context) -> bool>(sub_dir: &str, opt_fn: F) {
let input_bytes = std::fs::read(&path).unwrap();
let input = String::from_utf8_lossy(&input_bytes);

let mut ir = sway_ir::parser::parse(&input, &source_engine, ExperimentalFlags::default())
.unwrap_or_else(|parse_err| {
println!("{}: {parse_err}", path.display());
panic!()
});
let mut ir = sway_ir::parser::parse(
&input,
&source_engine,
ExperimentalFlags {
new_encoding: false,
},
)
.unwrap_or_else(|parse_err| {
println!("{}: {parse_err}", path.display());
panic!()
});

let first_line = input.split('\n').next().unwrap();

Expand Down
2 changes: 1 addition & 1 deletion sway-lib-core/generate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ remove_generated_code "STRARRAY_ENCODE"
START=1
END=64
for ((i=END;i>=START;i--)); do
CODE="impl AbiEncode for str[$i] { fn abi_encode(self, ref mut buffer: Buffer) { use ::str::*; let s = from_str_array(self); let len = s.len(); let ptr = s.as_ptr(); let mut i = 0; while i < len { let byte = ptr.add::<u8>(i).read::<u8>(); buffer.push(byte); i += 1; } } }"
CODE="impl AbiEncode for str[$i] { fn abi_encode(self, ref mut buffer: Buffer) { use ::str::*; let s = from_str_array(self); let len = s.len(); let ptr = s.as_ptr(); let mut i = 0; while i < len { let byte = ptr.add::<u8>(i).read::<u8>(); buffer.push_byte(byte); i += 1; } } }"
sed -i "s/\/\/ BEGIN STRARRAY_ENCODE/\/\/ BEGIN STRARRAY_ENCODE\n$CODE/g" ./src/codec.sw
done

Expand Down
Loading

0 comments on commit 98cdaac

Please sign in to comment.