Restrict var statements to the top of functions

This commit is contained in:
Nigel Tao committed 2018-12-27 11:19:22 +11:00
1 parent 84f9d3a915
commit cbe19f50e0
5 files changed
+36 -56

No files matched your search

+1 -3
View File
@@ -540,9 +540,7 @@ func (c *Checker) checkFuncBody(node *a.Node) error {
localVars: c.localVars[n.QQID()],
}
// Fill in the TypeMap with all local variables. Note that they have
// function scope and can be hoisted, JavaScript style, a la
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/var
// Fill in the TypeMap with all local variables.
if err := q.tcheckVars(n.Body()); err != nil {
return &Error{
Err: err,
+12 -38
View File
@@ -24,47 +24,21 @@ import (
func (q *checker) tcheckVars(block []*a.Node) error {
for _, o := range block {
if o.Kind() != a.KVar {
break
}
q.errFilename, q.errLine = o.AsRaw().FilenameLine()
switch o.Kind() {
case a.KIf:
for o := o.AsIf(); o != nil; o = o.ElseIf() {
if err := q.tcheckVars(o.BodyIfTrue()); err != nil {
return err
}
if err := q.tcheckVars(o.BodyIfFalse()); err != nil {
return err
}
}
case a.KIOBind:
if err := q.tcheckVars(o.AsIOBind().Body()); err != nil {
return err
}
case a.KIterate:
for o := o.AsIterate(); o != nil; o = o.ElseIterate() {
if err := q.tcheckVars(o.Body()); err != nil {
return err
}
}
case a.KVar:
o := o.AsVar()
name := o.Name()
if _, ok := q.localVars[name]; ok {
return fmt.Errorf("check: duplicate var %q", name.Str(q.tm))
}
if err := q.tcheckTypeExpr(o.XType(), 0); err != nil {
return err
}
q.localVars[name] = o.XType()
case a.KWhile:
if err := q.tcheckVars(o.AsWhile().Body()); err != nil {
return err
}
o := o.AsVar()
name := o.Name()
if _, ok := q.localVars[name]; ok {
return fmt.Errorf("check: duplicate var %q", name.Str(q.tm))
}
if err := q.tcheckTypeExpr(o.XType(), 0); err != nil {
return err
}
q.localVars[name] = o.XType()
}
return nil
}