Skip to content

Commit 1d1b5bb

Browse files
committed
Forbid to redeclare variables, builtins, functions.
1 parent f716dc5 commit 1d1b5bb

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

checker/checker.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -875,6 +875,18 @@ func (v *visitor) PointerNode(node *ast.PointerNode) (reflect.Type, info) {
875875
}
876876

877877
func (v *visitor) VariableDeclaratorNode(node *ast.VariableDeclaratorNode) (reflect.Type, info) {
878+
if _, ok := v.config.Types[node.Name]; ok {
879+
return v.error(node, "cannot redeclare %v", node.Name)
880+
}
881+
if _, ok := v.config.Functions[node.Name]; ok {
882+
return v.error(node, "cannot redeclare function %v", node.Name)
883+
}
884+
if _, ok := v.config.Builtins[node.Name]; ok {
885+
return v.error(node, "cannot redeclare builtin %v", node.Name)
886+
}
887+
if _, ok := v.lookupVariable(node.Name); ok {
888+
return v.error(node, "cannot redeclare variable %v", node.Name)
889+
}
878890
vtype, vinfo := v.visit(node.Value)
879891
v.scopes = append(v.scopes, scope{node.Name, vtype, vinfo})
880892
t, i := v.visit(node.Expr)

checker/checker_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,26 @@ repeat("0", 1/0)
507507
cannot use float64 as argument (type int) to call repeat (1:14)
508508
| repeat("0", 1/0)
509509
| .............^
510+
511+
let map = 42; map
512+
cannot redeclare builtin map (1:5)
513+
| let map = 42; map
514+
| ....^
515+
516+
let len = 42; len
517+
cannot redeclare builtin len (1:5)
518+
| let len = 42; len
519+
| ....^
520+
521+
let Float = 42; Float
522+
cannot redeclare Float (1:5)
523+
| let Float = 42; Float
524+
| ....^
525+
526+
let foo = 1; let foo = 2; foo
527+
cannot redeclare variable foo (1:18)
528+
| let foo = 1; let foo = 2; foo
529+
| .................^
510530
`
511531

512532
func TestCheck_error(t *testing.T) {

parser/parser.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,11 +193,13 @@ func (p *parser) parseVariableDeclaration() Node {
193193
value := p.parseExpression(0)
194194
p.expect(Operator, ";")
195195
node := p.parseExpression(0)
196-
return &VariableDeclaratorNode{
196+
let := &VariableDeclaratorNode{
197197
Name: variableName.Value,
198198
Value: value,
199199
Expr: node,
200200
}
201+
let.SetLocation(variableName.Location)
202+
return let
201203
}
202204

203205
func (p *parser) parseConditional(node Node) Node {

0 commit comments

Comments
 (0)