Skip to content

Commit

Permalink
wip: keep record where global variable is declare
Browse files Browse the repository at this point in the history
  • Loading branch information
gravataLonga committed Jul 12, 2022
1 parent 4cd871b commit 17250ce
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
12 changes: 7 additions & 5 deletions semantic/semantic.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ package semantic
import (
"fmt"
"ninja/ast"
"ninja/token"
)

// Semantic here is where we are going doing some semantic analysis
// using visitor pattern
type Semantic struct {
scopeStack Stack
globalVariable map[string]ast.Expression
globalVariable []string
errors []string
}

Expand Down Expand Up @@ -43,6 +42,7 @@ func (s *Semantic) exitScope() {
// declare will keep track of declare variables
func (s *Semantic) declare(name string) {
if s.scopeStack.IsEmpty() {
s.globalVariable = append(s.globalVariable, name)
return
}

Expand All @@ -57,10 +57,12 @@ func (s *Semantic) resolve(name string) {
return
}

*peek = Scope{name: true}
(*peek)[name] = true
}

func (s *Semantic) expectIdentifierDeclare(name string, tok token.Token) bool {
func (s *Semantic) expectIdentifierDeclare(ident *ast.Identifier) bool {
name := ident.Value
tok := ident.Token
peek, ok := s.scopeStack.Peek()
if !ok {
s.NewError("There aren't any scope active %s", name)
Expand Down Expand Up @@ -101,7 +103,7 @@ func (s *Semantic) analysis(node ast.Node) ast.Node {
s.analysis(v)
}
case *ast.Identifier:
s.expectIdentifierDeclare(node.Value, node.Token)
s.expectIdentifierDeclare(node)
case *ast.VarStatement:
s.declare(node.Name.Value)
s.analysis(node.Value)
Expand Down
9 changes: 9 additions & 0 deletions semantic/semantic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@ func TestScopeVariablesWrong(t *testing.T) {
}
}

func TestMarkVariableAsGlobal(t *testing.T) {
s := testSemantic("var a = 0", t)

if len(s.globalVariable) <= 0 {
t.Fatalf("Variable a isn't mark as global")
}

}

// checkParserErrors check if there are parser errors
func checkParserErrors(t *testing.T, p *parser.Parser) {
errors := p.Errors()
Expand Down

0 comments on commit 17250ce

Please sign in to comment.