@exercism/codemirror-lang-elm 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.js ADDED
@@ -0,0 +1,829 @@
1
+ import { ExternalTokenizer, ContextTracker, LRParser } from '@lezer/lr';
2
+ import { syntaxTree, indentService, LRLanguage, foldNodeProp, LanguageSupport } from '@codemirror/language';
3
+ import { styleTags, tags } from '@lezer/highlight';
4
+ import { snippetCompletion, completeFromList, ifNotIn } from '@codemirror/autocomplete';
5
+ import { NodeWeakMap } from '@lezer/common';
6
+
7
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
8
+ const LineComment = 1,
9
+ BlockComment = 2,
10
+ DocComment = 3,
11
+ blockOpen = 120,
12
+ blockSep = 121,
13
+ blockEnd = 122,
14
+ accessDot = 123,
15
+ Qualifier = 4,
16
+ closeBrace = 12,
17
+ closeParen = 27,
18
+ comma = 32,
19
+ closeBracket = 34,
20
+ then = 47,
21
+ _else = 48,
22
+ of = 51,
23
+ _in = 80;
24
+
25
+ // The tokenizer reads back this far to find the start of a line. A line that is
26
+ // indented further than this counts as a continuation, which is harmless.
27
+ const maxIndentation = 400;
28
+ function isSpace(ch) {
29
+ return ch == 32 /* Ch.Space */ || ch == 9 /* Ch.Tab */ || ch == 10 /* Ch.Newline */ || ch == 13 /* Ch.Return */;
30
+ }
31
+ function isUpper(ch) {
32
+ return ch >= 65 /* Ch.UpperA */ && ch <= 90 /* Ch.UpperZ */;
33
+ }
34
+ function isLower(ch) {
35
+ return ch >= 97 /* Ch.LowerA */ && ch <= 122 /* Ch.LowerZ */;
36
+ }
37
+ function isIdentChar(ch) {
38
+ return (isUpper(ch) ||
39
+ isLower(ch) ||
40
+ (ch >= 48 /* Ch.Zero */ && ch <= 57 /* Ch.Nine */) ||
41
+ ch == 95 /* Ch.Underscore */ ||
42
+ ch >= 161 /* Ch.Latin1 */);
43
+ }
44
+ function wordAt(input, offset) {
45
+ let word = "";
46
+ for (let pos = offset; isIdentChar(input.peek(pos)); pos++)
47
+ word += String.fromCharCode(input.peek(pos));
48
+ return word;
49
+ }
50
+ function startsComment(input) {
51
+ return ((input.next == 45 /* Ch.Minus */ && input.peek(1) == 45 /* Ch.Minus */) ||
52
+ (input.next == 123 /* Ch.BraceL */ && input.peek(1) == 45 /* Ch.Minus */));
53
+ }
54
+ // ── Comments ──────────────────────────────────────────────────────────────────
55
+ /// Elm's block comments nest, so `{- {- -} -}` is one comment. A token rule
56
+ /// can't count the nesting, so comments are read here. `{-|` starts a
57
+ /// documentation comment.
58
+ const comments = new ExternalTokenizer((input) => {
59
+ if (input.next == 45 /* Ch.Minus */) {
60
+ if (input.peek(1) != 45 /* Ch.Minus */)
61
+ return;
62
+ let pos = 2;
63
+ while (input.peek(pos) != 10 /* Ch.Newline */ && input.peek(pos) != -1 /* Ch.EOF */)
64
+ pos++;
65
+ input.acceptToken(LineComment, pos);
66
+ return;
67
+ }
68
+ if (input.next != 123 /* Ch.BraceL */ || input.peek(1) != 45 /* Ch.Minus */)
69
+ return;
70
+ const term = input.peek(2) == 124 /* Ch.Pipe */ ? DocComment : BlockComment;
71
+ let depth = 0;
72
+ for (let pos = 0;; pos++) {
73
+ const ch = input.peek(pos);
74
+ if (ch == -1 /* Ch.EOF */) {
75
+ input.acceptToken(term, pos);
76
+ return;
77
+ }
78
+ if (ch == 123 /* Ch.BraceL */ && input.peek(pos + 1) == 45 /* Ch.Minus */) {
79
+ depth++;
80
+ pos++;
81
+ }
82
+ else if (ch == 45 /* Ch.Minus */ && input.peek(pos + 1) == 125 /* Ch.BraceR */) {
83
+ depth--;
84
+ pos++;
85
+ if (!depth) {
86
+ input.acceptToken(term, pos + 1);
87
+ return;
88
+ }
89
+ }
90
+ }
91
+ });
92
+ // ── Layout ────────────────────────────────────────────────────────────────────
93
+ /// One open block, and the column its items line up on. The file is the
94
+ /// outermost block, at column 0.
95
+ class Layout {
96
+ constructor(parent, column) {
97
+ this.parent = parent;
98
+ this.column = column;
99
+ this.hash = (parent ? parent.hash * 31 : 0) + column + 1;
100
+ }
101
+ }
102
+ const topLayout = new Layout(null, 0);
103
+ // The column of the current position, and whether it is the first thing on its
104
+ // line. A tab moves to the next multiple of four, which is what elm-format
105
+ // would turn it into.
106
+ function lineInfo(input) {
107
+ let column = 0;
108
+ let firstOnLine = true;
109
+ let offset = -1;
110
+ for (; offset > -maxIndentation; offset--) {
111
+ const ch = input.peek(offset);
112
+ if (ch == -1 /* Ch.EOF */ || ch == 10 /* Ch.Newline */ || ch == 13 /* Ch.Return */)
113
+ break;
114
+ if (!isSpace(ch))
115
+ firstOnLine = false;
116
+ }
117
+ if (offset == -maxIndentation)
118
+ return { column: maxIndentation, firstOnLine: false };
119
+ for (let pos = offset + 1; pos < 0; pos++) {
120
+ if (input.peek(pos) == 9 /* Ch.Tab */)
121
+ column += 4 - (column % 4);
122
+ else
123
+ column++;
124
+ }
125
+ return { column, firstOnLine };
126
+ }
127
+ // A block closes in front of a token that can't go inside it. In
128
+ // `let x = 1 in x`, the `in` ends the block although it is on the same line.
129
+ function closesBlock(input, stack) {
130
+ switch (input.next) {
131
+ case 41 /* Ch.ParenR */:
132
+ return !stack.canShift(closeParen);
133
+ case 93 /* Ch.BracketR */:
134
+ return !stack.canShift(closeBracket);
135
+ case 125 /* Ch.BraceR */:
136
+ return !stack.canShift(closeBrace);
137
+ case 44 /* Ch.Comma */:
138
+ return !stack.canShift(comma);
139
+ }
140
+ if (!isLower(input.next))
141
+ return false;
142
+ switch (wordAt(input, 0)) {
143
+ case "in":
144
+ return !stack.canShift(_in);
145
+ case "then":
146
+ return !stack.canShift(then);
147
+ case "else":
148
+ return !stack.canShift(_else);
149
+ case "of":
150
+ return !stack.canShift(of);
151
+ default:
152
+ return false;
153
+ }
154
+ }
155
+ /// The block markers Elm doesn't write. A block opens at the first token after
156
+ /// `let` or `of`. A line that starts at the block's column starts its next
157
+ /// item. The block ends at the first line that starts further left, in front of
158
+ /// a token that can't go inside it, or at the end of the file.
159
+ const layout = new ExternalTokenizer((input, stack) => {
160
+ const cx = stack.context;
161
+ const nested = cx.parent != null;
162
+ if (input.next == -1 /* Ch.EOF */) {
163
+ if (stack.canShift(blockOpen))
164
+ input.acceptToken(blockOpen);
165
+ else if (nested && stack.canShift(blockEnd))
166
+ input.acceptToken(blockEnd);
167
+ return;
168
+ }
169
+ // The grammar skips whitespace and comments, so layout is decided in front
170
+ // of the tokens that are left.
171
+ if (isSpace(input.next) || startsComment(input))
172
+ return;
173
+ if (stack.canShift(blockOpen)) {
174
+ input.acceptToken(blockOpen);
175
+ return;
176
+ }
177
+ if (nested && closesBlock(input, stack) && stack.canShift(blockEnd)) {
178
+ input.acceptToken(blockEnd);
179
+ return;
180
+ }
181
+ const { column, firstOnLine } = lineInfo(input);
182
+ if (!firstOnLine)
183
+ return;
184
+ if (nested && column < cx.column && stack.canShift(blockEnd))
185
+ input.acceptToken(blockEnd);
186
+ else if (column == cx.column && stack.canShift(blockSep))
187
+ input.acceptToken(blockSep);
188
+ }, { contextual: true });
189
+ /// The stack of open blocks. Each block remembers the column of its first
190
+ /// token, and the tokenizer above compares every line with it.
191
+ const trackLayout = new ContextTracker({
192
+ start: topLayout,
193
+ shift(context, term, stack, input) {
194
+ var _a;
195
+ if (term == blockOpen)
196
+ return new Layout(context, lineInfo(input).column);
197
+ if (term == blockEnd)
198
+ return (_a = context.parent) !== null && _a !== void 0 ? _a : context;
199
+ return context;
200
+ },
201
+ hash: (context) => context.hash,
202
+ });
203
+ // ── Dots ──────────────────────────────────────────────────────────────────────
204
+ /// Two kinds of dot that a token rule can't tell apart.
205
+ ///
206
+ /// The module part of a qualified name, such as `List.` in `List.map` or
207
+ /// `Html.Attributes.` in `Html.Attributes.class`, becomes one `Qualifier`
208
+ /// token. That way `Maybe.Just` is one constructor and `Dict.Dict` is one type.
209
+ ///
210
+ /// A dot written straight after a name or a closing bracket reads a field, as
211
+ /// in `model.count` or `(f x).name`. A dot with a space in front of it starts
212
+ /// an accessor function, as in `List.map .name people`.
213
+ const dots = new ExternalTokenizer((input, stack) => {
214
+ if (input.next == 46 /* Ch.Dot */) {
215
+ if (!isLower(input.peek(1)))
216
+ return;
217
+ const before = input.peek(-1);
218
+ if (!(isIdentChar(before) || before == 41 /* Ch.ParenR */ || before == 125 /* Ch.BraceR */))
219
+ return;
220
+ if (stack.canShift(accessDot))
221
+ input.acceptToken(accessDot, 1);
222
+ return;
223
+ }
224
+ if (!isUpper(input.next))
225
+ return;
226
+ let pos = 0;
227
+ let end = 0;
228
+ while (isUpper(input.peek(pos))) {
229
+ while (isIdentChar(input.peek(pos)))
230
+ pos++;
231
+ if (input.peek(pos) != 46 /* Ch.Dot */)
232
+ break;
233
+ const after = input.peek(pos + 1);
234
+ if (!isUpper(after) && !isLower(after))
235
+ break;
236
+ pos++;
237
+ end = pos;
238
+ }
239
+ if (end && stack.canShift(Qualifier))
240
+ input.acceptToken(Qualifier, end);
241
+ });
242
+
243
+ // This file was generated by lezer-generator. You probably shouldn't edit it.
244
+ const spec_lowerIdent = {__proto__:null,port:14, effect:16, module:18, where:22, if:92, then:94, else:96, case:100, of:102, as:108, let:134, in:160, exposing:168, import:180, type:186, alias:188, infix:204};
245
+ const spec_operatorToken = {__proto__:null,"=":34, "-":40, "::":42, "|":78, "->":130, ":":140, "..":170};
246
+ const parser = LRParser.deserialize({
247
+ version: 14,
248
+ states: "EtQ`QXOOOOQT'#Ds'#DsOOQR'#FO'#FOQwQZOOO!qQ]O'#DrO!{Q]O'#CbO#TQXO'#CbO#]QXO'#CbO!{Q]O'#EXO#bQXO'#EaO#jQXO'#EeO`QXO'#EvQwQZOOOOQV'#Cs'#CsO#oQXO'#CsOOQT'#De'#DeO#tQ]O'#DjO#{Q]O'#DmO$SQXO'#DnOOQT'#FY'#FYOOQT'#Ej'#EjO$[Q]O,5:hO$cQXO'#DiO$hQ]O,5:^O$yQ]O,5:hOOQR'#Cf'#CfO%zQXO'#CfO&PQXO,58|O!{Q]O,58|O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constructor Number String Char ) ( ParenExpression UnitExpression TupleExpression , ParenOperator ] [ ListExpression RecordUpdateExpression RecordBase | AccessorFunction FieldAccess CallExpression Callee NegateExpression IfExpression if then else CaseExpression case of CaseBranch AsPattern as PatternVariable ConsPattern ConstructorPattern Wildcard NegativeNumber UnitPattern TuplePattern ParenPattern ListPattern RecordPattern -> LetExpression let TypeAnnotation DeclName : Type TypeApplication TypeConstructor TypeVariable ParenType RecordType FieldType ValueDeclaration DestructuringDeclaration in LambdaExpression \\ ExposingList exposing .. ExposedValue ExposedType ExposedOperator ImportDeclaration import ModuleAlias TypeAliasDeclaration type alias TypeName TypeParameter TypeDeclaration ConstructorDefinition ConstructorName PortDeclaration InfixDeclaration infix",
252
+ maxTerm: 141,
253
+ context: trackLayout,
254
+ nodeProps: [
255
+ ["openedBy", 12,"{",27,"(",34,"["],
256
+ ["closedBy", 13,"}",28,")",35,"]"],
257
+ ["isolate", 25,""]
258
+ ],
259
+ skippedNodes: [0,1,2,3],
260
+ repeatNodeCount: 16,
261
+ tokenData: "6u~RrXY#]YZ#]]^#]pq#]qr#nrs$ruv#nvw#nwx.Sxy0Yyz0_z{#n{|#n|}0d}!O#n!O!P0i!P!Q#n!Q!R2b!R![3v![!]#n!^!_#n!_!`#n!`!a#n!a!b#n!c!}4s!}#O5e#O#P5j#P#Q5o#Q#R#n#R#S5t#T#o5y#o#p6k#p#q#n#q#r6p~#bS#q~XY#]YZ#]]^#]pq#]~#s_#u~qr#nuv#nvw#nz{#n{|#n}!O#n!O!P#n!P!Q#n![!]#n!^!_#n!_!`#n!`!a#n!a!b#n#Q#R#n#p#q#n~$uWOY%_Zr%_rs)cs#O%_#O#P&P#P;'S%_;'S;=`)]<%lO%_~%bWOY%_Zr%_rs%zs#O%_#O#P&P#P;'S%_;'S;=`)]<%lO%_~&POi~~&SUOY%_Z#i%_#i#j&f#j;'S%_;'S;=`)]<%lO%_~&iYOY%_Zr%_rs%zs#O%_#O#P&P#P#o%_#o#p'X#p;'S%_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~!Q![2|!g!h3[#X#Y3[~3_R{|3h}!O3h!Q![3n~3kP!Q![3n~3sPh~!Q![3n~3{Sh~!O!P2v!Q![3v!g!h3[#X#Y3[~4[R!Q![4e!c!i4e#T#Z4e~4jRh~!Q![4e!c!i4e#T#Z4e~4xV#t~!Q![4s!c!}4s#R#S4s#T#o4s$g;'S4s;'S;=`5_<%lO4s~5bP;=`<%l4s~5jOs~~5oO!t~~5tOr~~5yO![~~6OV#s~!Q![5y!c!}5y#R#S5y#T#o5y$g;'S5y;'S;=`6e<%lO5y~6hP;=`<%l5y~6pO]~~6uO[~",
262
+ tokenizers: [comments, layout, dots, 0],
263
+ topRules: {"Program":[0,5]},
264
+ specialized: [{term: 127, get: (value) => spec_lowerIdent[value] || -1},{term: 129, get: (value) => spec_operatorToken[value] || -1}],
265
+ tokenPrec: 1784
266
+ });
267
+
268
+ // The functions, types and constructors of the modules that every Exercism Elm
269
+ // exercise can import: elm/core, plus elm/regex, elm/parser, elm/time,
270
+ // elm/random and elm/json from the track's `elm.json`.
271
+ const words = (text) => text.split(/\s+/).filter(Boolean);
272
+ const modules = {
273
+ Basics: {
274
+ values: words(`
275
+ toFloat round floor ceiling truncate max min compare not xor modBy
276
+ remainderBy negate abs clamp sqrt logBase e pi cos sin tan acos asin atan
277
+ atan2 degrees radians turns toPolar fromPolar isNaN isInfinite identity
278
+ always never`),
279
+ types: words("Int Float Bool Order Never"),
280
+ constructors: words("True False LT EQ GT"),
281
+ },
282
+ List: {
283
+ values: words(`
284
+ singleton repeat range map indexedMap foldl foldr filter filterMap length
285
+ reverse member all any maximum minimum sum product append concat concatMap
286
+ intersperse map2 map3 map4 map5 sort sortBy sortWith isEmpty head tail
287
+ take drop partition unzip`),
288
+ types: words("List"),
289
+ },
290
+ String: {
291
+ values: words(`
292
+ isEmpty length reverse repeat replace append concat split join words lines
293
+ slice left right dropLeft dropRight contains startsWith endsWith indexes
294
+ indices toInt fromInt toFloat fromFloat fromChar cons uncons toList
295
+ fromList toUpper toLower pad padLeft padRight trim trimLeft trimRight map
296
+ filter foldl foldr any all`),
297
+ types: words("String"),
298
+ },
299
+ Char: {
300
+ values: words(`
301
+ isUpper isLower isAlpha isAlphaNum isDigit isOctDigit isHexDigit toUpper
302
+ toLower toLocaleUpper toLocaleLower toCode fromCode`),
303
+ types: words("Char"),
304
+ },
305
+ Maybe: {
306
+ values: words("withDefault map map2 map3 map4 map5 andThen"),
307
+ types: words("Maybe"),
308
+ constructors: words("Just Nothing"),
309
+ },
310
+ Result: {
311
+ values: words("map map2 map3 map4 map5 andThen withDefault toMaybe fromMaybe mapError"),
312
+ types: words("Result"),
313
+ constructors: words("Ok Err"),
314
+ },
315
+ Tuple: {
316
+ values: words("pair first second mapFirst mapSecond mapBoth"),
317
+ },
318
+ Dict: {
319
+ values: words(`
320
+ empty singleton insert update remove isEmpty member get size keys values
321
+ toList fromList map foldl foldr filter partition union intersect diff
322
+ merge`),
323
+ types: words("Dict"),
324
+ },
325
+ Set: {
326
+ values: words(`
327
+ empty singleton insert remove isEmpty member size union intersect diff
328
+ toList fromList map foldl foldr filter partition`),
329
+ types: words("Set"),
330
+ },
331
+ Array: {
332
+ values: words(`
333
+ empty initialize repeat fromList isEmpty length get set push append slice
334
+ toList toIndexedList map indexedMap foldl foldr filter`),
335
+ types: words("Array"),
336
+ },
337
+ Bitwise: {
338
+ values: words("and or xor complement shiftLeftBy shiftRightBy shiftRightZfBy"),
339
+ },
340
+ Debug: {
341
+ values: words("toString log todo"),
342
+ },
343
+ Regex: {
344
+ values: words(`
345
+ fromString fromStringWith never contains split find replace splitAtMost
346
+ findAtMost replaceAtMost`),
347
+ types: words("Regex Options Match"),
348
+ },
349
+ Parser: {
350
+ values: words(`
351
+ run int float number symbol keyword variable end succeed problem oneOf map
352
+ backtrackable commit andThen lazy loop sequence spaces lineComment
353
+ multiComment getChompedString chompIf chompWhile chompUntil
354
+ chompUntilEndOr mapChompedString withIndent getIndent getPosition getRow
355
+ getCol getOffset getSource token deadEndsToString`),
356
+ types: words("Parser DeadEnd Problem Step Trailing Nestable"),
357
+ constructors: words("Loop Done Forbidden Optional Mandatory NotNestable Nestable"),
358
+ },
359
+ Time: {
360
+ values: words(`
361
+ now every posixToMillis millisToPosix utc here toYear toMonth toDay
362
+ toWeekday toHour toMinute toSecond toMillis customZone`),
363
+ types: words("Posix Zone Month Weekday"),
364
+ constructors: words(`
365
+ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Mon Tue Wed Thu Fri Sat
366
+ Sun`),
367
+ },
368
+ Random: {
369
+ values: words(`
370
+ generate step initialSeed int float uniform weighted constant list pair
371
+ map map2 map3 andThen lazy independentSeed minInt maxInt`),
372
+ types: words("Generator Seed"),
373
+ },
374
+ "Json.Decode": {
375
+ values: words(`
376
+ string bool int float nullable list array dict keyValuePairs oneOrMore
377
+ field at index maybe oneOf decodeString decodeValue map map2 map3 lazy
378
+ value null succeed fail andThen errorToString`),
379
+ types: words("Decoder Value Error"),
380
+ },
381
+ "Json.Encode": {
382
+ values: words("encode string int float bool null list array set object dict"),
383
+ types: words("Value"),
384
+ },
385
+ };
386
+ // Elm imports these into every module, and exposes the names listed here
387
+ // without a module prefix.
388
+ const defaultImports = words("Basics List Maybe Result String Char Tuple Debug Platform Cmd Sub");
389
+ const defaultExposed = {
390
+ values: modules.Basics.values,
391
+ types: [
392
+ ...modules.Basics.types,
393
+ "List",
394
+ "Maybe",
395
+ "Result",
396
+ "String",
397
+ "Char",
398
+ "Program",
399
+ "Cmd",
400
+ "Sub",
401
+ ],
402
+ constructors: [...modules.Basics.constructors, "Just", "Nothing", "Ok", "Err"],
403
+ };
404
+
405
+ /// Snippets for the constructs people write most often in Elm.
406
+ const snippets = [
407
+ snippetCompletion("${name} : ${Type} -> ${Type}\n${name} ${arg} =\n\t${}", {
408
+ label: "fun",
409
+ detail: "function with annotation",
410
+ type: "keyword",
411
+ }),
412
+ snippetCompletion("case ${expression} of\n\t${pattern} ->\n\t\t${}", {
413
+ label: "case",
414
+ detail: "of",
415
+ type: "keyword",
416
+ }),
417
+ snippetCompletion("if ${condition} then\n\t${}\n\nelse\n\t${}", {
418
+ label: "if",
419
+ detail: "then else",
420
+ type: "keyword",
421
+ }),
422
+ snippetCompletion("let\n\t${name} =\n\t\t${value}\nin\n${}", {
423
+ label: "let",
424
+ detail: "in",
425
+ type: "keyword",
426
+ }),
427
+ snippetCompletion("\\${x} -> ${}", {
428
+ label: "\\",
429
+ detail: "lambda",
430
+ type: "keyword",
431
+ }),
432
+ snippetCompletion("type ${Name}\n\t= ${First}\n\t| ${Second}", {
433
+ label: "type",
434
+ detail: "custom type",
435
+ type: "keyword",
436
+ }),
437
+ snippetCompletion("type alias ${Name} =\n\t{ ${field} : ${Type}\n\t}", {
438
+ label: "type alias",
439
+ detail: "record",
440
+ type: "keyword",
441
+ }),
442
+ snippetCompletion("module ${Name} exposing (${names})\n\n${}", {
443
+ label: "module",
444
+ detail: "header",
445
+ type: "keyword",
446
+ }),
447
+ snippetCompletion("import ${Module} exposing (${names})", {
448
+ label: "import",
449
+ detail: "exposing",
450
+ type: "keyword",
451
+ }),
452
+ ];
453
+ const keywords = "if then else case of let in type alias module exposing import as port"
454
+ .split(" ")
455
+ .map((label) => ({ label, type: "keyword" }));
456
+ function membersToCompletions(members) {
457
+ var _a, _b;
458
+ return [
459
+ ...members.values.map((label) => ({ label, type: "function" })),
460
+ ...((_a = members.types) !== null && _a !== void 0 ? _a : []).map((label) => ({ label, type: "type" })),
461
+ ...((_b = members.constructors) !== null && _b !== void 0 ? _b : []).map((label) => ({ label, type: "enum" })),
462
+ ];
463
+ }
464
+ const moduleNames = Object.keys(modules)
465
+ .filter((name) => !name.includes("."))
466
+ .concat("Json")
467
+ .map((label) => ({ label, type: "namespace" }));
468
+ const dontComplete = ["String", "Char", "LineComment", "BlockComment", "DocComment"];
469
+ const Identifier = /^\w*$/;
470
+ // A word straight after a dot names a member of a module or a field of a
471
+ // record, and the sources for bare names have nothing useful to say there.
472
+ function afterDot(context) {
473
+ const word = context.matchBefore(/\w*/);
474
+ const from = word ? word.from : context.pos;
475
+ return from > 0 && context.state.sliceDoc(from - 1, from) == ".";
476
+ }
477
+ const fixedNames = completeFromList([
478
+ ...snippets,
479
+ ...keywords,
480
+ ...membersToCompletions(defaultExposed),
481
+ ...moduleNames,
482
+ ]);
483
+ /// Keywords, snippets, the names Elm imports into every module, and the module
484
+ /// names. It offers nothing inside strings and comments, or after a dot.
485
+ const elmCompletion = ifNotIn(dontComplete, (context) => afterDot(context) ? null : fixedNames(context));
486
+ function imports(state) {
487
+ const found = [];
488
+ const doc = state.doc;
489
+ const top = syntaxTree(state).topNode;
490
+ for (const node of top.getChildren("ImportDeclaration")) {
491
+ const name = node.getChild("ModuleName");
492
+ if (!name)
493
+ continue;
494
+ const alias = node.getChild("ModuleAlias");
495
+ const exposing = node.getChild("ExposingList");
496
+ const exposed = [];
497
+ let exposesAll = false;
498
+ if (exposing) {
499
+ exposesAll = !!exposing.getChild("..");
500
+ for (const item of exposing.getChildren("ExposedValue"))
501
+ exposed.push(doc.sliceString(item.from, item.to));
502
+ for (const item of exposing.getChildren("ExposedType")) {
503
+ const type = item.firstChild;
504
+ if (type)
505
+ exposed.push(doc.sliceString(item.from, type.to));
506
+ }
507
+ }
508
+ found.push({
509
+ module: doc.sliceString(name.from, name.to),
510
+ alias: alias ? doc.sliceString(alias.from, alias.to) : null,
511
+ exposesAll,
512
+ exposed,
513
+ });
514
+ }
515
+ return found;
516
+ }
517
+ /// The members of a module after its name and a dot: `List.` offers `map` and
518
+ /// `foldl`, and after `import Dict as D`, `D.` offers what `Dict.` does.
519
+ const moduleCompletionSource = (context) => {
520
+ const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
521
+ if (dontComplete.includes(inner.name))
522
+ return null;
523
+ const match = context.matchBefore(/(?:[A-Z]\w*\.)+\w*/);
524
+ if (!match)
525
+ return null;
526
+ const lastDot = match.text.lastIndexOf(".");
527
+ const qualifier = match.text.slice(0, lastDot);
528
+ const from = match.from + lastDot + 1;
529
+ let module = qualifier;
530
+ for (const imp of imports(context.state))
531
+ if (imp.alias == qualifier)
532
+ module = imp.module;
533
+ const members = modules[module];
534
+ if (members)
535
+ return { from, options: membersToCompletions(members), validFor: Identifier };
536
+ // `Json.` is the start of `Json.Decode` and `Json.Encode`.
537
+ const prefix = module + ".";
538
+ const submodules = Object.keys(modules)
539
+ .filter((name) => name.startsWith(prefix))
540
+ .map((name) => ({ label: name.slice(prefix.length), type: "namespace" }));
541
+ return submodules.length ? { from, options: submodules, validFor: Identifier } : null;
542
+ };
543
+ /// The names an import brings in without a prefix: those in its `exposing`
544
+ /// list, or every member for `exposing (..)`.
545
+ const importedCompletionSource = (context) => {
546
+ const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
547
+ if (dontComplete.includes(inner.name) || afterDot(context))
548
+ return null;
549
+ const word = context.matchBefore(/\w+/);
550
+ if (!word && !context.explicit)
551
+ return null;
552
+ const options = [];
553
+ for (const imp of imports(context.state)) {
554
+ if (defaultImports.includes(imp.module) && !imp.exposesAll && !imp.exposed.length)
555
+ continue;
556
+ const members = modules[imp.module];
557
+ if (imp.exposesAll && members)
558
+ options.push(...membersToCompletions(members));
559
+ for (const label of imp.exposed)
560
+ options.push({ label, type: /^[A-Z]/.test(label) ? "type" : "function" });
561
+ }
562
+ return options.length
563
+ ? { from: word ? word.from : context.pos, options, validFor: Identifier }
564
+ : null;
565
+ };
566
+ // ── Fields ────────────────────────────────────────────────────────────────────
567
+ /// The field names written in the file, after a record and a dot, as in
568
+ /// `model.` or `.` at the start of an accessor function.
569
+ const fieldCompletionSource = (context) => {
570
+ const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
571
+ if (dontComplete.includes(inner.name))
572
+ return null;
573
+ const match = context.matchBefore(/(^|[^\w.]|[a-z_]\w*|[)}])\.\w*/);
574
+ if (!match || /^[A-Z]/.test(match.text))
575
+ return null;
576
+ const from = match.from + match.text.lastIndexOf(".") + 1;
577
+ const doc = context.state.doc;
578
+ const seen = new Set();
579
+ const options = [];
580
+ syntaxTree(context.state).iterate({
581
+ enter(node) {
582
+ if (node.name != "FieldName")
583
+ return;
584
+ const label = doc.sliceString(node.from, node.to);
585
+ if (!label || seen.has(label) || node.to == context.pos)
586
+ return;
587
+ seen.add(label);
588
+ options.push({ label, type: "property" });
589
+ },
590
+ });
591
+ return options.length ? { from, options, validFor: Identifier } : null;
592
+ };
593
+ // ── Names declared in the file ────────────────────────────────────────────────
594
+ // Every node here opens a scope: the names it binds are visible inside it and
595
+ // nowhere else. The declarations of a `let` can see each other, so the whole
596
+ // `LetExpression` is one scope.
597
+ const ScopeNodes = new Set([
598
+ "Program",
599
+ "ValueDeclaration",
600
+ "LetExpression",
601
+ "CaseBranch",
602
+ "LambdaExpression",
603
+ ]);
604
+ function patternVariables(node, def) {
605
+ if (node.name == "PatternVariable")
606
+ def(node, "variable");
607
+ else
608
+ for (let ch = node.firstChild; ch; ch = ch.nextSibling)
609
+ patternVariables(ch, def);
610
+ }
611
+ // What a declaration adds to the scope around it. Returning true stops the walk
612
+ // going inside it.
613
+ const gatherers = {
614
+ ValueDeclaration(node, def) {
615
+ var _a;
616
+ const name = node.getChild("DeclName");
617
+ const hasParams = ((_a = name === null || name === void 0 ? void 0 : name.nextSibling) === null || _a === void 0 ? void 0 : _a.name) != "=";
618
+ if (name)
619
+ def(name, hasParams ? "function" : "variable");
620
+ return true;
621
+ },
622
+ TypeAnnotation(node, def) {
623
+ var _a;
624
+ const name = node.getChild("DeclName");
625
+ const isFunction = !!((_a = node.getChild("Type")) === null || _a === void 0 ? void 0 : _a.getChild("->"));
626
+ if (name)
627
+ def(name, isFunction ? "function" : "variable");
628
+ return true;
629
+ },
630
+ PortDeclaration(node, def) {
631
+ const name = node.getChild("DeclName");
632
+ if (name)
633
+ def(name, "function");
634
+ return true;
635
+ },
636
+ DestructuringDeclaration(node, def) {
637
+ if (node.firstChild)
638
+ patternVariables(node.firstChild, def);
639
+ return true;
640
+ },
641
+ TypeDeclaration(node, def) {
642
+ const name = node.getChild("TypeName");
643
+ if (name)
644
+ def(name, "type");
645
+ for (const con of node.getChildren("ConstructorDefinition")) {
646
+ const conName = con.getChild("ConstructorName");
647
+ if (conName)
648
+ def(conName, "enum");
649
+ }
650
+ return true;
651
+ },
652
+ TypeAliasDeclaration(node, def) {
653
+ const name = node.getChild("TypeName");
654
+ if (name)
655
+ def(name, "type");
656
+ return true;
657
+ },
658
+ ModuleDeclaration() {
659
+ return true;
660
+ },
661
+ ImportDeclaration(node, def) {
662
+ const alias = node.getChild("ModuleAlias");
663
+ if (alias)
664
+ def(alias, "namespace");
665
+ return true;
666
+ },
667
+ };
668
+ // The names a scope node binds itself: a function's parameters, a lambda's
669
+ // arguments and the variables in a `case` pattern.
670
+ function ownBindings(node, def) {
671
+ switch (node.name) {
672
+ case "ValueDeclaration":
673
+ case "LambdaExpression":
674
+ case "CaseBranch":
675
+ for (let ch = node.firstChild; ch && ch.name != "=" && ch.name != "->"; ch = ch.nextSibling)
676
+ if (ch.name != "DeclName")
677
+ patternVariables(ch, def);
678
+ break;
679
+ }
680
+ }
681
+ const cache = new NodeWeakMap();
682
+ function getScope(doc, node) {
683
+ const cached = cache.get(node);
684
+ if (cached)
685
+ return cached;
686
+ const completions = [];
687
+ const seen = new Set();
688
+ const def = (n, type) => {
689
+ const label = doc.sliceString(n.from, n.to);
690
+ if (!label || seen.has(label))
691
+ return;
692
+ seen.add(label);
693
+ completions.push({ label, type });
694
+ };
695
+ ownBindings(node, def);
696
+ const walk = (parent) => {
697
+ for (let ch = parent.firstChild; ch; ch = ch.nextSibling) {
698
+ const gather = gatherers[ch.name];
699
+ if (gather && gather(ch, def))
700
+ continue;
701
+ if (!ScopeNodes.has(ch.name))
702
+ walk(ch);
703
+ }
704
+ };
705
+ walk(node);
706
+ cache.set(node, completions);
707
+ return completions;
708
+ }
709
+ /// Completes the names declared in the file that are in scope at the cursor:
710
+ /// top-level functions, types and constructors, parameters, and the names bound
711
+ /// by `let`, `case` and lambdas.
712
+ const localCompletionSource = (context) => {
713
+ const inner = syntaxTree(context.state).resolveInner(context.pos, -1);
714
+ if (dontComplete.includes(inner.name) || afterDot(context))
715
+ return null;
716
+ const word = context.matchBefore(/\w+/);
717
+ if (!word && !context.explicit)
718
+ return null;
719
+ let options = [];
720
+ for (let pos = inner; pos; pos = pos.parent)
721
+ if (ScopeNodes.has(pos.name))
722
+ options = options.concat(getScope(context.state.doc, pos));
723
+ // The name being typed is in the tree as a declaration of its own, and
724
+ // offering it back as its own completion helps nobody.
725
+ if (word)
726
+ options = options.filter((o) => o.label != word.text);
727
+ return { options, from: word ? word.from : context.pos, validFor: Identifier };
728
+ };
729
+
730
+ // Folding a declaration or block keeps its first line in view, which is the
731
+ // line that says what was folded away.
732
+ function foldBody(node, state) {
733
+ const line = state.doc.lineAt(node.from);
734
+ return node.to > line.to ? { from: line.to, to: node.to } : null;
735
+ }
736
+ // The tree can't say where a new line belongs, because a block ends at its last
737
+ // token and the new line is past that. So the line above decides. A line that
738
+ // ends by opening something is followed by one indented under it, as
739
+ // elm-format lays it out, and any other line is followed by one at its own
740
+ // indentation.
741
+ const opensBlock = /(=|->|\bof|\blet|\bthen|\belse|\bin|\(|\[|\{|,|\|>|<\||\+\+|&&|\|\|)$/;
742
+ const startsDeclaration = /^\s*(in|else)\b/;
743
+ const indentElm = indentService.of((context, pos) => {
744
+ const inside = syntaxTree(context.state).resolveInner(pos, -1).name;
745
+ if (inside == "BlockComment" || inside == "DocComment" || inside == "String")
746
+ return null;
747
+ let line = context.lineAt(pos, -1);
748
+ while (!/\S/.test(line.text) && line.from > 0)
749
+ line = context.lineAt(line.from - 1, -1);
750
+ if (!/\S/.test(line.text))
751
+ return 0;
752
+ const code = line.text.replace(/\s*--.*$/, "").trimEnd();
753
+ const base = context.lineIndent(line.from);
754
+ if (startsDeclaration.test(context.state.doc.sliceString(pos, pos + 10)))
755
+ return Math.max(0, base - context.unit);
756
+ if (/\bin$/.test(code))
757
+ return base;
758
+ if (opensBlock.test(code))
759
+ return base + context.unit;
760
+ return base;
761
+ });
762
+ const elmLanguage = LRLanguage.define({
763
+ name: "elm",
764
+ parser: parser.configure({
765
+ props: [
766
+ foldNodeProp.add({
767
+ "ValueDeclaration TypeDeclaration TypeAliasDeclaration": foldBody,
768
+ "LetExpression CaseExpression CaseBranch": foldBody,
769
+ "ListExpression RecordExpression RecordUpdateExpression RecordType": foldBody,
770
+ "BlockComment DocComment": foldBody,
771
+ }),
772
+ styleTags({
773
+ "module import exposing port effect where": tags.moduleKeyword,
774
+ "type alias as infix": tags.definitionKeyword,
775
+ "let in": tags.definitionKeyword,
776
+ "if then else case of": tags.controlKeyword,
777
+ Number: tags.number,
778
+ String: tags.string,
779
+ Char: tags.character,
780
+ Wildcard: tags.atom,
781
+ LineComment: tags.lineComment,
782
+ BlockComment: tags.blockComment,
783
+ DocComment: tags.docComment,
784
+ Qualifier: tags.namespace,
785
+ "ModuleName ModuleAlias": tags.namespace,
786
+ "DeclName": tags.definition(tags.variableName),
787
+ "ValueDeclaration/DeclName TypeAnnotation/DeclName PortDeclaration/DeclName": tags.definition(tags.function(tags.variableName)),
788
+ PatternVariable: tags.definition(tags.variableName),
789
+ "Callee/Variable": tags.function(tags.variableName),
790
+ Variable: tags.variableName,
791
+ "ExposedValue": tags.variableName,
792
+ "Constructor ConstructorName": tags.className,
793
+ "TypeName ExposedType": tags.definition(tags.typeName),
794
+ TypeConstructor: tags.typeName,
795
+ "TypeVariable TypeParameter": tags.typeName,
796
+ "FieldName RecordBase": tags.propertyName,
797
+ AccessorFunction: tags.propertyName,
798
+ Operator: tags.operator,
799
+ "- ::": tags.operator,
800
+ "= ->": tags.definitionOperator,
801
+ ":": tags.typeOperator,
802
+ '| .. "\\\\"': tags.operator,
803
+ ", accessDot": tags.separator,
804
+ "( )": tags.paren,
805
+ "[ ]": tags.squareBracket,
806
+ "{ }": tags.brace,
807
+ }),
808
+ ],
809
+ }),
810
+ languageData: {
811
+ commentTokens: { line: "--", block: { open: "{-", close: "-}" } },
812
+ closeBrackets: { brackets: ["(", "[", "{", '"'] },
813
+ indentOnInput: /^\s*(in|else)$/,
814
+ },
815
+ });
816
+ /// Elm language support, with completion for keywords, snippets, the core
817
+ /// modules and the names declared in the file.
818
+ function elm() {
819
+ return new LanguageSupport(elmLanguage, [
820
+ indentElm,
821
+ elmLanguage.data.of({ autocomplete: elmCompletion }),
822
+ elmLanguage.data.of({ autocomplete: moduleCompletionSource }),
823
+ elmLanguage.data.of({ autocomplete: importedCompletionSource }),
824
+ elmLanguage.data.of({ autocomplete: fieldCompletionSource }),
825
+ elmLanguage.data.of({ autocomplete: localCompletionSource }),
826
+ ]);
827
+ }
828
+
829
+ export { elm, elmCompletion, elmLanguage, fieldCompletionSource, importedCompletionSource, localCompletionSource, moduleCompletionSource, parser, snippets };