| 1 | //Copyright 2012 Vastech SA (PTY) LTD |
| 2 | // |
| 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 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package golang |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "path" |
| 20 | "text/template" |
| 21 | |
| 22 | "github.com/goccmack/gocc/internal/ast" |
| 23 | "github.com/goccmack/gocc/internal/config" |
| 24 | "github.com/goccmack/gocc/internal/io" |
| 25 | "github.com/goccmack/gocc/internal/parser/lr1/items" |
| 26 | "github.com/goccmack/gocc/internal/parser/symbols" |
| 27 | ) |
| 28 | |
| 29 | func GenParser(pkg, outDir string, prods ast.SyntaxProdList, itemSets *items.ItemSets, symbols *symbols.Symbols, cfg config.Config) { |
| 30 | tmpl, err := template.New("parser").Parse(parserSrc[1:]) |
| 31 | if err != nil { |
| 32 | panic(err) |
| 33 | } |
| 34 | wr := new(bytes.Buffer) |
| 35 | if err := tmpl.Execute(wr, getParserData(pkg, prods, itemSets, symbols, cfg)); err != nil { |
| 36 | panic(err) |
| 37 | } |
| 38 | io.WriteFile(path.Join(outDir, "parser", "parser.go"), wr.Bytes()) |
| 39 | } |
| 40 | |
| 41 | type parserData struct { |
| 42 | Debug bool |
| 43 | ErrorImport string |
| 44 | TokenImport string |
| 45 | NumProductions int |
| 46 | NumStates int |
| 47 | NumSymbols int |
| 48 | } |
| 49 | |
| 50 | func getParserData(pkg string, prods ast.SyntaxProdList, itemSets *items.ItemSets, symbols *symbols.Symbols, cfg config.Config) *parserData { |
| 51 | return &parserData{ |
| 52 | Debug: cfg.DebugParser(), |
| 53 | ErrorImport: path.Join(pkg, "errors"), |
| 54 | TokenImport: path.Join(pkg, "token"), |
| 55 | NumProductions: len(prods), |
| 56 | NumStates: itemSets.Size(), |
| 57 | NumSymbols: symbols.NumSymbols(), |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | const parserSrc = ` |
| 62 | // Code generated by gocc; DO NOT EDIT. |
| 63 | |
| 64 | package parser |
| 65 | |
| 66 | import ( |
| 67 | "fmt" |
| 68 | "strings" |
| 69 | |
| 70 | parseError "{{.ErrorImport}}" |
| 71 | "{{.TokenImport}}" |
| 72 | ) |
| 73 | |
| 74 | const ( |
| 75 | numProductions = {{.NumProductions}} |
| 76 | numStates = {{.NumStates}} |
| 77 | numSymbols = {{.NumSymbols}} |
| 78 | ) |
| 79 | |
| 80 | // Stack |
| 81 | |
| 82 | type stack struct { |
| 83 | state []int |
| 84 | attrib []Attrib |
| 85 | } |
| 86 | |
| 87 | const iNITIAL_STACK_SIZE = 100 |
| 88 | |
| 89 | func newStack() *stack { |
| 90 | return &stack{ |
| 91 | state: make([]int, 0, iNITIAL_STACK_SIZE), |
| 92 | attrib: make([]Attrib, 0, iNITIAL_STACK_SIZE), |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | func (s *stack) reset() { |
| 97 | s.state = s.state[:0] |
| 98 | s.attrib = s.attrib[:0] |
| 99 | } |
| 100 | |
| 101 | func (s *stack) push(state int, a Attrib) { |
| 102 | s.state = append(s.state, state) |
| 103 | s.attrib = append(s.attrib, a) |
| 104 | } |
| 105 | |
| 106 | func (s *stack) top() int { |
| 107 | return s.state[len(s.state)-1] |
| 108 | } |
| 109 | |
| 110 | func (s *stack) peek(pos int) int { |
| 111 | return s.state[pos] |
| 112 | } |
| 113 | |
| 114 | func (s *stack) topIndex() int { |
| 115 | return len(s.state) - 1 |
| 116 | } |
| 117 | |
| 118 | func (s *stack) popN(items int) []Attrib { |
| 119 | lo, hi := len(s.state)-items, len(s.state) |
| 120 | |
| 121 | attrib := s.attrib[lo:hi] |
| 122 | |
| 123 | s.state = s.state[:lo] |
| 124 | s.attrib = s.attrib[:lo] |
| 125 | |
| 126 | return attrib |
| 127 | } |
| 128 | |
| 129 | func (s *stack) String() string { |
| 130 | w := new(strings.Builder) |
| 131 | fmt.Fprintf(w, "stack:\n") |
| 132 | for i, st := range s.state { |
| 133 | fmt.Fprintf(w, "\t%d: %d , ", i, st) |
| 134 | if s.attrib[i] == nil { |
| 135 | fmt.Fprintf(w, "nil") |
| 136 | } else { |
| 137 | switch attr := s.attrib[i].(type) { |
| 138 | case *token.Token: |
| 139 | fmt.Fprintf(w, "%s", attr.Lit) |
| 140 | default: |
| 141 | fmt.Fprintf(w, "%v", attr) |
| 142 | } |
| 143 | } |
| 144 | fmt.Fprintf(w, "\n") |
| 145 | } |
| 146 | return w.String() |
| 147 | } |
| 148 | |
| 149 | // Parser |
| 150 | |
| 151 | type Parser struct { |
| 152 | stack *stack |
| 153 | nextToken *token.Token |
| 154 | pos int |
| 155 | Context Context |
| 156 | } |
| 157 | |
| 158 | type Scanner interface { |
| 159 | Scan() (tok *token.Token) |
| 160 | } |
| 161 | |
| 162 | func NewParser() *Parser { |
| 163 | p := &Parser{stack: newStack()} |
| 164 | p.Reset() |
| 165 | return p |
| 166 | } |
| 167 | |
| 168 | func (p *Parser) Reset() { |
| 169 | p.stack.reset() |
| 170 | p.stack.push(0, nil) |
| 171 | } |
| 172 | |
| 173 | func (p *Parser) Error(err error, scanner Scanner) (recovered bool, errorAttrib *parseError.Error) { |
| 174 | errorAttrib = &parseError.Error{ |
| 175 | Err: err, |
| 176 | ErrorToken: p.nextToken, |
| 177 | ErrorSymbols: p.popNonRecoveryStates(), |
| 178 | ExpectedTokens: make([]string, 0, 8), |
| 179 | } |
| 180 | for t, action := range actionTab[p.stack.top()].actions { |
| 181 | if action != nil { |
| 182 | errorAttrib.ExpectedTokens = append(errorAttrib.ExpectedTokens, token.TokMap.Id(token.Type(t))) |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | if action := actionTab[p.stack.top()].actions[token.TokMap.Type("error")]; action != nil { |
| 187 | p.stack.push(int(action.(shift)), errorAttrib) // action can only be shift |
| 188 | } else { |
| 189 | return |
| 190 | } |
| 191 | |
| 192 | if action := actionTab[p.stack.top()].actions[p.nextToken.Type]; action != nil { |
| 193 | recovered = true |
| 194 | } |
| 195 | for !recovered && p.nextToken.Type != token.EOF { |
| 196 | p.nextToken = scanner.Scan() |
| 197 | if action := actionTab[p.stack.top()].actions[p.nextToken.Type]; action != nil { |
| 198 | recovered = true |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | return |
| 203 | } |
| 204 | |
| 205 | func (p *Parser) popNonRecoveryStates() (removedAttribs []parseError.ErrorSymbol) { |
| 206 | if rs, ok := p.firstRecoveryState(); ok { |
| 207 | errorSymbols := p.stack.popN(p.stack.topIndex() - rs) |
| 208 | removedAttribs = make([]parseError.ErrorSymbol, len(errorSymbols)) |
| 209 | for i, e := range errorSymbols { |
| 210 | removedAttribs[i] = e |
| 211 | } |
| 212 | } else { |
| 213 | removedAttribs = []parseError.ErrorSymbol{} |
| 214 | } |
| 215 | return |
| 216 | } |
| 217 | |
| 218 | // recoveryState points to the highest state on the stack, which can recover |
| 219 | func (p *Parser) firstRecoveryState() (recoveryState int, canRecover bool) { |
| 220 | recoveryState, canRecover = p.stack.topIndex(), actionTab[p.stack.top()].canRecover |
| 221 | for recoveryState > 0 && !canRecover { |
| 222 | recoveryState-- |
| 223 | canRecover = actionTab[p.stack.peek(recoveryState)].canRecover |
| 224 | } |
| 225 | return |
| 226 | } |
| 227 | |
| 228 | func (p *Parser) newError(err error) error { |
| 229 | e := &parseError.Error{ |
| 230 | Err: err, |
| 231 | StackTop: p.stack.top(), |
| 232 | ErrorToken: p.nextToken, |
| 233 | } |
| 234 | actRow := actionTab[p.stack.top()] |
| 235 | for i, t := range actRow.actions { |
| 236 | if t != nil { |
| 237 | e.ExpectedTokens = append(e.ExpectedTokens, token.TokMap.Id(token.Type(i))) |
| 238 | } |
| 239 | } |
| 240 | return e |
| 241 | } |
| 242 | |
| 243 | func (p *Parser) Parse(scanner Scanner) (res interface{}, err error) { |
| 244 | p.Reset() |
| 245 | p.nextToken = scanner.Scan() |
| 246 | for acc := false; !acc; { |
| 247 | action := actionTab[p.stack.top()].actions[p.nextToken.Type] |
| 248 | if action == nil { |
| 249 | if recovered, errAttrib := p.Error(nil, scanner); !recovered { |
| 250 | p.nextToken = errAttrib.ErrorToken |
| 251 | return nil, p.newError(nil) |
| 252 | } |
| 253 | if action = actionTab[p.stack.top()].actions[p.nextToken.Type]; action == nil { |
| 254 | panic("Error recovery led to invalid action") |
| 255 | } |
| 256 | } |
| 257 | {{- if .Debug }} |
| 258 | fmt.Printf("S%d %s %s\n", p.stack.top(), token.TokMap.TokenString(p.nextToken), action) |
| 259 | {{- end }} |
| 260 | |
| 261 | switch act := action.(type) { |
| 262 | case accept: |
| 263 | res = p.stack.popN(1)[0] |
| 264 | acc = true |
| 265 | case shift: |
| 266 | p.stack.push(int(act), p.nextToken) |
| 267 | p.nextToken = scanner.Scan() |
| 268 | case reduce: |
| 269 | prod := productionsTable[int(act)] |
| 270 | attrib, err := prod.ReduceFunc(p.stack.popN(prod.NumSymbols), p.Context) |
| 271 | if err != nil { |
| 272 | return nil, p.newError(err) |
| 273 | } else { |
| 274 | p.stack.push(gotoTab[p.stack.top()][prod.NTType], attrib) |
| 275 | } |
| 276 | default: |
| 277 | panic("unknown action: " + action.String()) |
| 278 | } |
| 279 | } |
| 280 | return res, nil |
| 281 | } |
| 282 | ` |