Skip to content

Be more specific on the the special case of condition expressions of if expressions #1553

Closed as not planned
@ttzytt

Description

@ttzytt

The grammar for if expressions is described as:

image

Notice that there is a special case for the condition expression "except struct expression." Not sure if I'm correct, but I think this meant to specify the cases that result in ambiguity, such as

if A{} {
}

Where A is a struct. In this case, I assume the parser/compiler cannot determine whether A itself is a variable and the following {} is the block, or alternatively, A{} as a whole is an expression.

However, there are other cases leading to compile errors even if the condition expression is not struct expression, below are two examples:

use std::ops;
struct A;
struct B;

impl ops::Add<B> for A{
    type Output = bool;
    fn add(self, rhs : B) -> bool{true}
}

impl A{
    fn to_bool(self) -> bool {true}
}

fn main(){
    if A{}.to_bool() {()} // ex1
    if A{} + B{} {()} //ex2
}

In ex1 a method call expression is shown, and in ex2 an operator expression is shown.

Adding paratheses around the two expressions will resolve the error.

I feel like this needs to be better explained in the reference other than "except struct expression," as the expression does not have to be struct expression to induce error.

If I understood the problem correctly, I'm willing to submit a PR for this using similar examples, please point me out if the original description is intentional.

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