50 lines
1.3 KiB
Go
50 lines
1.3 KiB
Go
package core
|
|
|
|
import (
|
|
"git.akyoto.dev/cli/q/src/asm"
|
|
"git.akyoto.dev/cli/q/src/errors"
|
|
"git.akyoto.dev/cli/q/src/expression"
|
|
"git.akyoto.dev/cli/q/src/types"
|
|
)
|
|
|
|
// CompileNew compiles a `new` function call which allocates a struct.
|
|
func (f *Function) CompileNew(root *expression.Expression) (types.Type, error) {
|
|
var (
|
|
parameters = root.Children[1:]
|
|
nameNode = parameters[0]
|
|
pkg = f.Package
|
|
name string
|
|
)
|
|
|
|
if nameNode.IsLeaf() {
|
|
name = nameNode.Token.Text(f.File.Bytes)
|
|
} else {
|
|
pkg = nameNode.Children[0].Token.Text(f.File.Bytes)
|
|
name = nameNode.Children[1].Token.Text(f.File.Bytes)
|
|
}
|
|
|
|
if pkg != f.File.Package {
|
|
if f.File.Imports == nil {
|
|
return nil, errors.New(&errors.UnknownPackage{Name: pkg}, f.File, nameNode.Token.Position)
|
|
}
|
|
|
|
imp, exists := f.File.Imports[pkg]
|
|
|
|
if !exists {
|
|
return nil, errors.New(&errors.UnknownPackage{Name: pkg}, f.File, nameNode.Token.Position)
|
|
}
|
|
|
|
imp.Used = true
|
|
}
|
|
|
|
typ, exists := f.Structs[pkg+"."+name]
|
|
|
|
if !exists {
|
|
return nil, errors.New(&errors.UnknownType{Name: name}, f.File, nameNode.Token.Position)
|
|
}
|
|
|
|
f.SaveRegister(f.CPU.Input[0])
|
|
f.RegisterNumber(asm.MOVE, f.CPU.Input[0], typ.Size())
|
|
f.CallSafe(f.Functions["mem.alloc"], f.CPU.Input[:1])
|
|
return &types.Pointer{To: typ}, nil
|
|
}
|