Globals to compiler

This commit is contained in:
Chuck Smith
2024-02-20 16:07:01 -05:00
parent 6ba2d3abe4
commit e8254fc996
7 changed files with 213 additions and 0 deletions

View File

@@ -18,6 +18,8 @@ type Compiler struct {
lastInstruction EmittedInstruction
previousInstruction EmittedInstruction
symbolTable *SymbolTable
}
func New() *Compiler {
@@ -26,6 +28,7 @@ func New() *Compiler {
constants: []object.Object{},
lastInstruction: EmittedInstruction{},
previousInstruction: EmittedInstruction{},
symbolTable: NewSymbolTable(),
}
}
@@ -164,6 +167,22 @@ func (c *Compiler) Compile(node ast.Node) error {
}
}
case *ast.LetStatement:
err := c.Compile(node.Value)
if err != nil {
return err
}
symbol := c.symbolTable.Define(node.Name.Value)
c.emit(code.OpSetGlobal, symbol.Index)
case *ast.Identifier:
symbol, ok := c.symbolTable.Resolve(node.Value)
if !ok {
return fmt.Errorf("undefined varible %s", node.Value)
}
c.emit(code.OpGetGlobal, symbol.Index)
}
return nil