1 | 'use strict'
|
2 | const Parser = require('./parser.js')
|
3 | const util = require('util')
|
4 |
|
5 | const dump = _ => util.inspect(_, {colors: true, depth: 10, breakLength: Infinity})
|
6 | class DebugParser extends Parser {
|
7 | stateName (state) {
|
8 |
|
9 | return (state.parser && state.parser.name) || state.name || ('anonymous')
|
10 | }
|
11 | runOne () {
|
12 | const callStack = this.stack.concat(this.state).map(_ => this.stateName(_)).join(' <- ')
|
13 | console.log('RUN', callStack, dump({line: this.line, col: this.col, char: this.char, ret: this.state.returned}))
|
14 | return super.runOne()
|
15 | }
|
16 | finish () {
|
17 | const obj = super.finish()
|
18 |
|
19 | if (this.stack.length) {
|
20 | throw new Parser.Error('All states did not return by end of stream')
|
21 | }
|
22 | return obj
|
23 | }
|
24 | callStack () {
|
25 | const callStack = this.stack.map(_ => this.stateName(_)).join(' ').replace(/\S/g, ' ')
|
26 | return callStack ? callStack + ' ' : ''
|
27 | }
|
28 | next (fn) {
|
29 | console.log(' ', this.callStack(), 'NEXT', this.stateName(fn))
|
30 | return super.next(fn)
|
31 | }
|
32 | goto (fn) {
|
33 | console.log(' ', this.callStack(), 'GOTO', this.stateName(fn))
|
34 | super.next(fn)
|
35 | return false
|
36 | }
|
37 | call (fn, returnWith) {
|
38 | console.log(' ', this.callStack(), 'CALL', fn.name, returnWith ? '-> ' + returnWith.name : '')
|
39 | if (returnWith) super.next(returnWith)
|
40 | this.stack.push(this.state)
|
41 | this.state = {parser: fn, buf: '', returned: null}
|
42 | }
|
43 | callNow (fn, returnWith) {
|
44 | console.log(' ', this.callStack(), 'CALLNOW', fn.name, returnWith ? '-> ' + returnWith.name : '')
|
45 | if (returnWith) super.next(returnWith)
|
46 | this.stack.push(this.state)
|
47 | this.state = {parser: fn, buf: '', returned: null}
|
48 | return false
|
49 | }
|
50 | return (value) {
|
51 | console.log(' ', this.callStack(), 'RETURN')
|
52 | return super.return(value)
|
53 | }
|
54 | returnNow (value) {
|
55 | console.log(' ', this.callStack(), 'RETURNNOW')
|
56 | super.return(value)
|
57 | return false
|
58 | }
|
59 | }
|
60 | module.exports = DebugParser
|