Need a review about semantic analysis

Hello like title said, just need a pair of eye for just checking if what i’m doing with semantic analysis is correct or no. Basically i’m just checking if a variable was already declare or not.

Anyone can give me ways of improve and/or any tips, name convention, patterns, improve in speed, etc.

You can check it here:
main/semantic ← code where need a bit of help.

Thank you all in advance, your help count a lot to me, i’m newbie with golang.

Best Regards,

No one would like to review it?

I only have a basic understanding of compilation, but I’m a bit confused about what (*semantic.Semantic).expectIdentifierDeclare does. It looks to me like here is supposed to be the actual check to make sure that an identifier is declared, but it assumes if it cannot find the identifier in the current scope, that it must be a global. Does this language support closures or nested scopes, e.g.:

function () {
    var a = true;
    {
        var b = a;
    }
}

If so, you might want to loop through the scopeStack frames to see if an outer frame declares the variable.

EDIT: It also appears to me that global variables can be redefined because you’re using a slice for globals instead of a *Scope. Maybe this is intentional, but if not, perhaps you could change the definition of Semantic to:

type Semantic struct {
	scopeStack      Stack
	globalVariables Scope
	localVariables  map[ast.Node]int
	errors          []string
}

func New() *Semantic {
	s := &Semantic{
		scopeStack: make(Stack, 1, 8),	// might as well pre-reserve some
		globalVariables: Scope{},		// capacity to avoid those early
	}									// reallocations from 1 -> 2 -> 4 -> 8
	s.scopeStack[0] = &s.globalVariables
	return s
}

/* ... */

func (s *Semantic) declare(name string) {
// don't need this any more because there's now always a scope on the stack.
// the first one is the global scope.
//
//	if s.scopeStack.IsEmpty() {
//		s.globalVariables = append(s.globalVariables, name)
//		return
//	}

	peek, _ := s.scopeStack.Peek()
	(*peek).Put(name, false)
}

Thank you so much for your time and spend your time in review it. Mean a lot to me, thank you very much again.

Yeah i’m confuse too, that why i can’t decide best way of doing. What i’m trying to do is fixing following code:

var a = "global";
function createB() {
  var b = a;
  return b;
}
var a = "other global";
function createC() {
   var c = a;
   return c;
}

puts(createdB()); // this need to print "global", but it will print "other global";
puts(createA()); // It will print "other global";  

So my problem, is not make a correct snapshot of Environment, that was my initial problem of implementing a semantic analysis.

About this,

Yeah, i’m original ideia is you can redefined global variables, but probably you are right, that is a good point.