/
block-map.go
404 lines (329 loc) · 9.23 KB
/
block-map.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
package wikifier
import (
"fmt"
"regexp"
"strconv"
"strings"
)
var (
keyNormalizer = regexp.MustCompile(`\W`)
keySplitter = regexp.MustCompile(`(.+)_(\d+)`)
)
// Map represents a Key-value dictionary.
// It is a quiki data type as well as the base of many block types.
type Map struct {
noFormatValues bool
didParse bool
mapList []*mapListEntry
*parserBlock
*variableScope
}
type mapListEntry struct {
keyTitle string // displayed key text
key string // actual underlying key
value interface{} // string, block, or mixed []interface{}
typ valueType // value type
pos position // position where the item started
metas map[string]bool // metadata
}
func (entry *mapListEntry) setMeta(key string, val bool) {
if val == false {
delete(entry.metas, key)
return
}
entry.metas[key] = val
}
func (entry *mapListEntry) meta(key string) bool {
return entry.metas[key]
}
type mapParser struct {
key interface{}
values []interface{}
escape bool
inValue bool
startPos position
pos position
overwroteKey interface{}
overwroteWith interface{}
appendedKey interface{}
}
// NewMap creates a new map, given the main block of the page it is to be associated with.
func NewMap(mb block) *Map {
underlying := &parserBlock{
openPos: position{0, 0}, // FIXME
parentB: mb,
parentC: mb,
typ: "map",
element: newElement("div", "map"),
genericCatch: &genericCatch{},
}
return &Map{false, false, nil, underlying, newVariableScope()}
}
func newMapBlock(name string, b *parserBlock) block {
return &Map{false, false, nil, b, newVariableScope()}
}
func (m *Map) parse(page *Page) {
// already parsed
if m.didParse {
return
}
m.didParse = true
p := new(mapParser)
for _, pc := range m.posContent() {
p.pos = pc.position
// infer start position to this one
if p.startPos.none() {
p.startPos = pc.position
}
switch item := pc.content.(type) {
// block
case block:
if p.inValue {
// first item
if len(p.values) == 0 {
p.startPos = p.pos
}
// add item
p.values = append(p.values, item)
} else {
// overwrote a key
p.overwroteKey = p.key
p.overwroteWith = item
p.key = item
}
m.warnMaybe(p)
// parse the block
item.parse(page)
case string:
item = strings.TrimSpace(item)
if item == "" {
continue
}
for i, c := range item {
m.handleChar(page, i, p, c)
}
}
}
// positional warnings
m.warnMaybe(p)
keyHR, valueHR := humanReadableValue(p.key), humanReadableValue(p.values)
// end of map warnings
if valueHR != "" || p.inValue {
// looks like we were in the middle of a value
m.warn(p.pos, "Value "+valueHR+" for key "+keyHR+" not terminated")
} else if keyHR != "" {
// we were in the middle of a key
m.warn(p.pos, "Stray key "+keyHR+" ignored")
}
}
func (m *Map) handleChar(page *Page, i int, p *mapParser, c rune) {
if c == ':' && !p.inValue && !p.escape {
// first colon indicates we're entering a value
p.inValue = true
} else if c == '\\' && !p.escape {
// escape
p.escape = true
} else if c == ';' && !p.escape {
// semicolon indicates termination of a pair
strKey, isStrKey := p.key.(string)
keyTitle := ""
// determine key
if (isStrKey && strKey == "") || p.key == nil {
// this is something like
// : value; (can be text or block though)
strKey = "anon_" + strconv.Itoa(i)
p.key = strKey
// no keyTitle
} else if !p.inValue {
// if there is a key but we aren't in the value,
// it is something like
// value; (can be text or block though)
// better to prefix text with : for less ambiguity
if isStrKey && strKey[0] != '-' {
m.warn(p.pos, "Standalone text should be prefixed with ':")
}
p.values = append(p.values, p.key)
strKey = "anon_" + strconv.Itoa(i)
p.key = strKey
// no keyTitle
} else {
// otherwise it's a normal key-value pair
// (can be text or block though)
// we have to convert this to a string key somehow, so use the address
if !isStrKey {
strKey = fmt.Sprintf("%p", p.key)
}
// normalize the key for internal use
strKey = strings.TrimSpace(strKey)
keyTitle = strKey
strKey = keyNormalizer.ReplaceAllString(strKey, "_")
p.key = strKey
}
// fix the value
// this returns either a string, block, HTML, or []interface{} combination
// strings next to each other are merged; empty strings are removed
valueToStore := fixValuesForStorage(p.values, page, !m.noFormatValues)
// if this key exists, rename it to the next available <key>_key_<n>
for exist, err := m.Get(strKey); exist != nil && err != nil; {
matches := keySplitter.FindStringSubmatch(strKey)
keyName, keyNumber := matches[1], matches[2]
// first one, so make it _2
if matches == nil {
strKey += "_2"
p.key = strKey
continue
}
// it has _n, so increment that
newKeyNumber, _ := strconv.Atoi(keyNumber)
newKeyNumber++
strKey = keyName + "_" + strconv.Itoa(newKeyNumber)
p.key = strKey
}
// store the value in the underlying variableScope
m.Set(strKey, valueToStore)
// store the value in the map list
m.mapList = append(m.mapList, &mapListEntry{
keyTitle: keyTitle, // displayed key
value: valueToStore, // string, block, or mixed []interface{}
typ: getValueType(valueToStore), // type of value
key: strKey, // actual underlying key
pos: p.startPos, // position where the item started
})
// check for warnings once more
m.warnMaybe(p)
// reset status
p.inValue = false
p.key = nil
p.values = nil
} else {
// any other character; add to key or value
// if it was escaped but not a parser char, add the \
add := string(c)
if p.escape && c != ';' && c != ':' && c != '\\' {
add = "\\" + add
}
p.escape = false
// this is part of the value
if p.inValue {
// first item
if len(p.values) == 0 {
p.startPos = p.pos
p.values = append(p.values, add)
return
}
// check previous item
last := p.values[len(p.values)-1]
if lastStr, ok := last.(string); ok {
// previous item was a string, so append it
p.values[len(p.values)-1] = lastStr + add
} else {
// previous item was not a string,
// so start a new string item
p.values = append(p.values, add)
}
return
}
// this is part of the key
// starting a new key
if p.key == nil {
p.startPos = p.pos
p.key = add
return
}
// check current key
if lastStr, ok := p.key.(string); ok {
// already working on a string key, so append it
p.key = lastStr + add
} else if strings.TrimSpace(add) != "" {
// previous item was not a string
// trying to add text to a non-text key...
// (above ignores whitespace chars)
p.appendedKey = p.key
}
}
}
// getEntry fetches the MapListEntry for a key.
func (m *Map) getEntry(key string) *mapListEntry {
for _, entry := range m.mapList {
if entry.key == key {
return entry
}
}
return nil
}
// getKeyPos returns the position where a key started.
// If the key doesn't exist, it returns the position where the map started.
func (m *Map) getKeyPos(key string) position {
if entry := m.getEntry(key); entry != nil {
return entry.pos
}
return m.openPos
}
// produce warnings as needed at current parser state
func (m *Map) warnMaybe(p *mapParser) {
hrKey := humanReadableValue(p.key)
// string keys spanning multiple lines are fishy
if strKey, ok := p.key.(string); ok && strings.ContainsRune(strKey, '\n') {
m.warn(p.pos, "Suspicious key "+hrKey)
}
// tried to append an object key
if p.appendedKey != nil {
appendText := humanReadableValue(p.appendedKey)
m.warn(p.pos, "Stray text after "+appendText+" ignored")
p.appendedKey = nil
}
// overwrote a key
if p.overwroteKey != nil {
old := humanReadableValue(p.overwroteKey)
new := humanReadableValue(p.overwroteWith)
m.warn(p.pos, "Overwrote "+old+" with "+new)
p.overwroteKey = nil
p.overwroteWith = nil
}
}
// default behavior for maps is to run html() on all children
// and replace the block value in the map with the generated element
func (m *Map) html(page *Page, el element) {
if m.noFormatValues {
return
}
for i, entry := range m.mapList {
m.mapList[i].value = prepareForHTML(entry.value, page, entry.pos)
m.setOwn(entry.key, m.mapList[i].value)
}
}
// since maps can be stored in variables and are generated on the fly,
// we sometimes need the main block to associate them with
func (m *Map) mainBlock() block {
var b block = m
for b.parentBlock() != nil {
b = b.parentBlock()
}
return b
}
// Map returns the actual underlying Go map.
func (m *Map) Map() map[string]interface{} {
return m.vars
}
// Keys returns a string of actual underlying map keys.
func (m *Map) Keys() []string {
keys := make([]string, len(m.vars))
i := 0
for key := range m.vars {
keys[i] = key
i++
}
return keys
}
// OrderedKeys returns a string of map keys in the order
// provided in the source. Keys that were set internally
// (and not from quiki source code) are omitted.
func (m *Map) OrderedKeys() []string {
keys := make([]string, len(m.mapList))
i := 0
for _, entry := range m.mapList {
keys[i] = entry.key
i++
}
return keys
}