@exercism/codemirror-lang-java 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/CHANGELOG.md ADDED
@@ -0,0 +1,70 @@
1
+ ## 1.0.1
2
+
3
+ The README is restructured. This release is the first published from GitHub Actions, with npm provenance.
4
+
5
+ ## 1.0.0
6
+
7
+ This is Exercism's first release of the package, published as
8
+ `@exercism/codemirror-lang-java`. It adds completion of keywords, common
9
+ classes, snippets and the names in scope, and uses Exercism's fork of the
10
+ grammar, `@exercism/lezer-java`.
11
+
12
+ ## 6.0.2 (2025-06-19)
13
+
14
+ ### Bug fixes
15
+
16
+ Add a .d.cts file to make TypeScript happy.
17
+ ## 6.0.1 (2022-10-24)
18
+
19
+ ### Bug fixes
20
+
21
+ Fix (non-)auto indentation in template strings and comments.
22
+
23
+ ## 6.0.0 (2022-06-08)
24
+
25
+ ### Breaking changes
26
+
27
+ Update dependencies to 6.0.0
28
+
29
+ ## 0.20.1 (2022-05-29)
30
+
31
+ ### Bug fixes
32
+
33
+ Fix indentation of braced blocks.
34
+
35
+ ## 0.20.0 (2022-04-20)
36
+
37
+ ### Breaking changes
38
+
39
+ Update dependencies to 0.20.0
40
+
41
+ ## 0.19.1 (2021-08-11)
42
+
43
+ ### Bug fixes
44
+
45
+ Fix incorrect versions for @lezer dependencies.
46
+
47
+ ## 0.19.0 (2021-08-11)
48
+
49
+ ### Breaking changes
50
+
51
+ Update dependencies to 0.19.0
52
+
53
+ ## 0.18.0 (2021-03-03)
54
+
55
+ ### Breaking changes
56
+
57
+ Update dependencies to 0.18.
58
+
59
+ ## 0.17.1 (2021-01-06)
60
+
61
+ ### New features
62
+
63
+ The package now also exports a CommonJS module.
64
+
65
+ ## 0.17.0 (2020-12-29)
66
+
67
+ ### Breaking changes
68
+
69
+ First numbered release.
70
+
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ <!-- NOTE: README.md is generated from src/README.md -->
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # @codemirror/lang-java [![NPM version](https://img.shields.io/npm/v/@codemirror/lang-java.svg)](https://www.npmjs.org/package/@codemirror/lang-java)
4
+
5
+ ## Exercism's fork
6
+
7
+ This is Exercism's fork of [@codemirror/lang-java](https://code.haverbeke.berlin/codemirror/lang-java).
8
+ Exercism uses it in the Java editor on [exercism.org](https://exercism.org).
9
+ It is published on npm as `@exercism/codemirror-lang-java`.
10
+ Our changes are on the `exercism` branch, and the `main` branch follows upstream.
11
+ Below this section, the README is upstream's.
12
+
13
+ The fork adds autocomplete to the upstream package:
14
+
15
+ - Java keywords, literals and primitive types.
16
+ - Common classes from `java.lang`, `java.util`, `java.util.stream` and `java.util.function`.
17
+ - Snippets for `main`, methods, classes, interfaces, enums, records, `if`, the loops, `switch`, `try` and `throw`.
18
+ - Names declared in the file that are in scope at the cursor: classes, methods, fields, enum constants, record components, type parameters, parameters, local variables, loop and catch variables, lambda parameters and pattern variables. A local variable is offered only after its declaration.
19
+
20
+ Completion offers nothing in strings and comments, while you type a new name, and after a `.` or `::`.
21
+
22
+ The package uses Exercism's fork of the grammar, `@exercism/lezer-java`, in place of `@lezer/java`. The fork parses nested generics (`Map<String, List<String>>`) and lets `to`, `with` and the other module declaration words be used as names.
23
+
24
+ ### Install
25
+
26
+ ```
27
+ npm install @exercism/codemirror-lang-java
28
+ ```
29
+
30
+ ### Building and testing
31
+
32
+ To build and test it from a checkout, run `npm install` (which also builds the package), then `npm test`.
33
+
34
+ ### Contributing
35
+
36
+ Contributions to this fork follow the Exercism [Code of Conduct](https://exercism.org/docs/using/legal/code-of-conduct).
37
+ Please read about how to [contribute to Exercism](https://exercism.org/docs/building).
38
+
39
+ ---
40
+
41
+ [ [**WEBSITE**](https://codemirror.net/) | [**ISSUES**](https://code.haverbeke.berlin/codemirror/dev/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://code.haverbeke.berlin/codemirror/lang-java/src/branch/main/CHANGELOG.md) ]
42
+
43
+ This package implements Java language support for the
44
+ [CodeMirror](https://codemirror.net/) code editor.
45
+
46
+ The [project page](https://codemirror.net/) has more information, a
47
+ number of [examples](https://codemirror.net/examples/) and the
48
+ [documentation](https://codemirror.net/docs/).
49
+
50
+ This code is released under an
51
+ [MIT license](https://code.haverbeke.berlin/codemirror/lang-java/tree/main/LICENSE).
52
+
53
+ We aim to be an inclusive, welcoming community. To make that explicit,
54
+ we have a [code of
55
+ conduct](http://contributor-covenant.org/version/1/1/0/) that applies
56
+ to communication around the project.
57
+
58
+ ## Usage
59
+
60
+ ```javascript
61
+ import {EditorView, basicSetup} from "codemirror"
62
+ import {java} from "@exercism/codemirror-lang-java"
63
+
64
+ const view = new EditorView({
65
+ parent: document.body,
66
+ doc: `public static void main(String[] args) {}`,
67
+ extensions: [basicSetup, java()]
68
+ })
69
+ ```
70
+
71
+ ## API Reference
72
+
73
+ <dl>
74
+ <dt id="user-content-java">
75
+ <code><strong><a href="#user-content-java">java</a></strong>() → <a href="https://codemirror.net/docs/ref#language.LanguageSupport">LanguageSupport</a></code></dt>
76
+
77
+ <dd><p>Java language support. Includes snippet, keyword, built-in class and local name completion.</p>
78
+ </dd>
79
+ <dt id="user-content-javalanguage">
80
+ <code><strong><a href="#user-content-javalanguage">javaLanguage</a></strong>: <a href="https://codemirror.net/docs/ref#language.LRLanguage">LRLanguage</a></code></dt>
81
+
82
+ <dd><p>A language provider based on the <a href="https://code.haverbeke.berlin/lezer/java">Lezer Java
83
+ parser</a>, extended with
84
+ highlighting and indentation information.</p>
85
+ </dd>
86
+ <dt id="user-content-snippets">
87
+ <code><strong><a href="#user-content-snippets">snippets</a></strong>: readonly <a href="https://codemirror.net/docs/ref#autocomplete.Completion">Completion</a>[]</code></dt>
88
+
89
+ <dd><p>A collection of Java-related <a href="https://codemirror.net/docs/ref#autocomplete.snippet">snippets</a>.</p>
90
+ </dd>
91
+ <dt id="user-content-builtins">
92
+ <code><strong><a href="#user-content-builtins">builtins</a></strong>: readonly <a href="https://codemirror.net/docs/ref#autocomplete.Completion">Completion</a>[]</code></dt>
93
+
94
+ <dd><p>Keywords, literals, primitive types and the commonly used classes
95
+ from <code>java.lang</code>, <code>java.util</code> and its subpackages.</p>
96
+ </dd>
97
+ <dt id="user-content-localcompletionsource">
98
+ <code><strong><a href="#user-content-localcompletionsource">localCompletionSource</a></strong>: <a href="https://codemirror.net/docs/ref#autocomplete.CompletionSource">CompletionSource</a></code></dt>
99
+
100
+ <dd><p>Completion source that looks up names declared in Java code
101
+ (classes, methods, fields, parameters and local variables) that
102
+ are in scope at the cursor.</p>
103
+ </dd>
104
+ </dl>
package/dist/index.cjs ADDED
@@ -0,0 +1,350 @@
1
+ 'use strict';
2
+
3
+ var lezerJava = require('@exercism/lezer-java');
4
+ var language = require('@codemirror/language');
5
+ var autocomplete = require('@codemirror/autocomplete');
6
+ var common = require('@lezer/common');
7
+
8
+ /**
9
+ A collection of Java-related [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
10
+ */
11
+ const snippets = [
12
+ autocomplete.snippetCompletion("public static void main(String[] args) {\n\t${}\n}", {
13
+ label: "main",
14
+ detail: "method",
15
+ type: "keyword"
16
+ }),
17
+ autocomplete.snippetCompletion("public ${void} ${name}(${params}) {\n\t${}\n}", {
18
+ label: "public",
19
+ detail: "method declaration",
20
+ type: "keyword"
21
+ }),
22
+ autocomplete.snippetCompletion("private ${void} ${name}(${params}) {\n\t${}\n}", {
23
+ label: "private",
24
+ detail: "method declaration",
25
+ type: "keyword"
26
+ }),
27
+ autocomplete.snippetCompletion("class ${Name} {\n\t${}\n}", {
28
+ label: "class",
29
+ detail: "definition",
30
+ type: "keyword"
31
+ }),
32
+ autocomplete.snippetCompletion("interface ${Name} {\n\t${}\n}", {
33
+ label: "interface",
34
+ detail: "definition",
35
+ type: "keyword"
36
+ }),
37
+ autocomplete.snippetCompletion("enum ${Name} {\n\t${}\n}", {
38
+ label: "enum",
39
+ detail: "definition",
40
+ type: "keyword"
41
+ }),
42
+ autocomplete.snippetCompletion("record ${Name}(${fields}) {\n\t${}\n}", {
43
+ label: "record",
44
+ detail: "definition",
45
+ type: "keyword"
46
+ }),
47
+ autocomplete.snippetCompletion("if (${condition}) {\n\t${}\n}", {
48
+ label: "if",
49
+ detail: "block",
50
+ type: "keyword"
51
+ }),
52
+ autocomplete.snippetCompletion("if (${condition}) {\n\t${}\n} else {\n\t\n}", {
53
+ label: "if",
54
+ detail: "/ else block",
55
+ type: "keyword"
56
+ }),
57
+ autocomplete.snippetCompletion("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", {
58
+ label: "for",
59
+ detail: "loop",
60
+ type: "keyword"
61
+ }),
62
+ autocomplete.snippetCompletion("for (${var} ${item} : ${items}) {\n\t${}\n}", {
63
+ label: "for",
64
+ detail: "each loop",
65
+ type: "keyword"
66
+ }),
67
+ autocomplete.snippetCompletion("while (${condition}) {\n\t${}\n}", {
68
+ label: "while",
69
+ detail: "loop",
70
+ type: "keyword"
71
+ }),
72
+ autocomplete.snippetCompletion("do {\n\t${}\n} while (${condition});", {
73
+ label: "do",
74
+ detail: "loop",
75
+ type: "keyword"
76
+ }),
77
+ autocomplete.snippetCompletion("switch (${value}) {\n\tcase ${a}:\n\t\t${}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n}", {
78
+ label: "switch",
79
+ detail: "statement",
80
+ type: "keyword"
81
+ }),
82
+ autocomplete.snippetCompletion("try {\n\t${}\n} catch (${Exception} ${e}) {\n\t\n}", {
83
+ label: "try",
84
+ detail: "/ catch block",
85
+ type: "keyword"
86
+ }),
87
+ autocomplete.snippetCompletion("throw new ${IllegalArgumentException}(${message});", {
88
+ label: "throw",
89
+ detail: "exception",
90
+ type: "keyword"
91
+ }),
92
+ autocomplete.snippetCompletion("System.out.println(${});", {
93
+ label: "println",
94
+ detail: "print a line",
95
+ type: "function"
96
+ })
97
+ ];
98
+
99
+ const cache = new common.NodeWeakMap();
100
+ const ScopeNodes = new Set([
101
+ "Program",
102
+ "ClassDeclaration", "InterfaceDeclaration", "EnumDeclaration", "RecordDeclaration",
103
+ "ClassBody", "InterfaceBody", "EnumBody", "RecordBody", "AnnotationTypeBody",
104
+ "MethodDeclaration", "ConstructorDeclaration", "ConstructorBody",
105
+ "Block", "SwitchBlock", "LambdaExpression",
106
+ "ForStatement", "EnhancedForStatement", "CatchClause", "TryWithResourcesStatement"
107
+ ]);
108
+ function child(node, name) {
109
+ let found = [];
110
+ for (let cur = node.firstChild; cur; cur = cur.nextSibling)
111
+ if (cur.name == name)
112
+ found.push(cur);
113
+ return found;
114
+ }
115
+ // Defines the declaration's own name. The declaration is a scope of
116
+ // its own, so the walk stops here and its contents are gathered when
117
+ // the cursor is inside it.
118
+ function named(type) {
119
+ return (node, def) => {
120
+ for (let d of child(node, "Definition"))
121
+ def(d, type);
122
+ return true;
123
+ };
124
+ }
125
+ // Defines each name in `int a = 1, b;`. With `ordered`, the names
126
+ // only appear after their declarator.
127
+ function declarators(type, ordered) {
128
+ return (node, def) => {
129
+ for (let decl of child(node, "VariableDeclarator"))
130
+ for (let d of child(decl, "Definition"))
131
+ def(d, type, ordered ? decl.to : -1);
132
+ return true;
133
+ };
134
+ }
135
+ function parameter(node, def) {
136
+ for (let d of child(node, "Definition"))
137
+ def(d, "variable");
138
+ for (let decl of child(node, "VariableDeclarator"))
139
+ for (let d of child(decl, "Definition"))
140
+ def(d, "variable");
141
+ return true;
142
+ }
143
+ const gatherCompletions = {
144
+ ClassDeclaration: named("class"),
145
+ InterfaceDeclaration: named("interface"),
146
+ EnumDeclaration: named("enum"),
147
+ RecordDeclaration: named("class"),
148
+ RecordComponent: named("property"),
149
+ CompactConstructorDeclaration: () => true,
150
+ AnnotationTypeDeclaration: () => true,
151
+ MethodDeclaration: named("method"),
152
+ ConstructorDeclaration: () => true,
153
+ EnumConstant: named("constant"),
154
+ TypeParameter: named("type"),
155
+ FieldDeclaration: declarators("property", false),
156
+ ConstantDeclaration: declarators("constant", false),
157
+ LocalVariableDeclaration: declarators("variable", true),
158
+ FormalParameter: parameter,
159
+ SpreadParameter: parameter,
160
+ CatchFormalParameter: parameter,
161
+ Resource: parameter,
162
+ // The variable of `for (String s : list)`. A classic for loop's
163
+ // ForSpec holds a LocalVariableDeclaration, which the walk finds next.
164
+ ForSpec: (node, def) => { for (let d of child(node, "Definition"))
165
+ def(d, "variable"); },
166
+ InferredParameters: parameter,
167
+ // `o instanceof String s` defines `s` from there on.
168
+ TypePattern: (node, def) => {
169
+ for (let d of child(node, "Definition"))
170
+ def(d, "variable", node.to);
171
+ return true;
172
+ },
173
+ __proto__: null
174
+ };
175
+ function getScope(doc, node) {
176
+ let cached = cache.get(node);
177
+ if (cached)
178
+ return cached;
179
+ let names = [], top = true;
180
+ let def = (node, type, after = -1) => {
181
+ names.push({ completion: { label: doc.sliceString(node.from, node.to), type }, after });
182
+ };
183
+ // A lambda's single parameter (`x -> x + 1`) is a bare Definition.
184
+ if (node.name == "LambdaExpression")
185
+ for (let d of child(node, "Definition"))
186
+ def(d, "variable");
187
+ node.cursor(common.IterMode.IncludeAnonymous).iterate(cur => {
188
+ if (top) {
189
+ top = false;
190
+ }
191
+ else if (cur.name) {
192
+ let gather = gatherCompletions[cur.name];
193
+ if (gather && gather(cur.node, def) || ScopeNodes.has(cur.name))
194
+ return false;
195
+ }
196
+ else if (cur.to - cur.from > 8192) {
197
+ // Allow caching for bigger internal nodes
198
+ for (let c of getScope(doc, cur.node))
199
+ names.push(c);
200
+ return false;
201
+ }
202
+ });
203
+ cache.set(node, names);
204
+ return names;
205
+ }
206
+ const Identifier = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;
207
+ const dontComplete = [
208
+ "StringLiteral", "CharacterLiteral", "TextBlock", "LineComment", "BlockComment",
209
+ "Definition", "Label", ".", "::"
210
+ ];
211
+ // `foo.bar|` or `Foo::bar|`: the name after the dot belongs to
212
+ // another object, so names from this file don't apply.
213
+ function inMemberAccess(node) {
214
+ let prev = node.prevSibling;
215
+ return !!prev && (prev.name == "." || prev.name == "::");
216
+ }
217
+ // While someone types the type of a new field (`class A { Str| }`),
218
+ // the parser reads the half-typed word as the name of a constructor
219
+ // that has no parameters yet. That word is a type, so we complete it.
220
+ function isHalfTypedMember(node) {
221
+ var _a, _b;
222
+ return node.name == "Definition" && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) == "ConstructorDeclaration" &&
223
+ !!((_b = node.nextSibling) === null || _b === void 0 ? void 0 : _b.type.isError);
224
+ }
225
+ // Finds the node before the cursor, and whether completion applies there.
226
+ function wordBefore(context) {
227
+ var _a;
228
+ let inner = language.syntaxTree(context.state).resolveInner(context.pos, -1);
229
+ let word = inner.name == "MethodName" ? (_a = inner.firstChild) !== null && _a !== void 0 ? _a : inner : inner;
230
+ let member = inMemberAccess(word) || !!word.parent && word.parent.name == "MethodName" && inMemberAccess(word.parent);
231
+ let skip = member || (dontComplete.indexOf(inner.name) > -1 && !isHalfTypedMember(inner));
232
+ return { inner, word, skip };
233
+ }
234
+ /**
235
+ Wraps a completion source so that it stays quiet in strings,
236
+ comments, new names and member names (`list.si|`).
237
+ */
238
+ function ifInCode(source) {
239
+ return context => wordBefore(context).skip ? null : source(context);
240
+ }
241
+ /**
242
+ Completion source that looks up names declared in Java code
243
+ (classes, methods, fields, parameters and local variables) that
244
+ are in scope at the cursor.
245
+ */
246
+ const localCompletionSource = context => {
247
+ let { inner, word, skip } = wordBefore(context);
248
+ if (skip)
249
+ return null;
250
+ let isWord = word.name == "Identifier" || word.name == "TypeName" || isHalfTypedMember(word) ||
251
+ word.to - word.from < 20 && Identifier.test(context.state.sliceDoc(word.from, word.to));
252
+ if (!isWord && !context.explicit)
253
+ return null;
254
+ let options = [], seen = new Set();
255
+ for (let pos = inner; pos; pos = pos.parent) {
256
+ if (!ScopeNodes.has(pos.name))
257
+ continue;
258
+ for (let { completion, after } of getScope(context.state.doc, pos)) {
259
+ if (after >= context.pos || seen.has(completion.label))
260
+ continue;
261
+ seen.add(completion.label);
262
+ options.push(completion);
263
+ }
264
+ }
265
+ return {
266
+ options,
267
+ from: isWord ? word.from : context.pos,
268
+ validFor: Identifier
269
+ };
270
+ };
271
+
272
+ /**
273
+ A language provider based on Exercism's fork of the [Lezer Java
274
+ parser](https://code.haverbeke.berlin/lezer/java), extended with
275
+ highlighting and indentation information.
276
+ */
277
+ const javaLanguage = language.LRLanguage.define({
278
+ name: "java",
279
+ parser: lezerJava.parser.configure({
280
+ props: [
281
+ language.indentNodeProp.add({
282
+ IfStatement: language.continuedIndent({ except: /^\s*({|else\b)/ }),
283
+ TryStatement: language.continuedIndent({ except: /^\s*({|catch|finally)\b/ }),
284
+ LabeledStatement: language.flatIndent,
285
+ SwitchBlock: context => {
286
+ let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
287
+ return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
288
+ },
289
+ Block: language.delimitedIndent({ closing: "}" }),
290
+ BlockComment: () => null,
291
+ Statement: language.continuedIndent({ except: /^{/ })
292
+ }),
293
+ language.foldNodeProp.add({
294
+ ["Block SwitchBlock ClassBody ElementValueArrayInitializer ModuleBody EnumBody " +
295
+ "ConstructorBody InterfaceBody ArrayInitializer"]: language.foldInside,
296
+ BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
297
+ })
298
+ ]
299
+ }),
300
+ languageData: {
301
+ commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
302
+ indentOnInput: /^\s*(?:case |default:|\{|\})$/
303
+ }
304
+ });
305
+ let kw = (type, detail) => (label) => detail ? { label, type, detail } : { label, type };
306
+ const keywords = ("abstract assert break case catch class continue default do else enum extends final " +
307
+ "finally for if implements import instanceof interface native new package permits private protected " +
308
+ "public record return sealed static strictfp super switch synchronized this throw throws transient try " +
309
+ "var void volatile while yield").split(" ").map(kw("keyword"));
310
+ const literals = "true false null".split(" ").map(kw("constant"));
311
+ const primitives = "boolean byte char double float int long short".split(" ").map(kw("type"));
312
+ const javaLang = ("Boolean Byte Character CharSequence Class Comparable Double Enum Exception Float " +
313
+ "Integer Iterable Long Math Number Object Record Runnable Short String StringBuilder System Thread " +
314
+ "Throwable Void ArithmeticException ArrayIndexOutOfBoundsException ClassCastException " +
315
+ "IllegalArgumentException IllegalStateException IndexOutOfBoundsException NullPointerException " +
316
+ "NumberFormatException RuntimeException UnsupportedOperationException").split(" ").map(kw("class", "java.lang"));
317
+ const annotations = "Override Deprecated FunctionalInterface SuppressWarnings SafeVarargs"
318
+ .split(" ").map(kw("type", "annotation"));
319
+ const javaUtil = ("ArrayDeque ArrayList Arrays Collection Collections Comparator Deque HashMap HashSet " +
320
+ "Iterator LinkedHashMap LinkedHashSet LinkedList List Map Objects Optional PriorityQueue Queue Random " +
321
+ "Scanner Set SortedMap TreeMap TreeSet").split(" ").map(kw("class", "java.util"));
322
+ const javaUtilMore = [
323
+ ...("Collectors IntStream Stream".split(" ").map(kw("class", "java.util.stream"))),
324
+ ...("BiFunction Consumer Function Predicate Supplier".split(" ").map(kw("interface", "java.util.function")))
325
+ ];
326
+ /**
327
+ Keywords, literals, primitive types and the commonly used classes
328
+ from `java.lang`, `java.util` and its subpackages.
329
+ */
330
+ const builtins = keywords.concat(literals, primitives, javaLang, annotations, javaUtil, javaUtilMore);
331
+ /**
332
+ Java language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-java.snippets),
333
+ keyword, built-in class and local name completion.
334
+ */
335
+ function java() {
336
+ return new language.LanguageSupport(javaLanguage, [
337
+ javaLanguage.data.of({
338
+ autocomplete: ifInCode(autocomplete.completeFromList(snippets.concat(builtins)))
339
+ }),
340
+ javaLanguage.data.of({
341
+ autocomplete: localCompletionSource
342
+ })
343
+ ]);
344
+ }
345
+
346
+ exports.builtins = builtins;
347
+ exports.java = java;
348
+ exports.javaLanguage = javaLanguage;
349
+ exports.localCompletionSource = localCompletionSource;
350
+ exports.snippets = snippets;
@@ -0,0 +1,33 @@
1
+ import { LanguageSupport, LRLanguage } from '@codemirror/language';
2
+ import { Completion, CompletionSource } from '@codemirror/autocomplete';
3
+
4
+ /**
5
+ A collection of Java-related [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
6
+ */
7
+ declare const snippets: readonly Completion[];
8
+
9
+ /**
10
+ Completion source that looks up names declared in Java code
11
+ (classes, methods, fields, parameters and local variables) that
12
+ are in scope at the cursor.
13
+ */
14
+ declare const localCompletionSource: CompletionSource;
15
+
16
+ /**
17
+ A language provider based on Exercism's fork of the [Lezer Java
18
+ parser](https://code.haverbeke.berlin/lezer/java), extended with
19
+ highlighting and indentation information.
20
+ */
21
+ declare const javaLanguage: LRLanguage;
22
+ /**
23
+ Keywords, literals, primitive types and the commonly used classes
24
+ from `java.lang`, `java.util` and its subpackages.
25
+ */
26
+ declare const builtins: readonly Completion[];
27
+ /**
28
+ Java language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-java.snippets),
29
+ keyword, built-in class and local name completion.
30
+ */
31
+ declare function java(): LanguageSupport;
32
+
33
+ export { builtins, java, javaLanguage, localCompletionSource, snippets };
@@ -0,0 +1,33 @@
1
+ import { LanguageSupport, LRLanguage } from '@codemirror/language';
2
+ import { Completion, CompletionSource } from '@codemirror/autocomplete';
3
+
4
+ /**
5
+ A collection of Java-related [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
6
+ */
7
+ declare const snippets: readonly Completion[];
8
+
9
+ /**
10
+ Completion source that looks up names declared in Java code
11
+ (classes, methods, fields, parameters and local variables) that
12
+ are in scope at the cursor.
13
+ */
14
+ declare const localCompletionSource: CompletionSource;
15
+
16
+ /**
17
+ A language provider based on Exercism's fork of the [Lezer Java
18
+ parser](https://code.haverbeke.berlin/lezer/java), extended with
19
+ highlighting and indentation information.
20
+ */
21
+ declare const javaLanguage: LRLanguage;
22
+ /**
23
+ Keywords, literals, primitive types and the commonly used classes
24
+ from `java.lang`, `java.util` and its subpackages.
25
+ */
26
+ declare const builtins: readonly Completion[];
27
+ /**
28
+ Java language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-java.snippets),
29
+ keyword, built-in class and local name completion.
30
+ */
31
+ declare function java(): LanguageSupport;
32
+
33
+ export { builtins, java, javaLanguage, localCompletionSource, snippets };
package/dist/index.js ADDED
@@ -0,0 +1,344 @@
1
+ import { parser } from '@exercism/lezer-java';
2
+ import { syntaxTree, LRLanguage, indentNodeProp, flatIndent, continuedIndent, delimitedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';
3
+ import { snippetCompletion, completeFromList } from '@codemirror/autocomplete';
4
+ import { NodeWeakMap, IterMode } from '@lezer/common';
5
+
6
+ /**
7
+ A collection of Java-related [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
8
+ */
9
+ const snippets = [
10
+ /*@__PURE__*/snippetCompletion("public static void main(String[] args) {\n\t${}\n}", {
11
+ label: "main",
12
+ detail: "method",
13
+ type: "keyword"
14
+ }),
15
+ /*@__PURE__*/snippetCompletion("public ${void} ${name}(${params}) {\n\t${}\n}", {
16
+ label: "public",
17
+ detail: "method declaration",
18
+ type: "keyword"
19
+ }),
20
+ /*@__PURE__*/snippetCompletion("private ${void} ${name}(${params}) {\n\t${}\n}", {
21
+ label: "private",
22
+ detail: "method declaration",
23
+ type: "keyword"
24
+ }),
25
+ /*@__PURE__*/snippetCompletion("class ${Name} {\n\t${}\n}", {
26
+ label: "class",
27
+ detail: "definition",
28
+ type: "keyword"
29
+ }),
30
+ /*@__PURE__*/snippetCompletion("interface ${Name} {\n\t${}\n}", {
31
+ label: "interface",
32
+ detail: "definition",
33
+ type: "keyword"
34
+ }),
35
+ /*@__PURE__*/snippetCompletion("enum ${Name} {\n\t${}\n}", {
36
+ label: "enum",
37
+ detail: "definition",
38
+ type: "keyword"
39
+ }),
40
+ /*@__PURE__*/snippetCompletion("record ${Name}(${fields}) {\n\t${}\n}", {
41
+ label: "record",
42
+ detail: "definition",
43
+ type: "keyword"
44
+ }),
45
+ /*@__PURE__*/snippetCompletion("if (${condition}) {\n\t${}\n}", {
46
+ label: "if",
47
+ detail: "block",
48
+ type: "keyword"
49
+ }),
50
+ /*@__PURE__*/snippetCompletion("if (${condition}) {\n\t${}\n} else {\n\t\n}", {
51
+ label: "if",
52
+ detail: "/ else block",
53
+ type: "keyword"
54
+ }),
55
+ /*@__PURE__*/snippetCompletion("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", {
56
+ label: "for",
57
+ detail: "loop",
58
+ type: "keyword"
59
+ }),
60
+ /*@__PURE__*/snippetCompletion("for (${var} ${item} : ${items}) {\n\t${}\n}", {
61
+ label: "for",
62
+ detail: "each loop",
63
+ type: "keyword"
64
+ }),
65
+ /*@__PURE__*/snippetCompletion("while (${condition}) {\n\t${}\n}", {
66
+ label: "while",
67
+ detail: "loop",
68
+ type: "keyword"
69
+ }),
70
+ /*@__PURE__*/snippetCompletion("do {\n\t${}\n} while (${condition});", {
71
+ label: "do",
72
+ detail: "loop",
73
+ type: "keyword"
74
+ }),
75
+ /*@__PURE__*/snippetCompletion("switch (${value}) {\n\tcase ${a}:\n\t\t${}\n\t\tbreak;\n\tdefault:\n\t\tbreak;\n}", {
76
+ label: "switch",
77
+ detail: "statement",
78
+ type: "keyword"
79
+ }),
80
+ /*@__PURE__*/snippetCompletion("try {\n\t${}\n} catch (${Exception} ${e}) {\n\t\n}", {
81
+ label: "try",
82
+ detail: "/ catch block",
83
+ type: "keyword"
84
+ }),
85
+ /*@__PURE__*/snippetCompletion("throw new ${IllegalArgumentException}(${message});", {
86
+ label: "throw",
87
+ detail: "exception",
88
+ type: "keyword"
89
+ }),
90
+ /*@__PURE__*/snippetCompletion("System.out.println(${});", {
91
+ label: "println",
92
+ detail: "print a line",
93
+ type: "function"
94
+ })
95
+ ];
96
+
97
+ const cache = /*@__PURE__*/new NodeWeakMap();
98
+ const ScopeNodes = /*@__PURE__*/new Set([
99
+ "Program",
100
+ "ClassDeclaration", "InterfaceDeclaration", "EnumDeclaration", "RecordDeclaration",
101
+ "ClassBody", "InterfaceBody", "EnumBody", "RecordBody", "AnnotationTypeBody",
102
+ "MethodDeclaration", "ConstructorDeclaration", "ConstructorBody",
103
+ "Block", "SwitchBlock", "LambdaExpression",
104
+ "ForStatement", "EnhancedForStatement", "CatchClause", "TryWithResourcesStatement"
105
+ ]);
106
+ function child(node, name) {
107
+ let found = [];
108
+ for (let cur = node.firstChild; cur; cur = cur.nextSibling)
109
+ if (cur.name == name)
110
+ found.push(cur);
111
+ return found;
112
+ }
113
+ // Defines the declaration's own name. The declaration is a scope of
114
+ // its own, so the walk stops here and its contents are gathered when
115
+ // the cursor is inside it.
116
+ function named(type) {
117
+ return (node, def) => {
118
+ for (let d of child(node, "Definition"))
119
+ def(d, type);
120
+ return true;
121
+ };
122
+ }
123
+ // Defines each name in `int a = 1, b;`. With `ordered`, the names
124
+ // only appear after their declarator.
125
+ function declarators(type, ordered) {
126
+ return (node, def) => {
127
+ for (let decl of child(node, "VariableDeclarator"))
128
+ for (let d of child(decl, "Definition"))
129
+ def(d, type, ordered ? decl.to : -1);
130
+ return true;
131
+ };
132
+ }
133
+ function parameter(node, def) {
134
+ for (let d of child(node, "Definition"))
135
+ def(d, "variable");
136
+ for (let decl of child(node, "VariableDeclarator"))
137
+ for (let d of child(decl, "Definition"))
138
+ def(d, "variable");
139
+ return true;
140
+ }
141
+ const gatherCompletions = {
142
+ ClassDeclaration: /*@__PURE__*/named("class"),
143
+ InterfaceDeclaration: /*@__PURE__*/named("interface"),
144
+ EnumDeclaration: /*@__PURE__*/named("enum"),
145
+ RecordDeclaration: /*@__PURE__*/named("class"),
146
+ RecordComponent: /*@__PURE__*/named("property"),
147
+ CompactConstructorDeclaration: () => true,
148
+ AnnotationTypeDeclaration: () => true,
149
+ MethodDeclaration: /*@__PURE__*/named("method"),
150
+ ConstructorDeclaration: () => true,
151
+ EnumConstant: /*@__PURE__*/named("constant"),
152
+ TypeParameter: /*@__PURE__*/named("type"),
153
+ FieldDeclaration: /*@__PURE__*/declarators("property", false),
154
+ ConstantDeclaration: /*@__PURE__*/declarators("constant", false),
155
+ LocalVariableDeclaration: /*@__PURE__*/declarators("variable", true),
156
+ FormalParameter: parameter,
157
+ SpreadParameter: parameter,
158
+ CatchFormalParameter: parameter,
159
+ Resource: parameter,
160
+ // The variable of `for (String s : list)`. A classic for loop's
161
+ // ForSpec holds a LocalVariableDeclaration, which the walk finds next.
162
+ ForSpec: (node, def) => { for (let d of child(node, "Definition"))
163
+ def(d, "variable"); },
164
+ InferredParameters: parameter,
165
+ // `o instanceof String s` defines `s` from there on.
166
+ TypePattern: (node, def) => {
167
+ for (let d of child(node, "Definition"))
168
+ def(d, "variable", node.to);
169
+ return true;
170
+ },
171
+ __proto__: null
172
+ };
173
+ function getScope(doc, node) {
174
+ let cached = cache.get(node);
175
+ if (cached)
176
+ return cached;
177
+ let names = [], top = true;
178
+ let def = (node, type, after = -1) => {
179
+ names.push({ completion: { label: doc.sliceString(node.from, node.to), type }, after });
180
+ };
181
+ // A lambda's single parameter (`x -> x + 1`) is a bare Definition.
182
+ if (node.name == "LambdaExpression")
183
+ for (let d of child(node, "Definition"))
184
+ def(d, "variable");
185
+ node.cursor(IterMode.IncludeAnonymous).iterate(cur => {
186
+ if (top) {
187
+ top = false;
188
+ }
189
+ else if (cur.name) {
190
+ let gather = gatherCompletions[cur.name];
191
+ if (gather && gather(cur.node, def) || ScopeNodes.has(cur.name))
192
+ return false;
193
+ }
194
+ else if (cur.to - cur.from > 8192) {
195
+ // Allow caching for bigger internal nodes
196
+ for (let c of getScope(doc, cur.node))
197
+ names.push(c);
198
+ return false;
199
+ }
200
+ });
201
+ cache.set(node, names);
202
+ return names;
203
+ }
204
+ const Identifier = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;
205
+ const dontComplete = [
206
+ "StringLiteral", "CharacterLiteral", "TextBlock", "LineComment", "BlockComment",
207
+ "Definition", "Label", ".", "::"
208
+ ];
209
+ // `foo.bar|` or `Foo::bar|`: the name after the dot belongs to
210
+ // another object, so names from this file don't apply.
211
+ function inMemberAccess(node) {
212
+ let prev = node.prevSibling;
213
+ return !!prev && (prev.name == "." || prev.name == "::");
214
+ }
215
+ // While someone types the type of a new field (`class A { Str| }`),
216
+ // the parser reads the half-typed word as the name of a constructor
217
+ // that has no parameters yet. That word is a type, so we complete it.
218
+ function isHalfTypedMember(node) {
219
+ var _a, _b;
220
+ return node.name == "Definition" && ((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) == "ConstructorDeclaration" &&
221
+ !!((_b = node.nextSibling) === null || _b === void 0 ? void 0 : _b.type.isError);
222
+ }
223
+ // Finds the node before the cursor, and whether completion applies there.
224
+ function wordBefore(context) {
225
+ var _a;
226
+ let inner = syntaxTree(context.state).resolveInner(context.pos, -1);
227
+ let word = inner.name == "MethodName" ? (_a = inner.firstChild) !== null && _a !== void 0 ? _a : inner : inner;
228
+ let member = inMemberAccess(word) || !!word.parent && word.parent.name == "MethodName" && inMemberAccess(word.parent);
229
+ let skip = member || (dontComplete.indexOf(inner.name) > -1 && !isHalfTypedMember(inner));
230
+ return { inner, word, skip };
231
+ }
232
+ /**
233
+ Wraps a completion source so that it stays quiet in strings,
234
+ comments, new names and member names (`list.si|`).
235
+ */
236
+ function ifInCode(source) {
237
+ return context => wordBefore(context).skip ? null : source(context);
238
+ }
239
+ /**
240
+ Completion source that looks up names declared in Java code
241
+ (classes, methods, fields, parameters and local variables) that
242
+ are in scope at the cursor.
243
+ */
244
+ const localCompletionSource = context => {
245
+ let { inner, word, skip } = wordBefore(context);
246
+ if (skip)
247
+ return null;
248
+ let isWord = word.name == "Identifier" || word.name == "TypeName" || isHalfTypedMember(word) ||
249
+ word.to - word.from < 20 && Identifier.test(context.state.sliceDoc(word.from, word.to));
250
+ if (!isWord && !context.explicit)
251
+ return null;
252
+ let options = [], seen = new Set();
253
+ for (let pos = inner; pos; pos = pos.parent) {
254
+ if (!ScopeNodes.has(pos.name))
255
+ continue;
256
+ for (let { completion, after } of getScope(context.state.doc, pos)) {
257
+ if (after >= context.pos || seen.has(completion.label))
258
+ continue;
259
+ seen.add(completion.label);
260
+ options.push(completion);
261
+ }
262
+ }
263
+ return {
264
+ options,
265
+ from: isWord ? word.from : context.pos,
266
+ validFor: Identifier
267
+ };
268
+ };
269
+
270
+ /**
271
+ A language provider based on Exercism's fork of the [Lezer Java
272
+ parser](https://code.haverbeke.berlin/lezer/java), extended with
273
+ highlighting and indentation information.
274
+ */
275
+ const javaLanguage = /*@__PURE__*/LRLanguage.define({
276
+ name: "java",
277
+ parser: /*@__PURE__*/parser.configure({
278
+ props: [
279
+ /*@__PURE__*/indentNodeProp.add({
280
+ IfStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|else\b)/ }),
281
+ TryStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|catch|finally)\b/ }),
282
+ LabeledStatement: flatIndent,
283
+ SwitchBlock: context => {
284
+ let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
285
+ return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
286
+ },
287
+ Block: /*@__PURE__*/delimitedIndent({ closing: "}" }),
288
+ BlockComment: () => null,
289
+ Statement: /*@__PURE__*/continuedIndent({ except: /^{/ })
290
+ }),
291
+ /*@__PURE__*/foldNodeProp.add({
292
+ ["Block SwitchBlock ClassBody ElementValueArrayInitializer ModuleBody EnumBody " +
293
+ "ConstructorBody InterfaceBody ArrayInitializer"]: foldInside,
294
+ BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
295
+ })
296
+ ]
297
+ }),
298
+ languageData: {
299
+ commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
300
+ indentOnInput: /^\s*(?:case |default:|\{|\})$/
301
+ }
302
+ });
303
+ let kw = (type, detail) => (label) => detail ? { label, type, detail } : { label, type };
304
+ const keywords = /*@__PURE__*/("abstract assert break case catch class continue default do else enum extends final " +
305
+ "finally for if implements import instanceof interface native new package permits private protected " +
306
+ "public record return sealed static strictfp super switch synchronized this throw throws transient try " +
307
+ "var void volatile while yield").split(" ").map(/*@__PURE__*/kw("keyword"));
308
+ const literals = /*@__PURE__*/"true false null".split(" ").map(/*@__PURE__*/kw("constant"));
309
+ const primitives = /*@__PURE__*/"boolean byte char double float int long short".split(" ").map(/*@__PURE__*/kw("type"));
310
+ const javaLang = /*@__PURE__*/("Boolean Byte Character CharSequence Class Comparable Double Enum Exception Float " +
311
+ "Integer Iterable Long Math Number Object Record Runnable Short String StringBuilder System Thread " +
312
+ "Throwable Void ArithmeticException ArrayIndexOutOfBoundsException ClassCastException " +
313
+ "IllegalArgumentException IllegalStateException IndexOutOfBoundsException NullPointerException " +
314
+ "NumberFormatException RuntimeException UnsupportedOperationException").split(" ").map(/*@__PURE__*/kw("class", "java.lang"));
315
+ const annotations = /*@__PURE__*/"Override Deprecated FunctionalInterface SuppressWarnings SafeVarargs"
316
+ .split(" ").map(/*@__PURE__*/kw("type", "annotation"));
317
+ const javaUtil = /*@__PURE__*/("ArrayDeque ArrayList Arrays Collection Collections Comparator Deque HashMap HashSet " +
318
+ "Iterator LinkedHashMap LinkedHashSet LinkedList List Map Objects Optional PriorityQueue Queue Random " +
319
+ "Scanner Set SortedMap TreeMap TreeSet").split(" ").map(/*@__PURE__*/kw("class", "java.util"));
320
+ const javaUtilMore = [
321
+ ...(/*@__PURE__*/"Collectors IntStream Stream".split(" ").map(/*@__PURE__*/kw("class", "java.util.stream"))),
322
+ ...(/*@__PURE__*/"BiFunction Consumer Function Predicate Supplier".split(" ").map(/*@__PURE__*/kw("interface", "java.util.function")))
323
+ ];
324
+ /**
325
+ Keywords, literals, primitive types and the commonly used classes
326
+ from `java.lang`, `java.util` and its subpackages.
327
+ */
328
+ const builtins = /*@__PURE__*/keywords.concat(literals, primitives, javaLang, annotations, javaUtil, javaUtilMore);
329
+ /**
330
+ Java language support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-java.snippets),
331
+ keyword, built-in class and local name completion.
332
+ */
333
+ function java() {
334
+ return new LanguageSupport(javaLanguage, [
335
+ javaLanguage.data.of({
336
+ autocomplete: ifInCode(completeFromList(snippets.concat(builtins)))
337
+ }),
338
+ javaLanguage.data.of({
339
+ autocomplete: localCompletionSource
340
+ })
341
+ ]);
342
+ }
343
+
344
+ export { builtins, java, javaLanguage, localCompletionSource, snippets };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@exercism/codemirror-lang-java",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Java language support for the CodeMirror code editor, with autocomplete, for Exercism",
5
+ "scripts": {
6
+ "test": "cm-runtests",
7
+ "prepare": "cm-buildhelper src/java.ts"
8
+ },
9
+ "keywords": [
10
+ "editor",
11
+ "code"
12
+ ],
13
+ "author": {
14
+ "name": "Marijn Haverbeke",
15
+ "email": "marijn@haverbeke.berlin",
16
+ "url": "http://marijnhaverbeke.nl"
17
+ },
18
+ "type": "module",
19
+ "main": "dist/index.cjs",
20
+ "exports": {
21
+ "import": "./dist/index.js",
22
+ "require": "./dist/index.cjs"
23
+ },
24
+ "types": "dist/index.d.ts",
25
+ "module": "dist/index.js",
26
+ "sideEffects": false,
27
+ "license": "MIT",
28
+ "dependencies": {
29
+ "@codemirror/autocomplete": "^6.0.0",
30
+ "@codemirror/language": "^6.0.0",
31
+ "@codemirror/state": "^6.0.0",
32
+ "@exercism/lezer-java": "^1.0.0",
33
+ "@lezer/common": "^1.0.0"
34
+ },
35
+ "devDependencies": {
36
+ "@codemirror/buildhelper": "^1.0.0"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/exercism/codemirror-lang-java.git"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "LICENSE",
45
+ "README.md",
46
+ "CHANGELOG.md"
47
+ ],
48
+ "homepage": "https://github.com/exercism/codemirror-lang-java#readme",
49
+ "bugs": {
50
+ "url": "https://github.com/exercism/codemirror-lang-java/issues"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }