Skip to content

Commit

Permalink
deduct constant number type for array and slice init
Browse files Browse the repository at this point in the history
  • Loading branch information
douyixuan committed Aug 28, 2024
1 parent 9b0aa98 commit 0d68a92
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
18 changes: 11 additions & 7 deletions compiler/compiler/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,21 @@ func (c *Compiler) compileConstantNode(v *parser.ConstantNode) value.Value {
case parser.NUMBER:
var intType *types.Int = i64

if v.TargetType != nil {
intType = c.parserTypeToType(v.TargetType).(*types.Int)
}
// Use context to detect which type that should be returned
// Is used to detect if a number should be i32 or i64 etc...
var wantedType types.Type
if len(c.contextAssignDest) > 0 {
wantedType = c.contextAssignDest[len(c.contextAssignDest)-1].Type
}
// todo: better strategy
// var wantedType types.Type
// if len(c.contextAssignDest) > 0 {
// wantedType = c.contextAssignDest[len(c.contextAssignDest)-1].Type
// }

// Create the correct type of int based on context
if t, ok := wantedType.(*types.Int); ok {
intType = t
}
// if t, ok := wantedType.(*types.Int); ok {
// intType = t
// }

return value.Value{
Value: constant.NewInt(intType.Type, v.Value),
Expand Down
7 changes: 4 additions & 3 deletions compiler/parser/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,10 @@ func (on OperatorNode) String() string {
type ConstantNode struct {
baseNode

Type DataType
Value int64
ValueStr string
Type DataType
TargetType TypeNode
Value int64
ValueStr string
}

type DataType uint8
Expand Down
10 changes: 10 additions & 0 deletions compiler/parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,11 @@ func (p *parser) parseOneWithOptions(withAheadParse, withArithAhead, withIdentif
Type: NUMBER,
Value: int64(len(items)),
}
for _, i := range items {
if ii, ok := i.(*ConstantNode); ok {
ii.TargetType = sliceItemType
}
}
res = &InitializeSliceNode{
Type: sliceItemType,
Len: len,
Expand Down Expand Up @@ -239,6 +244,11 @@ func (p *parser) parseOneWithOptions(withAheadParse, withArithAhead, withIdentif
items := p.parseUntil(lexer.Item{Type: lexer.OPERATOR, Val: "}"})
p.inAllocRightHand = prevInAlloc

for _, i := range items {
if ii, ok := i.(*ConstantNode); ok {
ii.TargetType = arrayItemType
}
}
// Array init
res = &InitializeArrayNode{
Type: arrayItemType,
Expand Down

0 comments on commit 0d68a92

Please sign in to comment.