Skip to content

An owned if/match join passed to a &T parameter is refused: "if expression of type str cannot produce &str" #1754

Closed

Description

@ehartford

Spec: §3.8 ("When a function takes &T and you pass an owned T, the compiler automatically borrows it"); D22 ruling §8.2 (rule 1: all arms of one exact type keep it; rule 2: the owned result type is established by an enclosing owned expected type or by the non-reference arms; rule 5: an owned temporary is never borrowed to force a reference result).

fn f(s: &str) -> i64: s.len()
fn main:
    let a = "x".clone()
    let c = true
    print(f"{f(a ++ \"yy\")}")                           // 3
    print(f"{f(if c: a ++ \"yy\" else: a ++ \"z\")}")    // refused
error: if expression of type `str` cannot produce `&str`

check_call passes the parameter type &str as the argument's expected type, and resolve_contextual_join keeps it as the join's final_type (the soft-anchor branch does not fire because &str accepts str through auto-ref), so every owned arm fails final_is_ref. Per D22 §8.2 the join is str and the call borrows it, exactly as it borrows a ++ "yy".

A narrow fix in resolve_contextual_join (a &T expectation is not an owned anchor) is not enough: the arms are checked under the &str expectation first, so a string-literal arm is typed &str and then fails as a non-Copy reference arm of an owned join (if …: text ++ "(…)" else: "the generator", SemaCheck.w). The expectation an argument meets at a &T parameter needs to be decided once for the arms and the join.

Found while fixing #1712. That fix gives method arguments their declared parameter type as the expectation (as check_call does) but, because of this bug, not for &T parameters: two call sites in the compiler's own source (lower_debug_write_literal(buf, if …: a ++ b else: c ++ d, 0), pool_intern(if …: text ++ "(…)" else: "the generator")) would otherwise stop compiling. When this is fixed, method_sig_expected_arg_type should publish &T too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions