Skip to content

Commit

Permalink
fix: better error message for unused variable
Browse files Browse the repository at this point in the history
The error message now reports the line where the variable was first
declared, rather than the end of the block in which id had to be
used.
  • Loading branch information
tucats committed Jan 4, 2025
1 parent 6a77cb6 commit 1b0ed6f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 25 deletions.
33 changes: 9 additions & 24 deletions compiler/symbols.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
package compiler

import (
"sort"
"strings"

"github.com/tucats/ego/errors"
)

type scope struct {
module string
depth int
usage map[string]bool
usage map[string]*errors.Error
}

type scopeStack []scope
Expand All @@ -19,7 +16,7 @@ func newScope(name string, line int) scope {
return scope{
module: name,
depth: line,
usage: make(map[string]bool),
usage: make(map[string]*errors.Error),
}
}

Expand All @@ -43,25 +40,11 @@ func (c *Compiler) PopScope() error {
return nil
}

names := []string{}

scope := c.scopes[len(c.scopes)-1]
for name, used := range scope.usage {
if !used {
names = append(names, name)
}
}

if len(names) > 0 {
sort.Strings(names)

module := scope.module
if module != "" {
c.b.SetName(module)
module = ", at " + module
for _, used := range scope.usage {
if used != nil {
return used
}

return c.error(errors.ErrUnusedVariable, strings.Join(names, ", ")+module)
}

c.scopes = c.scopes[:len(c.scopes)-1]
Expand All @@ -74,7 +57,9 @@ func (c *Compiler) CreateVariable(name string) *Compiler {
c.PushScope()
}

c.scopes[len(c.scopes)-1].usage[name] = false
if _, found := c.scopes[len(c.scopes)-1].usage[name]; !found {
c.scopes[len(c.scopes)-1].usage[name] = c.error(errors.ErrUnusedVariable, name)
}

return c
}
Expand All @@ -84,7 +69,7 @@ func (c *Compiler) UseVariable(name string) *Compiler {
// given variable. If found, mark it as used.
for i := len(c.scopes) - 1; i >= 0; i-- {
if _, found := c.scopes[i].usage[name]; found {
c.scopes[i].usage[name] = true
c.scopes[i].usage[name] = nil

break
}
Expand Down
2 changes: 1 addition & 1 deletion tools/buildver.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.5-1176
1.5-1177

0 comments on commit 1b0ed6f

Please sign in to comment.