github.com/goplus/gogen@v1.16.0/internal/stack.go (about) 1 /* 2 Copyright 2021 The GoPlus Authors (goplus.org) 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 http://www.apache.org/licenses/LICENSE-2.0 7 Unless required by applicable law or agreed to in writing, software 8 distributed under the License is distributed on an "AS IS" BASIS, 9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 See the License for the specific language governing permissions and 11 limitations under the License. 12 */ 13 14 package internal 15 16 import ( 17 "go/ast" 18 "go/constant" 19 "go/types" 20 ) 21 22 // ----------------------------------------------------------------------------- 23 24 const defaultStkSize = 64 25 26 type Elem struct { 27 Val ast.Expr 28 Type types.Type 29 CVal constant.Value 30 Src ast.Node 31 } 32 33 // A Stack represents a FILO container. 34 type Stack struct { 35 data []*Elem 36 } 37 38 // NewStack creates a Stack instance. 39 func NewStack() (p *Stack) { 40 return &Stack{data: make([]*Elem, 0, defaultStkSize)} 41 } 42 43 // Init initializes this Stack object. 44 func (p *Stack) Init() { 45 p.data = make([]*Elem, 0, defaultStkSize) 46 } 47 48 // Get returns the value at specified index. 49 func (p *Stack) Get(idx int) *Elem { 50 return p.data[len(p.data)+idx] 51 } 52 53 // Set returns the value at specified index. 54 func (p *Stack) Set(idx int, v *Elem) { 55 p.data[len(p.data)+idx] = v 56 } 57 58 // GetArgs returns all arguments of a function. 59 func (p *Stack) GetArgs(arity int) []*Elem { 60 return p.data[len(p.data)-arity:] 61 } 62 63 // Ret pops n values from this stack, and then pushes results. 64 func (p *Stack) Ret(arity int, results ...*Elem) { 65 p.data = append(p.data[:len(p.data)-arity], results...) 66 } 67 68 // Push pushes a value into this stack. 69 func (p *Stack) Push(v *Elem) { 70 p.data = append(p.data, v) 71 } 72 73 // PopN pops n elements. 74 func (p *Stack) PopN(n int) { 75 p.data = p.data[:len(p.data)-n] 76 } 77 78 // Pop pops a value from this stack. 79 func (p *Stack) Pop() *Elem { 80 n := len(p.data) 81 v := p.data[n-1] 82 p.data = p.data[:n-1] 83 return v 84 } 85 86 // Len returns count of stack elements. 87 func (p *Stack) Len() int { 88 return len(p.data) 89 } 90 91 // SetLen sets count of stack elements. 92 func (p *Stack) SetLen(base int) { 93 p.data = p.data[:base] 94 } 95 96 // -----------------------------------------------------------------------------