Commit graph

464 commits

Author SHA1 Message Date
zees-dev
dffa29c599
feat: forc call json output (#7156)
## Description

This PR adds JSON output support for `forc-call` CLI.

Additionally, it adds JSON support for `tracing-subscriber` in
`forc-tracing` - with option to omit logs from other libraries (via
regex).
- JSON tracing-subscriber ignores colored output
- Forc-call hooks into this tracing-subscriber (using `Json` variant) to
output JSON response

### Changelog

This pull request introduces enhancements to the `forc-call` plugin,
focusing on improving output formatting, streamlining verbosity
handling, and updating test cases to reflect these changes.
The most significant updates include the addition of a JSON output
format, the removal of the `Verbosity` struct, and modifications to test
cases to handle optional results.

### Output Formatting Enhancements:
* Added a new `Json` variant to the `OutputFormat` enum for outputting
full tracing information in JSON format. Implemented the `Write` trait
for `OutputFormat` to handle different output styles.
(`forc-plugins/forc-client/src/cmd/call.rs`,
[forc-plugins/forc-client/src/cmd/call.rsR60-R87](diffhunk://#diff-466e2f9659cab303594eb73a846768ecdbc1a13030e5869cdac51ddde87dd313R60-R87))
* Updated the `Command` struct to include a short option (`-o`) for
specifying the output format.
(`forc-plugins/forc-client/src/cmd/call.rs`,
[forc-plugins/forc-client/src/cmd/call.rsL319-R319](diffhunk://#diff-466e2f9659cab303594eb73a846768ecdbc1a13030e5869cdac51ddde87dd313L319-R319))

### Verbosity Handling Simplification:
* Removed the `Verbosity` struct and its associated methods. Verbosity
is now directly represented as an integer (`cmd.verbosity`) for
simplicity. (`forc-plugins/forc-client/src/cmd/call.rs`,
[[1]](diffhunk://#diff-466e2f9659cab303594eb73a846768ecdbc1a13030e5869cdac51ddde87dd313R60-R87);
`forc-plugins/forc-client/src/op/call/call_function.rs`,
[[2]](diffhunk://#diff-7da99987eeed69f070b781a5692d3acc7028308b8538ca129d79452ccc057fdeL2-R2)
[[3]](diffhunk://#diff-7da99987eeed69f070b781a5692d3acc7028308b8538ca129d79452ccc057fdeL54-L57)
[[4]](diffhunk://#diff-7da99987eeed69f070b781a5692d3acc7028308b8538ca129d79452ccc057fdeL181-R185)
[[5]](diffhunk://#diff-7da99987eeed69f070b781a5692d3acc7028308b8538ca129d79452ccc057fdeL216-R227)

### Test Case Updates:
* Modified test cases to handle optional results by calling `.unwrap()`
on the `result` field where applicable. This ensures compatibility with
changes to how results are processed.
(`forc-plugins/forc-client/src/op/call/call_function.rs`,
[[1]](diffhunk://#diff-7da99987eeed69f070b781a5692d3acc7028308b8538ca129d79452ccc057fdeL356-R387)
through
[[2]](diffhunk://#diff-7da99987eeed69f070b781a5692d3acc7028308b8538ca129d79452ccc057fdeL661-R710)

These changes improve the usability and maintainability of the
`forc-call` plugin, making it more robust and user-friendly.

Note: This is a pre-requisite to resolve
https://github.com/FuelLabs/sway/issues/7019; the output script in the
JSON can be directly parsed into a `tx.json` file for `forc-debug`.

## Checklist

- [ ] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
2025-05-09 20:07:27 +12:00
Hannes Karppila
1c885cf0f1
codegen optimization: symbolic fuel-vm interpretation (#7109)
## Description

This PR adds an initial support to symbolic fuel-vm interpretation to
improve codegen. The symbolic execution is designed to be extended in
later PRs. In it's current form, it provides three distinct
improvements:

1. If a temporary (allocated) register contains a value already held in
another register, we can use that other register instead. This reduces
register pressure, and removes unnecessary `mov` ops.
2. If a register already has the value we're setting it to, we can
eliminate the instruction doing so.
3. For conditional jump instructions, if the value of the condition is
known, one of the branches can be elminated. In such cases, the
instruction is either removed or replaced with an unconditional jump.
Dead code elimination pass can then potentially remove the
now-unreachable branch.

In addition to these changes, this PR takes the optimization level into
account for asm generation. For debug builds, we only run the
optimization passes once. But for release builds we run the optimization
passes multiple times, until we either cannot eliminate any more
operations, or until a fixed upper limit of rounds. For instance, this
means that if the new pass added in this PR manages to eliminate a
branch, and then dead code elimination removes that code, it could allow
the interpretation pass to do even more work.

To account for new optimization passes, I also organized them to mulple
files, so that the ones which create private types are scoped well and
thus easier to read.


## Impact

project | size before | size after | size reduction
-|-|-|-
mira-v1-core | 89.384 KB | 83.480 KB | 6.6%


## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book). No changes required!
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works. Just updated pre-existing ones!
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Vaivaswatha N <vaivaswatha.nagaraj@fuel.sh>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-05-05 10:50:08 +03:00
zees-dev
66c9c1f856
sway-book: fix forc call examples (#7133)
## Description

This pull request introduces updates to the documentation and examples
for the `forc call` command, improving clarity, organization, and
usability.
The most significant changes include restructuring the documentation
into a new file, updating the book summary to reflect this change, and
enhancing the examples in the codebase for better readability.

Added dedicated section for `forc-call` under testing heading.

<img width="1309" alt="image"
src="https://github.com/user-attachments/assets/446f6846-e294-472c-9e71-a3f1192960c5"
/>

### Documentation Updates:

* **New Documentation File for `forc call`**: The detailed documentation
for the `forc call` command has been moved to a new file,
`docs/book/src/forc/plugins/forc_client/forc_call_docs.md`. This
includes comprehensive usage examples, parameter encoding details, and
troubleshooting tips.
* **Removal of Old Documentation**: The old `forc_call.md` file has been
removed, as its content has been migrated to the new structured format.

### Book Summary Update:

* **Updated `SUMMARY.md`**: The book summary has been updated to include
a link to the new `forc call` documentation under the "Testing" section
for better navigation.

### Code Example Enhancements:

* **Improved Examples in `call.rs`**: Examples in the `forc call`
command's code file (`forc-plugins/forc-client/src/cmd/call.rs`) have
been reformatted for clarity. Each example now uses markdown-style code
blocks and descriptive headings, making them easier to follow.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-05-02 16:27:47 +12:00
Igor Rončević
5f64b96f9c
Implement panic expression (#7073)
## Description

This PR introduces the `panic` expression to the language, as defined in
the [ABI Errors
RFC](https://github.com/FuelLabs/sway-rfcs/blob/master/rfcs/0014-abi-errors.md#panic).

The `panic` expression can be used without arguments, or accept an
argument that implements the `std::marker::Error` trait. The `Error`
trait is implemented by the compiler for the unit `()`, string slices,
and `#[error_type]` enums.

Using the `panic` expression without arguments gives the symetry with
the `return` expression and acts in the same way as having unit as an
argument.

```
panic;
panic ();
panic "This is some error.";
panic Errors::SomeError(42);
```

Panicking without an argument or with unit as argument is discouraged to
use. In the upcoming PR that finalizes the ABI errors feature, we will
emit a warning if the `panic` is used without arguments or with unit as
argument.

`panic` expression is available in all program kinds. In predicates it
currently compiles only to revert. Once `__dbg` intrinsic is
implemented, we can consider compiling to it in predicates. In the
upcoming PR, the `error_codes` entry in the ABI JSON will be available
for all program kinds.

The dead code analysis for the `panic` expression is implemented in the
straightforward way, following the current approach of connecting
reverts to the exit node. This will be revisted in a separate PR,
together with the open TODOs in the DCA implementation of `Return`.
Essentially, we want reverting/panicking to connect to program exit and
implicit returns to the exit node.

Additionally, the PR:
- extends `forc test` CLI attributes with `--revert-codes` that prints
revert codes even if tests are successful but revert.
- updates outdated "Logs Inside Tests" chapter in the documentation on
unit testing.
- extends the snapshot testing infrastructure to support `forc test` in
snapshot tests.
- fixes #7072.

Partially addresses #6765.

## Breaking Change

`panic` is a new reserved keyword. Once the `error_type` feature becomes
integrated, compiling any existing code containing a "panic" as an
identifier will result in an "Identifiers cannot be a reserved keyword."
error.

In this PR, `panic` keyword is hidden behind the `error_type` feature
flag. This prevents existing code from breaking, unless opted-in.

Note that, although being behind a feature flag, `panic` cannot be used
in conditional compilation, means in combination with the
`#[cfg(experimental_error_type = true/false)]`. The reason is that `cfg`
evaluation happens after parsing, and we can either parse `panic` as a
keyword or identifier during the parsing, because we cannot distinguish
ambiguous cases like `panic;` or just `panic`.

This limitation means, that introducing `panic` to `std` can be done
only once the `error_type` feature is fully integrated. In practice,
this is not a serious limitation, because introducing `panic` in `std`
would anyhow, due to effort and design decisions, happen after the
feature is integrated.

We will provide a migration for this breaking change that will migrate
the existing "panic" identifiers to "r#panic".

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-04-30 20:07:05 +10:00
Sophie Dankel
7206479528
Add forc-publish to release binaries (#7129)
## Description


## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-04-30 00:55:36 +00:00
Daniel Frederico Lins Leite
26e2ef875c
Support for const generics in structs (#7076)
## Description

Part of https://github.com/FuelLabs/sway/issues/6860.

This PR enables code like below to be written now. This will allow the
implementation of `iter()` for arrays.

```sway
struct S<T, const N: u64> {}

impl<T, const N: u64> S<T, N> {
    pub fn len_xxx(self) -> u64 {
        N
    }
}
```

Limited to `structs` now. `enum` will be implemented in a future PR.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: IGI-111 <igi-111@protonmail.com>
2025-04-29 19:16:48 -03:00
Igor Rončević
76268dcff7
Add support for experimental features in the parsing phase (#7124)
## Description

This PR brings support for experimental features to the parsing phase.
This is needed so that we can support use cases like, e.g., adding new
language keywords behind a feature flag.

A concrete example would be the `panic` keyword added in #7073. The
parsing of the `panic` token differs if it is interpreted as a keyword
(when the `error_type` experimental feature is active) or as a regular
identifier (when `error_type` is off).

Because `ExperimentalFeatures` are needed in the `Parse::parse(parser:
&mut Parser)` methods, the `Parser` got extended with the `experimental`
field.

The consequence of bringing the `ExperimentalFeatures` to the parsing
phase is, that `swayfmt` and `forc fmt` can also require an experimental
feature to be set, to properly parse a project. In those tools,
`ExperimentalFeatures` are passed as a field on the `Formatter`.

Note that this PR does not put the provided experimental flags into use.
The first concrete usage will be in #7073.

This PR is a prerequisite for #7073. 

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-04-29 11:36:37 +12:00
zees-dev
5f999595d3
forc-call: missing contract retrieval refactor (#7115)
## Description

Using `fuels-rs` SDK to retrieve missing contracts for a forc-call
query.

This function/improvement was introduced in the `fuels-rs` sdk here:
https://github.com/FuelLabs/fuels-rs/pull/1628

Addresses: https://github.com/FuelLabs/sway/issues/7113

## Checklist

- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-04-24 05:31:23 +00:00
kaya
760a2bfc7b
chore: bump fuel-core to 0.43.1 and fuels to 0.72 (#7110)
## Description

Dependency bump to get fuels 0.72 and fuel-core 0.43.1 support.

---------

Co-authored-by: bitzoic <bitzoic.eth@gmail.com>
2025-04-24 13:50:40 +10:00
Daniel Frederico Lins Leite
f736fce7ac
Debug trait and its auto implementation (#7015)
## Description

This PR implements the `__dbg(...)` intrinsic, which is very similar to
Rust `dbg!(...)` macro.

Up until now, it has being the norm to use `__log` to debug values.
Given that this is NOT the first use case for log, we have always found
some issues with it: log does not work on predicates, log does not show
"private" fields like `Vec::capacity` and others.

To solve these problems `__dbg` is being introduced:
1 - it will work on all program types, including predicates;
2 - it also prints the file name, line and column;
3 - All types will have an automatic implementation of Debug if
possible, which can still be customized.
4 - Even `raw_ptr` and other non "loggable" types, have `Debug` impls.
5 - `__dbg` will be completely stripped in the release build by default.
It can be turned on again if needed.

So this:

```
// Aggregates
let _ = __dbg((1u64, 2u64));
let _ = __dbg([1u64, 2u64]);

// Structs and Enums
let _ = __dbg(S { });
let _ = __dbg(E::None);
let _ = __dbg(E::Some(S { }));
```

will generate this:

```
[src/main.sw:19:13] = (1, 2)
[src/main.sw:20:13] = [1, 2]
[src/main.sw:23:13] = S { }
[src/main.sw:24:13] = None
[src/main.sw:25:13] = E(S { })
```

How does this work?

`__dbg(value)` intrinsic is desugared into `{ let f = Formatter{};
f.print_str(...); let value = value; value.fmt(f); value }`.

`Formatter` is similar to Rust's one. The difference is that we still do
not support string formatting, so the `Formatter` has a lot of `print_*`
functions.

And each `print` function calls a "syscall". This `syscall` uses `ecal`
under the hood and it follows unix write syscall schema.

```sway
// ssize_t write(int fd, const void buf[.count], size_t count);
fn syscall_write(fd: u64, buf: raw_ptr, count: u64) {
    asm(id: 1000, fd: fd, buf: buf, count: count) {
        ecal id fd buf count;
    }
}
```

For that to work, the VM interpreter must have its `EcalState` setup and
interpret syscall number 1000 as `write`. This PR does this for `forc
test` and our `e2e test suite`.

Each test in `forc test` will capture these calls and only print to the
terminal when requested with the `--log` flag.

## Garbage Collector and auto generated

Before, we were associating all auto-generated code with a pseudo file
called "&lt;autogenerated&gt;.sw" that was never garbage collected.

This generated a problem inside the LSP when the `auto_impl.rs` ran a
second time because of a collision in the "shareable type" map. When we
try to solve this collision, choosing to keep the old value or to insert
the new, the type inside the map points to already collected types and
the compiler panics. This is a known problem.

The workaround for this is to break the auto-generated code into
multiple files. Now they are named "main.autogenerated.sw", for example.
We create one pseudo-file for each real file that needs one.

When we garbage collect one file, `main.sw`, for example, we also
collect its associated auto-generated file.

## Checklist

- [ ] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-04-22 07:49:31 -03:00
Daniel Frederico Lins Leite
f607a674e3
More Sway compiler optimizations (#7093)
## Description

This PR is a prequel to https://github.com/FuelLabs/sway/pull/7015,
trying to optimize the compiler to alleviate the hit of having more
items, `impl` etc...

We have here two optimizations:
1 - We spend a lot of time counting newlines when converting byte
offsets to `LineCol`. Now, we calculate line offsets just once, and use
binary search later to find which line a byte offset is at.
2 - `QueryEngine::get_programs_cache_entry` was cloning the whole
`TyProgram`. That is why `did_change_with_caching` was always getting
worse, as the program was increasing in size. Now all compilation stages
are behind `Arc`, which makes the `clone` free.

## Analysis

Putting a `dbg!(...)` like the image below, and calling `counts`
(https://github.com/nnethercote/counts).

```
cargo bench -- traverse 2>&1 | grep "sway-types/src/span.rs:29:9" | counts
```


![image](https://github.com/user-attachments/assets/b0b97eb3-9ba6-47d1-9b63-f3ded4ef2978)

I get the following results:

```
972102 counts
(  1)   156720 (16.1%, 16.1%): [sway-types/src/span.rs:29:9] self.pos = 0
(  2)    15900 ( 1.6%, 17.8%): [sway-types/src/span.rs:29:9] self.pos = 104
(  3)    15840 ( 1.6%, 19.4%): [sway-types/src/span.rs:29:9] self.pos = 107
(  4)     2280 ( 0.2%, 19.6%): [sway-types/src/span.rs:29:9] self.pos = 19281
(  5)     2280 ( 0.2%, 19.9%): [sway-types/src/span.rs:29:9] self.pos = 19285
(  6)     2280 ( 0.2%, 20.1%): [sway-types/src/span.rs:29:9] self.pos = 19287
(  7)     2280 ( 0.2%, 20.3%): [sway-types/src/span.rs:29:9] self.pos = 19292
(  8)     2280 ( 0.2%, 20.6%): [sway-types/src/span.rs:29:9] self.pos = 19323
(  9)     2280 ( 0.2%, 20.8%): [sway-types/src/span.rs:29:9] self.pos = 19327
( 10)     2280 ( 0.2%, 21.0%): [sway-types/src/span.rs:29:9] self.pos = 19329
( 11)     2280 ( 0.2%, 21.3%): [sway-types/src/span.rs:29:9] self.pos = 19334
( 12)      870 ( 0.1%, 21.4%): [sway-types/src/span.rs:29:9] self.pos = 4285
...
```

This means that `line_col` is being called 972k times. 16% is for
position zero, which should be trivial. The rest will iterate the whole
file source code to count number of lines. Making the real complexity of
the work here something like `O(qty * self.pos)`. And some values of
`self.pos` are not trivial at all.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-04-21 12:36:15 -07:00
João Matos
3afc5c18c8
Improved trait coherence checking (#6844)
## Description

This PR refines trait coherence checking to guarantee that there is only
one valid implementation for each trait. It introduces improved orphan
rules and more rigorous overlap checks to prevent conflicting trait
implementations. With these changes, the system now more reliably
enforces coherence, ensuring that traits are implemented uniquely, and
reducing potential ambiguities.

This approach mirrors Rust’s design by enforcing two distinct safety and
coherence checks on trait implementations:

**1. Orphan Rules Check**
The orphan rules require that for any trait implementation, either the
trait or the type must be defined within the current package. This
restriction prevents external packages from implementing foreign traits
for foreign types, which could otherwise lead to conflicting
implementations and ambiguities across different parts of a codebase.
Essentially, it helps maintain clear ownership and boundaries of trait
implementations.

**2. Overlap Impl Check**
The overlap impl check ensures that no two trait implementations can
apply to the same type in an ambiguous manner. If two implementations
could potentially match the same type, it would be unclear which one
should be used, leading to coherence issues. By enforcing that
implementations do not overlap, the system guarantees that trait
resolution is unambiguous and predictable.

Together, these checks promote a robust and maintainable system by
ensuring that trait implementations are both locally controlled (orphan
rules) and non-conflicting (overlap check).

The test suite has been updated to comply with the new rules. However,
there is one current limitation regarding arrays. For arrays, the
coherence checks have been relaxed to avoid the need for numerous
concrete implementations in the standard library for traits like `Eq`
and `PartialEq`. This decision was made because support for const
generics is expected soon, which will allow these traits to be
implemented more cleanly.

Closes issue https://github.com/FuelLabs/sway/issues/5892.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-04-17 22:57:45 +01:00
Daniel Frederico Lins Leite
2b06d79568
Sway compiler optimizations (#7080)
## Description

This PR is a prequel to https://github.com/FuelLabs/sway/pull/7015.

`Debug` trait auto-implementation is causing some performance issues. So
this PR will try to compensate by doing the following optimizations:

1 - `filter_dummy_methods` is cloning `TyFunctionDecl` needlessly.
Another small optimization is that instead of calling
`ConcurrentSlab::get(...)` and cloning and dropping an `Arc`. There is a
new `ConcurrentSlab::map(...)` method that avoids all that.

2 - A lot of time was being spent on `node_dependencies`. One the
primary wastes was hashing nodes multiple times. To avoid that, each
node will "memoize" its own hash, and a `Hasher` that does nothing is
being used. This means that each node's hash will only be calculated
once.

3 - The third optimization is a little bit more polemic. It involved the
fact that we clone `TyFunctionDecl` a LOT. And some fields are more
expensive than others, for example, `body`, `parameters` and
`constraints`. To alleviate these excessive clonings, these fields are
now behind an `Arc` (because LSP need them to be thread safe), and there
is a "COW` mechanism specifically for them when they need mutation.

## Detailed analysis

The first step is to compile `forc` and run Valgrind. My analysis was
done using the debug build; values may vary on the release build, of
course.

```
cd test/src/e2e_vm_tests/test_programs/should_pass/language/intrinsics/transmute
cargo r -p for
valgrind --tool=callgrind --dump-instr=yes --simulate-cache=yes --collect-jumps=yes /home/xunilrj/github/sway/target/debug/forc build
```

The first that caught my attention was a function called
`filter_dummy_methods` that is called around 150k times. Inside of it,
there is a useless call to `TyFunctinDecl::clone()`. If Valgrind is
correct, this `clone` is spending 10% of the compilation. This explains
the first optimization.


![image](https://github.com/user-attachments/assets/712def8a-d57f-417e-a8f0-63a9a547ed47)

Another 20% of the time is spent inside `order_ast_nodes_by_dependency`.


![image](https://github.com/user-attachments/assets/bd5f3a1d-5e42-4130-ba41-5e592033ca75)

Inside this function, there is a function called
`recursively_depends_on` that corresponds to 10% of the compilation, and
more than half of it is spent hashing nodes. This explains the second
optimization.


![image](https://github.com/user-attachments/assets/ab691d78-e691-4fd6-a2e7-6cd8d7d0c469)

Another source of waste is the amount of `TyFunctionDecl::clone` that we
call. It amounts to 12% of the compilation time. The problem is that it
is much harder to remove/optimize these clones.

I assume that a lot of these clones are not needed. One of the reasons
is the way `SubtsType` and other monomorphization mechanisms were built;
we first need to clone something, and then we try to mutate the cloned
version. I don´t have a number, but I imagine in a lot of cases, the
cloning and the mutation were not needed. **Maybe someone can come up
with a test to see if we can avoid cloning/mutation. I bet that this
will increase performance tremendously.**


![image](https://github.com/user-attachments/assets/650ae7ff-dc1e-4817-8af1-894df820b90c)

But what I did was I chose all the fields that are costly to be cloned:
`body`, `parameters`, `call_path`, `type_parameters`, `return_type`, and
`where_clause`; and I put them behind an `Arc`. If my assumption is
correct, making them cheap to be cloned will improve performance because
we will just clone their `Arc`, and never mutate them.

Unfortunately, there is no easy way to avoid cloning in some cases. For
example, when monomorphizing, our algorithms don´t know "from the
outside" that a `body` will never change, and we trigger the COW
mechanism and end up cloning the item inside the `Arc`, even when we
don´t need it.


![image](https://github.com/user-attachments/assets/2ac9aa4c-ea89-4515-ae6f-52fea61f0ff1)

## Checklist

- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: IGI-111 <igi-111@protonmail.com>
2025-04-14 23:20:43 -07:00
kaya
ba3a0d5635
feat: registry source resolution and builds (#7038)
## Description
closes #3752, #6903.

Adds registry source resolutions and support for building.
2025-04-09 21:09:47 -07:00
zees-dev
4d18d52749
forc call verbosity levels (#7074)
## Description

- Introduces verbosity levels for the `forc-call` command, replacing the
`show-receipts` flag
- Inspired by [`forge test` verbosity
levels](https://book.getfoundry.sh/reference/forge/forge-test#evm-options);
i.e. can specify `-v=1` or `-vv`, etc.
- Verbosity `v1` prints the following additional info:
  - logs
- Verbosity `v2` prints the following additional info:
  - receipts
  - script json (`tx.json`)

Note: The `tx.json` printed in the response can be used by `forc-debug`
to debug the transaction
^ Addresses: https://github.com/FuelLabs/sway/issues/7019

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
2025-04-10 11:11:28 +12:00
BlockyJ
1c68f1c9e0
Add --generate-hexfile flag to forc build for hex-encoded output (#7032)
close #5017 

PR adds new `--generate-hexfile` flag to the `forc build` command,
enabling it to output a hex-encoded JSON representation of the compiled
binary alongside the `.bin` file.

####  Changes
- Added `--generate-hexfile` flag to `forc build`.
- Outputs a `.json` file containing the hex-encoded script binary (e.g.,
`contract-hex.json`).
- Ensures bundler compatibility for frontend/SDK consumption.

#### 🧪 Example Output
```json
{
  "hex": "0xdeadbeefcafebabe..."
}
```

#### 📦 Example Usage

```bash
forc build --generate-hexfile
```

Generates:
- `contract.bin` (as before)
- `contract-hex.json` (new hex representation)


## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
Co-authored-by: zees-dev <63374656+zees-dev@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-04-08 12:13:13 +00:00
zees-dev
d6410e37f0
Forc call transfers (#7056)
## Description

Implementation of direct transfer of assets to an address using
`forc-call` binary.
Refactor of the `forc-call` binary since it now supports 3 code paths:
- calling (query or tx submission) contracts
- transferring assets directly to an address (recipient and/or contract)
- listing contract functions with call examples

## Usage

```sh
# transfer default asset (eth) to `0x2c7Fd852EF2BaE281e90ccaDf18510701989469f7fc4b042F779b58a39919Eec`
forc-call 0x2c7Fd852EF2BaE281e90ccaDf18510701989469f7fc4b042F779b58a39919Eec --amount 2 --mode=live
```

### Output

```log
warning: No signing key or wallet flag provided. Using default signer: 0x6b63804cfbf9856e68e5b6e7aef238dc8311ec55bec04df774003a2c96e0418e

Transferring 2 0xf8f8b6283d7fa5b672b530cbb84fcccb4ff8dc40f8176ef4544ddb1f1952ad07 to recipient address 0x2c7fd852ef2bae281e90ccadf18510701989469f7fc4b042f779b58a39919eec...

tx hash: e4e931276a500cce1b5303cb594c0477968124ab0f70e77995bbb4499e0c3350
```

## Additional notes

- Inspired by `cast send` where if the CLI is called without a function
signature, it transfers value (eth) to the target address based on the
`--value` parameter; `forc-call` does the same via the `--amount` param
- One can specify the `asset` to be sent; defaults to native network
asset (`eth`)
- Transfers only work with `--mode=live`; since there is no
simulation/dry-run functionality available for this
- Transfers to both contracts and user recipients is supported

## Checklist

- [ ] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: kaya <kaya.gokalp@fuel.sh>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-04-06 23:38:47 -07:00
kaya
8e162c9661
fix: run forc-publish tarball tests sequentially to remove flakiness (#7064)
## Description

close #7063.

`forc-publish` tarball tests are setting the current working director
with `env::set_current_dir`. One thing to note here is `env` module is
changing things for the whole process. Here is the
[docs](https://doc.rust-lang.org/std/env/index.html):

> Inspection and manipulation of the process’s environment.

So setting `env::set_current_dir` changes the current dir on all
threads. By default cargo runs tests in parallel using multiple threads
in a single process. This means, tarball tests are racing with each
other and changing each other's working directory making the tests
flaky.
2025-04-04 19:02:16 +13:00
zees-dev
aad8c7775e
Update fuels version to 0.71 and vm to 0.59.2 (#7053)
## Description

Updates the fuels version to `0.71`, and the `fuel-vm` crates to
`0.59.2`

Also closes: https://github.com/FuelLabs/sway/issues/6976

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-04-03 21:02:35 -07:00
Daniel Frederico Lins Leite
34aa19ca86
TypeArgument as enum to support const generics (#7052)
## Description

Continuation of https://github.com/FuelLabs/sway/pull/7044.
This PR converts `TypeArgument` to an enum to support "const generic" in
the future. It is being done separately because it changes a lot of
files.

No change in behaviour is expected.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-04-01 20:19:35 -03:00
Daniel Frederico Lins Leite
4eb0705fce
Merge type and const generics (#7044)
## Description

This PR only brings type and const generic arguments to the same `Vec`.
It is being done separately because it changes a lot of files.

No change in behaviour is expected.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-03-31 21:40:42 +11:00
Igor Rončević
74282e2c7b
Defining, parsing, and checking #[attribute]s (#6986)
## Description

This PR reimplements how `#[attribute]`s are parsed, defined, and
checked. It fixes the following issues we had with attributes:
- attributes were in general not checked for their expected and allowed
usage.
- when checked, checks were fixing particular reported issues and were
scattered through various compilation phases: lexing, parsing, and tree
conversion.
- when checked, reported errors in some cases had bugs and were
overalapping with other errors and warnings.
- attribute handling was not centralized, but rahter scattered throught
the whole code base, and mostly done at use sites.

For concrete examples of these issues, see the list of closed issues
below.

The PR:
- encapsulates the attributes handling within a single abstraction:
`Attributes`.
- assigns the following properties to every attribute:
  - _target_: what kind of elements an attribute can annotate.
- _multiplicity_: if more then one attribute of the same kind can be
applied to an element.
- _arguments multiplicity_: a range defining how many arguments an
attribute can or must have.
- _arguments value expectation_: if attribute arguments are expected to
have values.
- validates those properties in a single place, during the
`convert_parse_tree`. Note that this means that modules with attribute
issues will now consistently not reach the type checking phase. This was
previously the case for some of the issues with attributes where custom
checks where done during the type checking phase. #6987 proposes to move
those checks after the tree conversion phase, allowing the continuation
of compilation.
- adds the `AttributeKind::Unknow` to preserve unknown attributes in the
typed tree.
- removes redundant code related to attributes: specific warnings and
errors, specialized parsing, repetitive and error-prone at use site
checks, etc.
- removes the unused `Doc` attribute.

The PR also introduces a new pattern in emitting errors. The
`attr_decls_to_attributes` function will always return `Attributes` even
if they have errors, because:
- we expect the compilation to continue even in the case of errors.
- we expect those errors to be ignored if a valid `#[cfg]` attribute
among those evaluates to false.
- we expect them to be emitted with eventual other errors, or alone, at
the end of the tree conversion of the annotated element.

For more details, see the comment on `attr_decls_to_attributes` and
`cfg_eval`.

Closes #6880; closes #6913; closes #6914; closes #6915; closes #6916;
closes #6917; closes #6918; closes #6931; closes #6981; closes #6983;
closes #6984; closes #6985.

## Breaking changes

Strictly seen, this PR can cause breaking changes, but only in the case
of invalid existing attribute usage. We treat those breaking changes as
bug fixes in the compiler and, thus, do not have them behind a feature
flag.

E.g., this kind of code was possible before, but will now emit and
error:
```sway
#[storage(read, write, read, write)]
struct Struct {}
```

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-03-24 09:34:31 +11:00
zees-dev
6cd732b56e
forc-call list functions support with example call usage (#7018)
## Description
Adds optional `--list-functions` CLI arg to `forc call`.

With provided ABI and a contract address; calling `forc-call` with
`--list-functions` will list all available functions in the contract and
additionally display example CLI usage to call the respective functions
with default/basic parameters.

## Example output
```sh
> forc call -- \               
  --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
  23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 --list-functions

Available functions in contract: 23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4

test_array(a: [u64; 10]) -> [u64; 10]
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_array "[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]"

test_b256(a: b256) -> b256
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_b256 "0x0000000000000000000000000000000000000000000000000000000000000000"

test_bytes(a: Bytes) -> Bytes
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_bytes "0x"

test_complex_struct(a: ComplexStruct) -> ComplexStruct
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_complex_struct "{({aa, 0}, 0), (Active:false), 0, {{0, aaaa}, aaaa}}"

test_empty() -> ()
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_empty 

test_empty_no_return() -> ()
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_empty_no_return 

test_enum(a: Status) -> Status
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_enum "(Active:false)"

test_enum_with_complex_generic(a: GenericEnum) -> GenericEnum
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_enum_with_complex_generic "(container:{{0, aaaa}, aaaa})"

test_enum_with_generic(a: GenericEnum) -> GenericEnum
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_enum_with_generic "(container:{0, aaaa})"

test_option(a: Option) -> Option
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_option "(None:())"

test_str(a: str) -> str
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_str "hello"

test_str_array(a: str[10]) -> str[10]
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_str_array "aaaaaaaaaa"

test_str_slice(a: str) -> str
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_str_slice "hello"

test_struct(a: User) -> User
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_struct "{aa, 0}"

test_struct_with_generic(a: GenericStruct) -> GenericStruct
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_struct_with_generic "{0, aaaa}"

test_tuple(a: (u64, bool)) -> (u64, bool)
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_tuple "(0, false)"

test_u128(a: U128) -> U128
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_u128 "0"

test_u16(a: u16) -> u16
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_u16 "0"

test_u256(a: U256) -> U256
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_u256 "0"

test_u32(a: u32) -> u32
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_u32 "0"

test_u64(a: u64) -> u64
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_u64 "0"

test_u8(a: u8) -> u8
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_u8 "0"

test_unit(a: ()) -> ()
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_unit "()"

test_vector(a: Vec<u64>) -> Vec<u64>
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      test_vector "[0, 0]"

transfer(amount_to_transfer: u64, asset_id: AssetId, recipient: Identity) -> ()
  forc call \
      --abi ./forc-plugins/forc-client/test/data/contract_with_types/contract_with_types-abi.json \
      23190a0648a92ac42f58dc2f4159ee28cdd1448bbcaabd272ec42a00e8e4aed4 \
      transfer "0" "{0x0000000000000000000000000000000000000000000000000000000000000000}" "(Address:{0x0000000000000000000000000000000000000000000000000000000000000000})"
```

Addresses https://github.com/FuelLabs/sway/issues/6935

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-03-18 15:09:10 +13:00
Sophie Dankel
f46a2dc453
chore: add more information to lib-std project manifest (#7003)
## Description

These fields will be used when the package is published to forc.pub
registry.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-03-17 17:17:18 -07:00
Igor Rončević
58114d7e68
Promote experimental features (#7016)
## Description

This PR promotes the following experimental features to standard ones:
- #6701
- #6883
- #6994
- #7006

Additionally, the PR stenghtens the migration infrastructure by checking
some additional cases in selecting corresponding typed elements in
desugared code which were not checked before.

Closes #6701.
Closes #6883.
Closes #6994.
Closes #7006.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-03-13 20:47:01 +11:00
SwayStar123
a5d9d2835f
Merge std and core libraries (#6729)
## Description
Merges the two libraries. They were initially separate to separate the
core logic and fuel vm specific functionality, but that separation is no
longer maintained so having a merged library is better.

Closes #6708

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: Sophie <47993817+sdankel@users.noreply.github.com>
Co-authored-by: Igor Rončević <ironcev@hotmail.com>
2025-03-12 23:52:38 +01:00
IGI-111
ef377e78bf
Add description to forc-node (#7013)
## Description

Descriptions are required for crates.io published packages.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-03-11 16:48:41 +00:00
Igor Rončević
c8c4d2bb3b
Add migration for merging core and std libraries (#7010)
## Description

This PR adds migration step for merging `core` and `std` libraries, as
explained in the Breaking Changes chapter of #7006.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-03-11 10:51:45 +00:00
Igor Rončević
1f407fadb2
Add migration for Bytes::into(self) -> b256 to Bytes::try_into (#7009)
## Description

This PR adds migration step for migrating `<bytes>.into()` calls to
`<bytes>.try_into().unwrap`, as explained in the Breaking Changes
chapter of #6994.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-03-11 21:19:30 +11:00
Igor Rončević
8b3d822112
Implement trees visitors and migrations for TryFrom<Bytes> for b256 (#7005)
## Description

This PR:
- extends infrastructure for writing migrations that modify individual
expressions and do not need access to a broader scope. It does that by
providing lexed and typed tree visitors. Visiting lexed and typed tree
is implemented to the level needed to write the migration for `impl
TryFrom<Bytes> for b256`.
- implements the migration for `impl TryFrom<Bytes> for b256` as
explained in #6994.

Adding `#[cfg(experimental_try_from_bytes_for_b256 = true)]` to the
`impl TryFrom<Bytes> for b256` revealed that there existed already an
`impl TryFrom<Bytes> for b256` in `std::primitive_conversions::b256`.
Due the lack of trait coherence there was no any errors when it was
re-implemented in `std::bytes`.

This PR marks the existing impl in `std::primitive_conversions::b256`
with `#[cfg(experimental_try_from_bytes_for_b256 = false)]` so that it
will be removed in the next breaking release, in favor of the new impl
in `std::bytes`.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-03-11 11:20:13 +11:00
Sophie Dankel
8c0cc20df8
chore: Change blob ID calculation in forc-deploy to use configurables offset (#6991)
## Description

Closes https://github.com/FuelLabs/sway/issues/6990

The main change here is switching from using the data section offset to
using the configurables offset in the blob loader in forc-deploy.

TODO: update the loader-abi.json test file(s) once deployment to testnet
is working.

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-03-06 15:43:02 +11:00
Sophie Dankel
ba7c4a9297
ci: upgrade to rust 1.85.0 (#6979)
## Description


## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-03-04 11:28:22 +04:00
zees-dev
20973803db
forc-call logs support (#6968)
## Description
- Added support for viewing emitted logs when making a transaction using
forc-call
- Added `show_receipts` param (default-false) - so we can optionally
prnt out all receipts
- The CLI output becomes too long for a call with multiple receipts;
this is a minor UI enhancement

Addresses https://github.com/FuelLabs/sway/issues/6887

## Example usage/output

```sway
script;

struct ExampleParams {
    test_val: u32,
    test_str: str,
    test_tuple: (u32, u64),
}

fn main() -> u64 {
    log("hiiii");
    log(123);
    log(ExampleParams { test_val: 5, test_str: "hello world", test_tuple: (1,2) });
    5
}
```

<img width="986" alt="image"
src="https://github.com/user-attachments/assets/3725ff17-29c9-43d7-98cc-4cacfc213ecb"
/>

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
Co-authored-by: kayagokalp <kayagokalp123@gmail.com>
2025-03-01 14:26:16 +13:00
Sophie Dankel
597ecfb6e0
chore: move dev dependencies to workspace (#6966)
## Description

Moves dev dependencies to the workspace Cargo.toml for consistent
versions in tests.

Inspired by https://github.com/FuelLabs/sway/pull/6955

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-02-28 11:44:11 +11:00
Daniel Frederico Lins Leite
d8854fad08
Const generic feature toggle, parser and errors. (#6926)
## Description

This PR is part of https://github.com/FuelLabs/sway/issues/6860, and it
is officially introducing the `const_generic` feature toggle.

For the moment, it is parsing syntax such as `const N: u64` and it is
returning an error explaining that the feature is off; on the other
hand, it is also returning an error saying that const generics are still
not supported in impl traits when the feature is on. Future PRs will
replicate this error in all possible places.

Nothing else is implemented and it is reserved for future PRs.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: IGI-111 <igi-111@protonmail.com>
2025-02-18 09:28:19 +11:00
Kaya Gökalp
15899514eb
feat: add forc-node command for easily bootstrapping a node (#6473) 2025-02-15 12:34:45 +11:00
Sophie Dankel
828e3c207b
chore: cargo update (#6929)
## Description

Ran `cargo-update` to get the latest version of fuels-rs and fuel.core.

Updated the test `contract_call_with_abi` to pass. Context:
https://fuellabs.slack.com/archives/C01KBNGSWGJ/p1738755301379719?thread_ts=1738755301.379719&cid=C01KBNGSWGJ

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-02-15 08:33:05 +11:00
zees-dev
696cb57883
minor: Migrate forc-call node_url (#6920)
## Description
Migrated the `node_url` function; addressing the todo.
Also refactored the function to ease readability and maintainability.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
2025-02-14 15:01:28 +13:00
Igor Rončević
bb7c99b24a
Implement partial equivalence and extend forc migrate tool (#6900)
## Description

This PR:
- implements partial equivalence in the `core::ops`, as explained in
detail in #6883. The implementation is opt-in and behind the
`partial_eq` experimental feature flag.
- implements `forc migrate` migration steps for automatic migration to
`partial_eq` feature.
- extends the infrastructure for writing `forc migrate` migrations.
- preserves `Annotation`s on `LexedModule`s in the `LexedProgram`.
(Those were before stripped off and not available in the compiled
`Programs`. This resulted in loss off `//!` doc-comments that are
represented as `doc-comment` annotations.)

Extensions in the `forc migrate` infrastructure include:
- possibility to postpone migration steps. This allows writing
multi-step migrations where the first step is usually early adopting an
experimental feature by using `cfg` attributes in code. This possibility
is crucial for migrating our own codebase where we want to early-adopt
and test and stabilize experimental features.
- possibility to match elements on both mutable and immutable parsed
trees. The initial assumption that immutable matching on typed trees
will always be sufficient does not hold. Experimental `cfg` attributes
can remove parts of typed trees that might be needed in analysis.
- `LexedLocate(As)Annotated` for easier location and retrieval of
`Annotated` elements.
- additional implementations of existing traits.
- additional `Modifier`s for modifying existing elements in the lexed
tree.
- `New` struct for convenient creation of often needed lexed tree
elements. Note that we do not expect migrations to generate large new
parts of lexed trees, but mostly to modify or copy and modify existing
ones.

Almost all of the changes in the Sway files are done automatically by
the migration steps. The only manual change was in the `core` library
(`std` library is also automatically migrated) and in slight extension
of two of the tests.

Note that some of the tests have `Eq` traits in trait constraints. As
explained in the #6883, it is not necessary to change those to
`PartialEq`. We might consider changing some of them, for testing
purposes, and such a change is done on one of the tests that was testing
the behavior of the `Eq` trait. But for the majority of the tests, there
is no strict need for switching from `Eq` to `PartialEq`.

Rolling `PartialEq` out in the tests provoked three existing issues that
will be fixed in separate PRs: #6897, #6898, #6899.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-02-11 10:02:45 -03:00
Sophie Dankel
eafd99e857
feat: Add forc-publish plugin (#6890)
## Description

Closes https://github.com/FuelLabs/sway/issues/6889

Currently it only works when running locally, as the forc.pub server is
not yet live. Allows users to publish a package by running `forc
publish` in the root of the package directory. Workspaces not yet
supported.

It's intentionally not yet added to the release process (will be done in
https://github.com/FuelLabs/sway/issues/6891)

To test it locally, run the
[forc.pub](https://github.com/FuelLabs/forc.pub/) server and web app
locally (see that repo's README for more details).

1. Start DB ./scripts/start_local_db.sh
2. Start server cargo run
3. Start frontend cd app && npm start - opens localhost:3000
4. Get API token from local webapp -> Login with Github -> API Tokens ->
Generate new token
5. Edit `std-lib-core/Forc.toml` and add a version key, i.e. `version =
0.1.0`
6. Run `forc publish` from this branch:
https://github.com/FuelLabs/forc.pub/pull/29 and you'll be prompted to
enter the token.

## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: Marcos Henrich <marcoshenrich@gmail.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
Co-authored-by: Kaya Gökalp <kaya.gokalp@fuel.sh>
2025-02-10 21:59:37 -08:00
zees-dev
0de1c32c22
plugin: forc-call (#6791)
## Description
The following PR introduces a new forc plugin; `forc-call`.

This plugin allows users to call functions on deployed contracts using
the `forc call` command.
This is ideal for quickly querying the state of a deployed contract.

In this first implementation; the contract ABI is required (as a path to
a local JSON file or a URL to a remote JSON file).

This is inspired by the [`cast
call`](https://book.getfoundry.sh/reference/cast/cast-call) tool; which
is a popular tool for interacting with deployed contracts on Ethereum.
The implementation is based on the following Github issue:
https://github.com/FuelLabs/sway/issues/6725

In the current implementation, you can query a contract state using the
`forc call` command by providing the target contract ID, it's respective
ABI file, and the function name (selector) and arguments.

<details>
  <summary>Forc Call CLI</summary>
  
  ```sh
  forc call --help
  ```

  ```
Call a contract function

Usage: forc call [OPTIONS] <CONTRACT_ID> <FUNCTION> [ARGS]...

Arguments:
  <CONTRACT_ID>
          The contract ID to call

  <FUNCTION>
The function signature to call. When ABI is provided, this should be a
selector (e.g. "transfer") When no ABI is provided, this should be the
full function signature (e.g. "transfer(address,u64)")

  [ARGS]...
          Arguments to pass into main function with forc run

Options:
      --abi <ABI>
          Optional path or URI to a JSON ABI file

      --node-url <NODE_URL>
The URL of the Fuel node to which we're submitting the transaction. If
unspecified, checks the manifest's `network` table, then falls back to
`http://127.0.0.1:4000`
          
You can also use `--target`, `--testnet`, or `--mainnet` to specify the
Fuel node.
          
          [env: FUEL_NODE_URL=]

      --target <TARGET>
          Use preset configurations for deploying to a specific target.
          
You can also use `--node-url`, `--testnet`, or `--mainnet` to specify
the Fuel node.
          
          Possible values are: [local, testnet, mainnet]

      --testnet
          Use preset configuration for testnet.
          
You can also use `--node-url`, `--target`, or `--mainnet` to specify the
Fuel node.

      --mainnet
          Use preset configuration for mainnet.
          
You can also use `--node-url`, `--target`, or `--testnet` to specify the
Fuel node.

      --signing-key <SIGNING_KEY>
          Derive an account from a secret key to make the call
          
          [env: SIGNING_KEY=]

      --wallet
          Use forc-wallet to make the call

      --amount <AMOUNT>
          Amount of native assets to forward with the call
          
          [default: 0]

      --asset-id <ASSET_ID>
          Asset ID to forward with the call

      --gas-forwarded <GAS_FORWARDED>
          Amount of gas to forward with the call

      --mode <MODE>
The execution mode to use for the call; defaults to dry-run; possible
values: dry-run, simulate, live
          
          [default: dry-run]

      --gas-price <PRICE>
          Gas price for the transaction

      --script-gas-limit <SCRIPT_GAS_LIMIT>
          Gas limit for the transaction

      --max-fee <MAX_FEE>
          Max fee for the transaction

      --tip <TIP>
          The tip for the transaction

      --external-contracts <EXTERNAL_CONTRACTS>
The external contract addresses to use for the call If none are
provided, the call will automatically extract contract addresses from
the function arguments and use them for the call as external contracts

  -h, --help
          Print help (see a summary with '-h')

  -V, --version
          Print version
  ```
</details>

### Example usage

```sh
forc call 0xe18de7c7c8c61a1c706dccb3533caa00ba5c11b5230da4428582abf1b6831b4d --abi ./out/debug/counter-contract-abi.json add 1 2
```

- where
`0xe18de7c7c8c61a1c706dccb3533caa00ba5c11b5230da4428582abf1b6831b4d` is
the contract ID
- where `./out/debug/counter-contract-abi.json` is the path to the ABI
file
- where `add` is the function name (selector)
- where `1 2` are the arguments to the function

^ the sway code for the add function could be:

```sway
contract;
abi MyContract {
    fn add(a: u64, b: u64) -> u64;
}
impl MyContract for Contract {
    fn add(a: u64, b: u64) -> u64 {
        a + b
    }
}
```

## Implementation details

1. The provided ABI file downloaded (unless local path is provided)
2. The ABI is parsed into internal representation
3. The provided function selector e.g. `add` is matched with the
extracted functions from the ABI
4. The provided arguments are parsed into the appropriate types which
match the extracted function's inputs
5. The function selector and args are then converted into the `Token`
enum, which is then ABI encoded as part of the `ContractCall` struct
6. The `ContractCall` struct is then used to make a request to the node
to call the function
7. The response is then decoded into the appropriate type (based on
matched function's output type)

^ In the implementation, we don't use the `abigen!` macro since this is
a compile time parser of the ABI file; instead we make use of the lower
level encoding and decoding primitives and functions from the [Rust
SDK](https://github.com/FuelLabs/fuels-rs).

## Live example on testnet

### Example 1

The example contract above with `add` function has been deployed on
testnet - with ABI file available
[here](https://pastebin.com/raw/XY3awY3T).
The add function can be called via the CLI:

```sh
cargo run -p forc-client --bin call -- \
  --testnet \
  --abi https://pastebin.com/raw/XY3awY3T \
  0xe18de7c7c8c61a1c706dccb3533caa00ba5c11b5230da4428582abf1b6831b4d \
  add 1 2
```

### Example 2 - get `owner` of Mira DEX contract

```sh
cargo run -p forc-client --bin call -- \
  --testnet \
  --abi https://raw.githubusercontent.com/mira-amm/mira-v1-periphery/refs/heads/main/fixtures/mira-amm/mira_amm_contract-abi.json \
  0xd5a716d967a9137222219657d7877bd8c79c64e1edb5de9f2901c98ebe74da80 \
  owner
```

Note: Testnet contract address
[here](https://docs.mira.ly/developer-guides/developer-overview#testnet-deployment)

## Encoding of primitive types

When passing in function arguments, the following types are encoded as
follows:

| Types | Example input | Notes |

|-----------------------------------------------|----------------------------------------------------------------------|------------------------------------------------------------------------------------------------|
| bool | `true` or `false` | |
| u8, u16, u32, u64, u128, u256 | `42` | |
| b256 |
`0x0000000000000000000000000000000000000000000000000000000000000042` or
`0000000000000000000000000000000000000000000000000000000000000042` |
`0x` prefix is optional |
| bytes, RawSlice | `0x42` or `42` | `0x` prefix is optional |
| String, StringSlice, StringArray (Fixed-size) | `"abc"` | |
| Tuple | `(42, true)` | The types in tuple can be different |
| Array (Fixed-size), Vector (Dynamic) | `[42, 128]` | The types in
array or vector must be the same; i.e. you cannot have `[42, true]` |
| Struct | `{42, 128}` | Since structs are packed encoded, the attribute
names are not encoded; i.e. `{42, 128}`; this could represent the
following `struct Polygon { x: u64, y: u64 }` |
| Enum | `(Active: true)` or `(1: true)` | Enums are key-val pairs with
keys as being variant name (case-sensitive) or variant index (starting
from 0) and values as being the variant value; this could represent the
following `enum MyEnum { Inactive, Active(bool) }` |

<details>
  <summary>Encoding cheat-sheet</summary>

A few of the common types are encoded as follows:

| Types | Encoding Description | Example |

|--------------------------------------------|--------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|
| bool, u8 | Encoded as a single byte. `bool`: 0x00 (false) or 0x01
(true); `u8` is the byte itself. | `bool(true) = 0x01`, `u8(42) = 0x2A`
|
| u16 | 2-byte, big-endian | `u16(42) = 0x002A` |
| u32 | 4-byte, big-endian | `u32(42) = 0x0000002A` |
| u64 | 8-byte, big-endian | `u64(42) = 0x000000000000002A` |
| u128 | 16-byte, big-endian | `u128(42) =
0x0000000000000000000000000000002A` |
| u256, b256 | 32-byte value. For u256: big-endian integer; For b256:
raw 32 bytes | `u256(42) = 32-bytes ending with ...0000002A`, `b256(...)
= exactly the 32-byte array` |
| Tuples, Arrays, Structs (Fixed-size) | Concatenate the encodings of
each element/field with no extra padding | `(u8(1), bool(true)) = 0x01
0x01`; `[u16;2]: [42,100] = 0x002A0064`; `struct {u8,u8}: 0x0102` |
| Enums | `u64` variant index + encoded variant data with no extra
padding | `MySumType::X(42): 0x0000000000000000 000000000000002A` |
| Bytes, String, RawSlice, Vector (Dynamic) | `u64` length prefix + raw
data, no padding | `"abc" = length=3: 0x0000000000000003 0x61 0x62 0x63`
|

^ This is based on the docs here:
https://docs.fuel.network/docs/specs/abi/argument-encoding
</details>

## Future improvements

1. Support for function signature based calls without ABI
2. Support for raw calldata input
3. Function selector completion - given ABI file


## Checklist

- [x] I have linked to any relevant issues.
- [x] 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: zees-dev <zees-dev@users.noreply.github.com>
Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-02-07 02:30:52 +00:00
Joshua Batty
0a56930e05
forc-debug: Add ABI support for decoding log values (#6856)
## Description
Adds support for ABI files in `forc-debug` to decode log values while
debugging using the CLI. Users can now:

for example:

```
tx tx.json abi.json 
```

When the Sway ABI Registry is available, the debugger will automatically
fetch ABIs for deployed contracts. Have an issue open to implement this
here #6862

Updates documentation to show decoded log output, adds tab completion
for ABI files, and refreshes bytecode examples to match current output.

The `test_cli` test has been updated to take an ABI and check that the
correct decoded value is returned.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-02-04 06:16:29 +01:00
João Matos
9df66cea21
Fix clippy warnings for Rust 1.84.0 (#6877)
## Description

Fix clippy warnings for Rust 1.84.0
2025-02-03 21:55:35 +00:00
Vaivaswatha N
8c5afa394b
ZK opcodes in the Sway assembly (#6876)
Depends on https://github.com/FuelLabs/sway/pull/6851.

---------

Co-authored-by: green <xgreenx9999@gmail.com>
Co-authored-by: IGI-111 <igi-111@protonmail.com>
2025-02-03 10:40:45 -08:00
zees-dev
55358dae6e
chore: upgrade fuels-rs sdk to 0.70 (#6851)
## Description
Updated the `fuels-rs` SDK to `0.77`.
This required updating transitive dependencies to the relevant versions
specified in fuels-rs sdk.

## Dependency tree

```mermaid
graph TD
    sway[sway]
    fuelsrs[fuels-rs]
    fuelabi[fuel-abi-types]
    fuelvm[fuel-vm]
    forcwallet[forc-wallet]
    fcoreclient[fuels-core]
    fvmprivate[fuel-vm-private]

    %% Main dependency relationships
    sway --> fuelsrs
    fuelsrs --> fuelabi
    fuelsrs --> fuelvm
    fuelsrs --> forcwallet
    fuelsrs --> fcoreclient
    
    %% Secondary dependencies
    fcoreclient --> fvmprivate
    fvmprivate --> fuelvm
    
    %% forc-wallet dependencies
    forcwallet --> fuelvm
    forcwallet --> fuelsrs

    %% Styling
    classDef primary fill:#d0e1f9,stroke:#4a90e2,stroke-width:2px
    classDef secondary fill:#e8f4ea,stroke:#66b366,stroke-width:2px
    
    class sway,fuelsrs primary
    class fuelabi,fuelvm,forcwallet,fcoreclient,fvmprivate secondary

    %% Add notes
    subgraph Note
        note[Update forc-wallet first due to circular dependency]
        style note fill:#fff4e6,stroke:#ffab40,stroke-width:1px
    end
```

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.

---------

Co-authored-by: z <zees-dev@users.noreply.github.com>
Co-authored-by: Sophie Dankel <47993817+sdankel@users.noreply.github.com>
Co-authored-by: hal3e <git@hal3e.io>
2025-02-01 15:20:08 +13:00
Joshua Batty
f0ed57af00
Use compiler source map directly in forc-debug (#6872)
## Description
Replace the custom HashMap-based source map implementation in
`forc-debug` with the compiler's source map format directly. This
simplifies our source mapping logic and maintains better consistency
with the compiler's source location tracking, while preserving all
existing functionality.

Key changes:
- Remove custom source map types and use compiler's SourceMap
- Simplify breakpoint verification using compiler spans
- Add test to verify source map instruction-to-line mappings

closes #6733

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-01-30 21:44:51 +00:00
Sophie Dankel
9e1c320cea
fix: Adds generic trait impls to forc-doc (#6850)
## Description

Closes https://github.com/FuelLabs/sway/issues/6848

Also adds the visibility keyword `pub` to public functions

## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-01-23 08:40:21 +11:00
Igor Rončević
7aa59f987c
Add forc-migrate tool (#6790)
## Description

This PR introduces `forc-migrate`, a Forc tool for migrating Sway
projects to the next breaking change version of Sway.

The tool addresses two points crucial for code updates caused by
breaking changes:
- it informs developers about the breaking changes and **assists in
planing and executing** the migration.
- it **automatically changes source code** where possible, reducing the
manual effort needed for code changes.

Besides adding the `forc-migrate` tool, the PR:
- extends `Diagnostic` to support migration diagnostics aside with
errors and warnings.
- changes `swayfmt` to support generating source code from arbitrary
lexed trees. The change is a minimal one done only in the parts of
`swayfmt` that are executed by migration steps written in this PR.
Adapting `swayfmt` to fully support arbitrary lexed trees will be done
in #6779.

The migration for the `references` feature, migrating `ref mut` to
`&mut`, is developed only partially, to demonstrate the development and
usage of automatic migrations that alter the original source code.

The intended usage of the tool is documented in detail in the "forc
migrate" chapter of The Sway Book: _Forc reference > Plugins >
forc_migrate_. (The generated documentation has issues that are caused
by the documentation generation bug explained in #6792. These issues
will be fixed in a separate PR that will fix it for all the plugins.)

We expect the `forc-migrate` to evolve based on the developer's
feedback. Some of the possible extensions of the tool are:
- adding additional CLI options, e.g., for executing only specific
migration steps, or ignoring them.
- passing parameters to migration steps from the CLI.
- not allowing updates by default, if the repository contains modified
or untracked files.
- migrating workspaces.
- migrating other artifacts, e.g., Forc.toml files or contract IDs.
- migrating between arbitrary versions of Sway.
- migrating SDK code.
- etc.
 
`forc-migrate` also showed a clear need for better infrastructure for
writing static analyzers and transforming Sway code. The approach used
in the implementation of this PR should be seen as a pragmatic
beginning, based on the reuse of what we currently have. Some future
options are discussed in #6836.

## Demo

### `forc migrate show`

Shows the breaking change features and related migration steps. This
command can be run anywhere and does not require a Sway project.

```
Breaking change features:
  - storage_domains    (https://github.com/FuelLabs/sway/issues/6701)
  - references         (https://github.com/FuelLabs/sway/issues/5063)

Migration steps (1 manual and 1 semiautomatic):
storage_domains
  [M] Review explicitly defined slot keys in storage declarations (`in` keywords)

references
  [S] Replace `ref mut` function parameters with `&mut`

Experimental feature flags:
- for Forc.toml:  experimental = { storage_domains = true, references = true }
- for CLI:        --experimental storage_domains,references
```

### `forc migrate check`

Performs a dry-run of the migration on a concrete Sway project. It
outputs all the occurrences in code that need to be reviewed or changed,
as well as the migration time effort:

```
info: [storage_domains] Review explicitly defined slot keys in storage declarations (`in` keywords)
  --> /home/kebradalaonda/Desktop/M Forc migrate tool/src/main.sw:19:10
   |
...
19 |     y in b256::zero(): u64 = 0,
   |          ------------
20 |     z: u64 = 0,
21 |     a in calculate_slot_address(): u64 = 0,
   |          ------------------------
22 |     b in 0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20: u64 = 0,
   |          ------------------------------------------------------------------
   |
   = help: If the slot keys used in `in` keywords represent keys generated for `storage` fields
   = help: by the Sway compiler, those keys might need to be recalculated.
   = help:  
   = help: The previous formula for calculating storage field keys was: `sha256("storage.<field name>")`.
   = help: The new formula is:                                          `sha256((0u8, "storage.<field name>"))`.
   = help:  
   = help: For a detailed migration guide see: https://github.com/FuelLabs/sway/issues/6701
____

Migration effort:

storage_domains
  [M] Review explicitly defined slot keys in storage declarations (`in` keywords)
      Occurrences:     3    Migration effort (hh::mm): ~00:06

references
  [S] Replace `ref mut` function parameters with `&mut`
      Occurrences:     0    Migration effort (hh::mm): ~00:00

Total migration effort (hh::mm): ~00:06
``` 

### `forc migrate run`

Runs the migration steps and guides developers through the migration
process.

## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.
2025-01-20 13:14:20 +01:00
Joshua Batty
9cd1b3913d
migrate from shellfish to rustyline with enhanced CLI features (#6830)
## Description
This PR migrates the `forc debug` CLI from `shellfish` to `rustyline`,
providing enhanced interactive debugging features. Key improvements
include:

- Command history with persistence
- Intelligent command completion for debugger commands, register names,
and transaction files
- Command suggestions/corrections for typos
- Contextual hints showing command descriptions

The migration also reorganizes the CLI code into separate modules for
better maintainability while preserving all existing debugger
functionality.

See video below for demo. 


https://github.com/user-attachments/assets/429b0e85-c922-4a26-8bca-fca9af34e00a


## 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).
- [ ] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [ ] 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.
2025-01-17 12:21:57 +01:00
jjcnn
2b2ce517d1
Refactor the module structure of the namespace module (#6291)
## Description

Fixes #5498.

This PR contains a major refactoring of the namespace module, which is
responsible for keeping track of the symbol bindings in the program. The
refactoring is intended to reduce memory allocation during compilation,
and also fixes a number of minor bugs related to path resolution.

### Advice to the reviewer:

I recommend reviewing this PR in 3 steps:
1. Review the PR description. If something in the description is
unclear, then leave a review comment, and I will try to address the
issue. The code changes will be significantly easier to review once you
get the overall idea of what is happening.
2. Review the files `sway-core/src/semantic_analysis/namespace/root.rs`,
`sway-core/src/semantic_analysis/namespace/namespace.rs` and
`sway-core/src/language/call_path.rs`. These files contain the major
datastructure changes, and if anything in those files needs to be
addressed, then there is limited value in reviewing the rest of the code
changes.
3. Review the remaining files. These code changes are all consequences
of the changes in step 2, so it shouldn't take too much time, even
though there are quite a few changes.

### Remaining issues

No remaining issues except for what reviwers bring up.

### Breaking changes

As illustrated by one of the test cases the PR makes paths to external
libraries such as `::core::codec::*` illegal. This is a bugfix rather
than a change in behavior (the correct path is `core::codec::*`), but
may require updates of existing programs.

Additionally, the visibility check for modules was broken, so some
modules declared using `mod x` would have incorrectly been considered
public even though it should have been declared `pub mod x`. Again, this
is a bugfix rather than a change of behavior, but may require updates of
existing programs.

### Changes made by this PR

_Representation of the dependency graph_ (main file:
`sway-core/src/semantic_analysis/namespace/root.rs`)

Previous: External libraries were represented as submodules of every
module in the program. This meant that every module in every external
package was cloned for every module in the program, and recursively so,
since external libraries could also have dependencies that required
clones for every module. In particular, `std` has `core` as a
dependency:

```
                       core:

                       "" (lib.sw)
          /         /     |         \      \	
   primitives  raw_ptr  raw_slice  slice   ...


                        std:

                          "" (lib.sw)
          /         /        |         \                      \	
       core    constants    vec     primitive_conversions    ...
    / / | \ \       |        |         |        |     \
      ...         core      core      core     b256   ...
               / / | \ \  / / | \ \ / / | \ \   | 
                 ...        ...       ...     core
                                            / / | \ \
					       ...  


                      External library:


                          "" (lib.sw)
          /         /           |              \
       core        std         submodule        ...
    / / | \ \     /   \       /       \    \
      ...       core  ...   core      std    ...
             / / | \ \   / / | \ \    /   \   
                 ...        ...     core   ... 
                                  / / | \ \
				   	       

                         Main program:


                          "" (main.sw)
          /         /           |                        \
       core        std     external library                 submodule
    / / | \ \     /   \       /       \    \               /  |       \
      ...       core  ...   core      std    submodule  core  std    external library
             / / | \ \   / / | \ \    /   \      /  \    / \  /   \      /       |     \
                 ...        ...     core   ...  ... ...  ...  core ...  core    std    ...
                                  / / | \ \                   / \        / \    / \ 
                                                              ...        ... core  ...
                                                                              / \
                                                                              ...

```

Changes in this PR: External libraries are now represented only at the
package root. The root module is given the same name as the package so
that paths beginning with the package name can be resolved as a module
path. If multiple libraries depend on the same external library, then
they each contain a clone (this can be resolved a at later stage by
introducing a global table of libraries).

```
                       core:

                       core (lib.sw)
          /         /     |         \      \	
   primitives  raw_ptr  raw_slice  slice   ...


                        std:

                     std (lib.sw)    ====== externals =====>   core
                                                             / / | \ \
           /      |          |                \                 ...
      constants  vec   primitive_conversions    ...             
                           /     \
                        b256     ...


                   External library:

     external_lib (lib.sw)  === externals ===>   core
        /          \                          / / | \ \
    submodule      ...                           ...
       |
      ...                                        std    == externals => core
                                              / / | \ \              / / | \ \
                                                 ...                    ...       				   	       


                     Main program:

    main_program (main.sw)  === externals ===>  core
      /           \                          / / | \ \
  submodule      ...                            ...
      |
     ...                                        std      == externals => core
                                             / / | \ \                / / | \ \
                                                ...                      ...       				   	       

                                            extenral_lib == externals => core
                                             / / | \ \                / / | \ \
                                                ...                      ...       				   	       

                                                                         std      == externals => core  
                                                                      / / | \ \                / / | \ \
                                                                         ...                      ...       			
```
Reasoning: This change dramatically reduces the amount of cloning of
external libraries. The cloning is not eliminated completely, since
multiple libraries may have the same library as a dependency (e.g.,
`core` is used as a dependency for both the program and `std`, so if the
program depends on `std`, then there will be two clones of `core` in the
tree). The remaining cloning can be eliminated by introducing a global
table of libraries, which should be doable without making significant
changes to the path resolution algorithm.

_Callpath representation_ (main file:
sway-core/src/language/call_path.rs)

Previous: Paths to externals were considered relative to current module.
This worked because all externals existed a submodules of every module.
Paths inside the current package were ambiguous, and were either
interpreted relative to current module or relative to the root module.
The root module did not have a name, so the empty path was used to
indicate the root module.

Now: All full paths start with the name of the package, which is also
the name of the root module. If the first identifier is not the name of
the current package, then we look in the externals of that package, and
if the name isn't found there we throw an error. Note that the name of
an external is defined in Forc.toml, and may be different from the name
used inside the external library (e.g., a library may call itself `X`,
but a project may use `X` as an external under the name `Y`). This means
that any path that escapes from a library must have its package name
changed.

Reasoning: This is all a conseqence of the change to the representation
of the dependency graph. We need to be able to the rely on the package
name in order to resolve the path within the correct pacakge.
Additionally, if a path escapes from a dependency to a dependent, then
the package name must be changed to what the package is called in the
dependent.

_CallPath.callpath_type_ (main file:
sway-core/src/language/call_path.rs)

Previous: The CallPath struct contained a flag `is_absolute`, which, if
set, was used to mean two different things. For parsed paths it was used
to signal that the path started with `::`, i.e., that the path should be
resolved relative to the current package root. For paths generated
during typechecking the flag was used to indicate that the path was a
full path, i.e., that it should either be resolved relative to the
current package root or that it was a path to an external library.

Now: `is_absolute` has been replaced with `callpath_type`, which has 3
possible values: `RelativeToPackageRoot`, which indicates that the path
started with `::`, `Full`, which indicates that the path starts with the
package name, and `Ambiguous`, which indicates that the path should
either be resolved relative to the current module, or that it is a full
path referring to an external library.

Reasoning: A path has 3 different states, so a boolean flag is not
sufficient to represent all states.

_Path representation_ (main file: sway-core/src/language/call_path.rs)

Previous: Full paths always pointed to the module containing the
declaration of the thing that the path resolves to.

Now: Full paths point to a module where the suffix is bound. This may
not be the module containing the declaration of the thing the suffix is
bound to, because the binding may be the result of an import. The trait
map is special in that the path to the actual declaration is used as a
key in the map, so for traits we use the canonical path, which point to
the module where the declaration resides.

Reasoning: The previous definition of full paths required a duplication
of the symbol resolution algorithm in order to construct the full path,
and it was getting very difficult to maintain. In the vast majority of
cases we only need the full path to indicate somewhere where the symbol
can be resolved, and don't actually need to know where the declaration
resides. In the few cases where we do need to know the path to the
declaration (the trait map uses these paths as keys) we can generate the
canonical path by first converting to the full path, and then resolving
the path and using the path stored with the binding in the lexical
scope, since this is the path to the actual declaration. Additionally,
the previous solution was only able to generate full paths for paths
where the suffix is an identifier - for other suffix types we could not
generate a full path. This has now been changed so that we can generate
full paths for all paths, although canonical paths are still restricted
to paths with an identifier as the suffix. This also moves us closer to
a situation where we can represent semantic (canonical) paths separately
from syntactic callpaths.

_Namespace.init removed_ (main file:
sway-core/src/semantic_analysis/namespace/namespace.rs)

Previous: The `Namespace` struct contained an `init` module which was
used as a template for new modules, a clone of which was created every
time the collection pass or the typechecker entered a submodule. This
template contained all external libraries as submodules, as well as (for
contract pacakges) a (new) declaration of `CONTRACT_ID`.

Now: The `init` module has been removed. When the collection pass or the
typechecker enters a new submodule, `Namespace` creates a new `Module`
(if none exists yet for the relevant submodule), and populates it with
implicit imports (`core::prelude::*` and `std::prelude::*`, and for
contract packages `CONTRACT_ID`).

Reasoning: The current solution makes it significantly clearer what is
in a new `Module` object. Additionally, the declaration of `CONTRACT_ID`
is no longer duplicated in each module - it is now declared once in the
root module, and imported everywhere else.

_namespace encapsulation_ (main file:
sway-core/src/semantic_analysis/namespace/namespace.rs)

Previous: The `Namespace` struct contained methods to extract the
underlying datastructures in the `namespace` module.

Now: An attempt has been made to encapsulate the `namespace` module a
little bit more, so that changes and lookups to the datastructures in
the `namespace` module are done by calling methods on the Namespace
struct rather than letting the caller extract the datastructures and
manipulating them directly.

Reasoning: When the datastructures are manipulated in many different
places it makes it very hard to track down all the places that need to
be changed when making changes to the datastructure. The current
solution is not perfect, but it does encapsulate things a bit better
than before.


### Minor changes and improvements

A few minor improvements have been made:

- A compilation unit (`core`, `std`, etc.) is now referred to as a
_package_. (Note: The `Root` struct should probably be renamed to
`Package` for consistency)
- The visibility check for path resolution in `type_resolve.rs` had to
be updated because path resolution was changed. The current version is
not perfect, but it does improve the faulty check we had before.
- `TyModule` so far contained a clone of the `Namespace` struct in the
state it was in when typechecking of the relevant module was done. The
`Namespace` object was never used except for the one in the root module,
so I have moved the `Namespace` clone to `TyProgram`, thus eliminating
quite a bit of unnecessary cloning (the Namespace struct owns the
current package `Root` object, and thus cloning the `Namespace` struct
clones the entire dependency graph). For error handling purposes in
sway-lsp we save the current namespace in `TypeCheckFailed` rather than
in `TyModule`, which also significantly reduces memory allocation during
compilation.

### Updated tests

A number of tests have been updated for various reasons:

- Improved or changed error messages
- Module visibility was not checked correctly, so some tests had to have
certain submodules made public.
- In once case, `core::str_slice` was referenced using the path
`::core::str_slice`. This is invalid, but since `core` used to be
treated as a submodule of every module in the program, the path resolved
anyway. (This also shows that the invalid paths in issue #5498 are now
actually treated as invalid - I have not added regression tests of that
issue, since it seems unlikely that we will reintroduce the bug).

### Unresolved issues

- The `Namespace` struct is cloned before the symbol collection phase.
This is expensive, since the `Namespace` struct at that point contains
the entire dependency graph (minus the modules of the current package).
Ideally we would like the symbol collection phase and the typechecker to
use the same `Namespace` struct, but at the moment the Module struct is
unable to perform updates from parsed to typechecked declarations, so
this isn't possible. The cloning happens in `sway-core/src/lib.rs` and
`sway-core/src/semantic_analysis/namespace/contract_helpers.rs`. Once we
represent externals as a global table we should be able to change the
`Root.externals` map to only use references into the global table, which
will make the cloning step much cheaper.

- `contract_helpers.rs` throws a regular compiler error if typechecking
fails, but that should be an ICE, since it is generated code that is
failing to typecheck.

- Paths may in some cases escape from external packages to the current
package. If this happens across multiple packages, then this may result
in the path no longer being valid. For instance, if A depends on B,
which in turn depends on C, then a path may escape from C via B into A,
but since A does not have C as a direct dependency, then the path can no
longer be resolved. This again can be fixed once we introduce a global
table of externals.

- The visibility check in `type_resolve.rs` is insufficient, because it
doesn't handle enum variants and associated types correctly.


## Checklist

- [x] I have linked to any relevant issues.
- [x] I have commented my code, particularly in hard-to-understand
areas.
- [x] I have updated the documentation where relevant (API docs, the
reference, and the Sway book).
- [x] If my change requires substantial documentation changes, I have
[requested support from the DevRel
team](https://github.com/FuelLabs/devrel-requests/issues/new/choose)
- [x] I have added tests that prove my fix is effective or that my
feature works.
- [x] I have added (or requested a maintainer to add) the necessary
`Breaking*` or `New Feature` labels where relevant.
- [x] 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).
- [x] I have requested a review from the relevant team or maintainers.

---------

Co-authored-by: João Matos <joao@tritao.eu>
Co-authored-by: Joshua Batty <joshpbatty@gmail.com>
2025-01-17 00:55:37 +00:00