Skip to content

Rust output fails to compile (E0308) wherever a string literal is returned as, or assigned to, a str/string type, which maps to owned String #84

Description

@matt-edmondson

What's wrong

RustGenerator's TypeMappings maps str and string to the owned type String. A string literal is written as a bare "..." (LanguageGeneratorBase, and RustGenerator does not override it), which in Rust is a &'static str. Wherever the two meet, the generated code does not compile.

Reproduction

Found with a scratch app against Coder at aae2bb6, and the output compiled with rustc (edition 2021):

AST Rust output rustc
FunctionDeclaration("greet") { ReturnType = "str" } whose body is ReturnStatement(Literal.Text("hello")) pub fn greet() -> String { return "hello"; } error[E0308]: mismatched types (expected String, found &str)
VariableDeclaration("name", "str", Literal.Text("x")) let mut name: String = "x"; error[E0308]: mismatched types

The same AST compiles in the other targets. The tests miss it because the Rust compile tests only use &str parameters, and RustGeneratorTests.Types_AreMappedToRustSpellings asserts -> String without ever returning a literal.

Suggested fix

When a string literal's target is an owned String, write String::from("…") (or "…".to_string()). The target can be:

  • the return of a function whose return type maps to String
  • the initialiser of a String-typed local, let, or field
  • a field value in a construction

Keep the bare literal where the target is &str or unknown. A simpler alternative is to always write String::from("…") for text literals in Rust. That is correct everywhere an owned String is expected, and borrows to &str automatically only in some positions, so check the call-argument cases.

Acceptance criteria

  • A rustc compile test that returns and assigns a string literal to str/string-typed targets builds cleanly.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingreadyFully specified; implement as written

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions