Skip to content

Commit

Permalink
transformer: fix using a constant, instead of a fn parameter with the…
Browse files Browse the repository at this point in the history
… same name (fix vlang#19766) (vlang#19773)
  • Loading branch information
mwmuni authored Nov 5, 2023
1 parent 1f8fbb5 commit e7f0c6b
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
32 changes: 32 additions & 0 deletions vlib/v/tests/const_with_fn_param_with_the_same_name_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const zoom_factor = 1.1

fn abc(zoom_factor f64) {
assert zoom_factor != 1.1, 'zoom_factor here is the parameter name, not the constant from above'
assert zoom_factor * 10 < 2
assert zoom_factor * 10 > 0.9
dump(zoom_factor)
a := if zoom_factor < 1 { 1 } else { -1 }
assert a == 1
}

fn def(zfactor f64) {
assert zfactor != zoom_factor, 'zfactor is different than zoom_factor in both name and value'
dump(zfactor)
a := if zfactor < 1 { 1 } else { -1 }
assert a == 1
}

fn xyz(zfactor f64) {
assert zfactor != zoom_factor, 'both zfactor and the const zoom_factor should be available, and have different values'
dump(zfactor)
z := if zoom_factor < 1 { 1 } else { -1 }
assert z == -1
dump(zoom_factor)
assert zoom_factor * 10 > 10.0
}

fn test_a_const_should_not_be_used_inside_fn_that_have_parameters_with_the_same_name() {
abc(0.1)
def(0.1)
xyz(0.1)
}
7 changes: 5 additions & 2 deletions vlib/v/transformer/transformer.v
Original file line number Diff line number Diff line change
Expand Up @@ -696,8 +696,7 @@ pub fn (mut t Transformer) expr(mut node ast.Expr) ast.Expr {
}
else {}
}
}
*/
}*/
else {}
}
return node
Expand All @@ -713,6 +712,10 @@ pub fn (mut t Transformer) call_expr(mut node ast.CallExpr) ast.Expr {
fn (mut t Transformer) trans_const_value_to_literal(mut expr ast.Expr) {
mut expr_ := expr
if mut expr_ is ast.Ident {
// if there is a local variable or a fn parameter, that has the same name as the constant, do not do the substitution:
if _ := expr_.scope.find_var(expr_.name) {
return
}
if mut obj := t.table.global_scope.find_const(expr_.mod + '.' + expr_.name) {
if mut obj.expr is ast.BoolLiteral {
expr = obj.expr
Expand Down

0 comments on commit e7f0c6b

Please sign in to comment.