Skip to content

Commit

Permalink
refactor: 切换数字类型为IntType(可配置),同时修复一个值复制问题
Browse files Browse the repository at this point in the history
  • Loading branch information
fy0 committed Apr 24, 2024
1 parent 053ea09 commit 090bcc1
Show file tree
Hide file tree
Showing 15 changed files with 247 additions and 209 deletions.
10 changes: 5 additions & 5 deletions builtin_functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
func funcCeil(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
v, ok := params[0].ReadFloat()
if ok {
return VMValueNewInt(int64(math.Ceil(v)))
return VMValueNewInt(IntType(math.Ceil(v)))
} else {
ctx.Error = errors.New("类型错误: 只能是float")
}
Expand All @@ -19,7 +19,7 @@ func funcCeil(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
func funcRound(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
v, ok := params[0].ReadFloat()
if ok {
return VMValueNewInt(int64(math.Round(v)))
return VMValueNewInt(IntType(math.Round(v)))
} else {
ctx.Error = errors.New("类型错误: 只能是float")
}
Expand All @@ -29,7 +29,7 @@ func funcRound(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
func funcFloor(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
v, ok := params[0].ReadFloat()
if ok {
return VMValueNewInt(int64(math.Floor(v)))
return VMValueNewInt(IntType(math.Floor(v)))
} else {
ctx.Error = errors.New("类型错误: 只能是float")
}
Expand Down Expand Up @@ -63,12 +63,12 @@ func funcInt(ctx *Context, this *VMValue, params []*VMValue) *VMValue {
return params[0]
case VMTypeFloat:
v, _ := params[0].ReadFloat()
return VMValueNewInt(int64(v))
return VMValueNewInt(IntType(v))
case VMTypeString:
s, _ := params[0].ReadString()
val, err := strconv.ParseInt(s, 10, 64)
if err == nil {
return VMValueNewInt(val)
return VMValueNewInt(IntType(val))
} else {
ctx.Error = errors.New("值错误: 无法进行 int() 转换: " + s)
}
Expand Down
8 changes: 4 additions & 4 deletions bytecode.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,17 @@ const (
func (code *ByteCode) CodeString() string {
switch code.T {
case TypePushIntNumber:
return "push.int " + strconv.FormatInt(code.Value.(int64), 10)
return "push.int " + strconv.FormatInt(int64(code.Value.(IntType)), 10)
case TypePushFloatNumber:
return "push.flt " + strconv.FormatFloat(code.Value.(float64), 'f', 2, 64)
case TypePushString:
return "push.str " + code.Value.(string)
case TypePushRange:
return "push.range"
case TypePushArray:
return "push.arr " + strconv.FormatInt(code.Value.(int64), 10)
return "push.arr " + strconv.FormatInt(int64(code.Value.(IntType)), 10)
case TypePushDict:
return "push.dict " + strconv.FormatInt(code.Value.(int64), 10)
return "push.dict " + strconv.FormatInt(int64(code.Value.(IntType)), 10)
case TypePushComputed:
computed, _ := code.Value.(*VMValue).ReadComputed()
return "push.computed " + computed.Expr
Expand All @@ -141,7 +141,7 @@ func (code *ByteCode) CodeString() string {
return "push.func " + computed.Name

case TypeInvoke:
return "invoke " + strconv.FormatInt(code.Value.(int64), 10)
return "invoke " + strconv.FormatInt(int64(code.Value.(IntType)), 10)

case TypeInvokeSelf:
return "invoke.self " + code.Value.(string)
Expand Down
60 changes: 30 additions & 30 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,33 +6,33 @@ import (
)

type ParserData struct {
counterStack []int64 // f-string 嵌套计数,在解析时中起作用
varnameStack []string // 另一个解析用栈
jmpStack []int64
breakStack []int64 // break,用时创建
continueStack []int64 // continue用,用时创建
counterStack []IntType // f-string 嵌套计数,在解析时中起作用
varnameStack []string // 另一个解析用栈
jmpStack []IntType
breakStack []IntType // break,用时创建
continueStack []IntType // continue用,用时创建
loopInfo []struct {
continueIndex int
breakIndex int
}
loopLayer int64 // 当前loop层数
loopLayer int // 当前loop层数
codeStack []struct {
code []ByteCode
index int
}
}

type BufferSpan struct {
begin int64
end int64
begin IntType
end IntType
ret *VMValue
text string
}

func (pd *ParserData) init() {
pd.counterStack = []int64{}
pd.counterStack = []IntType{}
pd.varnameStack = []string{}
pd.jmpStack = []int64{} // 不复用counterStack的原因是在 ?: 算符中两个都有用到
pd.jmpStack = []IntType{} // 不复用counterStack的原因是在 ?: 算符中两个都有用到
pd.codeStack = []struct {
code []ByteCode
index int
Expand Down Expand Up @@ -84,14 +84,14 @@ func (e *Parser) WriteCode(T CodeType, value interface{}) {
e.codeIndex += 1
}

func (p *Parser) AddDiceDetail(begin int64, end int64) {
func (p *Parser) AddDiceDetail(begin IntType, end IntType) {
p.WriteCode(TypeDetailMark, BufferSpan{begin: begin, end: end})
}

func (e *Parser) AddOp(operator CodeType) {
var val interface{} = nil
if operator == TypeJne || operator == TypeJmp {
val = int64(0)
val = IntType(0)
}
e.WriteCode(operator, val)
}
Expand All @@ -102,18 +102,18 @@ func (e *Parser) AddLoadName(value string) {

func (e *Parser) PushIntNumber(value string) {
val, _ := strconv.ParseInt(value, 10, 64)
e.WriteCode(TypePushIntNumber, int64(val))
e.WriteCode(TypePushIntNumber, IntType(val))
}

func (e *Parser) PushStr(value string) {
e.WriteCode(TypePushString, value)
}

func (e *Parser) PushArray(value int64) {
func (e *Parser) PushArray(value IntType) {
e.WriteCode(TypePushArray, value)
}

func (e *Parser) PushDict(value int64) {
func (e *Parser) PushDict(value IntType) {
e.WriteCode(TypePushDict, value)
}

Expand All @@ -129,7 +129,7 @@ func (e *Parser) PushGlobal() {
e.WriteCode(TypePushGlobal, nil)
}

func (e *Parser) AddFormatString(value string, num int64) {
func (e *Parser) AddFormatString(value string, num IntType) {
//e.PushStr(value)
e.WriteCode(TypeLoadFormatString, num) // num
}
Expand Down Expand Up @@ -176,16 +176,16 @@ func (e *Parser) NamePop() string {
}

func (e *Parser) OffsetPush() {
e.jmpStack = append(e.jmpStack, int64(e.codeIndex)-1)
e.jmpStack = append(e.jmpStack, IntType(e.codeIndex)-1)
}

func (p *Parser) ContinuePush() {
if p.loopLayer > 0 {
if p.continueStack == nil {
p.continueStack = []int64{}
p.continueStack = []IntType{}
}
p.AddOp(TypeJmp)
p.continueStack = append(p.continueStack, int64(p.codeIndex)-1)
p.continueStack = append(p.continueStack, IntType(p.codeIndex)-1)
} else {
p.Error = errors.New("循环外不能放置continue")
}
Expand All @@ -198,7 +198,7 @@ func (p *Parser) ContinueSet(offsetB int) {
lastB := len(p.jmpStack) - 1 - offsetB
jmpIndex := p.jmpStack[lastB]
// 试出来的,这个是对的,那么也许while那个是错的??还是说因为while最后多push了一个jmp呢?
p.code[codeIndex].Value = -(int64(codeIndex) - jmpIndex)
p.code[codeIndex].Value = -(IntType(codeIndex) - jmpIndex)
}
}
}
Expand All @@ -207,18 +207,18 @@ func (p *Parser) BreakSet() {
if p.breakStack != nil {
info := p.loopInfo[len(p.loopInfo)-1]
for _, codeIndex := range p.breakStack[info.breakIndex:] {
p.code[codeIndex].Value = int64(p.codeIndex) - codeIndex - 1
p.code[codeIndex].Value = IntType(p.codeIndex) - codeIndex - 1
}
}
}

func (p *Parser) BreakPush() {
if p.loopLayer > 0 {
if p.breakStack == nil {
p.breakStack = []int64{}
p.breakStack = []IntType{}
}
p.AddOp(TypeJmp)
p.breakStack = append(p.breakStack, int64(p.codeIndex)-1)
p.breakStack = append(p.breakStack, IntType(p.codeIndex)-1)
} else {
p.Error = errors.New("循环外不能放置break")
}
Expand All @@ -228,7 +228,7 @@ func (e *Parser) OffsetPopAndSet() {
last := len(e.jmpStack) - 1
codeIndex := e.jmpStack[last]
e.jmpStack = e.jmpStack[:last]
e.code[codeIndex].Value = int64(int64(e.codeIndex) - codeIndex - 1)
e.code[codeIndex].Value = IntType(IntType(e.codeIndex) - codeIndex - 1)
//fmt.Println("XXXX", e.Code[codeIndex], "|", e.Top, codeIndex)
}

Expand All @@ -245,24 +245,24 @@ func (e *Parser) OffsetJmpSetX(offsetA int, offsetB int, rev bool) {
jmpIndex := e.jmpStack[lastB]

if rev {
e.code[codeIndex].Value = -(int64(e.codeIndex) - jmpIndex - 1)
e.code[codeIndex].Value = -(IntType(e.codeIndex) - jmpIndex - 1)
} else {
e.code[codeIndex].Value = int64(e.codeIndex) - jmpIndex - 1
e.code[codeIndex].Value = IntType(e.codeIndex) - jmpIndex - 1
}
}

func (e *Parser) CounterPush() {
e.counterStack = append(e.counterStack, 0)
}

func (e *Parser) CounterAdd(offset int64) {
func (e *Parser) CounterAdd(offset IntType) {
last := len(e.counterStack) - 1
if last != -1 {
e.counterStack[last] += offset
}
}

func (e *Parser) CounterPop() int64 {
func (e *Parser) CounterPop() IntType {
last := len(e.counterStack) - 1
num := e.counterStack[last]
e.counterStack = e.counterStack[:last]
Expand All @@ -279,12 +279,12 @@ func (e *Parser) FlagsPop() {
e.flagsStack = e.flagsStack[:last]
}

func (e *Parser) AddInvokeMethod(name string, paramsNum int64) {
func (e *Parser) AddInvokeMethod(name string, paramsNum IntType) {
e.WriteCode(TypePushIntNumber, paramsNum)
e.WriteCode(TypeInvokeSelf, name)
}

func (e *Parser) AddInvoke(paramsNum int64) {
func (e *Parser) AddInvoke(paramsNum IntType) {
//e.WriteCode(TypePushIntNumber, paramsNum)
e.WriteCode(TypeInvoke, paramsNum)
}
Expand Down
10 changes: 5 additions & 5 deletions roll.peg
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func_def_params <- '(' sp ')' sp { p.CounterPush() }
/ '(' sp { p.CounterPush(); p.CounterAdd(1) } identifier sp { p.NamePush(text) } (',' sp identifier sp { p.NamePush(text) } {p.CounterAdd(1)} )* ')' sp

stmtFunc <- 'func' sp1 identifier sp { p.NamePush(text) } func_def_params '{' sp { p.CodePush() } < stmtRoot? > '}' sp
{ num := p.CounterPop(); arr := []string{}; for i:=int64(0); i<num; i++ { arr = append(arr, p.NamePop()) }; p.AddStoreFunction(p.NamePop(), arr, string(text)) }
{ num := p.CounterPop(); arr := []string{}; for i:=IntType(0); i<num; i++ { arr = append(arr, p.NamePop()) }; p.AddStoreFunction(p.NamePop(), arr, string(text)) }

// 赋值
stmtAssign <- identifier sp { p.NamePush(text) } '=' sp exprRoot { p.AddStore(p.NamePop()) }
Expand All @@ -103,7 +103,7 @@ exprSlice <- exprTernary _sliceSuffix (!'=') { p.AddOp(TypeSliceGet) }
// 三元算符 ? :
exprValueIfExists <- exprLogicOr sp '?' sp { p.AddOp(TypeJne); p.OffsetPush() } exprLogicOr sp { p.AddOp(TypeJmp); p.OffsetPopAndSet(); p.OffsetPush(); } // 这里的Pop对应的是jne,所有jmp将攒到最后
exprTernary <- exprLogicOr sp '?' sp { p.AddOp(TypeJne); p.OffsetPush() } exprLogicOr sp ':' sp { p.AddOp(TypeJmp); p.OffsetPopAndSet(); p.OffsetPush() } exprLogicOr sp { p.OffsetPopAndSet() }
/ exprValueIfExists { p.CounterPush() } ( ',' sp exprValueIfExists {p.CounterAdd(1)} )* { p.PushStr(""); limit:=p.CounterPop()+1; for i:=int64(0); i<limit; i++ { p.OffsetPopAndSet() } }
/ exprValueIfExists { p.CounterPush() } ( ',' sp exprValueIfExists {p.CounterAdd(1)} )* { p.PushStr(""); limit:=p.CounterPop()+1; for i:=IntType(0); i<limit; i++ { p.OffsetPopAndSet() } }
/ exprLogicOr

// switch { case 1: ..., case 2: ... }
Expand Down Expand Up @@ -191,8 +191,8 @@ _diceMod2 <- ('min' nos { p.AddOp(TypeDiceSetMin) })?
_dicePearMod <- '优势' { p.PushIntNumber("2"); p.AddOp(TypeDiceSetTimes); p.PushIntNumber("1"); p.AddOp(TypeDiceSetKeepHighNum) }
/ '劣势' { p.PushIntNumber("2"); p.AddOp(TypeDiceSetTimes); p.PushIntNumber("1"); p.AddOp(TypeDiceSetKeepLowNum) }

detailStart <- { p.CounterPush(); p.CounterAdd(int64(token.begin)) }
detailEnd <- { p.AddDiceDetail(p.CounterPop(), int64(token.end)) }
detailStart <- { p.CounterPush(); p.CounterAdd(IntType(token.begin)) }
detailEnd <- { p.AddDiceDetail(p.CounterPop(), IntType(token.end)) }

// 3d20, 3d20d2, 2d20优势
_diceType1 <- nos [dD] nos
Expand Down Expand Up @@ -278,7 +278,7 @@ value <- 'true' sp { p.PushIntNumber("1") }
/ '{' sp '}' sp { p.PushDict(0) } item_get attr_get
/ '{' sp { p.CounterPush() } dict_item (',' sp dict_item )* ','? '}' sp { p.PushDict(p.CounterPop()) } item_get attr_get
/ 'func' sp func_def_params '{' sp { p.CodePush() } < stmtRoot? > '}' sp
{ num := p.CounterPop(); arr := []string{}; for i:=int64(0); i<num; i++ { arr = append(arr, p.NamePop()) }; p.AddStoreFunction("", arr, string(text)) }
{ num := p.CounterPop(); arr := []string{}; for i:=IntType(0); i<num; i++ { arr = append(arr, p.NamePop()) }; p.AddStoreFunction("", arr, string(text)) }


// 数字
Expand Down
20 changes: 10 additions & 10 deletions roll.peg.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 090bcc1

Please sign in to comment.