-
Notifications
You must be signed in to change notification settings - Fork 40
/
parinfer.js
1807 lines (1548 loc) · 54.1 KB
/
parinfer.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 */
//
// Parinfer 3.13.1
//
// Copyright 2015-2017 © Shaun Lebron
// MIT License
//
// Home Page: http://shaunlebron.github.io/parinfer/
// GitHub: https://github.com/shaunlebron/parinfer
//
// For DOCUMENTATION on this file, please see `doc/code.md`.
// Use `sync.sh` to keep the function/var links in `doc/code.md` accurate.
//
// -----------------------------------------------------------------------------
// 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.parinfer = factory()
}
}(this, function () { // start module anonymous scope
'use strict'
// CO TODO for easier porting:
// - identify any function hoisting
// - wrap string operations in a function: charAt access, .split, .join
// - wrap all stack operations in a function: concat
// ---------------------------------------------------------------------------
// Constants
// NOTE: this is a performance hack
// The main result object uses a lot of "unsigned integer or null" values.
// Using a negative integer is faster than actual null because it cuts down on
// type coercion overhead.
const UINT_NULL = -999
const INDENT_MODE = 'INDENT_MODE'
const PAREN_MODE = 'PAREN_MODE'
const BACKSLASH = '\\'
const BLANK_SPACE = ' '
const DOUBLE_SPACE = ' '
const DOUBLE_QUOTE = '"'
const NEWLINE = '\n'
const TAB = '\t'
const LINE_ENDING_REGEX = /\r?\n/
const MATCH_PAREN = {
'{': '}',
'}': '{',
'[': ']',
']': '[',
'(': ')',
')': '('
}
// toggle this to check the asserts during development (requires node.js runtime)
const RUN_ASSERTS = false
let assert
if (RUN_ASSERTS) {
assert = require('assert')
}
// ---------------------------------------------------------------------------
// Type Predicates
function isBoolean (x) {
return typeof x === 'boolean'
}
function isArray (x) {
return Array.isArray(x)
}
function isInteger (x) {
return typeof x === 'number' &&
isFinite(x) &&
Math.floor(x) === x
}
function isPositiveInt (i) {
return isInteger(i) && i >= 0
}
function isString (s) {
return typeof s === 'string'
}
function isChar (c) {
return isString(c) && strLen(c) === 1
}
function isArrayOfChars (arr) {
return isArray(arr) && arr.every(isChar)
}
// ---------------------------------------------------------------------------
// Language Helpers (helps with porting between different languages)
function arraySize (a) {
if (RUN_ASSERTS) {
assert(isArray(a), 'used arraySize with not an Array')
}
return a.length
}
function strLen (s) {
if (RUN_ASSERTS) {
assert(isString(s), 'used strLen with not a String')
}
return s.length
}
function strConcat (s1, s2) {
if (RUN_ASSERTS) {
assert(isString(s1), 'strConcat argument s1 is not a String')
assert(isString(s2), 'strConcat argument s2 is not a String')
}
return s1 + s2
}
function getCharFromString (s, idx) {
if (RUN_ASSERTS) {
assert(isString(s), 'getCharFromString argument s is not a String')
assert(isInteger(idx), 'getCharFromString argument idx is not an Integer')
}
return s[idx]
}
if (RUN_ASSERTS) {
assert(getCharFromString('abc', 0) === 'a')
assert(getCharFromString('abc', 1) === 'b')
}
function indexOf(arr, val) {
const len = arraySize(arr)
let i = 0
while (i < len) {
if (val === arr[i]) {
return i
}
i = i + 1
}
return -1
}
if (RUN_ASSERTS) {
assert(indexOf(['a','b','c'], 'a') === 0)
assert(indexOf(['a','b','c'], 'b') === 1)
assert(indexOf(['a','b','c'], 'c') === 2)
assert(indexOf(['a','b','c'], 'd') === -1)
}
// ---------------------------------------------------------------------------
// String Operations
function replaceWithinString (orig, startIdx, endIdx, replace) {
const head = orig.substring(0, startIdx)
const tail = orig.substring(endIdx)
const s1 = strConcat(head, replace)
return strConcat(s1, tail)
}
if (RUN_ASSERTS) {
assert(replaceWithinString('abc', 0, 2, '') === 'c')
assert(replaceWithinString('abc', 0, 1, 'x') === 'xbc')
assert(replaceWithinString('abc', 0, 2, 'x') === 'xc')
assert(replaceWithinString('abcdef', 3, 25, '') === 'abc')
}
function repeatString (text, n) {
let result = ''
let i = 0
while (i < n) {
result = result + text
i = i + 1
}
return result
}
if (RUN_ASSERTS) {
assert(repeatString('a', 2) === 'aa')
assert(repeatString('aa', 3) === 'aaaaaa')
assert(repeatString('aa', 0) === '')
assert(repeatString('', 0) === '')
assert(repeatString('', 5) === '')
}
function getLineEnding (text) {
// NOTE: We assume that if the CR char "\r" is used anywhere,
// then we should use CRLF line-endings after every line.
const i = text.search('\r')
if (i !== -1) {
return '\r\n'
}
return '\n'
}
// ---------------------------------------------------------------------------
// Stack Operations
function isStackEmpty (s) {
if (RUN_ASSERTS) {
assert(isArray(s), 'used isStackEmpty with not an Array')
}
return s.length === 0
}
function peek (arr, idxFromBack) {
const maxIdx = arraySize(arr) - 1
if (idxFromBack > maxIdx) {
return null
}
return arr[maxIdx - idxFromBack]
}
if (RUN_ASSERTS) {
assert(peek(['a'], 0) === 'a')
assert(peek(['a'], 1) === null)
assert(peek(['a', 'b', 'c'], 0) === 'c')
assert(peek(['a', 'b', 'c'], 1) === 'b')
assert(peek(['a', 'b', 'c'], 5) === null)
assert(peek([], 0) === null)
assert(peek([], 1) === null)
}
function stackPop (s) {
if (RUN_ASSERTS) {
assert(isArray(s), 'used stackPop with not an Array')
}
const itm = s.pop()
return itm
}
if (RUN_ASSERTS) {
assert(stackPop(['a']) === 'a')
assert(stackPop(['a', 'b', 'c']) === 'c')
const testArray1 = ['a', 'b']
assert(stackPop(testArray1) === 'b')
assert(arraySize(testArray1) === 1)
assert(stackPop(testArray1) === 'a')
assert(arraySize(testArray1) === 0)
stackPop(testArray1)
assert(arraySize(testArray1) === 0)
}
function stackPush (s, itm) {
if (RUN_ASSERTS) {
assert(isArray(s), 'used stackPush with not an Array')
assert(isString(itm) || itm, 'used stackPush without a second itm')
}
s.push(itm)
return null
}
if (RUN_ASSERTS) {
const testArray2 = ['a', 'b']
stackPush(testArray2, 'c')
assert(arraySize(testArray2) === 3)
assert(peek(testArray2, 0) === 'c')
assert(peek(testArray2, 1) === 'b')
}
function arraySlice (arr, fromIdx, toIdx) {
if (RUN_ASSERTS) {
assert(isArray(arr), 'used arrayslice with not an Array')
assert(isPositiveInt(fromIdx), 'arraySlice fromIdx should be a positive integer')
assert(isPositiveInt(toIdx), 'arraySlice toIdx should be a positive integer')
}
return arr.slice(fromIdx, toIdx)
// NOTE: use this for porting code if necessary
// let newArray = []
// const arrLen = arraySize(arr)
// let i = fromIdx
// while (i < toIdx && i < arrLen) {
// const itm = arr[i]
// stackPush(newArray, itm)
// i = i + 1
// }
//
// return newArray
}
if (RUN_ASSERTS) {
assert(arraySlice(['a', 'b', 'c'], 0, 1).join() === ['a'].join())
assert(arraySlice(['a', 'b', 'c'], 1, 2).join() === ['b'].join())
assert(arraySlice(['a', 'b', 'c', 'd', 'e'], 1, 3).join() === ['b', 'c'].join())
assert(arraySlice(['a', 'b', 'c', 'd', 'e'], 2, 25).join() === ['c', 'd', 'e'].join())
assert(arraySlice([], 2, 3).join() === [].join())
}
// ---------------------------------------------------------------------------
// Options Structure
function transformChange (change) {
if (!change) {
return undefined
}
const newLines = change.newText.split(LINE_ENDING_REGEX)
const oldLines = change.oldText.split(LINE_ENDING_REGEX)
// single line case:
// (defn foo| [])
// ^ newEndX, newEndLineNo
// +++
// multi line case:
// (defn foo
// ++++
// "docstring."
// ++++++++++++++++
// |[])
// ++^ newEndX, newEndLineNo
const prevOldLine = peek(oldLines, 0)
const lastOldLineLen = strLen(prevOldLine)
const prevNewLine = peek(newLines, 0)
const lastNewLineLen = strLen(prevNewLine)
let carryOverOldX = 0
if (arraySize(oldLines) === 1) {
carryOverOldX = change.x
}
const oldEndX = carryOverOldX + lastOldLineLen
let carryOverNewX = 0
if (arraySize(newLines) === 1) {
carryOverNewX = change.x
}
const newEndX = carryOverNewX + lastNewLineLen
const newEndLineNo = change.lineNo + arraySize(newLines) - 1
return {
x: change.x,
lineNo: change.lineNo,
oldText: change.oldText,
newText: change.newText,
oldEndX: oldEndX,
newEndX: newEndX,
newEndLineNo: newEndLineNo,
lookupLineNo: newEndLineNo,
lookupX: newEndX
}
}
function transformChanges (changes) {
if (arraySize(changes) === 0) {
return null
} else {
const lines = {}
const changesLen = arraySize(changes)
let i = 0
while (i < changesLen) {
const change = transformChange(changes[i])
let line = lines[change.lookupLineNo]
if (!line) {
line = {}
lines[change.lookupLineNo] = line
}
line[change.lookupX] = change
i = i + 1
}
return lines
}
}
function parseOptions (options) {
options = options || {}
return {
changes: options.changes,
commentChars: options.commentChars,
openParenChars: options.openParenChars,
closeParenChars: options.closeParenChars,
cursorLine: options.cursorLine,
cursorX: options.cursorX,
forceBalance: options.forceBalance,
partialResult: options.partialResult,
prevCursorLine: options.prevCursorLine,
prevCursorX: options.prevCursorX,
returnParens: options.returnParens,
selectionStartLine: options.selectionStartLine
}
}
// ---------------------------------------------------------------------------
// Result Structure
// This represents the running result. As we scan through each character
// of a given text, we mutate this structure to update the state of our
// system.
function initialParenTrail () {
return {
lineNo: UINT_NULL, // [integer] - line number of the last parsed paren trail
startX: UINT_NULL, // [integer] - x position of first paren in this range
endX: UINT_NULL, // [integer] - x position after the last paren in this range
openers: [], // [array of stack elements] - corresponding open-paren for each close-paren in this range
clamped: {
startX: UINT_NULL, // startX before paren trail was clamped
endX: UINT_NULL, // endX before paren trail was clamped
openers: [] // openers that were cut out after paren trail was clamped
}
}
}
function getInitialResult (text, options, mode, smart) {
const result = {
mode: mode, // @doc [enum] - current processing mode (INDENT_MODE or PAREN_MODE)
smart: smart, // @doc [boolean] - smart mode attempts special user-friendly behavior
origText: text, // @doc [string] - original text
origCursorX: UINT_NULL, // @doc [integer] - original cursorX option
origCursorLine: UINT_NULL, // @doc [integer] - original cursorLine option
inputLines: // @doc [string array] - input lines that we process line-by-line, char-by-char
text.split(LINE_ENDING_REGEX),
inputLineNo: -1, // @doc [integer] - the current input line number
inputX: -1, // @doc [integer] - the current input x position of the current character (ch)
lines: [], // @doc [string array] - output lines (with corrected parens or indentation)
lineNo: -1, // @doc [integer] - output line number we are on
ch: '', // @doc [string] - character we are processing (can be changed to indicate a replacement)
x: 0, // @doc [integer] - output x position of the current character (ch)
indentX: UINT_NULL, // @doc [integer] - x position of the indentation point if present
parenStack: [], // @doc [array of {ch,x,lineNo,indentDelta}] - stack of open-parens
//
// We track where we are in the Lisp tree by keeping a stack (array) of open-parens.
// Stack elements are objects containing keys {ch, x, lineNo, indentDelta}
// whose values are the same as those described here in this result structure.
tabStops: [], // @doc [array of {ch,x,lineNo,argX}]
//
// In Indent Mode, it is useful for editors to snap a line's indentation
// to certain critical points. Thus, we have a `tabStops` array of objects containing
// keys {ch, x, lineNo, argX}, which is just the state of the `parenStack` at the cursor line.
parenTrail: // @doc [array] - the range of parens at the end of a line
initialParenTrail(),
parenTrails: [], // @doc [array of {lineNo, startX, endX}] - all non-empty parenTrails to be returned
returnParens: false, // @doc [boolean] - determines if we return `parens` described below
parens: [], // @doc [array of {lineNo, x, closer, children}] - paren tree if `returnParens` is true
cursorX: UINT_NULL, // @doc [integer] - x position of the cursor
cursorLine: UINT_NULL, // @doc [integer] - line number of the cursor
prevCursorX: UINT_NULL, // @doc [integer] - x position of the previous cursor
prevCursorLine: UINT_NULL, // @doc [integer] - line number of the previous cursor
commentChars: [';'], // @doc [array of chars] - characters that signify a comment in the code
openParenChars: ['(', '[', '{'], // @doc [array of chars] - open parentheses characters
closeParenChars: [')', ']', '}'], // @doc [array of chars] - close parentheses characters
selectionStartLine: UINT_NULL, // @doc [integer] - line number of the current selection starting point
changes: null, // @doc [object] - mapping change.key to a change object (please see `transformChange` for object structure)
isInCode: true, // @doc [boolean] - indicates if we are currently in "code space" (not string or comment)
isEscaping: false, // @doc [boolean] - indicates if the next character will be escaped (e.g. `\c`). This may be inside string, comment, or code.
isEscaped: false, // @doc [boolean] - indicates if the current character is escaped (e.g. `\c`). This may be inside string, comment, or code.
isInStr: false, // @doc [boolean] - indicates if we are currently inside a string
isInComment: false, // @doc [boolean] - indicates if we are currently inside a comment
commentX: UINT_NULL, // @doc [integer] - x position of the start of comment on current line (if any)
quoteDanger: false, // @doc [boolean] - indicates if quotes are imbalanced inside of a comment (dangerous)
trackingIndent: false, // @doc [boolean] - are we looking for the indentation point of the current line?
skipChar: false, // @doc [boolean] - should we skip the processing of the current character?
success: false, // @doc [boolean] - was the input properly formatted enough to create a valid result?
partialResult: false, // @doc [boolean] - should we return a partial result when an error occurs?
forceBalance: false, // @doc [boolean] - should indent mode aggressively enforce paren balance?
maxIndent: UINT_NULL, // @doc [integer] - maximum allowed indentation of subsequent lines in Paren Mode
indentDelta: 0, // @doc [integer] - how far indentation was shifted by Paren Mode
// (preserves relative indentation of nested expressions)
trackingArgTabStop: null, // @doc [string] - enum to track how close we are to the first-arg tabStop in a list
//
// For example a tabStop occurs at `bar` below:
//
// ` (foo bar`
// 00011112222000 <-- state after processing char (enums below)
//
// 0 null => not searching
// 1 'space' => searching for next space
// 2 'arg' => searching for arg
//
// (We create the tabStop when the change from 2->0 happens.)
//
error: { // if 'success' is false, return this error to the user
name: null, // [string] - Parinfer's unique name for this error
message: null, // [string] - error message to display
lineNo: null, // [integer] - line number of error
x: null, // [integer] - start x position of error
extra: {
name: null,
lineNo: null,
x: null
}
},
errorPosCache: {} // [object] - maps error name to a potential error position
}
// Make sure no new properties are added to the result, for type safety.
// (uncomment only when debugging, since it incurs a perf penalty)
// Object.preventExtensions(result)
// Object.preventExtensions(result.parenTrail)
// merge options if they are valid
if (options) {
if (isInteger(options.cursorX)) {
result.cursorX = options.cursorX
result.origCursorX = options.cursorX
}
if (isInteger(options.cursorLine)) {
result.cursorLine = options.cursorLine
result.origCursorLine = options.cursorLine
}
if (isInteger(options.prevCursorX)) result.prevCursorX = options.prevCursorX
if (isInteger(options.prevCursorLine)) result.prevCursorLine = options.prevCursorLine
if (isInteger(options.selectionStartLine)) result.selectionStartLine = options.selectionStartLine
if (isArray(options.changes)) result.changes = transformChanges(options.changes)
if (isBoolean(options.partialResult)) result.partialResult = options.partialResult
if (isBoolean(options.forceBalance)) result.forceBalance = options.forceBalance
if (isBoolean(options.returnParens)) result.returnParens = options.returnParens
if (isChar(options.commentChars)) result.commentChars = [options.commentChars]
if (isArrayOfChars(options.commentChars)) result.commentChars = options.commentChars
if (isChar(options.openParenChars)) result.openParenChars = [options.openParenChars]
if (isArrayOfChars(options.openParenChars)) result.openParenChars = options.openParenChars
if (isChar(options.closeParenChars)) result.closeParenChars = [options.closeParenChars]
if (isArrayOfChars(options.closeParenChars)) result.closeParenChars = options.closeParenChars
}
return result
}
// ---------------------------------------------------------------------------
// Possible Errors
// `result.error.name` is set to any of these
const ERROR_QUOTE_DANGER = 'quote-danger'
const ERROR_EOL_BACKSLASH = 'eol-backslash'
const ERROR_UNCLOSED_QUOTE = 'unclosed-quote'
const ERROR_UNCLOSED_PAREN = 'unclosed-paren'
const ERROR_UNMATCHED_CLOSE_PAREN = 'unmatched-close-paren'
const ERROR_UNMATCHED_OPEN_PAREN = 'unmatched-open-paren'
const ERROR_LEADING_CLOSE_PAREN = 'leading-close-paren'
const ERROR_UNHANDLED = 'unhandled'
const errorMessages = {}
errorMessages[ERROR_QUOTE_DANGER] = 'Quotes must balanced inside comment blocks.'
errorMessages[ERROR_EOL_BACKSLASH] = 'Line cannot end in a hanging backslash.'
errorMessages[ERROR_UNCLOSED_QUOTE] = 'String is missing a closing quote.'
errorMessages[ERROR_UNCLOSED_PAREN] = 'Unclosed open-paren.'
errorMessages[ERROR_UNMATCHED_CLOSE_PAREN] = 'Unmatched close-paren.'
errorMessages[ERROR_UNMATCHED_OPEN_PAREN] = 'Unmatched open-paren.'
errorMessages[ERROR_LEADING_CLOSE_PAREN] = 'Line cannot lead with a close-paren.'
errorMessages[ERROR_UNHANDLED] = 'Unhandled error.'
function cacheErrorPos (result, errorName) {
const e = {
lineNo: result.lineNo,
x: result.x,
inputLineNo: result.inputLineNo,
inputX: result.inputX
}
result.errorPosCache[errorName] = e
return e
}
function createError (result, name) {
const cache = result.errorPosCache[name]
let keyLineNo = 'inputLineNo'
let keyX = 'inputX'
if (result.partialResult) {
keyLineNo = 'lineNo'
keyX = 'x'
}
let lineNo = 0
let x = 0
if (cache) {
lineNo = cache[keyLineNo]
x = cache[keyX]
} else {
lineNo = result[keyLineNo]
x = result[keyX]
}
const err = {
parinferError: true,
name: name,
message: errorMessages[name],
lineNo: lineNo,
x: x
}
const opener = peek(result.parenStack, 0)
if (name === ERROR_UNMATCHED_CLOSE_PAREN) {
// extra error info for locating the open-paren that it should've matched
const cache2 = result.errorPosCache[ERROR_UNMATCHED_OPEN_PAREN]
if (cache2 || opener) {
let lineNo2 = 0
let x2 = 0
if (cache2) {
lineNo2 = cache2[keyLineNo]
x2 = cache2[keyX]
} else {
lineNo2 = opener[keyLineNo]
x2 = opener[keyX]
}
err.extra = {
name: ERROR_UNMATCHED_OPEN_PAREN,
lineNo: lineNo2,
x: x2
}
}
} else if (name === ERROR_UNCLOSED_PAREN) {
err.lineNo = opener[keyLineNo]
err.x = opener[keyX]
}
return err
}
function exitToParenMode (reason) {
return { exitToParenMode: true, reason: reason }
}
// ---------------------------------------------------------------------------
// Line Operations
function isCursorAffected (result, start, end) {
if (result.cursorX === start &&
result.cursorX === end) {
return result.cursorX === 0
}
return result.cursorX >= end
}
function shiftCursorOnEdit (result, lineNo, start, end, replaceTxt) {
const oldLength = end - start
const newLength = strLen(replaceTxt)
const dx = newLength - oldLength
if (dx !== 0 &&
result.cursorLine === lineNo &&
result.cursorX !== UINT_NULL &&
isCursorAffected(result, start, end)) {
result.cursorX = result.cursorX + dx
}
}
function replaceWithinLine (result, lineNo, startIdx, endIdx, replaceTxt) {
const line = result.lines[lineNo]
const newLine = replaceWithinString(line, startIdx, endIdx, replaceTxt)
result.lines[lineNo] = newLine
shiftCursorOnEdit(result, lineNo, startIdx, endIdx, replaceTxt)
}
function insertWithinLine (result, lineNo, idx, insert) {
replaceWithinLine(result, lineNo, idx, idx, insert)
}
function initLine (result) {
result.x = 0
result.lineNo = result.lineNo + 1
// reset line-specific state
result.indentX = UINT_NULL
result.commentX = UINT_NULL
result.indentDelta = 0
delete result.errorPosCache[ERROR_UNMATCHED_CLOSE_PAREN]
delete result.errorPosCache[ERROR_UNMATCHED_OPEN_PAREN]
delete result.errorPosCache[ERROR_LEADING_CLOSE_PAREN]
result.trackingArgTabStop = null
result.trackingIndent = !result.isInStr
}
// if the current character has changed, commit its change to the current line.
function commitChar (result, origCh) {
const ch = result.ch
const origChLength = strLen(origCh)
const chLength = strLen(ch)
if (origCh !== ch) {
replaceWithinLine(result, result.lineNo, result.x, result.x + origChLength, ch)
result.indentDelta = result.indentDelta - origChLength - chLength
}
result.x = result.x + chLength
}
// ---------------------------------------------------------------------------
// Misc Utils
function clamp (val, minN, maxN) {
if (minN !== UINT_NULL) {
val = Math.max(minN, val)
}
if (maxN !== UINT_NULL) {
val = Math.min(maxN, val)
}
return val
}
// ---------------------------------------------------------------------------
// Questions about characters
function isOpenParen (ch, openParenChars) {
return indexOf(openParenChars, ch) !== -1
}
function isCloseParen (ch, closeParenChars) {
return indexOf(closeParenChars, ch) !== -1
}
function isValidCloseParen (parenStack, ch) {
if (isStackEmpty(parenStack)) {
return false
}
return peek(parenStack, 0).ch === MATCH_PAREN[ch]
}
function isWhitespace (result) {
const ch = result.ch
return !result.isEscaped && (ch === BLANK_SPACE || ch === DOUBLE_SPACE)
}
// can this be the last code character of a list?
function isClosable (result) {
const ch = result.ch
const isCloser = (isCloseParen(ch, result.closeParenChars) && !result.isEscaped)
return result.isInCode && !isWhitespace(result) && ch !== '' && !isCloser
}
function isCommentChar (ch, commentChars) {
return indexOf(commentChars, ch) !== -1
}
// ---------------------------------------------------------------------------
// Advanced operations on characters
function checkCursorHolding (result) {
const opener = peek(result.parenStack, 0)
const parent = peek(result.parenStack, 1)
let holdMinX = 0
if (parent) {
holdMinX = parent.x + 1
}
const holdMaxX = opener.x
const holding = (
result.cursorLine === opener.lineNo &&
holdMinX <= result.cursorX && result.cursorX <= holdMaxX
)
const shouldCheckPrev = !result.changes && result.prevCursorLine !== UINT_NULL
if (shouldCheckPrev) {
const prevHolding = (
result.prevCursorLine === opener.lineNo &&
holdMinX <= result.prevCursorX && result.prevCursorX <= holdMaxX
)
if (prevHolding && !holding) {
throw exitToParenMode('releaseCursorHold')
}
}
return holding
}
function trackArgTabStop (result, state) {
if (state === 'space') {
if (result.isInCode && isWhitespace(result)) {
result.trackingArgTabStop = 'arg'
}
} else if (state === 'arg') {
if (!isWhitespace(result)) {
const opener = peek(result.parenStack, 0)
opener.argX = result.x
result.trackingArgTabStop = null
}
}
}
// ---------------------------------------------------------------------------
// Literal character events
function onOpenParen (result) {
if (result.isInCode) {
const opener = {
inputLineNo: result.inputLineNo,
inputX: result.inputX,
lineNo: result.lineNo,
x: result.x,
ch: result.ch,
indentDelta: result.indentDelta,
maxChildIndent: UINT_NULL
}
if (result.returnParens) {
opener.children = []
opener.closer = {
lineNo: UINT_NULL,
x: UINT_NULL,
ch: ''
}
const parent1 = peek(result.parenStack, 0)
let parent2 = result.parens
if (parent1) {
parent2 = parent1.children
}
stackPush(parent2, opener)
}
stackPush(result.parenStack, opener)
result.trackingArgTabStop = 'space'
}
}
function setCloser (opener, lineNo, x, ch) {
opener.closer.lineNo = lineNo
opener.closer.x = x
opener.closer.ch = ch
}
function onMatchedCloseParen (result) {
const opener = peek(result.parenStack, 0)
if (result.returnParens) {
setCloser(opener, result.lineNo, result.x, result.ch)
}
result.parenTrail.endX = result.x + 1
stackPush(result.parenTrail.openers, opener)
if (result.mode === INDENT_MODE && result.smart && checkCursorHolding(result)) {
const origStartX = result.parenTrail.startX
const origEndX = result.parenTrail.endX
const origOpeners = result.parenTrail.openers
resetParenTrail(result, result.lineNo, result.x + 1)
result.parenTrail.clamped.startX = origStartX
result.parenTrail.clamped.endX = origEndX
result.parenTrail.clamped.openers = origOpeners
}
stackPop(result.parenStack)
result.trackingArgTabStop = null
}
function onUnmatchedCloseParen (result) {
if (result.mode === PAREN_MODE) {
const trail = result.parenTrail
const inLeadingParenTrail = trail.lineNo === result.lineNo && trail.startX === result.indentX
const canRemove = result.smart && inLeadingParenTrail
if (!canRemove) {
throw createError(result, ERROR_UNMATCHED_CLOSE_PAREN)
}
} else if (result.mode === INDENT_MODE && !result.errorPosCache[ERROR_UNMATCHED_CLOSE_PAREN]) {
cacheErrorPos(result, ERROR_UNMATCHED_CLOSE_PAREN)
const opener = peek(result.parenStack, 0)
if (opener) {
const e = cacheErrorPos(result, ERROR_UNMATCHED_OPEN_PAREN)
e.inputLineNo = opener.inputLineNo
e.inputX = opener.inputX
}
}
result.ch = ''
}
function onCloseParen (result) {
if (result.isInCode) {
if (isValidCloseParen(result.parenStack, result.ch)) {
onMatchedCloseParen(result)
} else {
onUnmatchedCloseParen(result)
}
}
}
function onTab (result) {
if (result.isInCode) {
result.ch = DOUBLE_SPACE
}
}
function onCommentChar (result) {
if (result.isInCode) {
result.isInComment = true
result.commentX = result.x
result.trackingArgTabStop = null
}
}
function onNewline (result) {
result.isInComment = false
result.ch = ''
}
function onQuote (result) {
if (result.isInStr) {
result.isInStr = false
} else if (result.isInComment) {
result.quoteDanger = !result.quoteDanger
if (result.quoteDanger) {
cacheErrorPos(result, ERROR_QUOTE_DANGER)
}
} else {
result.isInStr = true
cacheErrorPos(result, ERROR_UNCLOSED_QUOTE)
}
}
function onBackslash (result) {
result.isEscaping = true
}
function afterBackslash (result) {
result.isEscaping = false
result.isEscaped = true
if (result.ch === NEWLINE) {
if (result.isInCode) {
throw createError(result, ERROR_EOL_BACKSLASH)
}
onNewline(result)
}
}
// ---------------------------------------------------------------------------
// Character dispatch
function onChar (result) {
let ch = result.ch
result.isEscaped = false
if (result.isEscaping) afterBackslash(result)
else if (isOpenParen(ch, result.openParenChars)) onOpenParen(result)
else if (isCloseParen(ch, result.closeParenChars)) onCloseParen(result)
else if (ch === DOUBLE_QUOTE) onQuote(result)
else if (isCommentChar(ch, result.commentChars)) onCommentChar(result)
else if (ch === BACKSLASH) onBackslash(result)
else if (ch === TAB) onTab(result)
else if (ch === NEWLINE) onNewline(result)
ch = result.ch
result.isInCode = !result.isInComment && !result.isInStr
if (isClosable(result)) {
resetParenTrail(result, result.lineNo, result.x + strLen(ch))
}
const state = result.trackingArgTabStop
if (state) {
trackArgTabStop(result, state)
}
}
// ---------------------------------------------------------------------------
// Cursor Functions
function isCursorLeftOf (cursorX, cursorLine, x, lineNo) {
return (
cursorLine === lineNo &&
x !== UINT_NULL &&
cursorX !== UINT_NULL &&
cursorX <= x // inclusive since (cursorX = x) implies (x-1 < cursor < x)
)
}
function isCursorRightOf (cursorX, cursorLine, x, lineNo) {
return (
cursorLine === lineNo &&
x !== UINT_NULL &&
cursorX !== UINT_NULL &&
cursorX > x
)
}