Skip to content

Use SourceFile for code uniqueness in source manager #1380

@PhilippGackstatter

Description

@PhilippGackstatter

In order to get proper errors in tests, we have to ensure uniqueness of the "source code file" passed to the assembler. See this comment for details: #1353 (comment).

Ideally, we would refactor all code passed to assemble_program or assemble_library (or APIs that wrap those) to be an Arc<SourceFile> instead of a raw string, but that would be a bit of work and may not bring that much benefit to be really necessary. Still, there are two low-hanging fruits/places where we can gain something, especially because these are testing APIs that we use but are also user-facing. I would suggest applying the change to these APIs:

  • CodeExecutor::run
  • TransactionContext::execute_code_with_assembler

For the issue that was described in the thread in the above link, I tried a quick-fix by updating NoteBuilder::build to this:

let source_id = SourceId::new(self.serial_num[0].as_int() as u32 % u32::MAX);
let virtual_source_file = Arc::new(SourceFile::new(
  source_id,
    format!("inline_note_test_script_{}", source_id.to_u32()),
    self.code,
));
let code = assembler.clone().assemble_program(virtual_source_file).unwrap();

A better way would be to do this in NoteBuilder::code as suggested in the above link. The serial number is generated earlier (in NoteBuilder::new) from an RNG and then used here as randomness for the source ID and path. This resulted in an error message pointing to the correct source location.

We could add a SourceFileExt extension trait (behind testing) to make creation of an Arc<SourceFile> from a raw string very convenient with roughly the above logic. That will make it easy to convert existing test in the future or write new ones with minimal effort.

We should also add a couple of sentences to on all compile constructors to mention that passing an Arc<SourceFile> is preferable over raw strings for error quality purposes (but is not necessary when passing a file path in the first place). This applies to AccountComponent, NoteScript and TransactionScript.

To summarize, the task here is to:

  • Add a simple way to create an Arc<SourceFile> from a raw string and generate a random source ID and path or provide one (depending on whether we have access to randomness APIs).
  • Update the code executor, transaction context and note builder to pass such source files to the assemble APIs.
  • Add doc comments for compile methods.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions