-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstandard-clojure-style.js
4044 lines (3388 loc) · 135 KB
/
standard-clojure-style.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
/* global define */
// standard-clojure-style @@VERSION@@
//
// Copyright 2023 © Chris Oakman
// ISC License
// -----------------------------------------------------------------------------
// JS Module Boilerplate
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory)
} else if (typeof module === 'object' && module.exports) {
module.exports = factory()
} else {
root.standardClojureStyle = factory()
}
}(this, function () { // start module anonymous scope
'use strict'
// ---------------------------------------------------------------------------
// Type Predicates
function isString (s) {
return typeof s === 'string'
}
function isInteger (x) {
return typeof x === 'number' && isFinite(x) && Math.floor(x) === x
}
function isPositiveInt (i) {
return isInteger(i) && i >= 0
}
function isFunction (f) {
return typeof f === 'function'
}
function isObject (o) {
return typeof o === 'object'
}
function isArray (x) {
return Array.isArray(x)
}
// ---------------------------------------------------------------------------
// Language Helpers
// NOTE: wrapping these functions make it easier to port between languages
// returns the length of a String
function strLen (s) {
return s.length
}
// returns the length of an Array
function arraySize (a) {
return a.length
}
// returns the last item in an Array
// returns null if the Array has no items
function arrayLast (a) {
const s = arraySize(a)
if (s === 0) {
return null
} else {
return a[dec(s)]
}
}
function dropLast (arr) {
return arr.splice(0, dec(arraySize(arr)))
}
// given an array of objects, returns a new array of the values at obj[key]
function arrayPluck (arr, key) {
const arr2 = []
const size = arraySize(arr)
let idx = 0
while (idx < size) {
const itm = arr[idx]
arr2.push(itm[key])
idx = inc(idx)
}
return arr2
}
function arrayReverse (arr) {
return arr.reverse()
}
function strConcat (s1, s2) {
return '' + s1 + s2
}
function strConcat3 (s1, s2, s3) {
return '' + s1 + s2 + s3
}
function inc (n) {
return n + 1
}
function dec (n) {
return n - 1
}
const runtimeHasObjectKeys = isFunction(Object.keys)
// runs aFn(key, value) on every key/value pair inside of obj
function objectForEach (obj, aFn) {
if (runtimeHasObjectKeys) {
const keys = Object.keys(obj)
const numKeys = arraySize(keys)
let idx = 0
while (idx < numKeys) {
const key = keys[idx]
aFn(key, obj[key])
idx = inc(idx)
}
} else {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
aFn(key, obj[key])
}
}
}
}
function deleteObjKey (obj, key) {
delete obj[key]
return obj
}
function alwaysTrue () {
return true
}
// ---------------------------------------------------------------------------
// Stack Operations
function stackPeek (arr, idxFromBack) {
const maxIdx = dec(arraySize(arr))
if (idxFromBack > maxIdx) {
return null
}
return arr[maxIdx - idxFromBack]
}
function stackPop (s) {
const itm = s.pop()
return itm
}
function stackPush (s, itm) {
s.push(itm)
return null
}
// ---------------------------------------------------------------------------
// String Utils
// returns the character at position n inside of String s (0-indexed)
function charAt (s, n) {
return s.charAt(n)
}
// Returns the substring of s beginning at startIdx inclusive, and ending
// at endIdx, exclusive.
// Pass -1 to endIdx to mean "until the end of the string"
function substr (s, startIdx, endIdx) {
const len = strLen(s)
if (startIdx < 0 || startIdx > len) {
return ''
}
if (endIdx < 0) {
endIdx = len
} else if (endIdx > len) {
endIdx = len
}
return s.substring(startIdx, endIdx)
}
function repeatString (text, n) {
let result = ''
let i = 0
while (i < n) {
result = result + text
i = inc(i)
}
return result
}
// does String needle exist inside of String s?
function strIncludes (s, needle) {
return s.includes(needle)
}
function toUpperCase (s) {
return s.toUpperCase()
}
function strJoin (arr, s) {
return arr.join(s)
}
function rtrim (s) {
return s.trimEnd()
}
function strTrim (s) {
return s.trim()
}
function strStartsWith (s, startStr) {
return s.startsWith(startStr)
}
function strEndsWith (s, endStr) {
return s.endsWith(endStr)
}
function isStringWithChars (s) {
return isString(s) && s !== ''
}
function strReplaceFirst (s, find, replace) {
if (s === '') return ''
if (find === '') return s
return s.replace(find, replace)
}
const runtimeHasStringReplaceAll = isFunction(''.replaceAll)
function strReplaceAll (s, find, replace) {
if (runtimeHasStringReplaceAll) {
return s.replaceAll(find, replace)
} else {
let s2 = s
while (strIncludes(s2, find)) {
s2 = strReplaceFirst(s2, find, replace)
}
return s2
}
}
function crlfToLf (txt) {
return txt.replace(/\r\n/g, '\n')
}
// ---------------------------------------------------------------------------
// id generator
let idCounter = 0
function createId () {
idCounter = inc(idCounter)
return idCounter
}
// ---------------------------------------------------------------------------
// Node Types
// creates and returns an AST Node Object:
// - startIdx: start position in String (inclusive)
// - endIdx: end position in String (exclusive)
// - children: array of child Nodes
// - name: name of the Node
// - text: raw text of the Node (only for terminal nodes like Regex or Strings)
function Node (opts) {
return {
children: opts.children,
endIdx: opts.endIdx,
id: createId(),
name: opts.name,
startIdx: opts.startIdx,
text: opts.text
}
}
function Named (opts) {
return {
parse: (txt, pos) => {
const parser = getParser(opts.parser)
const node = parser.parse(txt, pos)
if (!node) {
return null
} else if (node && !isString(node.name)) {
node.name = opts.name
return node
} else {
return Node({
children: [node],
endIdx: node.endIdx,
name: opts.name,
startIdx: node.startIdx
})
}
}
}
}
// ---------------------------------------------------------------------------
// Terminal Parsers
// Terminal parser that matches any single character.
function AnyChar (opts) {
return {
name: opts.name,
parse: (txt, pos) => {
if (pos < strLen(txt)) {
return Node({
endIdx: inc(pos),
name: opts.name,
startIdx: pos,
text: charAt(txt, pos)
})
} else {
return null
}
}
}
}
// Terminal parser that matches one character.
function Char (opts) {
return {
isTerminal: true,
char: opts.char,
name: opts.name,
parse: function (txt, pos) {
if (pos < strLen(txt) && charAt(txt, pos) === opts.char) {
return Node({
endIdx: inc(pos),
name: opts.name,
startIdx: pos,
text: opts.char
})
} else {
return null
}
}
}
}
// Terminal parser that matches any single character, except one.
function NotChar (opts) {
return {
isTerminal: true,
char: opts.char,
name: opts.name,
parse: function (txt, pos) {
if (pos < strLen(txt)) {
const charAtThisPos = charAt(txt, pos)
if (charAtThisPos !== opts.char) {
return Node({
endIdx: inc(pos),
name: opts.name,
startIdx: pos,
text: charAtThisPos
})
}
}
return null
}
}
}
// Terminal parser that matches a String
function StringParser (opts) {
return {
name: opts.name,
parse: (txt, pos) => {
const len = strLen(opts.str)
if (pos + len <= strLen(txt)) {
const strToCompare = substr(txt, pos, pos + len)
if (opts.str === strToCompare) {
return Node({
endIdx: pos + len,
name: opts.name,
startIdx: pos,
text: opts.str
})
}
}
return null
}
}
}
function Regex (opts) {
return {
name: opts.name,
parse: (txt, pos) => {
// NOTE: this might be a perf issue; investigate later
const innerTxt = substr(txt, pos, -1)
const result = innerTxt.match(opts.regex)
// NOTE: uncomment this for development / testing
// const regexStr = opts.regex.toString()
// if (!strStartsWith(regexStr, '/^')) {
// throw new Error('Regex pattern "' + opts.name + '" does not have input boundary assertion: ' + regexStr)
// }
let matchedStr = null
if (result && isInteger(opts.groupIdx) && isString(result[inc(opts.groupIdx)])) {
matchedStr = result[inc(opts.groupIdx)]
} else if (result && isString(result[0])) {
matchedStr = result[0]
}
if (isString(matchedStr)) {
return Node({
endIdx: pos + strLen(matchedStr),
name: opts.name,
startIdx: pos,
text: matchedStr
})
}
return null
}
}
}
// ---------------------------------------------------------------------------
// Sequence Parsers
// parser that matches a linear sequence of other parsers
function Seq (opts) {
return {
isTerminal: false,
name: opts.name,
parse: (txt, pos) => {
const children = []
let endIdx = pos
let j = 0
const numParsers = arraySize(opts.parsers)
while (j < numParsers) {
const parser = opts.parsers[j]
const possibleNode = parser.parse(txt, endIdx)
if (possibleNode) {
appendChildren(children, possibleNode)
endIdx = possibleNode.endIdx
} else {
// else this is not a valid sequence: early return
return null
}
j = inc(j)
}
return Node({
children,
endIdx,
name: opts.name,
startIdx: pos
})
}
}
}
// matches the first matching of several parsers
function Choice (opts) {
return {
parse: (txt, pos) => {
let i = 0
const numParsers = arraySize(opts.parsers)
while (i < numParsers) {
const parser = getParser(opts.parsers[i])
const possibleNode = parser.parse(txt, pos)
if (possibleNode) return possibleNode
i = inc(i)
}
return null
}
}
}
// matches child parser zero or more times
function Repeat (opts) {
return {
parse: (txt, pos) => {
opts.parser = getParser(opts.parser)
let minMatches = 0
if (isPositiveInt(opts.minMatches)) {
minMatches = opts.minMatches
}
const children = []
let endIdx = pos
let lookForTheNextNode = true
while (lookForTheNextNode) {
const node = opts.parser.parse(txt, endIdx)
if (node) {
appendChildren(children, node)
endIdx = node.endIdx
} else {
lookForTheNextNode = false
}
}
let name2 = null
if (isString(opts.name) && endIdx > pos) name2 = opts.name
if (arraySize(children) >= minMatches) {
return Node({
children,
endIdx,
name: name2,
startIdx: pos
})
}
return null
}
}
}
// Parser that either matches a child parser or skips it
function Optional (parser) {
return {
parse: (txt, pos) => {
const node = parser.parse(txt, pos)
if (node && isString(node.text) && node.text !== '') {
return node
} else {
return Node({ startIdx: pos, endIdx: pos })
}
}
}
}
// ---------------------------------------------------------------------------
// Parser Helpers / Rename?
// FIXME: write this so it returns the new Array
function appendChildren (childrenArr, node) {
if (isString(node.name) && node.name !== '') {
childrenArr.push(node)
} else if (isArray(node.children)) {
let i = 0
const numChildren = arraySize(node.children)
while (i < numChildren) {
const child = node.children[i]
if (child) appendChildren(childrenArr, child)
i = inc(i)
}
}
}
function getParser (p) {
if (isString(p) && parsers[p]) {
return parsers[p]
} else if (isObject(p) && isFunction(p.parse)) {
return p
} else {
throw new Error('getParser error: could not find parser: ' + p)
}
}
// ---------------------------------------------------------------------------
// Parser Definitions
const parsers = {}
parsers.string = Seq(
{
name: 'string',
parsers: [
Regex({ regex: /^#?"/, name: '.open' }),
Optional(Regex({ regex: /^([^"\\]+|\\.)+/, name: '.body' })),
Optional(Char({ char: '"', name: '.close' }))
]
}
)
const whitespaceCommons = ' ,\\n\\r\\t\\f'
const whitespaceUnicodes = '\\u000B\\u001C\\u001D\\u001E\\u001F\\u2028\\u2029\\u1680\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2008\\u2009\\u200a\\u205f\\u3000'
const whitespaceChars = strConcat(whitespaceCommons, whitespaceUnicodes)
const tokenHeadChars = '()\\[\\]{}\\"@~^;`#\\\''
const tokenTailChars = '()\\[\\]{}\\"@^;`'
const tokenReStr = '[^' + tokenHeadChars + whitespaceChars + '][^' + tokenTailChars + whitespaceChars + ']*'
const charReStr = '\\\\[()\\[\\]{}"@^;`, ]'
parsers.token = Regex({ name: 'token', regex: new RegExp('^(##)?' + '(' + charReStr + '|' + tokenReStr + ')') })
parsers._ws = Regex({ name: 'whitespace', regex: new RegExp('^[' + whitespaceChars + ']+') })
parsers.comment = Regex({ name: 'comment', regex: /^;[^\n]*/ })
parsers.discard = Seq({
name: 'discard',
parsers: [
StringParser({ name: 'marker', str: '#_' }),
Repeat({ parser: '_gap' }),
Named({ name: '.body', parser: '_form' })
]
})
parsers.braces = Seq({
name: 'braces',
parsers: [
// NOTE: difference from cs_parser.py here
Choice({
parsers: [
Char({ name: '.open', char: '{' }),
StringParser({ name: '.open', str: '#{' }),
StringParser({ name: '.open', str: '#::{' }),
Regex({ name: '.open', regex: /^#:{1,2}[a-zA-Z][a-zA-Z0-9.-_]*{/ })
]
}),
Repeat({
name: '.body',
parser: Choice({ parsers: ['_gap', '_form', NotChar({ name: 'error', char: '}' })] })
}),
Optional(Char({ name: '.close', char: '}' }))
]
})
parsers.brackets = Seq({
name: 'brackets',
parsers: [
Char({ name: '.open', char: '[' }),
Repeat({
name: '.body',
parser: Choice({ parsers: ['_gap', '_form', NotChar({ name: 'error', char: ']' })] })
}),
Optional(Char({ name: '.close', char: ']' }))
]
})
parsers.parens = Seq({
name: 'parens',
parsers: [
Regex({ name: '.open', regex: /^(#\?@|#\?|#=|#)?\(/ }),
Repeat({
name: '.body',
parser: Choice({ parsers: ['_gap', '_form', NotChar({ char: ')', name: 'error' })] })
}),
Optional(Char({ name: '.close', char: ')' }))
]
})
parsers._gap = Choice({ parsers: ['_ws', 'comment', 'discard'] })
parsers.meta = Seq({
name: 'meta',
parsers: [
Repeat({
minMatches: 1,
parser: Seq({
parsers: [
Regex({ name: '.marker', regex: /^#?\^/ }),
Repeat({ parser: '_gap' }),
Named({ name: '.meta', parser: '_form' }),
Repeat({ parser: '_gap' })
]
})
}),
Named({ name: '.body', parser: '_form' })
]
})
parsers.wrap = Seq({
name: 'wrap',
parsers: [
Regex({ name: '.marker', regex: /^(@|'|`|~@|~|#')/ }),
Repeat({ parser: '_gap' }),
Named({ name: '.body', parser: '_form' })
]
})
parsers.tagged = Seq({
name: 'tagged',
parsers: [
Char({ char: '#' }),
Repeat({ parser: '_gap' }),
Named({ name: '.tag', parser: 'token' }),
Repeat({ parser: '_gap' }),
Named({ name: '.body', parser: '_form' })
]
})
parsers._form = Choice({ parsers: ['token', 'string', 'parens', 'brackets', 'braces', 'wrap', 'meta', 'tagged'] })
parsers.source = Repeat({
name: 'source',
parser: Choice({ parsers: ['_gap', '_form', AnyChar({ name: 'error' })] })
})
// ---------------------------------------------------------------------------
// Format Helpers
// TODO: some of this information should be calculated when parsing
// TODO: it would be nice if every paren open / close pair had a unique id
function nodeContainsText (node) {
return node && isString(node.text) && node.text !== ''
}
function isNodeWithNonBlankText (node) {
return nodeContainsText(node) && charAt(node.text, 0) !== ' '
}
function isNsNode (node) {
return node.name === 'token' && node.text === 'ns'
}
function isUseNode (node) {
return node && isString(node.text) && (node.text === ':use' || node.text === 'use')
}
function isRequireNode (node) {
return node && isString(node.text) && (node.text === ':require' || node.text === 'require')
}
function isRequireMacrosKeyword (node) {
return node && isString(node.text) && node.text === ':require-macros'
}
function isReferClojureNode (node) {
return node && isString(node.text) && (node.text === ':refer-clojure' || node.text === 'refer-clojure')
}
function isExcludeKeyword (node) {
return node && isString(node.text) && node.text === ':exclude'
}
function isOnlyKeyword (node) {
return node && isString(node.text) && node.text === ':only'
}
function isRenameKeyword (node) {
return node && isString(node.text) && node.text === ':rename'
}
function isAsKeyword (node) {
return node && isString(node.text) && node.text === ':as'
}
function isAsAliasKeyword (node) {
return node && isString(node.text) && node.text === ':as-alias'
}
function isReferKeyword (node) {
return node && isString(node.text) && node.text === ':refer'
}
function isDefaultKeyword (node) {
return node && isString(node.text) && node.text === ':default'
}
function isReferMacrosKeyword (node) {
return node && isString(node.text) && node.text === ':refer-macros'
}
function isIncludeMacrosNode (node) {
return node && isString(node.text) && node.text === ':include-macros'
}
function isBooleanNode (node) {
return node && isString(node.text) && (node.text === 'true' || node.text === 'false')
}
function isAllNode (node) {
return node && isString(node.text) && node.text === ':all'
}
function isKeywordNode (node) {
return node && isString(node.text) && strStartsWith(node.text, ':')
}
function isImportNode (node) {
return node && isString(node.text) && (node.text === ':import' || node.text === 'import')
}
function isNewlineNode (n) {
return n.name === 'whitespace' && isString(n.text) && strIncludes(n.text, '\n')
}
function isWhitespaceNode (n) {
return n.name === 'whitespace' || isNewlineNode(n)
}
function isCommaNode (n) {
return n.name === 'whitespace' && strIncludes(n.text, ',')
}
const parenOpenersTbl = {
'(': true,
'[': true,
'{': true,
'#{': true,
'#(': true,
'#?(': true,
'#?@(': true
}
function isParenOpener (n) {
return n && n.name === '.open' && (parenOpenersTbl[n.text] || isNamespacedMapOpener(n))
}
function isParenCloser (n) {
return n && n.name === '.close' && (n.text === ')' || n.text === ']' || n.text === '}')
}
function isTokenNode (n) {
return n.name === 'token'
}
function isTagNode (n) {
return n.name === '.tag'
}
function isStringNode (n) {
return n && n.name === 'string' && isArray(n.children) && arraySize(n.children) === 3 && n.children[1].name === '.body'
}
function getTextFromStringNode (n) {
return n.children[1].text
}
function isCommentNode (n) {
return n.name === 'comment'
}
function isReaderCommentNode (n) {
return n.name === 'discard'
}
function isDiscardNode (n) {
return n.name === 'marker' && n.text === '#_'
}
function isStandardCljIgnoreKeyword (n) {
return n.name === 'token' && n.text === ':standard-clj/ignore'
}
function isStandardCljIgnoreFileKeyword (n) {
return n.name === 'token' && n.text === ':standard-clj/ignore-file'
}
function nodeContainsTextAndNotWhitespace (n) {
return nodeContainsText(n) && !isWhitespaceNode(n)
}
function isMapLiteralOpener (n) {
return n && n.name === '.open' && n.text === '{'
}
function isVectorLiteralOpener (n) {
return n && n.name === '.open' && n.text === '['
}
function isSingleParenOpener (n) {
return n && n.name === '.open' && n.text === '('
}
function isAnonFnOpener (n) {
return n && n.name === '.open' && n.text === '#('
}
function isSetLiteralOpener (n) {
return n && n.name === '.open' && n.text === '#{'
}
function isNamespacedMapOpener (n) {
return n && n.name === '.open' && strStartsWith(n.text, '#:') && strEndsWith(n.text, '{')
}
function isReaderConditionalOpener (n) {
return n && n.name === '.open' && (n.text === '#?(' || n.text === '#?@(')
}
function isOpeningBraceNode (n) {
return n && n.name === 'braces' && isArray(n.children) && arraySize(n.children) === 3 && n.children[2].name === '.close' && n.children[2].text === '}'
}
function commentNeedsSpaceBefore (lineTxt, nodeTxt) {
return strStartsWith(nodeTxt, ';') && lineTxt !== '' && !strEndsWith(lineTxt, ' ') && !strEndsWith(lineTxt, '(') && !strEndsWith(lineTxt, '[') && !strEndsWith(lineTxt, '{')
}
// FIXME: there must be a way to do this with a single regex
function commentNeedsSpaceInside (commentTxt) {
return !commentTxt.match(/^;+ /) && !commentTxt.match(/^;+$/)
}
function isGenClassNode (node) {
return node && isString(node.text) && node.text === ':gen-class'
}
const genClassKeywordsTbl = {
':name': true,
':extends': true,
':implements': true,
':init': true,
':constructors': true,
':post-init': true,
':methods': true,
':main': true,
':factory': true,
':state': true,
':exposes': true,
':exposes-methods': true,
':prefix': true,
':impl-ns': true,
':load-impl-ns': true
}
function isGenClassKeyword (node) {
return node && isString(node.text) && genClassKeywordsTbl[node.text]
}
const genClassKeys = ['name', 'extends', 'implements', 'init', 'constructors', 'post-init', 'methods', 'main', 'factory', 'state', 'exposes', 'exposes-methods', 'prefix', 'impl-ns', 'load-impl-ns']
// These are all of the :gen-class keys and their value types:
// https://github.com/clojure/clojure/blob/master/src/clj/clojure/genclass.clj
//
// :name aname
// :extends aclass
// :implements [interface ...]
// :init name
// :constructors {[param-types] [super-param-types], ...}
// :post-init name
// :methods [ [name [param-types] return-type], ...]
// :main boolean
// :factory name
// :state name
// :exposes {protected-field-name {:get name :set name}, ...}
// :exposes-methods {super-method-name exposed-name, ...}
// :prefix string
// :impl-ns name
// :load-impl-ns boolean
//
// TODO: store these as an object instead of enumerating them individually like below?
// these are all of the possible :gen-class keywords that should have a token value
// FIXME: we need to confirm this is accurate for :extends, which should be a class name
function isGenClassNameKey (keyTxt) {
return (keyTxt === 'name' || keyTxt === 'extends' || keyTxt === 'init' || keyTxt === 'post-init' || keyTxt === 'factory' || keyTxt === 'state' || keyTxt === 'impl-ns')
}
function isGenClassBooleanKey (keyTxt) {
return (keyTxt === 'main' || keyTxt === 'load-impl-ns')
}
// recursively runs function f on every node in the tree
function recurseAllChildren (node, f) {
f(node)
if (node.children) {
const numChildren = arraySize(node.children)
let i = 0
while (i < numChildren) {
const childNode = node.children[i]
recurseAllChildren(childNode, f)
i = inc(i)
}
}
return null
}
// given a root node, returns a string of all the text found within its children
function getTextFromRootNode (rootNode) {
let s = ''
recurseAllChildren(rootNode, n => {
// edge case: add '#' text to .tag nodes
if (isTagNode(n)) {
s = strConcat(s, '#')
}
if (isStringWithChars(n.text)) {
s = strConcat(s, n.text)
}
})
return s
}
// given a root node, returns the last node that contains text from its children
function getLastChildNodeWithText (rootNode) {
let lastNode = null
recurseAllChildren(rootNode, n => {
if (isStringWithChars(n.text)) {
lastNode = n
}
})
return lastNode
}