v icon indicating copy to clipboard operation
v copied to clipboard

support smart casting receiver var

Open Delta456 opened this issue 6 months ago • 1 comments

Describe the feature

The method receiver should support smart casting so that it can be used like a normal statement

pub fn (mut expr Expr) remove_para() Expr {
    for mut expr is ParExpr {
        expr = expr.expr
    }
    return expr

}

is the same as:

for mut expr is ParExpr {
        expr = expr.expr
    }

}

But currently, this doesn't work

vlib/v/ast/ast.v:2732:15: error: field `expr` does not exist or have the same type in these sumtype `v.ast.Expr` variants: v.ast.NodeError, v.ast.AnonFn, v.ast.ArrayInit, v.ast.Assoc, v.ast.AtExpr, v.ast.BoolLiteral, v.ast.CTempVar, v.ast.CallExpr, v.ast.ChanInit, v.ast.CharLiteral, v.ast.Comment, v.ast.ComptimeCall, v.ast.ComptimeSelector, v.ast.ComptimeType, v.ast.ConcatExpr, v.ast.EnumVal, v.ast.FloatLiteral, v.ast.GoExpr, v.ast.Ident, v.ast.IfExpr, v.ast.IndexExpr, v.ast.InfixExpr, v.ast.IntegerLiteral, v.ast.LockExpr, v.ast.MapInit, v.ast.MatchExpr, v.ast.Nil, v.ast.None, v.ast.OffsetOf, v.ast.OrExpr, v.ast.PrefixExpr, v.ast.RangeExpr, v.ast.SelectExpr, v.ast.SpawnExpr, v.ast.SqlExpr, v.ast.StringInterLiteral, v.ast.StringLiteral, v.ast.StructInit, v.ast.TypeNode
 2730 | pub fn (mut expr Expr) remove_para() Expr {
 2731 |     for mut expr is ParExpr {
 2732 |         expr = expr.expr
      |                     ~~~~
 2733 |     }
 2734 |     return expr

The workaround is:

pub fn (mut expr Expr) remove_par() Expr {
	mut e := expr // tmp var here
	for mut e is ParExpr {
		e = e.expr
	}
	return e
}

Use Case

It is more convenient to use expr.remove_par() without using a temp var for smart cast

Proposed Solution

Given above

Other Information

No response

Acknowledgements

  • [ ] I may be able to implement this feature request
  • [ ] This feature might incur a breaking change

Version used

Latest

Environment details (OS name and version, etc.)

Not required

Delta456 avatar Jun 08 '25 07:06 Delta456

Connected to Huly®: V_0.6-23027

huly-for-github[bot] avatar Jun 08 '25 07:06 huly-for-github[bot]