This repository has been archived by the owner on Sep 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
parser.go
436 lines (410 loc) · 9.87 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
package mark
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
// parse holds the state of the parser.
type parse struct {
Nodes []Node
lex Lexer
options *Options
tr *parse
output string
peekCount int
token [3]item // three-token lookahead for parser
links map[string]*DefLinkNode // Deflink parsing, used RefLinks
renderFn map[NodeType]RenderFn // Custom overridden fns
}
// Return new parser
func newParse(input string, opts *Options) *parse {
return &parse{
lex: lex(input),
options: opts,
links: make(map[string]*DefLinkNode),
renderFn: make(map[NodeType]RenderFn),
}
}
// parse convert the raw text to Nodeparse.
func (p *parse) parse() {
Loop:
for {
var n Node
switch t := p.peek(); t.typ {
case itemEOF, itemError:
break Loop
case itemNewLine:
p.next()
case itemHr:
n = p.newHr(p.next().pos)
case itemHTML:
t = p.next()
n = p.newHTML(t.pos, t.val)
case itemDefLink:
n = p.parseDefLink()
case itemHeading, itemLHeading:
n = p.parseHeading()
case itemCodeBlock, itemGfmCodeBlock:
n = p.parseCodeBlock()
case itemList:
n = p.parseList()
case itemTable, itemLpTable:
n = p.parseTable()
case itemBlockQuote:
n = p.parseBlockQuote()
case itemIndent:
space := p.next()
// If it isn't followed by itemText
if p.peek().typ != itemText {
continue
}
p.backup2(space)
fallthrough
// itemText
default:
tmp := p.newParagraph(t.pos)
tmp.Nodes = p.parseText(p.next().val + p.scanLines())
n = tmp
}
if n != nil {
p.append(n)
}
}
}
// Root getter
func (p *parse) root() *parse {
if p.tr == nil {
return p
}
return p.tr.root()
}
// Render parse nodes to the wanted output
func (p *parse) render() {
var output string
for i, node := range p.Nodes {
// If there's a custom render function, use it instead.
if fn, ok := p.renderFn[node.Type()]; ok {
output = fn(node)
} else {
output = node.Render()
}
p.output += output
if output != "" && i != len(p.Nodes)-1 {
p.output += "\n"
}
}
}
// append new node to nodes-list
func (p *parse) append(n Node) {
p.Nodes = append(p.Nodes, n)
}
// next returns the next token
func (p *parse) next() item {
if p.peekCount > 0 {
p.peekCount--
} else {
p.token[0] = p.lex.nextItem()
}
return p.token[p.peekCount]
}
// peek returns but does not consume the next token.
func (p *parse) peek() item {
if p.peekCount > 0 {
return p.token[p.peekCount-1]
}
p.peekCount = 1
p.token[0] = p.lex.nextItem()
return p.token[0]
}
// backup backs the input stream tp one token
func (p *parse) backup() {
p.peekCount++
}
// backup2 backs the input stream up two tokens.
// The zeroth token is already there.
func (p *parse) backup2(t1 item) {
p.token[1] = t1
p.peekCount = 2
}
// parseText
func (p *parse) parseText(input string) (nodes []Node) {
// Trim whitespaces that not a line-break
input = regexp.MustCompile(`(?m)^ +| +(\n|$)`).ReplaceAllStringFunc(input, func(s string) string {
if reBr.MatchString(s) {
return s
}
return strings.Replace(s, " ", "", -1)
})
l := lexInline(input)
for token := range l.items {
var node Node
switch token.typ {
case itemBr:
node = p.newBr(token.pos)
case itemStrong, itemItalic, itemStrike, itemCode:
node = p.parseEmphasis(token.typ, token.pos, token.val)
case itemLink, itemAutoLink, itemGfmLink:
var title, href string
var text []Node
if token.typ == itemLink {
match := reLink.FindStringSubmatch(token.val)
text = p.parseText(match[1])
href, title = match[2], match[3]
} else {
var match []string
if token.typ == itemGfmLink {
match = reGfmLink.FindStringSubmatch(token.val)
} else {
match = reAutoLink.FindStringSubmatch(token.val)
}
href = match[1]
text = append(text, p.newText(token.pos, match[1]))
}
node = p.newLink(token.pos, title, href, text...)
case itemImage:
match := reImage.FindStringSubmatch(token.val)
node = p.newImage(token.pos, match[3], match[2], match[1])
case itemRefLink, itemRefImage:
match := reRefLink.FindStringSubmatch(token.val)
text, ref := match[1], match[2]
if ref == "" {
ref = text
}
if token.typ == itemRefLink {
node = p.newRefLink(token.typ, token.pos, token.val, ref, p.parseText(text))
} else {
node = p.newRefImage(token.typ, token.pos, token.val, ref, text)
}
case itemHTML:
node = p.newHTML(token.pos, token.val)
default:
node = p.newText(token.pos, token.val)
}
nodes = append(nodes, node)
}
return nodes
}
// parse inline emphasis
func (p *parse) parseEmphasis(typ itemType, pos Pos, val string) *EmphasisNode {
var re *regexp.Regexp
switch typ {
case itemStrike:
re = reStrike
case itemStrong:
re = reStrong
case itemCode:
re = reCode
case itemItalic:
re = reItalic
}
node := p.newEmphasis(pos, typ)
match := re.FindStringSubmatch(val)
text := match[len(match)-1]
if text == "" {
text = match[1]
}
node.Nodes = p.parseText(text)
return node
}
// parse heading block
func (p *parse) parseHeading() (node *HeadingNode) {
token := p.next()
level := 1
var text string
if token.typ == itemHeading {
match := reHeading.FindStringSubmatch(token.val)
level, text = len(match[1]), match[2]
} else {
match := reLHeading.FindStringSubmatch(token.val)
// using equal signs for first-level, and dashes for second-level.
text = match[1]
if match[2] == "-" {
level = 2
}
}
node = p.newHeading(token.pos, level, text)
node.Nodes = p.parseText(text)
return
}
func (p *parse) parseDefLink() *DefLinkNode {
token := p.next()
match := reDefLink.FindStringSubmatch(token.val)
name := strings.ToLower(match[1])
// name(lowercase), href, title
n := p.newDefLink(token.pos, name, match[2], match[3])
// store in links
links := p.root().links
if _, ok := links[name]; !ok {
links[name] = n
}
return n
}
// parse codeBlock
func (p *parse) parseCodeBlock() *CodeNode {
var lang, text string
token := p.next()
if token.typ == itemGfmCodeBlock {
codeStart := reGfmCode.FindStringSubmatch(token.val)
lang = codeStart[3]
text = token.val[len(codeStart[0]):]
} else {
text = reCodeBlock.trim(token.val, "")
}
return p.newCode(token.pos, lang, text)
}
func (p *parse) parseBlockQuote() (n *BlockQuoteNode) {
token := p.next()
// replacer
re := regexp.MustCompile(`(?m)^ *> ?`)
raw := re.ReplaceAllString(token.val, "")
// TODO(a8m): doesn't work right now with defLink(inside the blockQuote)
tr := &parse{lex: lex(raw), tr: p}
tr.parse()
n = p.newBlockQuote(token.pos)
n.Nodes = tr.Nodes
return
}
// parse list
func (p *parse) parseList() *ListNode {
token := p.next()
list := p.newList(token.pos, isDigit(token.val))
Loop:
for {
switch token = p.peek(); token.typ {
case itemLooseItem, itemListItem:
list.append(p.parseListItem())
default:
break Loop
}
}
return list
}
// parse listItem
func (p *parse) parseListItem() *ListItemNode {
token := p.next()
item := p.newListItem(token.pos)
token.val = strings.TrimSpace(token.val)
if p.isTaskItem(token.val) {
item.Nodes = p.parseTaskItem(token)
return item
}
tr := &parse{lex: lex(token.val), tr: p}
tr.parse()
for _, node := range tr.Nodes {
// wrap with paragraph only when it's a loose item
if n, ok := node.(*ParagraphNode); ok && token.typ == itemListItem {
item.Nodes = append(item.Nodes, n.Nodes...)
} else {
item.append(node)
}
}
return item
}
// parseTaskItem parses list item as a task item.
func (p *parse) parseTaskItem(token item) []Node {
checkbox := p.newCheckbox(token.pos, token.val[1] == 'x')
token.val = strings.TrimSpace(token.val[3:])
return append([]Node{checkbox}, p.parseText(token.val)...)
}
// isTaskItem tests if the given string is list task item.
func (p *parse) isTaskItem(s string) bool {
if len(s) < 5 || s[0] != '[' || (s[1] != 'x' && s[1] != ' ') || s[2] != ']' {
return false
}
return "" != strings.TrimSpace(s[3:])
}
// parse table
func (p *parse) parseTable() *TableNode {
table := p.newTable(p.next().pos)
// Align [ None, Left, Right, ... ]
// Header [ Cells: [ ... ] ]
// Data: [ Rows: [ Cells: [ ... ] ] ]
rows := struct {
Align []AlignType
Header []item
Cells [][]item
}{}
Loop:
for i := 0; ; {
switch token := p.next(); token.typ {
case itemTableRow:
i++
if i > 2 {
rows.Cells = append(rows.Cells, []item{})
}
case itemTableCell:
// Header
if i == 1 {
rows.Header = append(rows.Header, token)
// Alignment
} else if i == 2 {
rows.Align = append(rows.Align, parseAlign(token.val))
// Data
} else {
pos := i - 3
rows.Cells[pos] = append(rows.Cells[pos], token)
}
default:
p.backup()
break Loop
}
}
// Tranform to nodes
table.append(p.parseCells(Header, rows.Header, rows.Align))
// Table body
for _, row := range rows.Cells {
table.append(p.parseCells(Data, row, rows.Align))
}
return table
}
// parse cells and return new row
func (p *parse) parseCells(kind int, items []item, align []AlignType) *RowNode {
var row *RowNode
for i, item := range items {
if i == 0 {
row = p.newRow(item.pos)
}
cell := p.newCell(item.pos, kind, align[i])
cell.Nodes = p.parseText(item.val)
row.append(cell)
}
return row
}
// Used to consume lines(itemText) for a continues paragraphs
func (p *parse) scanLines() (s string) {
for {
tkn := p.next()
if tkn.typ == itemText || tkn.typ == itemIndent {
s += tkn.val
} else if tkn.typ == itemNewLine {
if t := p.peek().typ; t != itemText && t != itemIndent {
p.backup2(tkn)
break
}
s += tkn.val
} else {
p.backup()
break
}
}
return
}
// get align-string and return the align type of it
func parseAlign(s string) (typ AlignType) {
sfx, pfx := strings.HasSuffix(s, ":"), strings.HasPrefix(s, ":")
switch {
case sfx && pfx:
typ = Center
case sfx:
typ = Right
case pfx:
typ = Left
}
return
}
// test if given string is digit
func isDigit(s string) bool {
r, _ := utf8.DecodeRuneInString(s)
return unicode.IsDigit(r)
}