/
TreeNode.js
1517 lines (1270 loc) · 40.2 KB
/
TreeNode.js
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const AbstractNode = require("./AbstractNode.node.js")
const TreeUtils = require("./TreeUtils.js")
class ImmutableNode extends AbstractNode {
constructor(children, line, parent) {
super()
this._parent = parent
this._setLine(line)
this._setChildren(children)
}
execute(context) {
return Promise.all(this.getChildren().map(child => child.execute(context)))
}
getErrors() {
return []
}
getLineSyntax() {
return "any ".repeat(this.getWords().length).trim()
}
executeSync(context) {
return this.getChildren().map(child => child.executeSync(context))
}
isNodeJs() {
return typeof exports !== "undefined"
}
getOlderSiblings() {
return this.getParent()
.getChildren()
.slice(0, this.getIndex())
}
getYoungerSiblings() {
return this.getParent()
.getChildren()
.slice(this.getIndex() + 1)
}
getSiblings() {
return this.getParent()
.getChildren()
.filter(node => node !== this)
}
_getUid() {
if (!this._uid) this._uid = ImmutableNode._makeUniqueId()
return this._uid
}
// todo: rename getMother? grandMother et cetera?
getParent() {
return this._parent
}
getPoint() {
return this._getPoint()
}
_getPoint(relativeTo) {
return {
x: this._getXCoordinate(relativeTo),
y: this._getYCoordinate(relativeTo)
}
}
getPointRelativeTo(relativeTo) {
return this._getPoint(relativeTo)
}
getIndentation(relativeTo) {
return this.getXI().repeat(this._getXCoordinate(relativeTo) - 1)
}
_getYCoordinate(relativeTo) {
return this.isRoot(relativeTo)
? 0
: this._getRootNode(relativeTo)
.getTopDownArray()
.indexOf(this) + 1 // todo: may be slow for big trees.
}
isRoot(relativeTo) {
return relativeTo === this || !this.getParent()
}
getRootNode() {
return this._getRootNode()
}
_getRootNode(relativeTo) {
if (this.isRoot(relativeTo)) return this
return this.getParent()._getRootNode(relativeTo)
}
toString(indentCount = 0, language = this) {
if (this.isRoot()) return this._childrenToString(indentCount, language)
const content = language.getXI().repeat(indentCount) + this.getLine(language)
const value = content + (this.length ? language.getYI() + this._childrenToString(indentCount + 1, language) : "")
return value
}
getRest() {
return this.getWords().slice(1)
}
getWord(index) {
const words = this._getLine().split(this.getZI())
if (index < 0) index = words.length + index
return words[index]
}
_toHtml(indentCount) {
const path = this.getPathVector().join(" ")
const classes = {
nodeLine: "nodeLine",
xi: "xIncrement",
yi: "yIncrement",
nodeChildren: "nodeChildren"
}
const edge = this.getXI().repeat(indentCount)
// Set up the keyword part of the node
const edgeHtml = `<span class="${classes.nodeLine}" data-pathVector="${path}"><span class="${classes.xi}">${edge}</span>`
const lineHtml = this._getLineHtml()
const childrenHtml = this.length
? `<span class="${classes.yi}">${this.getYI()}</span>` +
`<span class="${classes.nodeChildren}">${this._childrenToHtml(indentCount + 1)}</span>`
: ""
return `${edgeHtml}${lineHtml}${childrenHtml}</span>`
}
_getWords(startFrom) {
if (!this._words) this._words = this._getLine().split(this.getZI())
return startFrom ? this._words.slice(startFrom) : this._words
}
getWords() {
return this._getWords(0)
}
getWordsFrom(startFrom) {
return this._getWords(startFrom)
}
getKeyword() {
return this.getWords()[0]
}
getBeam() {
const words = this.getWordsFrom(1)
return words.length ? words.join(this.getZI()) : undefined
}
getBeamWithChildren() {
// todo: deprecate
const beam = this.getBeam()
return (beam ? beam : "") + (this.length ? this.getYI() + this._childrenToString() : "")
}
getStack() {
return this._getStack()
}
_getStack(relativeTo) {
if (this.isRoot(relativeTo)) return []
const parent = this.getParent()
if (parent.isRoot(relativeTo)) return [this]
else return parent._getStack(relativeTo).concat([this])
}
getStackString() {
return this._getStack()
.map((node, index) => this.getXI().repeat(index) + node.getLine())
.join(this.getYI())
}
getLine(language = this) {
return this.getWords().join(language.getZI())
}
// todo: return array? getPathArray?
_getKeywordPath(relativeTo) {
if (this.isRoot(relativeTo)) return ""
else if (this.getParent().isRoot(relativeTo)) return this.getKeyword()
return this.getParent()._getKeywordPath(relativeTo) + this.getXI() + this.getKeyword()
}
getKeywordPathRelativeTo(relativeTo) {
return this._getKeywordPath(relativeTo)
}
getKeywordPath() {
return this._getKeywordPath()
}
getPathVector() {
return this._getPathVector()
}
getPathVectorRelativeTo(relativeTo) {
return this._getPathVector(relativeTo)
}
_getPathVector(relativeTo) {
if (this.isRoot(relativeTo)) return []
const path = this.getParent().getPathVector(relativeTo)
path.push(this.getIndex())
return path
}
getIndex() {
return this.getParent()._indexOfNode(this)
}
isTerminal() {
return !this.length
}
_getLineHtml() {
return this.getWords()
.map((word, index) => `<span class="word${index ? "" : " keyword"}">${TreeUtils.stripHtml(word)}</span>`)
.join(`<span class="zIncrement">${this.getZI()}</span>`)
}
_getXmlContent(indentCount) {
if (this.getBeam() !== undefined) return this.getBeamWithChildren()
return this.length
? `${indentCount === -1 ? "" : "\n"}${this._childrenToXml(indentCount > -1 ? indentCount + 2 : -1)}${" ".repeat(
indentCount
)}`
: ""
}
_toXml(indentCount) {
const indent = " ".repeat(indentCount)
const tag = this.getKeyword()
return `${indent}<${tag}>${this._getXmlContent(indentCount)}</${tag}>${indentCount === -1 ? "" : "\n"}`
}
_toObjectTuple() {
const beam = this.getBeam()
const length = this.length
const hasChildrenNoBeam = beam === undefined && length
const hasBeamAndHasChildren = beam !== undefined && length
// If the node has a beam and a subtree return it as a string, as
// Javascript object values can't be both a leaf and a tree.
const tupleValue = hasChildrenNoBeam ? this.toObject() : hasBeamAndHasChildren ? this.getBeamWithChildren() : beam
return [this.getKeyword(), tupleValue]
}
_indexOfNode(needleNode) {
let result = -1
this.getChildren().find((node, index) => {
if (node === needleNode) {
result = index
return true
}
})
return result
}
getTopDownArray() {
const arr = []
this._getTopDownArray(arr)
return arr
}
_hasColumns(columns) {
const words = this.getWords()
return columns.every((searchTerm, index) => searchTerm === words[index])
}
hasWord(index, word) {
return this.getWord(index) === word
}
getNodeByColumns(...columns) {
return this.getTopDownArray().find(node => node._hasColumns(columns))
}
getNodeByColumn(index, name) {
return this.getChildren().find(node => node.getWord(index) === name)
}
_getTopDownArray(arr) {
this.getChildren().forEach(child => {
arr.push(child)
child._getTopDownArray(arr)
})
}
getChildrenFirstArray() {
const arr = []
this._getChildrenFirstArray(arr)
return arr
}
_getChildrenFirstArray(arr) {
this.getChildren().forEach(child => {
child._getChildrenFirstArray(arr)
arr.push(child)
})
}
_getXCoordinate(relativeTo) {
return this._getStack(relativeTo).length
}
getParentFirstArray() {
const levels = this._getLevels()
const arr = []
levels.forEach(level => {
level.forEach(item => arr.push(item))
})
return arr
}
_getLevels() {
const levels = []
this.getTopDownArray().forEach(node => {
const level = node._getXCoordinate()
if (!levels[level]) levels[level] = []
levels[level].push(node)
})
return levels
}
_getChildren() {
if (!this._children) this._children = []
return this._children
}
getLines() {
return this._getChildren().map(node => node.getLine())
}
getChildren() {
return this._getChildren()
}
get length() {
return this.getChildren().length
}
_nodeAt(index) {
if (index < 0) index = this.length + index
return this.getChildren()[index]
}
nodeAt(indexOrArray) {
const type = typeof indexOrArray
if (type === "number") return this._nodeAt(indexOrArray)
if (indexOrArray.length === 1) return this._nodeAt(indexOrArray[0])
const first = indexOrArray[0]
const node = this._nodeAt(first)
if (!node) return undefined
return node.nodeAt(indexOrArray.slice(1))
}
_toObject() {
const obj = {}
this._getChildren().forEach(node => {
const tuple = node._toObjectTuple()
obj[tuple[0]] = tuple[1]
})
return obj
}
toHtml() {
return this._childrenToHtml(0)
}
_childrenToHtml(indentCount) {
return this.getChildren()
.map(node => node._toHtml(indentCount))
.join(`<span class="yIncrement">${this.getYI()}</span>`)
}
_childrenToString(indentCount, language = this) {
return this.getChildren()
.map(node => node.toString(indentCount, language))
.join(language.getYI())
}
childrenToString() {
return this._childrenToString()
}
// todo: implement
_getNodeJoinCharacter() {
return "\n"
}
compile(targetExtension) {
return this.getChildren()
.map(child => child.compile(targetExtension))
.join(this._getNodeJoinCharacter())
}
toXml() {
return this._childrenToXml(0)
}
toJson() {
return JSON.stringify(this.toObject(), null, " ")
}
findNodes(keywordPath) {
return this._getChildren().filter(node => {
if (node.getKeyword() === keywordPath) return true
return false
})
}
format(str) {
const that = this
return str.replace(/{([^\}]+)}/g, (match, path) => {
const node = that.getNode(path)
return node ? node.getBeam() : ""
})
}
getColumn(path) {
return this._getChildren().map(node => {
const cell = node.getNode(path)
return cell === undefined ? undefined : cell.getBeam()
})
}
getNodesByLinePrefixes(columns) {
const matches = []
this._getNodesByLinePrefixes(matches, columns)
return matches
}
_getNodesByLinePrefixes(matches, columns) {
const cols = columns.slice(0)
const prefix = cols.shift()
const candidates = this.getChildren().filter(child => child.getLine().startsWith(prefix))
if (!cols.length) return candidates.forEach(cand => matches.push(cand))
candidates.forEach(cand => cand._getNodesByLinePrefixes(matches, cols))
}
getNode(keywordPath) {
return this._getNodeByPath(keywordPath)
}
findBeam(keywordPath) {
const node = this._getNodeByPath(keywordPath)
return node === undefined ? undefined : node.getBeam()
}
_getNodeByPath(keywordPath) {
const xi = this.getXI()
if (!keywordPath.includes(xi)) {
const index = this.indexOfLast(keywordPath)
return index === -1 ? undefined : this._nodeAt(index)
}
const parts = keywordPath.split(xi)
const current = parts.shift()
const currentNode = this.getChildren()[this._getIndex()[current]]
return currentNode ? currentNode._getNodeByPath(parts.join(xi)) : undefined
}
getNext() {
if (this.isRoot()) return this
const index = this.getIndex()
const parent = this.getParent()
const length = parent.length
const next = index + 1
return next === length ? parent.getChildren()[0] : parent.getChildren()[next]
}
getPrevious() {
if (this.isRoot()) return this
const index = this.getIndex()
const parent = this.getParent()
const length = parent.length
const prev = index - 1
return prev === -1 ? parent.getChildren()[length - 1] : parent.getChildren()[prev]
}
_getUnionNames() {
if (!this.length) return []
const obj = {}
this._getChildren().forEach(node => {
if (!node.length) return undefined
node._getChildren().forEach(node => {
obj[node.getKeyword()] = 1
})
})
return Object.keys(obj)
}
getGraphByKey(key) {
const graph = this._getGraph((node, id) => node.getNodeByColumn(0, id), node => node.findBeam(key))
graph.push(this)
return graph
}
getGraph(idColumnNumber, parentIdColumnNumber) {
const graph = this._getGraph(
(node, id) => node.getNodeByColumn(idColumnNumber, id),
node => node.getWord(parentIdColumnNumber)
)
graph.push(this)
return graph
}
_getGraph(getNodeByIdFn, getParentIdFn) {
const parentId = getParentIdFn(this)
if (!parentId) return []
const parentNode = getNodeByIdFn(this.getParent(), parentId)
if (!parentNode) throw new Error(`"${this.getLine()} tried to extend "${parentId}" but "${parentId}" not found.`)
const graph = parentNode._getGraph(getNodeByIdFn, getParentIdFn)
graph.push(parentNode)
return graph
}
pathVectorToKeywordPath(pathVector) {
const path = pathVector.slice() // copy array
const names = []
let node = this
while (path.length) {
if (!node) return names
names.push(node.nodeAt(path[0]).getKeyword())
node = node.nodeAt(path.shift())
}
return names
}
toCsv() {
return this.toDelimited(",")
}
toDelimited(delimiter, header) {
const regex = new RegExp(`(\\n|\\"|\\${delimiter})`)
const cellFn = (str, row, column) => (!str.toString().match(regex) ? str : `"` + str.replace(/\"/g, `""`) + `"`)
header = header || this._getUnionNames()
return this._toDelimited(delimiter, header, cellFn)
}
_toDelimited(delimiter, header, cellFn) {
const headerRow = header.map((columnName, index) => cellFn(columnName, 0, index)).join(delimiter)
const rows = this._getChildren().map((node, rowNumber) => {
return header
.map((columnName, index) => {
const childNode = node.getNode(columnName)
const beam = childNode ? childNode.getBeamWithChildren() : ""
return cellFn(beam, rowNumber + 1, index)
})
.join(delimiter)
})
return headerRow + "\n" + rows.join("\n")
}
toTable() {
return this._toTable(100, false)
}
toFormattedTable(maxWidth, alignRight) {
return this._toTable(maxWidth, alignRight)
}
_toTable(maxWidth, alignRight = false) {
const header = this._getUnionNames()
const widths = header.map(col => (col.length > maxWidth ? maxWidth : col.length))
this._getChildren().forEach(node => {
if (!node.length) return true
header.forEach((col, index) => {
const cellValue = node.getNode(col).getBeam()
if (!cellValue) return true
const length = cellValue.toString().length
if (length > widths[index]) widths[index] = length > maxWidth ? maxWidth : length
})
})
const cellFn = (cellText, row, col) => {
const width = widths[col]
// Strip newlines in fixedWidth output
const cellValue = cellText.toString().replace(/\n/g, "\\n")
const cellLength = cellValue.length
if (cellLength > width) {
return cellValue.substr(0, width)
}
const padding = " ".repeat(width - cellLength)
return alignRight ? padding + cellValue : cellValue + padding
}
return this._toDelimited(" ", header, cellFn)
}
toSsv() {
return this.toDelimited(" ")
}
toOutline() {
return this._toOutline(node => node.getLine())
}
toMappedOutline(nodeFn) {
return this._toOutline(nodeFn)
}
// Adapted from: https://github.com/notatestuser/treeify.js
_toOutline(nodeFn) {
const growBranch = (outlineTreeNode, last, lastStates, nodeFn, callback) => {
let lastStatesCopy = lastStates.slice(0)
const node = outlineTreeNode.node
if (lastStatesCopy.push([outlineTreeNode, last]) && lastStates.length > 0) {
let line = ""
// keywordd on the "was last element" states of whatever we're nested within,
// we need to append either blankness or a branch to our line
lastStates.forEach((lastState, idx) => {
if (idx > 0) line += lastState[1] ? " " : "│"
})
// the prefix varies keywordd on whether the key contains something to show and
// whether we're dealing with the last element in this collection
// the extra "-" just makes things stand out more.
line += (last ? "└" : "├") + nodeFn(node)
callback(line)
}
if (!node) return
const length = node.length
let index = 0
node._getChildren().forEach(node => {
let lastKey = ++index === length
growBranch({ node: node }, lastKey, lastStatesCopy, nodeFn, callback)
})
}
let output = ""
growBranch({ node: this }, false, [], nodeFn, line => (output += line + "\n"))
return output
}
copyTo(node, index) {
const newNode = node._setLineAndChildren(this.getLine(), this.childrenToString(), index)
return newNode
}
toTsv() {
return this.toDelimited("\t")
}
getYI() {
return "\n"
}
getZI() {
return " "
}
getYIRegex() {
return new RegExp(this.getYI(), "g")
}
getXI() {
return " "
}
_textToBeamAndChildrenTuple(text) {
const lines = text.split(this.getYIRegex())
const firstLine = lines.shift()
const children = !lines.length
? undefined
: lines
.map(line => (line.substr(0, 1) === this.getXI() ? line : this.getXI() + line))
.map(line => line.substr(1))
.join(this.getYI())
return [firstLine, children]
}
_getLine() {
return this._line
}
_setLine(line = "") {
this._line = line
if (this._words) delete this._words
return this
}
_clearChildren() {
delete this._children
}
_setChildren(content, circularCheckArray) {
this._clearChildren()
if (!content) return this
// set from string
if (typeof content === "string") return this._parseString(content)
// set from tree object
if (content instanceof ImmutableNode) {
const me = this
content._getChildren().forEach(node => {
me._setLineAndChildren(node.getLine(), node.childrenToString())
})
return this
}
// If we set from object, create an array of inserted objects to avoid circular loops
if (!circularCheckArray) circularCheckArray = [content]
return this._setFromObject(content, circularCheckArray)
}
_setFromObject(content, circularCheckArray) {
for (let keyword in content) {
if (!content.hasOwnProperty(keyword)) continue
this._appendFromJavascriptObjectTuple(keyword, content[keyword], circularCheckArray)
}
return this
}
// todo: refactor the below.
_appendFromJavascriptObjectTuple(keyword, beam, circularCheckArray) {
const type = typeof beam
let line
let children
if (beam === null) line = keyword + " " + null
else if (beam === undefined) line = keyword
else if (type === "string") {
const tuple = this._textToBeamAndChildrenTuple(beam)
line = keyword + " " + tuple[0]
children = tuple[1]
} else if (type !== "object") line = keyword + " " + beam
else if (beam instanceof Date) line = keyword + " " + beam.getTime().toString()
else if (beam instanceof TreeNode) {
line = keyword
children = new TreeNode(beam.childrenToString(), beam.getLine())
} else if (type === "function") line = keyword + " " + beam.toString()
else if (circularCheckArray.indexOf(beam) === -1) {
circularCheckArray.push(beam)
line = keyword
const length = beam instanceof Array ? beam.length : Object.keys(beam).length
if (length) children = new TreeNode()._setChildren(beam, circularCheckArray)
} else {
// iirc this is return early from circular
return
}
this._setLineAndChildren(line, children)
}
_setLineAndChildren(line, children, index = this.length) {
const parserClass = this.parseNodeType(line)
const parsedNode = new parserClass(children, line, this)
const adjustedIndex = index < 0 ? this.length + index : index
this.getChildren().splice(adjustedIndex, 0, parsedNode)
if (this._index) this._makeIndex(adjustedIndex)
return parsedNode
}
_parseString(str) {
if (!str) return this
const lines = str.split(this.getYIRegex())
const parentStack = []
let currentIndentCount = -1
let lastNode = this
lines.forEach(line => {
const indentCount = this._getIndentCount(line)
if (indentCount > currentIndentCount) {
currentIndentCount++
parentStack.push(lastNode)
} else if (indentCount < currentIndentCount) {
// pop things off stack
while (indentCount < currentIndentCount) {
parentStack.pop()
currentIndentCount--
}
}
const lineContent = line.substr(currentIndentCount)
const parent = parentStack[parentStack.length - 1]
const parserClass = parent.parseNodeType(lineContent)
lastNode = new parserClass(undefined, lineContent, parent)
parent._getChildren().push(lastNode)
})
return this
}
_getIndex() {
// StringMap<int> {keyword: index}
// When there are multiple tails with the same keyword, _index stores the last beam.
return this._index || this._makeIndex()
}
getBeams() {
return this.getChildren().map(node => node.getBeam())
}
getChildrenByNodeType(type) {
return this.getChildren().filter(child => child instanceof type)
}
getNodeByType(type) {
return this.getChildren().find(child => child instanceof type)
}
indexOfLast(keyword) {
const result = this._getIndex()[keyword]
return result === undefined ? -1 : result
}
indexOf(keyword) {
if (!this.has(keyword)) return -1
const length = this.length
const nodes = this.getChildren()
for (let index = 0; index < length; index++) {
if (nodes[index].getKeyword() === keyword) return index
}
return -1
}
toObject() {
return this._toObject()
}
getKeywords() {
return this._getChildren().map(node => node.getKeyword())
}
_makeIndex(startAt = 0) {
if (!this._index || !startAt) this._index = {}
const nodes = this.getChildren()
const newIndex = this._index
const length = nodes.length
for (let index = startAt; index < length; index++) {
newIndex[nodes[index].getKeyword()] = index
}
return newIndex
}
_childrenToXml(indentCount) {
return this.getChildren()
.map(node => node._toXml(indentCount))
.join("")
}
_getIndentCount(str) {
let level = 0
const edgeChar = this.getXI()
while (str[level] === edgeChar) {
level++
}
return level
}
clone() {
return new this.constructor(this.childrenToString(), this.getLine())
}
// todo: rename to hasKeyword
has(keyword) {
return this._hasKeyword(keyword)
}
_hasKeyword(keyword) {
return this._getIndex()[keyword] !== undefined
}
_getKeywordByIndex(index) {
// Passing -1 gets the last item, et cetera
const length = this.length
if (index < 0) index = length + index
if (index >= length) return undefined
return this.getChildren()[index].getKeyword()
}
getKeywordMap() {
return {}
}
getCatchAllNodeClass(line) {
return this.constructor
}
parseNodeType(line) {
return this.getKeywordMap()[line.split(" ")[0]] || this.getCatchAllNodeClass(line)
}
static _makeUniqueId() {
if (this._uniqueId === undefined) this._uniqueId = 0
this._uniqueId++
return this._uniqueId
}
}
class TreeNode extends ImmutableNode {
getMTime() {
if (!this._mtime) this._updateMTime()
return this._mtime
}
_getChildrenMTime() {
const mTimes = this.getChildren().map(child => child.getTreeMTime())
const cmTime = this._getCMTime()
if (cmTime) mTimes.push(cmTime)
const newestTime = Math.max.apply(null, mTimes)
return this._setCMTime(newestTime || this._getNow())._getCMTime()
}
_getCMTime() {
return this._cmtime
}
_setCMTime(value) {
this._cmtime = value
return this
}
getTreeMTime() {
const mtime = this.getMTime()
const cmtime = this._getChildrenMTime()
return Math.max(mtime, cmtime)
}
_clearIndex() {
delete this._index
}
getInheritanceTree() {
const paths = {}
const result = new TreeNode()
this.getChildren().forEach(node => {
const key = node.getWord(0)
const parentKey = node.getWord(1)
const parentPath = paths[parentKey]
paths[key] = parentPath ? [parentPath, key].join(" ") : key
result.touchNode(paths[key])
})
return result
}
_expand(idColumnNumber, parentIdColumnNumber) {
const graph = this.getGraph(idColumnNumber, parentIdColumnNumber)
const result = new TreeNode()
graph.forEach(node => result.extend(node))
return new TreeNode().appendLineAndChildren(this.getLine(), result)
}
// todo: fix bug where you have duplicate IDs for different types!
getExpanded(idColumnNumber, parentIdColumnNumber) {
return this.getChildren()
.map(child => child._expand(idColumnNumber, parentIdColumnNumber))
.join("\n")
}
macroExpand(macroDefKeyword, macroUsageKeyword) {
const clone = this.clone()
const defs = clone.findNodes(macroDefKeyword)
const allUses = clone.findNodes(macroUsageKeyword)
const zi = clone.getZI()
defs.forEach(def => {
const macroName = def.getWord(1)
const uses = allUses.filter(node => node.hasWord(1, macroName))
const params = def.getWordsFrom(2)
const replaceFn = str => {
const paramValues = str.split(zi).slice(2)
let newTree = def.childrenToString()
params.forEach((param, index) => {
newTree = newTree.replace(new RegExp(param, "g"), paramValues[index])
})
return newTree
}
uses.forEach(node => {
node.replaceNode(replaceFn)
})
def.destroy()
})
return clone
}
setChildren(children) {
return this._setChildren(children)
}