@exercism/codemirror-lang-rust 0.0.0-stage → 1.0.0

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,574 @@
1
+ 'use strict';
2
+
3
+ var rust$1 = require('@lezer/rust');
4
+ var language = require('@codemirror/language');
5
+ var common = require('@lezer/common');
6
+ var autocomplete = require('@codemirror/autocomplete');
7
+
8
+ /**
9
+ A collection of Rust-related
10
+ [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
11
+ */
12
+ const snippets = [
13
+ autocomplete.snippetCompletion("fn ${name}(${params}) {\n\t${}\n}", {
14
+ label: "fn",
15
+ detail: "definition",
16
+ type: "keyword"
17
+ }),
18
+ autocomplete.snippetCompletion("fn ${name}(${params}) -> ${Type} {\n\t${}\n}", {
19
+ label: "fn",
20
+ detail: "definition with return type",
21
+ type: "keyword"
22
+ }),
23
+ autocomplete.snippetCompletion("pub fn ${name}(${params}) -> ${Type} {\n\t${}\n}", {
24
+ label: "pub fn",
25
+ detail: "public definition",
26
+ type: "keyword"
27
+ }),
28
+ autocomplete.snippetCompletion("fn ${name}(&self${params}) -> ${Type} {\n\t${}\n}", {
29
+ label: "fn",
30
+ detail: "method",
31
+ type: "keyword"
32
+ }),
33
+ autocomplete.snippetCompletion("struct ${Name} {\n\t${field}: ${Type},\n}", {
34
+ label: "struct",
35
+ detail: "definition",
36
+ type: "keyword"
37
+ }),
38
+ autocomplete.snippetCompletion("struct ${Name}(${Type});", {
39
+ label: "struct",
40
+ detail: "tuple struct",
41
+ type: "keyword"
42
+ }),
43
+ autocomplete.snippetCompletion("enum ${Name} {\n\t${Variant},\n}", {
44
+ label: "enum",
45
+ detail: "definition",
46
+ type: "keyword"
47
+ }),
48
+ autocomplete.snippetCompletion("trait ${Name} {\n\t${}\n}", {
49
+ label: "trait",
50
+ detail: "definition",
51
+ type: "keyword"
52
+ }),
53
+ autocomplete.snippetCompletion("impl ${Type} {\n\t${}\n}", {
54
+ label: "impl",
55
+ detail: "block",
56
+ type: "keyword"
57
+ }),
58
+ autocomplete.snippetCompletion("impl ${Trait} for ${Type} {\n\t${}\n}", {
59
+ label: "impl",
60
+ detail: "trait for type",
61
+ type: "keyword"
62
+ }),
63
+ autocomplete.snippetCompletion("let ${name} = ${value};", {
64
+ label: "let",
65
+ detail: "binding",
66
+ type: "keyword"
67
+ }),
68
+ autocomplete.snippetCompletion("let mut ${name} = ${value};", {
69
+ label: "let mut",
70
+ detail: "mutable binding",
71
+ type: "keyword"
72
+ }),
73
+ autocomplete.snippetCompletion("if ${condition} {\n\t${}\n}", {
74
+ label: "if",
75
+ detail: "block",
76
+ type: "keyword"
77
+ }),
78
+ autocomplete.snippetCompletion("if ${condition} {\n\t${}\n} else {\n\t${}\n}", {
79
+ label: "if",
80
+ detail: "/ else block",
81
+ type: "keyword"
82
+ }),
83
+ autocomplete.snippetCompletion("if let ${Some(x)} = ${value} {\n\t${}\n}", {
84
+ label: "if let",
85
+ detail: "pattern block",
86
+ type: "keyword"
87
+ }),
88
+ autocomplete.snippetCompletion("match ${value} {\n\t${pattern} => ${},\n}", {
89
+ label: "match",
90
+ detail: "expression",
91
+ type: "keyword"
92
+ }),
93
+ autocomplete.snippetCompletion("for ${item} in ${iter} {\n\t${}\n}", {
94
+ label: "for",
95
+ detail: "loop",
96
+ type: "keyword"
97
+ }),
98
+ autocomplete.snippetCompletion("while ${condition} {\n\t${}\n}", {
99
+ label: "while",
100
+ detail: "loop",
101
+ type: "keyword"
102
+ }),
103
+ autocomplete.snippetCompletion("while let ${Some(x)} = ${value} {\n\t${}\n}", {
104
+ label: "while let",
105
+ detail: "pattern loop",
106
+ type: "keyword"
107
+ }),
108
+ autocomplete.snippetCompletion("loop {\n\t${}\n}", {
109
+ label: "loop",
110
+ detail: "infinite loop",
111
+ type: "keyword"
112
+ }),
113
+ autocomplete.snippetCompletion("|${params}| ${}", {
114
+ label: "closure",
115
+ detail: "|params| body",
116
+ type: "keyword"
117
+ }),
118
+ autocomplete.snippetCompletion("#[derive(${Debug})]", {
119
+ label: "derive",
120
+ detail: "attribute",
121
+ type: "keyword"
122
+ }),
123
+ autocomplete.snippetCompletion("#[cfg(test)]\nmod tests {\n\tuse super::*;\n\n\t#[test]\n\tfn ${name}() {\n\t\t${}\n\t}\n}", {
124
+ label: "mod tests",
125
+ detail: "test module",
126
+ type: "keyword"
127
+ }),
128
+ autocomplete.snippetCompletion("#[test]\nfn ${name}() {\n\t${}\n}", {
129
+ label: "test",
130
+ detail: "test function",
131
+ type: "keyword"
132
+ })
133
+ ];
134
+
135
+ const kw = (type, detail) => (label) => detail ? { label, type, detail } : { label, type };
136
+ const keywordNames = "as async await break const continue crate dyn else enum extern false fn for if " +
137
+ "impl in let loop match mod move mut pub ref return self Self static struct super trait true type " +
138
+ "unsafe use where while";
139
+ /**
140
+ Rust's keywords, primitive types and the names a program can use
141
+ without importing them (the prelude), plus some common types from
142
+ `std`.
143
+ */
144
+ const builtins = [
145
+ ...keywordNames.split(" ").map(kw("keyword")),
146
+ ...("i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 bool char str").split(" ").map(kw("type")),
147
+ ...("String Vec Option Result Box").split(" ").map(kw("type", "prelude")),
148
+ ...("Some None Ok Err").split(" ").map(kw("enum", "prelude")),
149
+ ...("Clone Copy Debug Default Drop Eq PartialEq Ord PartialOrd Hash Iterator IntoIterator " +
150
+ "DoubleEndedIterator ExactSizeIterator Extend FromIterator From Into TryFrom TryInto AsRef AsMut " +
151
+ "ToString ToOwned Fn FnMut FnOnce Sized Send Sync").split(" ").map(kw("interface", "prelude")),
152
+ ...("HashMap HashSet BTreeMap BTreeSet VecDeque BinaryHeap").split(" ").map(kw("type", "std::collections")),
153
+ ...("Rc RefCell Cell Arc Mutex Ordering Display Formatter").split(" ").map(kw("type", "std")),
154
+ ...("std core alloc").split(" ").map(kw("namespace"))
155
+ ];
156
+ const macro = (template, label) => autocomplete.snippetCompletion(template, { label, type: "function", detail: "macro" });
157
+ /**
158
+ Completions for the macros in the standard library that programs
159
+ use most.
160
+ */
161
+ const macros = [
162
+ macro("println!(\"${}\")", "println!"),
163
+ macro("print!(\"${}\")", "print!"),
164
+ macro("eprintln!(\"${}\")", "eprintln!"),
165
+ macro("eprint!(\"${}\")", "eprint!"),
166
+ macro("format!(\"${}\")", "format!"),
167
+ macro("write!(${f}, \"${}\")", "write!"),
168
+ macro("writeln!(${f}, \"${}\")", "writeln!"),
169
+ macro("vec![${}]", "vec!"),
170
+ macro("panic!(\"${}\")", "panic!"),
171
+ macro("assert!(${})", "assert!"),
172
+ macro("assert_eq!(${left}, ${right})", "assert_eq!"),
173
+ macro("assert_ne!(${left}, ${right})", "assert_ne!"),
174
+ macro("debug_assert!(${})", "debug_assert!"),
175
+ macro("matches!(${value}, ${pattern})", "matches!"),
176
+ macro("dbg!(${})", "dbg!"),
177
+ macro("todo!()", "todo!"),
178
+ macro("unimplemented!()", "unimplemented!"),
179
+ macro("unreachable!()", "unreachable!")
180
+ ];
181
+ /**
182
+ Methods from the standard library that are common enough to offer
183
+ after a `.`, whatever the type of the value before it.
184
+ */
185
+ const commonMethods = ("abs all any as_bytes as_ref as_str binary_search bytes chain char_indices chars chunks clone cloned " +
186
+ "cmp collect contains contains_key copied count dedup ends_with entry enumerate eq expect extend " +
187
+ "filter filter_map find first flat_map flatten fold for_each get get_mut insert into_iter is_alphabetic " +
188
+ "is_ascii_digit is_digit is_empty is_err is_none is_numeric is_ok is_some is_whitespace iter iter_mut " +
189
+ "join keys last len lines map map_err max max_by_key min min_by_key next nth ok ok_or or_insert parse " +
190
+ "peekable pop position pow product push push_str remove replace rev skip sort sort_by sort_by_key " +
191
+ "sort_unstable split split_whitespace starts_with step_by sum take take_while to_ascii_lowercase " +
192
+ "to_ascii_uppercase to_digit to_lowercase to_owned to_string to_uppercase to_vec trim unwrap unwrap_or " +
193
+ "unwrap_or_default unwrap_or_else values windows zip").split(" ").map(kw("method", "std"));
194
+ const ScopeNodes = new Set([
195
+ "SourceFile", "Block", "DeclarationList",
196
+ "FunctionItem", "ClosureExpression", "ImplItem", "TraitItem",
197
+ "ForExpression", "MatchArm", "IfExpression", "WhileExpression"
198
+ ]);
199
+ const ItemTypes = {
200
+ FunctionItem: ["BoundIdentifier", "function"],
201
+ StructItem: ["TypeIdentifier", "class"],
202
+ UnionItem: ["TypeIdentifier", "class"],
203
+ EnumItem: ["TypeIdentifier", "enum"],
204
+ TraitItem: ["TypeIdentifier", "interface"],
205
+ TypeItem: ["TypeIdentifier", "type"],
206
+ ConstItem: ["BoundIdentifier", "constant"],
207
+ StaticItem: ["BoundIdentifier", "variable"],
208
+ ModItem: ["BoundIdentifier", "namespace"],
209
+ ExternCrateDeclaration: ["BoundIdentifier", "namespace"]
210
+ };
211
+ function name(doc, node) {
212
+ return node ? doc.sliceString(node.from, node.to) : "";
213
+ }
214
+ const isValueName = (name) => /^[a-z_]/.test(name);
215
+ // Collect the names bound by a pattern. Names that start with a capital
216
+ // letter, such as `None` in `match x { None => ... }`, refer to existing
217
+ // constants or variants, so they are skipped.
218
+ function patternNames(doc, pattern, add) {
219
+ if (pattern.name == "BoundIdentifier") {
220
+ let label = name(doc, pattern);
221
+ if (isValueName(label))
222
+ add(label);
223
+ }
224
+ else if (pattern.name != "MacroPattern" && pattern.name != "ScopedIdentifier") {
225
+ for (let ch = pattern.firstChild; ch; ch = ch.nextSibling)
226
+ patternNames(doc, ch, add);
227
+ }
228
+ }
229
+ function isPattern(node) {
230
+ return node.type.is("Pattern");
231
+ }
232
+ function typeParams(doc, node, defs) {
233
+ let list = node.getChild("TypeParamList");
234
+ if (!list)
235
+ return;
236
+ for (let ch = list.firstChild; ch; ch = ch.nextSibling) {
237
+ let id = ch.name == "TypeIdentifier" ? ch
238
+ : ch.name == "ConstParameter" ? ch.getChild("BoundIdentifier")
239
+ : ch.getChild("TypeIdentifier");
240
+ if (id)
241
+ defs.push({ label: name(doc, id), type: ch.name == "ConstParameter" ? "constant" : "type",
242
+ from: node.from, to: node.to });
243
+ }
244
+ }
245
+ function paramNames(doc, list, scope, defs) {
246
+ if (!list)
247
+ return;
248
+ for (let param of list.getChildren("Parameter")) {
249
+ for (let ch = param.firstChild; ch; ch = ch.nextSibling)
250
+ if (isPattern(ch)) {
251
+ patternNames(doc, ch, label => defs.push({ label, type: "variable", from: scope.from, to: scope.to }));
252
+ break;
253
+ }
254
+ }
255
+ }
256
+ // Names bound by `if let` and `while let`, which are visible in the
257
+ // first block only.
258
+ function letCondNames(doc, node, defs) {
259
+ let block = node.getChild("Block");
260
+ if (!block)
261
+ return;
262
+ let lets = node.getChildren("LetDeclaration");
263
+ let chain = node.getChild("LetChain");
264
+ if (chain)
265
+ lets = lets.concat(chain.getChildren("LetDeclaration"));
266
+ for (let decl of lets) {
267
+ for (let ch = decl.firstChild; ch; ch = ch.nextSibling)
268
+ if (isPattern(ch)) {
269
+ patternNames(doc, ch, label => defs.push({ label, type: "variable", from: block.from, to: block.to }));
270
+ break;
271
+ }
272
+ }
273
+ }
274
+ function itemNames(doc, scope, defs) {
275
+ for (let ch = scope.firstChild; ch; ch = ch.nextSibling) {
276
+ let item = ItemTypes[ch.name];
277
+ if (item) {
278
+ let id = ch.getChild(item[0]);
279
+ if (id)
280
+ defs.push({ label: name(doc, id), type: item[1], from: scope.from, to: scope.to });
281
+ }
282
+ else if (ch.name == "MacroDefinition") {
283
+ let id = ch.getChild("Identifier");
284
+ if (id)
285
+ defs.push({ label: name(doc, id) + "!", type: "function", from: scope.from, to: scope.to });
286
+ }
287
+ else if (ch.name == "UseDeclaration") {
288
+ let cur = ch.cursor();
289
+ while (cur.next() && cur.from < ch.to)
290
+ if (cur.name == "BoundIdentifier") {
291
+ let label = doc.sliceString(cur.from, cur.to);
292
+ defs.push({ label, type: isValueName(label) ? "namespace" : "type", from: scope.from, to: scope.to });
293
+ }
294
+ }
295
+ else if (ch.name == "LetDeclaration") {
296
+ let decl = ch;
297
+ for (let p = decl.firstChild; p; p = p.nextSibling)
298
+ if (isPattern(p)) {
299
+ patternNames(doc, p, label => defs.push({ label, type: "variable", from: decl.to, to: scope.to }));
300
+ break;
301
+ }
302
+ }
303
+ }
304
+ }
305
+ const scopeCache = new common.NodeWeakMap();
306
+ function getScope(doc, node) {
307
+ var _a;
308
+ let cached = scopeCache.get(node);
309
+ if (cached)
310
+ return cached;
311
+ let defs = [];
312
+ switch (node.name) {
313
+ case "SourceFile":
314
+ case "Block":
315
+ itemNames(doc, node, defs);
316
+ break;
317
+ case "DeclarationList":
318
+ // The items in an impl or trait body are reached through `Self::`
319
+ // or `.`, so only a module body adds names to the scope.
320
+ if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) == "ModItem")
321
+ itemNames(doc, node, defs);
322
+ break;
323
+ case "FunctionItem":
324
+ typeParams(doc, node, defs);
325
+ paramNames(doc, node.getChild("ParamList"), node, defs);
326
+ break;
327
+ case "ClosureExpression":
328
+ paramNames(doc, node.getChild("ParamList"), node, defs);
329
+ break;
330
+ case "ImplItem":
331
+ case "TraitItem":
332
+ typeParams(doc, node, defs);
333
+ break;
334
+ case "ForExpression": {
335
+ let block = node.getChild("Block");
336
+ for (let ch = node.firstChild; ch && block; ch = ch.nextSibling)
337
+ if (isPattern(ch)) {
338
+ patternNames(doc, ch, label => defs.push({ label, type: "variable", from: block.from, to: block.to }));
339
+ break;
340
+ }
341
+ break;
342
+ }
343
+ case "MatchArm":
344
+ for (let ch = node.firstChild; ch; ch = ch.nextSibling)
345
+ if (isPattern(ch)) {
346
+ patternNames(doc, ch, label => defs.push({ label, type: "variable", from: node.from, to: node.to }));
347
+ break;
348
+ }
349
+ break;
350
+ case "IfExpression":
351
+ case "WhileExpression":
352
+ letCondNames(doc, node, defs);
353
+ break;
354
+ }
355
+ scopeCache.set(node, defs);
356
+ return defs;
357
+ }
358
+ // The name of the type an impl block is for: `Clock` in both
359
+ // `impl Clock` and `impl fmt::Display for Clock`.
360
+ function implTarget(doc, impl) {
361
+ let body = impl.getChild("DeclarationList");
362
+ for (let ch = body === null || body === void 0 ? void 0 : body.prevSibling; ch; ch = ch.prevSibling) {
363
+ if (ch.name == "WhereClause")
364
+ continue;
365
+ let id = ch.name == "TypeIdentifier" ? ch : ch.getChild("TypeIdentifier");
366
+ if (!id && ch.name == "ScopedTypeIdentifier")
367
+ id = ch.lastChild;
368
+ return id ? name(doc, id) : "";
369
+ }
370
+ return "";
371
+ }
372
+ const memberCache = new common.NodeWeakMap();
373
+ function getMembers(doc, top) {
374
+ var _a;
375
+ let cached = memberCache.get(top);
376
+ if (cached)
377
+ return cached;
378
+ let fields = [], methods = [], paths = Object.create(null);
379
+ let addPath = (type, option) => (paths[type] || (paths[type] = [])).push(option);
380
+ let cur = top.cursor();
381
+ while (cur.next()) {
382
+ if (cur.name == "FieldDeclaration") {
383
+ let id = cur.node.getChild("FieldIdentifier");
384
+ if (id)
385
+ fields.push({ label: name(doc, id), type: "property" });
386
+ }
387
+ else if (cur.name == "EnumItem") {
388
+ let enumName = name(doc, cur.node.getChild("TypeIdentifier"));
389
+ let list = cur.node.getChild("EnumVariantList");
390
+ if (list)
391
+ for (let v of list.getChildren("EnumVariant"))
392
+ addPath(enumName, { label: name(doc, v.getChild("Identifier")), type: "enum" });
393
+ }
394
+ else if (cur.name == "ImplItem" || cur.name == "TraitItem") {
395
+ let owner = cur.name == "ImplItem" ? implTarget(doc, cur.node) : name(doc, cur.node.getChild("TypeIdentifier"));
396
+ let body = cur.node.getChild("DeclarationList");
397
+ if (body)
398
+ for (let ch = body.firstChild; ch; ch = ch.nextSibling) {
399
+ if (ch.name == "FunctionItem") {
400
+ let label = name(doc, ch.getChild("BoundIdentifier"));
401
+ let isMethod = !!((_a = ch.getChild("ParamList")) === null || _a === void 0 ? void 0 : _a.getChild("SelfParameter"));
402
+ if (isMethod)
403
+ methods.push({ label, type: "method" });
404
+ addPath(owner, { label, type: isMethod ? "method" : "function" });
405
+ }
406
+ else if (ch.name == "ConstItem") {
407
+ addPath(owner, { label: name(doc, ch.getChild("BoundIdentifier")), type: "constant" });
408
+ }
409
+ }
410
+ }
411
+ }
412
+ let result = { fields, methods, paths };
413
+ memberCache.set(top, result);
414
+ return result;
415
+ }
416
+ function dedupe(options) {
417
+ let seen = new Set();
418
+ return options.filter(o => !seen.has(o.label) && !!seen.add(o.label));
419
+ }
420
+ // Nodes where completion would only get in the way: inside literals and
421
+ // comments, and where the user is typing a new name.
422
+ const dontComplete = [
423
+ "String", "RawString", "Char", "LineComment", "BlockComment", "Integer", "Float", "Lifetime",
424
+ "BoundIdentifier", "FieldIdentifier"
425
+ ];
426
+ const DefinitionParents = new Set(["StructItem", "UnionItem", "EnumItem", "TraitItem", "TypeItem",
427
+ "AssociatedType", "TypeParamList", "EnumVariant", "MacroDefinition"]);
428
+ const PatternParents = new Set(["MatchArm", "TuplePattern", "OrPattern", "SlicePattern"]);
429
+ function inDontComplete(doc, node) {
430
+ var _a;
431
+ if (dontComplete.indexOf(node.name) > -1) {
432
+ // A field after `.` is a FieldIdentifier too, and is completed with members.
433
+ if (node.name == "FieldIdentifier" && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) == "FieldExpression")
434
+ return false;
435
+ // A capitalised name in a pattern, such as `None` in a match arm,
436
+ // refers to an existing constant or variant.
437
+ if (node.name == "BoundIdentifier" && !isValueName(name(doc, node)) && node.parent &&
438
+ PatternParents.has(node.parent.name))
439
+ return false;
440
+ return true;
441
+ }
442
+ if ((node.name == "TypeIdentifier" || node.name == "Identifier") && node.parent &&
443
+ DefinitionParents.has(node.parent.name))
444
+ return true;
445
+ for (let p = node; p; p = p.parent)
446
+ if (p.name == "LineComment" || p.name == "BlockComment" || p.name == "String" || p.name == "RawString")
447
+ return true;
448
+ return false;
449
+ }
450
+ const Identifier = /^[\w\xa1-￿]*$/;
451
+ // Describe what comes before the word being typed: a `.` (member access),
452
+ // a `Name::` path, or nothing.
453
+ function prefixOf(context, wordFrom) {
454
+ let before = context.state.sliceDoc(Math.max(0, wordFrom - 100), wordFrom);
455
+ if (/(^|[^.])\.\s*$/.test(before))
456
+ return { kind: "member", path: "" };
457
+ let path = /(\w+)\s*::\s*$/.exec(before);
458
+ if (path)
459
+ return { kind: "path", path: path[1] };
460
+ if (/::\s*$/.test(before))
461
+ return { kind: "path", path: "" };
462
+ return null;
463
+ }
464
+ /**
465
+ Completion source that looks up names declared in Rust code. It
466
+ offers names in scope at the cursor, fields and methods after `.`,
467
+ and variants and associated functions after `Type::`.
468
+ */
469
+ const localCompletionSource = (context) => {
470
+ let tree = language.syntaxTree(context.state);
471
+ let inner = tree.resolveInner(context.pos, -1);
472
+ if (inDontComplete(context.state.doc, inner))
473
+ return null;
474
+ let word = context.matchBefore(/[\w\xa1-￿]+/);
475
+ let from = word ? word.from : context.pos;
476
+ let prefix = prefixOf(context, from);
477
+ if (!word && !prefix && !context.explicit)
478
+ return null;
479
+ let doc = context.state.doc;
480
+ if ((prefix === null || prefix === void 0 ? void 0 : prefix.kind) == "member") {
481
+ let { fields, methods } = getMembers(doc, tree.topNode);
482
+ return { from, options: dedupe(fields.concat(methods, commonMethods)), validFor: Identifier };
483
+ }
484
+ if ((prefix === null || prefix === void 0 ? void 0 : prefix.kind) == "path") {
485
+ let type = prefix.path;
486
+ if (type == "Self") {
487
+ for (let p = inner; p; p = p.parent)
488
+ if (p.name == "ImplItem") {
489
+ type = implTarget(doc, p);
490
+ break;
491
+ }
492
+ else if (p.name == "TraitItem") {
493
+ type = name(doc, p.getChild("TypeIdentifier"));
494
+ break;
495
+ }
496
+ }
497
+ let options = getMembers(doc, tree.topNode).paths[type];
498
+ return options ? { from, options: dedupe(options), validFor: Identifier } : null;
499
+ }
500
+ let options = [];
501
+ for (let pos = inner; pos; pos = pos.parent) {
502
+ if (!ScopeNodes.has(pos.name))
503
+ continue;
504
+ for (let def of getScope(doc, pos))
505
+ if (def.from <= context.pos && def.to >= context.pos)
506
+ options.push({ label: def.label, type: def.type });
507
+ }
508
+ return { from, options: dedupe(options), validFor: Identifier };
509
+ };
510
+ const fromList = autocomplete.completeFromList(snippets.concat(builtins, macros));
511
+ /**
512
+ Completion source for Rust's keywords, built-in and prelude names,
513
+ standard macros and snippets. It stays quiet inside strings and
514
+ comments, after `.` and in `::` paths.
515
+ */
516
+ const keywordCompletionSource = context => {
517
+ let inner = language.syntaxTree(context.state).resolveInner(context.pos, -1);
518
+ if (inDontComplete(context.state.doc, inner))
519
+ return null;
520
+ let word = context.matchBefore(/[\w\xa1-￿!]+/);
521
+ if (prefixOf(context, word ? word.from : context.pos))
522
+ return null;
523
+ return fromList(context);
524
+ };
525
+
526
+ /**
527
+ A syntax provider based on the [Lezer Rust
528
+ parser](https://code.haverbeke.berlin/lezer/rust), extended with
529
+ highlighting and indentation information.
530
+ */
531
+ const rustLanguage = language.LRLanguage.define({
532
+ name: "rust",
533
+ parser: rust$1.parser.configure({
534
+ props: [
535
+ language.indentNodeProp.add({
536
+ IfExpression: language.continuedIndent({ except: /^\s*({|else\b)/ }),
537
+ "String BlockComment": () => null,
538
+ "AttributeItem": cx => cx.continue(),
539
+ "Statement MatchArm": language.continuedIndent()
540
+ }),
541
+ language.foldNodeProp.add(type => {
542
+ if (/(Block|edTokens|List)$/.test(type.name))
543
+ return language.foldInside;
544
+ if (type.name == "BlockComment")
545
+ return tree => ({ from: tree.from + 2, to: tree.to - 2 });
546
+ return undefined;
547
+ })
548
+ ]
549
+ }),
550
+ languageData: {
551
+ commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
552
+ indentOnInput: /^\s*(?:\{|\})$/,
553
+ closeBrackets: { stringPrefixes: ["b", "r", "br"] }
554
+ }
555
+ });
556
+ /**
557
+ Rust language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-rust.snippets),
558
+ keyword and local name completion.
559
+ */
560
+ function rust() {
561
+ return new language.LanguageSupport(rustLanguage, [
562
+ rustLanguage.data.of({ autocomplete: keywordCompletionSource }),
563
+ rustLanguage.data.of({ autocomplete: localCompletionSource })
564
+ ]);
565
+ }
566
+
567
+ exports.builtins = builtins;
568
+ exports.commonMethods = commonMethods;
569
+ exports.keywordCompletionSource = keywordCompletionSource;
570
+ exports.localCompletionSource = localCompletionSource;
571
+ exports.macros = macros;
572
+ exports.rust = rust;
573
+ exports.rustLanguage = rustLanguage;
574
+ exports.snippets = snippets;
@@ -0,0 +1,51 @@
1
+ import { LanguageSupport, LRLanguage } from '@codemirror/language';
2
+ import { Completion, CompletionSource } from '@codemirror/autocomplete';
3
+
4
+ /**
5
+ A collection of Rust-related
6
+ [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
7
+ */
8
+ declare const snippets: readonly Completion[];
9
+
10
+ /**
11
+ Rust's keywords, primitive types and the names a program can use
12
+ without importing them (the prelude), plus some common types from
13
+ `std`.
14
+ */
15
+ declare const builtins: readonly Completion[];
16
+ /**
17
+ Completions for the macros in the standard library that programs
18
+ use most.
19
+ */
20
+ declare const macros: readonly Completion[];
21
+ /**
22
+ Methods from the standard library that are common enough to offer
23
+ after a `.`, whatever the type of the value before it.
24
+ */
25
+ declare const commonMethods: readonly Completion[];
26
+ /**
27
+ Completion source that looks up names declared in Rust code. It
28
+ offers names in scope at the cursor, fields and methods after `.`,
29
+ and variants and associated functions after `Type::`.
30
+ */
31
+ declare const localCompletionSource: CompletionSource;
32
+ /**
33
+ Completion source for Rust's keywords, built-in and prelude names,
34
+ standard macros and snippets. It stays quiet inside strings and
35
+ comments, after `.` and in `::` paths.
36
+ */
37
+ declare const keywordCompletionSource: CompletionSource;
38
+
39
+ /**
40
+ A syntax provider based on the [Lezer Rust
41
+ parser](https://code.haverbeke.berlin/lezer/rust), extended with
42
+ highlighting and indentation information.
43
+ */
44
+ declare const rustLanguage: LRLanguage;
45
+ /**
46
+ Rust language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-rust.snippets),
47
+ keyword and local name completion.
48
+ */
49
+ declare function rust(): LanguageSupport;
50
+
51
+ export { builtins, commonMethods, keywordCompletionSource, localCompletionSource, macros, rust, rustLanguage, snippets };
@@ -0,0 +1,51 @@
1
+ import { LanguageSupport, LRLanguage } from '@codemirror/language';
2
+ import { Completion, CompletionSource } from '@codemirror/autocomplete';
3
+
4
+ /**
5
+ A collection of Rust-related
6
+ [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
7
+ */
8
+ declare const snippets: readonly Completion[];
9
+
10
+ /**
11
+ Rust's keywords, primitive types and the names a program can use
12
+ without importing them (the prelude), plus some common types from
13
+ `std`.
14
+ */
15
+ declare const builtins: readonly Completion[];
16
+ /**
17
+ Completions for the macros in the standard library that programs
18
+ use most.
19
+ */
20
+ declare const macros: readonly Completion[];
21
+ /**
22
+ Methods from the standard library that are common enough to offer
23
+ after a `.`, whatever the type of the value before it.
24
+ */
25
+ declare const commonMethods: readonly Completion[];
26
+ /**
27
+ Completion source that looks up names declared in Rust code. It
28
+ offers names in scope at the cursor, fields and methods after `.`,
29
+ and variants and associated functions after `Type::`.
30
+ */
31
+ declare const localCompletionSource: CompletionSource;
32
+ /**
33
+ Completion source for Rust's keywords, built-in and prelude names,
34
+ standard macros and snippets. It stays quiet inside strings and
35
+ comments, after `.` and in `::` paths.
36
+ */
37
+ declare const keywordCompletionSource: CompletionSource;
38
+
39
+ /**
40
+ A syntax provider based on the [Lezer Rust
41
+ parser](https://code.haverbeke.berlin/lezer/rust), extended with
42
+ highlighting and indentation information.
43
+ */
44
+ declare const rustLanguage: LRLanguage;
45
+ /**
46
+ Rust language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-rust.snippets),
47
+ keyword and local name completion.
48
+ */
49
+ declare function rust(): LanguageSupport;
50
+
51
+ export { builtins, commonMethods, keywordCompletionSource, localCompletionSource, macros, rust, rustLanguage, snippets };