@exercism/codemirror-lang-tcl 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,848 @@
1
+ 'use strict';
2
+
3
+ var lr = require('@lezer/lr');
4
+ var language = require('@codemirror/language');
5
+ var highlight = require('@lezer/highlight');
6
+ var autocomplete = require('@codemirror/autocomplete');
7
+
8
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
9
+ const Text = 1,
10
+ Option = 2,
11
+ noSpace = 92,
12
+ lineBreak = 93,
13
+ Comment = 3,
14
+ Expansion = 4,
15
+ braceOpen = 5,
16
+ braceClose = 6,
17
+ quoteOpen = 7,
18
+ quoteClose = 8,
19
+ bracketOpen = 9,
20
+ bracketClose = 10,
21
+ parenOpen = 11,
22
+ parenClose = 12,
23
+ Comma = 13,
24
+ Question = 14,
25
+ Colon = 15,
26
+ PowOp = 16,
27
+ MulOp = 17,
28
+ AddOp = 18,
29
+ ShiftOp = 19,
30
+ CompareOp = 20,
31
+ EqualOp = 21,
32
+ StringOp = 22,
33
+ InOp = 23,
34
+ BitAndOp = 24,
35
+ BitXorOp = 25,
36
+ BitOrOp = 26,
37
+ AndOp = 27,
38
+ OrOp = 28,
39
+ NotOp = 29,
40
+ BitNotOp = 30,
41
+ Proc = 31,
42
+ If = 32,
43
+ Elseif = 33,
44
+ Else = 34,
45
+ Then = 35,
46
+ While = 36,
47
+ For = 37,
48
+ Foreach = 38,
49
+ Expr = 39,
50
+ Set$1 = 40,
51
+ Namespace = 41,
52
+ Eval = 42,
53
+ Terminator = 51,
54
+ Number = 62;
55
+
56
+ // The four questions Tcl's grammar cannot answer, answered by asking the
57
+ // parser what it has room for. `tcl.grammar` says what they are; this is how
58
+ // each is decided.
59
+ //
60
+ // One tokenizer produces every piece of a word, because the decisions are the
61
+ // same decision seen from different sides. Whether `{` opens a braced word,
62
+ // whether `]` closes a command substitution, whether `if` is a conditional and
63
+ // whether two characters belong to one word are all the question of where the
64
+ // parser stands, and a tokenizer that answered one of them alone would have to
65
+ // guess at the rest.
66
+ const tab = 9, lineFeed = 10, carriage = 13, space = 32, bang = 33, quote = 34, hash = 35, dollar = 36, percent = 37, amp = 38, parenL = 40, parenR = 41, star = 42, plus = 43, comma = 44, dash = 45, slash = 47, zero = 48, nine = 57, colon = 58, semi = 59, lt = 60, eq = 61, gt = 62, question = 63, bracketL = 91, backslash = 92, bracketR = 93, caret = 94, underscore = 95, braceL = 123, pipe = 124, braceR = 125, tilde = 126;
67
+ function isBlank(ch) {
68
+ return ch == space || ch == tab || ch == carriage;
69
+ }
70
+ function isDigit(ch) {
71
+ return ch >= zero && ch <= nine;
72
+ }
73
+ function isLetter(ch) {
74
+ return (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122);
75
+ }
76
+ // What may follow a `$` and still be a variable. Anything else leaves the `$`
77
+ // an ordinary character, which is Tcl's own rule and the reason `$` alone
78
+ // prints a dollar sign.
79
+ function isNameChar(ch) {
80
+ return (isDigit(ch) ||
81
+ (ch >= 65 && ch <= 90) ||
82
+ (ch >= 97 && ch <= 122) ||
83
+ ch == underscore ||
84
+ ch == colon);
85
+ }
86
+ // Where Tcl considers a word to begin: at the start of the script, after
87
+ // whitespace or a terminator, and inside anything that opens a script or an
88
+ // index of its own. A brace or a quote anywhere else is a letter.
89
+ function startsWord(ch) {
90
+ return (ch < 0 ||
91
+ isBlank(ch) ||
92
+ ch == lineFeed ||
93
+ ch == semi ||
94
+ ch == bracketL ||
95
+ ch == braceL ||
96
+ ch == braceR ||
97
+ ch == parenL);
98
+ }
99
+ // Where a word cannot carry on: the pieces of one have to touch, so anything
100
+ // with whitespace or a terminator behind it starts a word of its own.
101
+ function separated(ch) {
102
+ return ch < 0 || isBlank(ch) || ch == lineFeed || ch == semi;
103
+ }
104
+ // The characters a run of ordinary text stops at. Each of them either means
105
+ // something here or means something to the tokenizer's next turn, which will
106
+ // hand it back as text if it turns out to mean nothing.
107
+ function stopsText(ch) {
108
+ return (ch < 0 ||
109
+ isBlank(ch) ||
110
+ ch == lineFeed ||
111
+ ch == semi ||
112
+ ch == backslash ||
113
+ ch == dollar ||
114
+ ch == bracketL ||
115
+ ch == bracketR ||
116
+ ch == braceL ||
117
+ ch == braceR ||
118
+ ch == parenL ||
119
+ ch == parenR ||
120
+ ch == quote);
121
+ }
122
+ // A word that is a command only where a command may start, and an operator
123
+ // that is a word. Both are settled the same way: the tokenizer offers the
124
+ // keyword and the parser takes it or does not.
125
+ const keywords = {
126
+ __proto__: null,
127
+ proc: Proc,
128
+ if: If,
129
+ elseif: Elseif,
130
+ else: Else,
131
+ then: Then,
132
+ while: While,
133
+ for: For,
134
+ foreach: Foreach,
135
+ expr: Expr,
136
+ set: Set$1,
137
+ namespace: Namespace,
138
+ eval: Eval,
139
+ eq: StringOp,
140
+ ne: StringOp,
141
+ in: InOp,
142
+ ni: InOp
143
+ };
144
+ // Longest first, so `**` is a power and not two multiplications.
145
+ const operators = [
146
+ ["**", PowOp],
147
+ ["<<", ShiftOp],
148
+ [">>", ShiftOp],
149
+ ["<=", CompareOp],
150
+ [">=", CompareOp],
151
+ ["==", EqualOp],
152
+ ["!=", EqualOp],
153
+ ["&&", AndOp],
154
+ ["||", OrOp],
155
+ ["*", MulOp],
156
+ ["/", MulOp],
157
+ ["%", MulOp],
158
+ ["+", AddOp],
159
+ ["-", AddOp],
160
+ ["<", CompareOp],
161
+ [">", CompareOp],
162
+ ["&", BitAndOp],
163
+ ["^", BitXorOp],
164
+ ["|", BitOrOp],
165
+ ["!", NotOp],
166
+ ["~", BitNotOp]
167
+ ];
168
+ function startsOperator(ch) {
169
+ return (ch == star ||
170
+ ch == slash ||
171
+ ch == percent ||
172
+ ch == plus ||
173
+ ch == dash ||
174
+ ch == lt ||
175
+ ch == gt ||
176
+ ch == eq ||
177
+ ch == bang ||
178
+ ch == amp ||
179
+ ch == caret ||
180
+ ch == pipe ||
181
+ ch == tilde);
182
+ }
183
+ const words$1 = new lr.ExternalTokenizer((input, stack) => {
184
+ const next = input.next;
185
+ if (next < 0)
186
+ return;
187
+ // Whitespace, a line continuation and a backslash escape are all the
188
+ // grammar's own tokens, and it reads them the same wherever they fall.
189
+ if (isBlank(next) || next == backslash)
190
+ return;
191
+ // `#` opens a comment where a command may start, and is a letter everywhere
192
+ // else. A comment carries on over a backslash-newline, as the manual says,
193
+ // and stops at the brace that closes the word it is written in: Tcl counts
194
+ // braces before it knows what a comment is, so `{a ;# b}` is a whole word
195
+ // and the comment inside it is three characters long.
196
+ if (next == hash && stack.canShift(Comment)) {
197
+ const braced = stack.canShift(braceClose);
198
+ let depth = 0;
199
+ let length = 0;
200
+ for (;;) {
201
+ const ch = input.peek(length);
202
+ if (ch < 0 || ch == lineFeed)
203
+ break;
204
+ if (ch == backslash && input.peek(length + 1) == lineFeed)
205
+ length += 2;
206
+ else if (ch == backslash && input.peek(length + 1) == carriage)
207
+ length += input.peek(length + 2) == lineFeed ? 3 : 2;
208
+ // A comment that ends on the backslash has nothing left to escape, and a
209
+ // token may not end past the file.
210
+ else if (ch == backslash)
211
+ length += input.peek(length + 1) < 0 ? 1 : 2;
212
+ else if (braced && ch == braceL)
213
+ (depth++, length++);
214
+ else if (braced && ch == braceR && depth-- == 0)
215
+ break;
216
+ else
217
+ length++;
218
+ }
219
+ input.acceptToken(Comment, length);
220
+ return;
221
+ }
222
+ // `{*}` in front of a word spreads it into several. It is the one brace that
223
+ // opens nothing.
224
+ if (next == braceL &&
225
+ input.peek(1) == star &&
226
+ input.peek(2) == braceR &&
227
+ startsWord(input.peek(-1)) &&
228
+ stack.canShift(Expansion)) {
229
+ input.acceptToken(Expansion, 3);
230
+ return;
231
+ }
232
+ // An index touches the variable it belongs to, so it is offered before the
233
+ // word is allowed to carry on. Everything that closes something is offered
234
+ // there too: a word that could still grow has to be ended by its closer
235
+ // rather than swallow it.
236
+ if (next == parenL && stack.canShift(parenOpen))
237
+ return input.acceptToken(parenOpen, 1);
238
+ if (next == parenR && stack.canShift(parenClose))
239
+ return input.acceptToken(parenClose, 1);
240
+ if (next == bracketR && stack.canShift(bracketClose))
241
+ return input.acceptToken(bracketClose, 1);
242
+ if (next == braceR && stack.canShift(braceClose))
243
+ return input.acceptToken(braceClose, 1);
244
+ if (next == quote && stack.canShift(quoteClose))
245
+ return input.acceptToken(quoteClose, 1);
246
+ // A terminator ends a command, and inside a quoted word it is a character
247
+ // like any other. Inside an expression it is neither: `expr` reads a line
248
+ // break as the space it would be anywhere else, so a condition may be
249
+ // written over as many lines as it needs, and the grammar skips it.
250
+ if (next == semi || next == lineFeed) {
251
+ if (stack.canShift(Terminator))
252
+ return;
253
+ if (stack.canShift(lineBreak))
254
+ return input.acceptToken(lineBreak, 1);
255
+ }
256
+ // The word under way carries on, because nothing stands between it and what
257
+ // comes next.
258
+ if (stack.canShift(noSpace) && !separated(input.peek(-1))) {
259
+ input.acceptToken(noSpace, 0);
260
+ return;
261
+ }
262
+ // What opens a word only opens one at the front of a word. An expression has
263
+ // no words in it, so `{` and `"` open there wherever they are written:
264
+ // `$x=={windows}` is a comparison against a one-word list.
265
+ const opens = startsWord(input.peek(-1)) || !stack.canShift(noSpace);
266
+ if (next == braceL && opens && stack.canShift(braceOpen)) {
267
+ return input.acceptToken(braceOpen, 1);
268
+ }
269
+ if (next == quote && opens && stack.canShift(quoteOpen) && closes(input, quote)) {
270
+ return input.acceptToken(quoteOpen, 1);
271
+ }
272
+ if (next == bracketL && stack.canShift(bracketOpen) && closes(input, bracketL)) {
273
+ return input.acceptToken(bracketOpen, 1);
274
+ }
275
+ // A variable, and a number in an expression, are the grammar's tokens.
276
+ if (next == dollar && (isNameChar(input.peek(1)) || input.peek(1) == braceL))
277
+ return;
278
+ if (isDigit(next) && stack.canShift(Number))
279
+ return;
280
+ if (next == comma && stack.canShift(Comma))
281
+ return input.acceptToken(Comma, 1);
282
+ if (next == question && stack.canShift(Question))
283
+ return input.acceptToken(Question, 1);
284
+ if (next == colon && stack.canShift(Colon))
285
+ return input.acceptToken(Colon, 1);
286
+ // A Tk binding is not a script until Tk has put a value in place of every
287
+ // `%x` in it, and the ones it leaves behind are read here: `%%` is a per
288
+ // cent sign and `%#` a serial number, and neither is the modulus they are
289
+ // spelled like. Nothing may follow a modulus that cannot begin an operand.
290
+ if (next != percent || (input.peek(1) != percent && input.peek(1) != hash)) {
291
+ if (startsOperator(next)) {
292
+ for (const [text, term] of operators) {
293
+ if (!matches(input, text))
294
+ continue;
295
+ if (stack.canShift(term))
296
+ return input.acceptToken(term, text.length);
297
+ break;
298
+ }
299
+ }
300
+ }
301
+ // Ordinary text. The first character is taken whatever it is, because
302
+ // everything it could have been has been offered and turned down.
303
+ let length = 1;
304
+ while (!stopsText(input.peek(length)))
305
+ length++;
306
+ // A word that stands alone may be a command, or one of the operators Tcl
307
+ // spells with letters.
308
+ if (endsWord(input.peek(length))) {
309
+ const term = keywords[input.read(input.pos, input.pos + length)];
310
+ if (term != null && stack.canShift(term))
311
+ return input.acceptToken(term, length);
312
+ }
313
+ // `-nocomplain`, `-exact`, `-command`: a switch is how nearly every command
314
+ // in Tcl is told what to do, and it is not the value that follows it. A
315
+ // letter has to come after the dash, so `-1` stays the number it is.
316
+ if (next == dash &&
317
+ isLetter(input.peek(1)) &&
318
+ separated(input.peek(-1)) &&
319
+ endsWord(input.peek(length)) &&
320
+ stack.canShift(Option)) {
321
+ return input.acceptToken(Option, length);
322
+ }
323
+ input.acceptToken(Text, length);
324
+ // Contextual, because most of what is decided above is decided by where the
325
+ // parser stands rather than by what the characters are, and `noSpace` has no
326
+ // width: the parser asks again from the same position in a new state, and a
327
+ // cached answer would be the old state's.
328
+ }, { contextual: true });
329
+ // Whether the character that opens something is ever answered, before the
330
+ // brace that closes the word runs out.
331
+ //
332
+ // A braced word holds no substitutions and no strings: Tcl reads `{a "b}` as
333
+ // five characters and complains about nothing. Read as the script it usually
334
+ // is, that quote opens a string with no end, and one line of somebody's test
335
+ // data would take the rest of the file with it. Looking for the answer first
336
+ // costs a scan as long as the word and settles it the way Tcl's own two
337
+ // passes do.
338
+ function closes(input, opener) {
339
+ const nests = opener == bracketL;
340
+ let brackets = 0;
341
+ let braces = 0;
342
+ for (let i = 1; i < 4096; i++) {
343
+ const ch = input.peek(i);
344
+ if (ch < 0)
345
+ return false;
346
+ if (ch == backslash) {
347
+ i++;
348
+ continue;
349
+ }
350
+ // A command substitution holds commands, which hold substitutions of their
351
+ // own. A quoted word holds nothing that can hold a quote, so the first one
352
+ // is the end of it whatever it stands inside.
353
+ if (nests) {
354
+ if (ch == bracketL)
355
+ brackets++;
356
+ else if (ch == bracketR && brackets-- == 0)
357
+ return true;
358
+ }
359
+ else if (ch == quote) {
360
+ return true;
361
+ }
362
+ if (ch == braceL)
363
+ braces++;
364
+ else if (ch == braceR && braces-- == 0)
365
+ return false;
366
+ }
367
+ return true;
368
+ }
369
+ function matches(input, text) {
370
+ for (let i = 0; i < text.length; i++)
371
+ if (input.peek(i) != text.charCodeAt(i))
372
+ return false;
373
+ return true;
374
+ }
375
+ // A keyword is a whole word or it is not a keyword. `iffy` is a command named
376
+ // iffy, and `elsewhere` is not an `else`.
377
+ function endsWord(ch) {
378
+ return separated(ch) || ch == bracketR || ch == braceR;
379
+ }
380
+
381
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
382
+ const parser = lr.LRParser.deserialize({
383
+ version: 14,
384
+ states: "6tO!gQROOO!nQRO'#D_O!uQRO'#D[OOQP'#D['#D[OOQP'#Eb'#EbO%jQRO'#DfO%qQRO'#DhO%xQRO'#DYO&aQRO'#DiO&aQRO'#DuO&kQRO'#DvO&uQRO'#DwO&aQRO'#DyO'PQRO'#DzO'gQRO'#D|O(QQRO'#EPO)OQRO'#EOOOQP'#Ea'#EaOOQP'#EQ'#EQO)fQRO'#E`O)tQRO'#E`QOQROOO*RQRO,59yO*lQRO'#D^OOQP,59v,59vOOQP'#Ee'#EeOOQP'#EU'#EUO*sQRO,5:QOOQP,5:Q,5:QO*zQRO,5:S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]$^$e$f$g$lQsWQtXQ!uvR#n!pWrWXv!pTz[|w!hq!i!l#Y#]#^#_#`#a#b#c#d#e#f#g#h#i$a$dR#Z!hw!mq!i!l#Y#]#^#_#`#a#b#c#d#e#f#g#h#i$a$dRyZR!P]R#R!SX`OPUdUdOPUR!YdQ!^gR#V!^Q!U_Q!cnQ!fpQ!}}[#T!U!c!f!}#s#wQ#s!vR#w#QQ!ywR#t!yQkTR!`kQ!R^Q!V`Q!osQ!ttQ#O!Pn#P!R!V!o!t#O#X#p#q#v#x$[$]$e$f$lQ#X!eQ#p!rQ#q!sQ#v!{Q#x#RQ$[#mQ$]#nQ$e$ZQ$f$^R$l$gQ$b#zR$i$bQ!qsS#l!o!sU#o!q#l$_R$_#qQ|[R!||QeOQfPRmUUcOPUR!XdW_OPUdQnV!vpWXYZ[^`ostvy|!P!R!V!e!o!p!r!s!t!u!{#O#R#X#m#n#p#q#r#v#x$Z$[$]$^$e$f$g$lQ}]S!vw!yQ#Q!SR#S!TT!]g!^T!xw!yTjTkQvY!^!Q^`st!P!R!V!e!o!r!s!t!{#O#R#X#m#n#p#q#v#x$Z$[$]$^$e$f$g$lQ!{yQ#r!uR$`#rQ!kqQ#[!iQ#k!lQ#z#YQ#|#]Q#}#^Q$O#_Q$P#`Q$Q#aQ$R#bQ$S#cQ$T#dQ$U#eQ$V#fQ$W#gQ$X#hQ$Y#iQ$h$aR$k$dT{[|",
387
+ nodeNames: "⚠ Text Option Comment Expansion { } \" \" [ ] ( ) , ? : ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp ExprOp proc if elseif else then while for foreach expr set namespace eval Script ProcCommand ProcName VariableSubstitution VariableName ArrayIndex CommandSubstitution Escape Terminator BracedVariableName Params BracedList ListWord QuotedWord Word BracedWord IfCommand Condition BracedExpr Number FunctionCall FunctionName ArgumentList ParenthesizedExpression ExprWord BinaryExpression UnaryExpression ConditionalExpression WhileCommand ForCommand ForeachCommand VarList ExprCommand SetCommand VariableDefinition NamespaceCommand NamespaceName Command CommandName",
388
+ maxTerm: 105,
389
+ skippedNodes: [0],
390
+ repeatNodeCount: 9,
391
+ tokenData: "(t~RYXYqYZ!P]^qpqqtu!U!O!P#t!Q!R$t!R![%i!]!^!P#O#P'l~vR#R~XYq]^qpqq~!UO!T~~!XU!Q![!k![!]#P!c!}!k#R#S!k#T#o!k#o#p#V~!pT!P~!Q![!k![!]#P!c!}!k#R#S!k#T#o!k~#SP![!]!k~#YTO#q#V#q#r#i#r;'S#V;'S;=`#n<%lO#V~#nO!U~~#qP;=`<%l#V~#wP!Q![#z~$PR!`~!Q![#z!g!h$Y#X#Y$Y~$]R{|$f}!O$f!Q![$l~$iP!Q![$l~$qP!`~!Q![$l~$yY!`~!O!P#z!Q![%i!d!e%z!g!h$Y!q!r&f!z!{&z#U#V%z#X#Y$Y#c#d&f#l#m&z~%nS!`~!O!P#z!Q![%i!g!h$Y#X#Y$Y~%}R!Q!R&W!R!S&W#R#S&W~&]R!`~!Q!R&W!R!S&W#R#S&W~&iQ!Q!Y&o#R#S&o~&tQ!`~!Q!Y&o#R#S&o~&}S!Q!['Z!c!i'Z#R#S'Z#T#Z'Z~'`S!`~!Q!['Z!c!i'Z#R#S'Z#T#Z'Z~'oVOY(UYZ(ZZ](U]^(f^;'S(U;'S;=`(n<%lO(U~(ZO!S~~(`Q#R~XY(Zpq(Z~(kP!S~YZ(Z~(qP;=`<%l(U",
392
+ tokenizers: [words$1, 0],
393
+ topRules: {"Script":[0,43]},
394
+ tokenPrec: 2230
395
+ });
396
+
397
+ /**
398
+ Snippets for the constructs written most often in Tcl.
399
+ */
400
+ const snippets = [
401
+ autocomplete.snippetCompletion("proc ${name} {${args}} {\n\t${}\n}", { label: "proc", detail: "definition", type: "keyword" }),
402
+ autocomplete.snippetCompletion("if {${condition}} {\n\t${}\n}", { label: "if", detail: "block", type: "keyword" }),
403
+ autocomplete.snippetCompletion("if {${condition}} {\n\t${}\n} else {\n\t${}\n}", { label: "if", detail: "/ else block", type: "keyword" }),
404
+ autocomplete.snippetCompletion("if {${condition}} {\n\t${}\n} elseif {${condition}} {\n\t${}\n} else {\n\t${}\n}", { label: "if", detail: "/ elseif / else block", type: "keyword" }),
405
+ autocomplete.snippetCompletion("for {set ${i} 0} {$${i} < ${n}} {incr ${i}} {\n\t${}\n}", { label: "for", detail: "loop", type: "keyword" }),
406
+ autocomplete.snippetCompletion("foreach ${item} ${list} {\n\t${}\n}", { label: "foreach", detail: "loop", type: "keyword" }),
407
+ autocomplete.snippetCompletion("while {${condition}} {\n\t${}\n}", { label: "while", detail: "loop", type: "keyword" }),
408
+ autocomplete.snippetCompletion("switch -- ${value} {\n\t${pattern} {\n\t\t${}\n\t}\n\tdefault {\n\t\t${}\n\t}\n}", { label: "switch", detail: "block", type: "keyword" }),
409
+ autocomplete.snippetCompletion("namespace eval ${name} {\n\t${}\n}", { label: "namespace", detail: "eval block", type: "keyword" }),
410
+ autocomplete.snippetCompletion("dict for {${key} ${value}} ${dict} {\n\t${}\n}", { label: "dict", detail: "for loop", type: "keyword" }),
411
+ autocomplete.snippetCompletion("try {\n\t${}\n} on error {${message}} {\n\t${}\n}", { label: "try", detail: "/ on error", type: "keyword" })
412
+ ];
413
+ // The branches of an `if`, offered after its first body.
414
+ const ifBranches = [
415
+ autocomplete.snippetCompletion("elseif {${condition}} {\n\t${}\n}", { label: "elseif", detail: "block", type: "keyword" }),
416
+ autocomplete.snippetCompletion("else {\n\t${}\n}", { label: "else", detail: "block", type: "keyword" }),
417
+ ...["elseif", "else", "then"].map(label => ({ label, type: "keyword" }))
418
+ ];
419
+ /**
420
+ The commands `tclsh` starts with. Tk's are not here: a script that has them
421
+ has loaded a package to get them, and a script that has not would be
422
+ offered a command it cannot run.
423
+ */
424
+ const commands = [
425
+ "after", "append", "apply", "array", "binary", "break", "catch", "cd",
426
+ "chan", "clock", "close", "concat", "continue", "coroutine", "dict", "encoding",
427
+ "eof", "error", "eval", "exec", "exit", "expr", "fblocked", "fconfigure",
428
+ "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets",
429
+ "glob", "global", "history", "if", "incr", "info", "interp", "join",
430
+ "lappend", "lassign", "lindex", "linsert", "list", "llength", "lmap",
431
+ "load", "lpop", "lrange", "lremove", "lrepeat", "lreplace", "lreverse",
432
+ "lsearch", "lseq", "lset", "lsort", "namespace", "open", "package", "pid",
433
+ "proc", "puts", "pwd", "read", "regexp", "regsub", "rename", "return",
434
+ "scan", "seek", "set", "socket", "source", "split", "string", "subst",
435
+ "switch", "tailcall", "tell", "throw", "time", "timerate", "trace", "try", "unload",
436
+ "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield",
437
+ "yieldto", "zlib", "oo::class", "oo::define", "oo::object"
438
+ ];
439
+ const commandOptions = [
440
+ ...snippets,
441
+ ...commands.map(label => ({ label, type: "function" }))
442
+ ];
443
+ const words = (list) => list.split(" ");
444
+ // The first word after these commands picks what the command does.
445
+ const subcommands = {
446
+ string: words("cat compare equal first index insert is last length map match range repeat replace reverse tolower totitle toupper trim trimleft trimright wordend wordstart"),
447
+ dict: words("append create exists filter for get getdef getwithdefault incr info keys lappend map merge remove replace set size unset update values with"),
448
+ array: words("anymore default donesearch exists for get names nextelement set size startsearch statistics unset"),
449
+ info: words("args body class cmdcount commands complete coroutine default errorstack exists frame functions globals hostname level library loaded locals nameofexecutable object patchlevel procs script sharedlibextension tclversion vars"),
450
+ file: words("atime attributes channels copy delete dirname executable exists extension isdirectory isfile join link lstat mkdir mtime nativename normalize owned pathtype readable readlink rename rootname separator size split stat system tail tempdir tempfile type volumes writable"),
451
+ namespace: words("children code current delete ensemble eval exists export forget import inscope origin parent path qualifiers tail unknown upvar which"),
452
+ clock: words("add clicks format microseconds milliseconds scan seconds"),
453
+ chan: words("blocked close configure copy create eof event flush gets names pending pipe pop postevent push puts read seek tell truncate"),
454
+ binary: words("decode encode format scan")
455
+ };
456
+ // The classes `string is` can test for.
457
+ const stringClasses = words("alnum alpha ascii boolean control dict digit double entier false graph integer list lower print punct space true upper wideinteger wordchar xdigit");
458
+ // The switches each command takes, offered once a `-` has been typed.
459
+ const switches = {
460
+ lsort: words("-ascii -dictionary -integer -real -command -increasing -decreasing -indices -index -stride -nocase -unique"),
461
+ lsearch: words("-exact -glob -regexp -sorted -all -inline -not -start -index -subindices -nocase -ascii -dictionary -integer -real -increasing -decreasing -bisect"),
462
+ regexp: words("-nocase -all -inline -indices -line -linestop -lineanchor -expanded -start -about --"),
463
+ regsub: words("-all -nocase -expanded -line -linestop -lineanchor -start -command --"),
464
+ switch: words("-exact -glob -regexp -nocase -matchvar -indexvar --"),
465
+ string: words("-nocase -length -strict -failindex"),
466
+ puts: words("-nonewline"),
467
+ unset: words("-nocomplain --"),
468
+ return: words("-code -level -errorcode -errorinfo -options"),
469
+ glob: words("-directory -join -nocomplain -path -tails -types --"),
470
+ lseq: words("-to -count -by"),
471
+ join: [],
472
+ error: []
473
+ };
474
+ // The functions and the word operators of `expr`.
475
+ const exprOptions = [
476
+ ...words("abs acos asin atan atan2 bool ceil cos cosh double entier exp floor fmod hypot int isinf isnan isqrt log log10 max min pow rand round sin sinh sqrt srand tan tanh wide")
477
+ .map(label => ({ label, type: "function" })),
478
+ ...words("eq ne in ni true false").map(label => ({ label, type: "keyword" }))
479
+ ];
480
+ const commandNodes = new Set([
481
+ "Command", "ProcCommand", "IfCommand", "WhileCommand", "ForCommand", "ForeachCommand",
482
+ "ExprCommand", "SetCommand", "NamespaceCommand"
483
+ ]);
484
+ // Where a name is being declared, so there is nothing to offer.
485
+ const declaring = new Set(["ProcName", "Params", "NamespaceName", "VarList"]);
486
+ function text(doc, node) {
487
+ return doc.sliceString(node.from, node.to);
488
+ }
489
+ // The body of `proc` and of `namespace eval` is the last word of the command.
490
+ function isProcBody(node) {
491
+ var _a;
492
+ return node.name == "BracedWord" && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) == "ProcCommand" && !node.nextSibling;
493
+ }
494
+ function isNamespaceBody(node) {
495
+ var _a;
496
+ return node.name == "BracedWord" && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) == "NamespaceCommand" &&
497
+ !!node.parent.getChild("eval") && !node.nextSibling;
498
+ }
499
+ // The names in a word that names variables: one name, or a braced list of
500
+ // them. An array element counts as its array, and a name built from a
501
+ // substitution can't be known.
502
+ function namesIn(doc, node, before = Infinity) {
503
+ if (!node || node.to > before)
504
+ return [];
505
+ const inner = node.firstChild;
506
+ if ((node.name == "VarList" || node.name == "VariableDefinition") && !(inner === null || inner === void 0 ? void 0 : inner.nextSibling) &&
507
+ ((inner === null || inner === void 0 ? void 0 : inner.name) == "BracedList" || (inner === null || inner === void 0 ? void 0 : inner.name) == "QuotedWord"))
508
+ node = inner;
509
+ let value = text(doc, node);
510
+ if (node.name == "BracedWord" || node.name == "BracedList" || node.name == "QuotedWord")
511
+ value = value.slice(1, -1);
512
+ return value.split(/\s+/)
513
+ .map(name => name.replace(/\(.*$/, ""))
514
+ .filter(name => name && !/[$[\]{}"\\]/.test(name));
515
+ }
516
+ // The names declared by one command: by `set`, `foreach` and the commands
517
+ // that write to a variable named in one of their words. A name counts once
518
+ // the word that holds it is written, so the body of a `foreach` sees its
519
+ // loop variables.
520
+ function declared(doc, command, before) {
521
+ if (command.name == "SetCommand")
522
+ return namesIn(doc, command.getChild("VariableDefinition"), before);
523
+ if (command.name == "ForeachCommand")
524
+ return namesIn(doc, command.getChild("VarList"), before);
525
+ if (command.name != "Command")
526
+ return [];
527
+ const name = command.firstChild;
528
+ if ((name === null || name === void 0 ? void 0 : name.name) != "CommandName")
529
+ return [];
530
+ const args = [];
531
+ for (let ch = name.nextSibling; ch; ch = ch.nextSibling)
532
+ args.push(ch);
533
+ const at = (...indices) => indices.flatMap(i => namesIn(doc, args[i], before));
534
+ switch (text(doc, name)) {
535
+ case "global": return at(...args.keys());
536
+ case "variable": return at(...[...args.keys()].filter(i => i % 2 == 0));
537
+ case "upvar": {
538
+ // A level is optional, and the names come in pairs after it: the
539
+ // caller's name, then the local one.
540
+ const start = args.length % 2;
541
+ return at(...[...args.keys()].filter(i => i > start && (i - start) % 2 == 1));
542
+ }
543
+ case "lassign": return at(...[...args.keys()].slice(1));
544
+ case "scan": return at(...[...args.keys()].slice(2));
545
+ case "incr":
546
+ case "append":
547
+ case "lappend":
548
+ case "lmap": return at(0);
549
+ case "gets":
550
+ case "catch": return at(1);
551
+ case "array": return args[0] && text(doc, args[0]) == "set" ? at(1) : [];
552
+ case "dict": {
553
+ const sub = args[0] ? text(doc, args[0]) : "";
554
+ return /^(set|unset|lappend|append|incr|for|map|update|with)$/.test(sub) ? at(1) : [];
555
+ }
556
+ }
557
+ return [];
558
+ }
559
+ // The parameter names of a `proc`, from `{a {b 1} args}` or a bare `args`.
560
+ function parameters(doc, proc) {
561
+ var _a;
562
+ const params = (_a = proc.getChild("Params")) === null || _a === void 0 ? void 0 : _a.firstChild;
563
+ if (!params)
564
+ return [];
565
+ if (params.name != "BracedList")
566
+ return namesIn(doc, params);
567
+ const out = [];
568
+ for (let ch = params.firstChild; ch; ch = ch.nextSibling) {
569
+ if (ch.name == "ListWord")
570
+ out.push(text(doc, ch));
571
+ else if (ch.name == "BracedList") {
572
+ const first = ch.getChild("ListWord");
573
+ if (first)
574
+ out.push(text(doc, first));
575
+ }
576
+ }
577
+ return out;
578
+ }
579
+ // The variables a scope declares before `before`. A nested `proc` or
580
+ // `namespace eval` body keeps its variables to itself.
581
+ function scopeVariables(doc, scope, before, out) {
582
+ const walk = (node) => {
583
+ for (let ch = node.firstChild; ch && ch.from < before; ch = ch.nextSibling) {
584
+ if (ch.name == "Comment" || isProcBody(ch) || isNamespaceBody(ch))
585
+ continue;
586
+ if (commandNodes.has(ch.name))
587
+ for (const name of declared(doc, ch, before))
588
+ out.add(name);
589
+ walk(ch);
590
+ }
591
+ };
592
+ walk(scope);
593
+ }
594
+ // The variables in scope at a node. A `proc` body sees its parameters and its
595
+ // own variables, and nothing from outside it unless it says `global` or
596
+ // `upvar`. A `namespace eval` body sees the variables around it as well.
597
+ function variablesAt(doc, node, before) {
598
+ const out = new Set();
599
+ for (let p = node; p; p = p.parent) {
600
+ if (isProcBody(p)) {
601
+ for (const name of parameters(doc, p.parent))
602
+ out.add(name);
603
+ scopeVariables(doc, p, before, out);
604
+ break;
605
+ }
606
+ if (isNamespaceBody(p) || p.name == "Script")
607
+ scopeVariables(doc, p, before, out);
608
+ }
609
+ return [...out];
610
+ }
611
+ // The namespaces a node sits in, outermost first.
612
+ function namespacesAround(doc, node) {
613
+ const out = [];
614
+ for (let p = node.parent; p; p = p.parent) {
615
+ if (isNamespaceBody(p)) {
616
+ const name = p.parent.getChild("NamespaceName");
617
+ if (name)
618
+ out.unshift(text(doc, name).replace(/^::/, ""));
619
+ }
620
+ }
621
+ return out;
622
+ }
623
+ // Every proc and namespace in the file. A proc can be called from anywhere
624
+ // once it is defined, and Tcl defines them all before a script's last line
625
+ // runs. A proc inside `namespace eval` is offered by its own name and by its
626
+ // qualified name.
627
+ function fileNames(doc, tree) {
628
+ const procs = new Set();
629
+ const namespaces = new Set();
630
+ tree.iterate({
631
+ enter(ref) {
632
+ if (ref.name == "ProcCommand") {
633
+ const nameNode = ref.node.getChild("ProcName");
634
+ if (!nameNode)
635
+ return;
636
+ const name = text(doc, nameNode);
637
+ procs.add(name);
638
+ const around = namespacesAround(doc, ref.node);
639
+ if (around.length && !name.startsWith("::"))
640
+ procs.add([...around, name].join("::"));
641
+ }
642
+ else if (ref.name == "NamespaceName") {
643
+ namespaces.add(text(doc, ref.node).replace(/^::/, ""));
644
+ }
645
+ }
646
+ });
647
+ return [
648
+ ...[...procs].filter(name => !/[$[]/.test(name)).map(label => ({ label, type: "function", boost: 1 })),
649
+ ...[...namespaces].filter(name => !/[$[]/.test(name)).map(label => ({ label, type: "namespace" }))
650
+ ];
651
+ }
652
+ const variableOptions = (names) => names.map(label => ({ label, type: "variable", boost: 2 }));
653
+ function dedupe(options) {
654
+ const seen = new Set();
655
+ return options.filter(o => {
656
+ var _a;
657
+ const key = o.label + "\u0000" + ((_a = o.detail) !== null && _a !== void 0 ? _a : "");
658
+ if (seen.has(key))
659
+ return false;
660
+ seen.add(key);
661
+ return true;
662
+ });
663
+ }
664
+ // What the cursor stands in, read from the nodes above it.
665
+ function contextOf(node) {
666
+ for (let p = node; p; p = p.parent) {
667
+ if (p.name == "Comment")
668
+ return "comment";
669
+ if (p.name == "QuotedWord")
670
+ return "string";
671
+ if (p.name == "BracedExpr" || p.name == "ExprWord" || p.name == "FunctionName")
672
+ return "expr";
673
+ if (declaring.has(p.name))
674
+ return "declaring";
675
+ if (p.name == "VariableDefinition")
676
+ return "definition";
677
+ if (p.name == "CommandSubstitution" || p.name == "BracedWord" || commandNodes.has(p.name))
678
+ return "code";
679
+ }
680
+ return "code";
681
+ }
682
+ // The command a word belongs to, and which of its words it is: 0 for the
683
+ // command's name.
684
+ function wordOf(node) {
685
+ for (let p = node; p === null || p === void 0 ? void 0 : p.parent; p = p.parent) {
686
+ if (commandNodes.has(p.parent.name)) {
687
+ let index = 0;
688
+ for (let ch = p.prevSibling; ch; ch = ch.prevSibling)
689
+ index++;
690
+ return { command: p.parent, index };
691
+ }
692
+ if (p.name == "CommandSubstitution" || p.name == "BracedWord")
693
+ return null;
694
+ }
695
+ return null;
696
+ }
697
+ /**
698
+ Completion for Tcl: the built-in commands and their subcommands and
699
+ switches, snippets, the functions of `expr`, and the procs, namespaces and
700
+ variables declared in the file. A variable is offered in the scope that
701
+ declares it, once it has been declared, and after a `$`. Nothing is
702
+ offered in comments, and inside a quoted string only after a `$`.
703
+ */
704
+ const tclCompletion = (context) => {
705
+ const { state, pos } = context;
706
+ const doc = state.doc;
707
+ const tree = language.syntaxTree(state);
708
+ const here = tree.resolveInner(pos, -1);
709
+ const where = contextOf(here);
710
+ if (where == "comment")
711
+ return null;
712
+ const dollar = context.matchBefore(/\$[\w:]*$/);
713
+ if (dollar) {
714
+ return { from: dollar.from + 1, options: variableOptions(variablesAt(doc, here, dollar.from)), validFor: /^[\w:]*$/ };
715
+ }
716
+ if (where == "string" || where == "declaring")
717
+ return null;
718
+ const word = context.matchBefore(/[\w:\-]*$/);
719
+ if (word.from == word.to && !context.explicit)
720
+ return null;
721
+ const result = (options) => ({ from: word.from, options: dedupe(options), validFor: /^[\w:\-]*$/ });
722
+ if (where == "expr")
723
+ return result(exprOptions);
724
+ const variables = variableOptions(variablesAt(doc, here, word.from));
725
+ if (where == "definition")
726
+ return result(variables);
727
+ // Find the word being typed. With nothing typed yet, it is the word after
728
+ // the last one on the line, or the name of a new command.
729
+ let found;
730
+ if (word.from < word.to) {
731
+ found = wordOf(tree.resolveInner(word.from, 1));
732
+ }
733
+ else {
734
+ const line = doc.lineAt(pos);
735
+ const before = doc.sliceString(line.from, pos).replace(/[ \t]+$/, "");
736
+ if (!before || /[;[{]$/.test(before))
737
+ found = null;
738
+ else {
739
+ const last = wordOf(tree.resolveInner(line.from + before.length, -1));
740
+ found = last && { command: last.command, index: countChildren(last.command) };
741
+ }
742
+ }
743
+ const names = fileNames(doc, tree);
744
+ if (!found || found.index == 0)
745
+ return result([...commandOptions, ...names, ...variables]);
746
+ const { command, index } = found;
747
+ const commandName = command.firstChild ? text(doc, command.firstChild) : "";
748
+ const typed = doc.sliceString(word.from, word.to);
749
+ if (command.name == "IfCommand")
750
+ return result([...ifBranches, ...names, ...variables]);
751
+ if (typed.startsWith("-")) {
752
+ const list = switches[commandName];
753
+ return list ? result(list.map(label => ({ label, type: "property" }))) : null;
754
+ }
755
+ if (index == 1 && subcommands[commandName]) {
756
+ return result(subcommands[commandName].map(label => ({ label, type: "method" })));
757
+ }
758
+ const argument = (i) => {
759
+ let ch = command.firstChild;
760
+ for (let n = 0; ch && n < i; n++)
761
+ ch = ch.nextSibling;
762
+ return ch ? text(doc, ch) : "";
763
+ };
764
+ if (commandName == "string" && index == 2 && argument(1) == "is") {
765
+ return result(stringClasses.map(label => ({ label, type: "constant" })));
766
+ }
767
+ return result([...variables, ...names]);
768
+ };
769
+ function countChildren(node) {
770
+ let n = 0;
771
+ for (let ch = node.firstChild; ch; ch = ch.nextSibling)
772
+ n++;
773
+ return n;
774
+ }
775
+
776
+ const braced = "BracedWord BracedList BracedExpr";
777
+ const tclLanguage = language.LRLanguage.define({
778
+ name: "tcl",
779
+ parser: parser.configure({
780
+ props: [
781
+ language.indentNodeProp.add({
782
+ [braced]: language.delimitedIndent({ closing: "}" }),
783
+ CommandSubstitution: language.delimitedIndent({ closing: "]" }),
784
+ ArrayIndex: language.delimitedIndent({ closing: ")" }),
785
+ // A command broken over several lines is continued with a backslash,
786
+ // and what follows stands one step in from the command that owns it.
787
+ "Command ProcCommand IfCommand WhileCommand ForCommand ForeachCommand ExprCommand SetCommand NamespaceCommand": language.continuedIndent(),
788
+ Comment: () => null
789
+ }),
790
+ language.foldNodeProp.add({
791
+ [braced]: language.foldInside,
792
+ CommandSubstitution: language.foldInside
793
+ }),
794
+ highlight.styleTags({
795
+ "proc": highlight.tags.definitionKeyword,
796
+ "if elseif else then while for foreach": highlight.tags.controlKeyword,
797
+ "expr": highlight.tags.operatorKeyword,
798
+ ExprOp: highlight.tags.operator,
799
+ "? :": highlight.tags.controlOperator,
800
+ Number: highlight.tags.number,
801
+ // A quoted word is a string from one quote to the other, and the
802
+ // substitutions inside it keep their own colours on top of that.
803
+ "QuotedWord/...": highlight.tags.string,
804
+ Escape: highlight.tags.escape,
805
+ Comment: highlight.tags.lineComment,
806
+ // A variable is written `$name`, and the `$` is part of the name
807
+ // rather than an operator on it.
808
+ VariableName: highlight.tags.variableName,
809
+ BracedVariableName: highlight.tags.variableName,
810
+ // The name a `proc` is being given, against the names of the commands
811
+ // it is made of.
812
+ "ProcCommand/ProcName/Text": highlight.tags.function(highlight.tags.definition(highlight.tags.variableName)),
813
+ "CommandName/Text": highlight.tags.function(highlight.tags.variableName),
814
+ // `set` and `namespace` are commands like any other, and are only
815
+ // written out in the grammar so the names they declare have nodes.
816
+ "set namespace": highlight.tags.function(highlight.tags.variableName),
817
+ "VariableDefinition/Text": highlight.tags.definition(highlight.tags.variableName),
818
+ "NamespaceName/Text": highlight.tags.namespace,
819
+ // A switch is how a command is told what to do, and is not the value
820
+ // it is told to do it with.
821
+ Option: highlight.tags.attributeName,
822
+ // `{*}` spreads a list into the words of a command, which is a thing
823
+ // done to a word rather than a word.
824
+ Expansion: highlight.tags.modifier,
825
+ "( )": highlight.tags.paren,
826
+ "[ ]": highlight.tags.squareBracket,
827
+ "{ }": highlight.tags.brace,
828
+ ",": highlight.tags.separator
829
+ })
830
+ ]
831
+ }),
832
+ languageData: {
833
+ closeBrackets: { brackets: ["(", "[", "{", '"'] },
834
+ commentTokens: { line: "#" },
835
+ indentOnInput: /^\s*(\}|\]|\))$/,
836
+ wordChars: "$:"
837
+ }
838
+ });
839
+ function tcl() {
840
+ return new language.LanguageSupport(tclLanguage, tclLanguage.data.of({ autocomplete: tclCompletion }));
841
+ }
842
+
843
+ exports.commands = commands;
844
+ exports.parser = parser;
845
+ exports.snippets = snippets;
846
+ exports.tcl = tcl;
847
+ exports.tclCompletion = tclCompletion;
848
+ exports.tclLanguage = tclLanguage;