Browse Source

make more progress on compiler/assembler

master
Brett Langdon 10 years ago
parent
commit
34b8ee8a4e
3 changed files with 48 additions and 9 deletions
  1. +12
    -8
      compiler/compiler.go
  2. +22
    -0
      compiler/instruction.go
  3. +14
    -1
      compiler/scope.go

+ 12
- 8
compiler/compiler.go View File

@ -45,28 +45,32 @@ func (compiler *Compiler) exitScope() *Scope {
func (compiler *Compiler) assemble(addNone bool) *gython.CodeObject {
if addNone {
// compiler.addOp(bytecode.LOAD_CONST)
// compiler.addOp(bytecode.RETURN_VALUE)
compiler.addOpWithObject(bytecode.LOAD_CONST, gython.None, compiler.currentScope.Constants)
compiler.addOp(bytecode.RETURN_VALUE)
}
codeobject := gython.NewCodeObject([]byte{}, []byte{}, 0)
return codeobject
}
func (compiler *Compiler) addOp(op bytecode.Opcode, value gython.Object) bool {
// TODO: add `value` object and get oparg
oparg := 0
func (compiler *Compiler) addOp(op bytecode.Opcode) {
instr := NewInstruction(op, nil, false)
compiler.currentScope.AddInstruction(instr)
}
func (compiler *Compiler) addOpWithObject(op bytecode.Opcode, value gython.Object, args *gython.Dict) {
oparg := args.Length()
args.SetItem(oparg, value)
instr := NewInstruction(op, oparg, true)
compiler.currentScope.AddInstruction(instr)
return true
}
func (compiler *Compiler) visitExpression(expr ast.Expression) bool {
switch expr := expr.(type) {
case *ast.Num:
compiler.addOp(bytecode.LOAD_CONST, expr.Value)
compiler.addOpWithObject(bytecode.LOAD_CONST, expr.Value, compiler.currentScope.Constants)
case *ast.Name:
compiler.addOp(bytecode.STORE_NAME, expr.Identifier)
compiler.addOpWithObject(bytecode.STORE_NAME, expr.Identifier, compiler.currentScope.Constants)
default:
fmt.Println(expr)
}


+ 22
- 0
compiler/instruction.go View File

@ -0,0 +1,22 @@
package compiler
import (
"github.com/brettlangdon/gython/bytecode"
"github.com/brettlangdon/gython/gython"
)
type Instruction struct {
Opcode bytecode.Opcode
Oparg *gython.Float
Hasarg bool
Line int
}
func NewInstruction(opcode bytecode.Opcode, oparg *gython.Float, hasarg bool) *Instruction {
return &Instruction{
Opcode: opcode,
Oparg: oparg,
Hasarg: hasarg,
Line: 0,
}
}

+ 14
- 1
compiler/scope.go View File

@ -1,12 +1,25 @@
package compiler
import "github.com/brettlangdon/gython/gython"
type Scope struct {
Instructions []*Instruction
Constants *gython.Dict
Names *gython.Dict
VariableNames *gython.Dict
FreeVariableNames *gython.Dict
CellVariableNames *gython.Dict
}
func NewScope() *Scope {
return &Scope{
Instructions: make([]*Instruction, 0),
Instructions: make([]*Instruction, 0),
Constants: gython.NewDict(),
Names: gython.NewDict(),
VariableNames: gython.NewDict(),
FreeVariableNames: gython.NewDict(),
CellVariableNames: gython.NewDict(),
}
}


Loading…
Cancel
Save