@exercism/codemirror-lang-cpp 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 +72 -0
- package/LICENSE +21 -0
- package/README.md +162 -2
- package/dist/index.cjs +1018 -0
- package/dist/index.d.cts +64 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +1007 -0
- package/package.json +54 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1018 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var lezerCpp = require('@exercism/lezer-cpp');
|
|
4
|
+
var language = require('@codemirror/language');
|
|
5
|
+
var autocomplete = require('@codemirror/autocomplete');
|
|
6
|
+
var common = require('@lezer/common');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
Snippets for the constructs that C and C++ share.
|
|
10
|
+
*/
|
|
11
|
+
const sharedSnippets = [
|
|
12
|
+
autocomplete.snippetCompletion("${type} ${name}(${params}) {\n\t${}\n}", {
|
|
13
|
+
label: "function",
|
|
14
|
+
detail: "definition",
|
|
15
|
+
type: "keyword"
|
|
16
|
+
}),
|
|
17
|
+
autocomplete.snippetCompletion("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", {
|
|
18
|
+
label: "for",
|
|
19
|
+
detail: "loop",
|
|
20
|
+
type: "keyword"
|
|
21
|
+
}),
|
|
22
|
+
autocomplete.snippetCompletion("int main() {\n\t${}\n\treturn 0;\n}", {
|
|
23
|
+
label: "main",
|
|
24
|
+
detail: "function",
|
|
25
|
+
type: "keyword"
|
|
26
|
+
}),
|
|
27
|
+
autocomplete.snippetCompletion("if (${condition}) {\n\t${}\n}", {
|
|
28
|
+
label: "if",
|
|
29
|
+
detail: "block",
|
|
30
|
+
type: "keyword"
|
|
31
|
+
}),
|
|
32
|
+
autocomplete.snippetCompletion("if (${condition}) {\n\t${}\n} else {\n\t${}\n}", {
|
|
33
|
+
label: "if",
|
|
34
|
+
detail: "/ else block",
|
|
35
|
+
type: "keyword"
|
|
36
|
+
}),
|
|
37
|
+
autocomplete.snippetCompletion("while (${condition}) {\n\t${}\n}", {
|
|
38
|
+
label: "while",
|
|
39
|
+
detail: "loop",
|
|
40
|
+
type: "keyword"
|
|
41
|
+
}),
|
|
42
|
+
autocomplete.snippetCompletion("do {\n\t${}\n} while (${condition});", {
|
|
43
|
+
label: "do",
|
|
44
|
+
detail: "loop",
|
|
45
|
+
type: "keyword"
|
|
46
|
+
}),
|
|
47
|
+
autocomplete.snippetCompletion("switch (${value}) {\ncase ${}:\n\t${}\n\tbreak;\ndefault:\n\tbreak;\n}", {
|
|
48
|
+
label: "switch",
|
|
49
|
+
detail: "statement",
|
|
50
|
+
type: "keyword"
|
|
51
|
+
}),
|
|
52
|
+
autocomplete.snippetCompletion("#include <${header}>", {
|
|
53
|
+
label: "#include",
|
|
54
|
+
detail: "system header",
|
|
55
|
+
type: "keyword"
|
|
56
|
+
}),
|
|
57
|
+
autocomplete.snippetCompletion("#include \"${header}\"", {
|
|
58
|
+
label: "#include",
|
|
59
|
+
detail: "local header",
|
|
60
|
+
type: "keyword"
|
|
61
|
+
}),
|
|
62
|
+
autocomplete.snippetCompletion("#define ${NAME} ${value}", {
|
|
63
|
+
label: "#define",
|
|
64
|
+
detail: "macro",
|
|
65
|
+
type: "keyword"
|
|
66
|
+
}),
|
|
67
|
+
autocomplete.snippetCompletion("#ifndef ${NAME}_H\n#define ${NAME}_H\n\n${}\n\n#endif", {
|
|
68
|
+
label: "#ifndef",
|
|
69
|
+
detail: "include guard",
|
|
70
|
+
type: "keyword"
|
|
71
|
+
})
|
|
72
|
+
];
|
|
73
|
+
/**
|
|
74
|
+
A collection of C-related
|
|
75
|
+
[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
|
|
76
|
+
*/
|
|
77
|
+
const cSnippets = sharedSnippets.concat([
|
|
78
|
+
autocomplete.snippetCompletion("struct ${name} {\n\t${}\n};", {
|
|
79
|
+
label: "struct",
|
|
80
|
+
detail: "definition",
|
|
81
|
+
type: "keyword"
|
|
82
|
+
}),
|
|
83
|
+
autocomplete.snippetCompletion("typedef struct {\n\t${}\n} ${name};", {
|
|
84
|
+
label: "typedef",
|
|
85
|
+
detail: "struct",
|
|
86
|
+
type: "keyword"
|
|
87
|
+
}),
|
|
88
|
+
autocomplete.snippetCompletion("enum ${name} {\n\t${}\n};", {
|
|
89
|
+
label: "enum",
|
|
90
|
+
detail: "definition",
|
|
91
|
+
type: "keyword"
|
|
92
|
+
})
|
|
93
|
+
]);
|
|
94
|
+
/**
|
|
95
|
+
A collection of C++-related
|
|
96
|
+
[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
|
|
97
|
+
*/
|
|
98
|
+
const cppSnippets = sharedSnippets.concat([
|
|
99
|
+
autocomplete.snippetCompletion("for (const auto &${item} : ${items}) {\n\t${}\n}", {
|
|
100
|
+
label: "for",
|
|
101
|
+
detail: "range loop",
|
|
102
|
+
type: "keyword"
|
|
103
|
+
}),
|
|
104
|
+
autocomplete.snippetCompletion("class ${Name} {\npublic:\n\t${Name}(${});\n\nprivate:\n\t${}\n};", {
|
|
105
|
+
label: "class",
|
|
106
|
+
detail: "definition",
|
|
107
|
+
type: "keyword"
|
|
108
|
+
}),
|
|
109
|
+
autocomplete.snippetCompletion("struct ${Name} {\n\t${}\n};", {
|
|
110
|
+
label: "struct",
|
|
111
|
+
detail: "definition",
|
|
112
|
+
type: "keyword"
|
|
113
|
+
}),
|
|
114
|
+
autocomplete.snippetCompletion("enum class ${Name} {\n\t${}\n};", {
|
|
115
|
+
label: "enum",
|
|
116
|
+
detail: "class",
|
|
117
|
+
type: "keyword"
|
|
118
|
+
}),
|
|
119
|
+
autocomplete.snippetCompletion("namespace ${name} {\n\n${}\n\n} // namespace ${name}", {
|
|
120
|
+
label: "namespace",
|
|
121
|
+
detail: "block",
|
|
122
|
+
type: "keyword"
|
|
123
|
+
}),
|
|
124
|
+
autocomplete.snippetCompletion("try {\n\t${}\n} catch (const ${std::exception} &${e}) {\n\t${}\n}", {
|
|
125
|
+
label: "try",
|
|
126
|
+
detail: "/ catch block",
|
|
127
|
+
type: "keyword"
|
|
128
|
+
}),
|
|
129
|
+
autocomplete.snippetCompletion("[${&}](${params}) {\n\t${}\n}", {
|
|
130
|
+
label: "lambda",
|
|
131
|
+
detail: "expression",
|
|
132
|
+
type: "keyword"
|
|
133
|
+
}),
|
|
134
|
+
autocomplete.snippetCompletion("template <typename ${T}>", {
|
|
135
|
+
label: "template",
|
|
136
|
+
detail: "declaration",
|
|
137
|
+
type: "keyword"
|
|
138
|
+
}),
|
|
139
|
+
autocomplete.snippetCompletion("#pragma once", {
|
|
140
|
+
label: "#pragma",
|
|
141
|
+
detail: "once",
|
|
142
|
+
type: "keyword"
|
|
143
|
+
})
|
|
144
|
+
]);
|
|
145
|
+
/**
|
|
146
|
+
Snippets for Objective-C. They cover C's constructs and the
|
|
147
|
+
Objective-C class, method, loop and literal forms.
|
|
148
|
+
*/
|
|
149
|
+
const objcSnippets = sharedSnippets.filter(s => !/^#(include|ifndef)/.test(s.label)).concat([
|
|
150
|
+
autocomplete.snippetCompletion("#import <${Foundation/Foundation.h}>", {
|
|
151
|
+
label: "#import",
|
|
152
|
+
detail: "system header",
|
|
153
|
+
type: "keyword"
|
|
154
|
+
}),
|
|
155
|
+
autocomplete.snippetCompletion("#import \"${header}\"", {
|
|
156
|
+
label: "#import",
|
|
157
|
+
detail: "local header",
|
|
158
|
+
type: "keyword"
|
|
159
|
+
}),
|
|
160
|
+
autocomplete.snippetCompletion("for (${id} ${item} in ${collection}) {\n\t${}\n}", {
|
|
161
|
+
label: "for",
|
|
162
|
+
detail: "in loop",
|
|
163
|
+
type: "keyword"
|
|
164
|
+
}),
|
|
165
|
+
autocomplete.snippetCompletion("- (${void})${name} {\n\t${}\n}", {
|
|
166
|
+
label: "method",
|
|
167
|
+
detail: "instance method",
|
|
168
|
+
type: "keyword"
|
|
169
|
+
}),
|
|
170
|
+
autocomplete.snippetCompletion("+ (${void})${name} {\n\t${}\n}", {
|
|
171
|
+
label: "method",
|
|
172
|
+
detail: "class method",
|
|
173
|
+
type: "keyword"
|
|
174
|
+
}),
|
|
175
|
+
autocomplete.snippetCompletion("- (instancetype)init {\n\tself = [super init];\n\tif (self) {\n\t\t${}\n\t}\n\treturn self;\n}", {
|
|
176
|
+
label: "init",
|
|
177
|
+
detail: "initializer",
|
|
178
|
+
type: "keyword"
|
|
179
|
+
}),
|
|
180
|
+
autocomplete.snippetCompletion("typedef NS_ENUM(NSInteger, ${Name}) {\n\t${}\n};", {
|
|
181
|
+
label: "NS_ENUM",
|
|
182
|
+
detail: "enum",
|
|
183
|
+
type: "keyword"
|
|
184
|
+
}),
|
|
185
|
+
autocomplete.snippetCompletion("^(${params}) {\n\t${}\n}", {
|
|
186
|
+
label: "block",
|
|
187
|
+
detail: "expression",
|
|
188
|
+
type: "keyword"
|
|
189
|
+
})
|
|
190
|
+
]);
|
|
191
|
+
/**
|
|
192
|
+
Snippets for the Objective-C `@` directives. They are offered when
|
|
193
|
+
the word being typed starts with `@`.
|
|
194
|
+
*/
|
|
195
|
+
const objcDirectiveSnippets = [
|
|
196
|
+
autocomplete.snippetCompletion("@interface ${Name} : ${NSObject}\n\n${}\n\n@end", {
|
|
197
|
+
label: "@interface",
|
|
198
|
+
detail: "declaration",
|
|
199
|
+
type: "keyword"
|
|
200
|
+
}),
|
|
201
|
+
autocomplete.snippetCompletion("@implementation ${Name}\n\n${}\n\n@end", {
|
|
202
|
+
label: "@implementation",
|
|
203
|
+
detail: "definition",
|
|
204
|
+
type: "keyword"
|
|
205
|
+
}),
|
|
206
|
+
autocomplete.snippetCompletion("@protocol ${Name} <NSObject>\n\n${}\n\n@end", {
|
|
207
|
+
label: "@protocol",
|
|
208
|
+
detail: "declaration",
|
|
209
|
+
type: "keyword"
|
|
210
|
+
}),
|
|
211
|
+
autocomplete.snippetCompletion("@property (nonatomic, ${strong}) ${NSString} *${name};", {
|
|
212
|
+
label: "@property",
|
|
213
|
+
detail: "declaration",
|
|
214
|
+
type: "keyword"
|
|
215
|
+
}),
|
|
216
|
+
autocomplete.snippetCompletion("@try {\n\t${}\n} @catch (NSException *${exception}) {\n\t${}\n}", {
|
|
217
|
+
label: "@try",
|
|
218
|
+
detail: "/ @catch block",
|
|
219
|
+
type: "keyword"
|
|
220
|
+
}),
|
|
221
|
+
autocomplete.snippetCompletion("@autoreleasepool {\n\t${}\n}", {
|
|
222
|
+
label: "@autoreleasepool",
|
|
223
|
+
detail: "block",
|
|
224
|
+
type: "keyword"
|
|
225
|
+
}),
|
|
226
|
+
autocomplete.snippetCompletion("@selector(${name})", {
|
|
227
|
+
label: "@selector",
|
|
228
|
+
detail: "expression",
|
|
229
|
+
type: "keyword"
|
|
230
|
+
}),
|
|
231
|
+
autocomplete.snippetCompletion("@[${}]", {
|
|
232
|
+
label: "@[",
|
|
233
|
+
detail: "array literal",
|
|
234
|
+
type: "keyword"
|
|
235
|
+
}),
|
|
236
|
+
autocomplete.snippetCompletion("@{${key}: ${value}}", {
|
|
237
|
+
label: "@{",
|
|
238
|
+
detail: "dictionary literal",
|
|
239
|
+
type: "keyword"
|
|
240
|
+
})
|
|
241
|
+
];
|
|
242
|
+
|
|
243
|
+
function words(str, type) {
|
|
244
|
+
return str.split(/\s+/).filter(w => w).map(label => ({ label, type }));
|
|
245
|
+
}
|
|
246
|
+
// Keywords and the fundamental types of C99, plus the names from
|
|
247
|
+
// <stdbool.h> and <stddef.h> that read like keywords.
|
|
248
|
+
const cKeywordNames = `
|
|
249
|
+
auto break case const continue default do else enum extern for goto if inline
|
|
250
|
+
register restrict return sizeof static struct switch typedef union volatile while
|
|
251
|
+
_Bool _Complex _Static_assert _Noreturn _Alignas _Alignof _Atomic _Thread_local`;
|
|
252
|
+
const cTypeNames = `char double float int long short signed unsigned void bool`;
|
|
253
|
+
const cConstantNames = `true false NULL`;
|
|
254
|
+
const cppKeywordNames = `
|
|
255
|
+
auto break case const continue default do else enum extern for goto if inline
|
|
256
|
+
register return sizeof static struct switch typedef union volatile while alignas alignof and and_eq bitand bitor catch class compl concept consteval
|
|
257
|
+
constexpr constinit const_cast co_await co_return co_yield decltype delete
|
|
258
|
+
dynamic_cast explicit export friend mutable namespace new noexcept not not_eq
|
|
259
|
+
operator or or_eq private protected public reinterpret_cast requires
|
|
260
|
+
static_assert static_cast template this thread_local throw try typeid typename
|
|
261
|
+
using virtual xor xor_eq override final`;
|
|
262
|
+
const cppTypeNames = `bool char char8_t char16_t char32_t double float int long short
|
|
263
|
+
signed unsigned void wchar_t`;
|
|
264
|
+
const cppConstantNames = `true false nullptr`;
|
|
265
|
+
/**
|
|
266
|
+
Keywords, fundamental types and constants for C.
|
|
267
|
+
*/
|
|
268
|
+
const cKeywords = [
|
|
269
|
+
...words(cKeywordNames, "keyword"),
|
|
270
|
+
...words(cTypeNames, "type"),
|
|
271
|
+
...words(cConstantNames, "constant")
|
|
272
|
+
];
|
|
273
|
+
/**
|
|
274
|
+
Keywords, fundamental types and constants for C++.
|
|
275
|
+
*/
|
|
276
|
+
const cppKeywords = [
|
|
277
|
+
...words(cppKeywordNames, "keyword"),
|
|
278
|
+
...words(cppTypeNames, "type"),
|
|
279
|
+
...words(cppConstantNames, "constant")
|
|
280
|
+
];
|
|
281
|
+
// The C standard library, grouped by header.
|
|
282
|
+
const cLibraryFunctions = `
|
|
283
|
+
printf fprintf sprintf snprintf vprintf vfprintf vsprintf vsnprintf scanf fscanf
|
|
284
|
+
sscanf puts fputs putchar fputc putc getchar fgetc getc fgets ungetc fopen fclose
|
|
285
|
+
fread fwrite fflush fseek ftell rewind feof ferror perror remove rename
|
|
286
|
+
malloc calloc realloc free abs labs llabs div ldiv atoi atol atoll atof strtol
|
|
287
|
+
strtoll strtoul strtoull strtod strtof rand srand qsort bsearch exit abort atexit
|
|
288
|
+
getenv system
|
|
289
|
+
strlen strcpy strncpy strcat strncat strcmp strncmp strchr strrchr strstr strspn
|
|
290
|
+
strcspn strpbrk strtok strdup strndup strerror memcpy memmove memset memcmp memchr
|
|
291
|
+
isalnum isalpha isblank iscntrl isdigit isgraph islower isprint ispunct isspace
|
|
292
|
+
isupper isxdigit tolower toupper
|
|
293
|
+
sqrt pow fabs floor ceil round trunc fmod exp log log2 log10 sin cos tan asin
|
|
294
|
+
acos atan atan2 hypot fmin fmax lround llround cbrt
|
|
295
|
+
assert time clock difftime mktime localtime gmtime strftime
|
|
296
|
+
va_start va_arg va_end va_copy`;
|
|
297
|
+
const cLibraryTypes = `
|
|
298
|
+
size_t ptrdiff_t FILE int8_t int16_t int32_t int64_t uint8_t uint16_t uint32_t
|
|
299
|
+
uint64_t intptr_t uintptr_t intmax_t uintmax_t time_t clock_t va_list div_t`;
|
|
300
|
+
const cLibraryConstants = `
|
|
301
|
+
EOF stdin stdout stderr EXIT_SUCCESS EXIT_FAILURE RAND_MAX INT_MAX INT_MIN UINT_MAX
|
|
302
|
+
LONG_MAX LONG_MIN ULONG_MAX LLONG_MAX LLONG_MIN ULLONG_MAX CHAR_BIT CHAR_MAX
|
|
303
|
+
CHAR_MIN SIZE_MAX INT8_MAX INT16_MAX INT32_MAX INT64_MAX UINT8_MAX UINT16_MAX
|
|
304
|
+
UINT32_MAX UINT64_MAX INT32_MIN INT64_MIN M_PI errno`;
|
|
305
|
+
/**
|
|
306
|
+
Names from the C standard library.
|
|
307
|
+
*/
|
|
308
|
+
const cLibrary = [
|
|
309
|
+
...words(cLibraryFunctions, "function"),
|
|
310
|
+
...words(cLibraryTypes, "type"),
|
|
311
|
+
...words(cLibraryConstants, "constant")
|
|
312
|
+
];
|
|
313
|
+
// Members of namespace std that common exercises use most.
|
|
314
|
+
const stdTypes = `
|
|
315
|
+
string string_view wstring vector array deque list forward_list map multimap set
|
|
316
|
+
multiset unordered_map unordered_set unordered_multimap unordered_multiset stack
|
|
317
|
+
queue priority_queue pair tuple optional variant any function unique_ptr
|
|
318
|
+
shared_ptr weak_ptr size_t ptrdiff_t int8_t int16_t int32_t int64_t uint8_t
|
|
319
|
+
uint16_t uint32_t uint64_t istream ostream iostream stringstream istringstream
|
|
320
|
+
ostringstream ifstream ofstream exception runtime_error logic_error
|
|
321
|
+
invalid_argument out_of_range domain_error length_error range_error
|
|
322
|
+
overflow_error underflow_error bad_alloc initializer_list numeric_limits
|
|
323
|
+
iterator reverse_iterator back_insert_iterator bitset complex regex smatch
|
|
324
|
+
mt19937 random_device uniform_int_distribution uniform_real_distribution
|
|
325
|
+
mutex lock_guard thread`;
|
|
326
|
+
const stdFunctions = `
|
|
327
|
+
sort stable_sort partial_sort nth_element reverse rotate shuffle unique remove
|
|
328
|
+
remove_if replace replace_if fill fill_n copy copy_if copy_n move swap transform
|
|
329
|
+
for_each find find_if find_if_not count count_if all_of any_of none_of equal
|
|
330
|
+
mismatch search min max minmax min_element max_element minmax_element clamp
|
|
331
|
+
lower_bound upper_bound binary_search equal_range merge includes set_union
|
|
332
|
+
set_intersection set_difference next_permutation prev_permutation iota
|
|
333
|
+
accumulate reduce inner_product partial_sum adjacent_difference gcd lcm abs
|
|
334
|
+
pow sqrt floor ceil round trunc fmod log log2 log10 exp sin cos tan atan2 hypot
|
|
335
|
+
to_string to_chars from_chars stoi stol stoll stoul stoull stof stod getline
|
|
336
|
+
make_pair make_tuple make_unique make_shared make_optional tie get begin end
|
|
337
|
+
rbegin rend cbegin cend size empty distance next prev advance back_inserter
|
|
338
|
+
inserter isalpha isdigit isalnum isspace isupper islower ispunct toupper
|
|
339
|
+
tolower exchange forward as_const ref cref hash`;
|
|
340
|
+
const stdObjects = `cout cin cerr clog endl npos ios`;
|
|
341
|
+
const stdNamespaces = `chrono ranges views literals filesystem this_thread`;
|
|
342
|
+
/**
|
|
343
|
+
The fixed-width integer types and `size_t`, which C++ code often
|
|
344
|
+
uses without `std::`.
|
|
345
|
+
*/
|
|
346
|
+
const cppGlobalTypes = words(cLibraryTypes, "type")
|
|
347
|
+
.filter(c => /_t$/.test(c.label));
|
|
348
|
+
/**
|
|
349
|
+
Names in namespace `std`, offered after `std::`, and on their own
|
|
350
|
+
when the file has `using namespace std;`.
|
|
351
|
+
*/
|
|
352
|
+
const stdNames = [
|
|
353
|
+
...words(stdTypes, "class"),
|
|
354
|
+
...words(stdFunctions, "function"),
|
|
355
|
+
...words(stdObjects, "variable"),
|
|
356
|
+
...words(stdNamespaces, "namespace")
|
|
357
|
+
];
|
|
358
|
+
const cHeaderNames = `
|
|
359
|
+
assert.h complex.h ctype.h errno.h fenv.h float.h inttypes.h iso646.h limits.h
|
|
360
|
+
locale.h math.h setjmp.h signal.h stdarg.h stdbool.h stddef.h stdint.h stdio.h
|
|
361
|
+
stdlib.h string.h tgmath.h time.h wchar.h wctype.h`;
|
|
362
|
+
const cppHeaderNames = `
|
|
363
|
+
algorithm any array atomic bitset cassert cctype cerrno cfloat charconv chrono
|
|
364
|
+
climits clocale cmath complex concepts condition_variable cstddef cstdint cstdio
|
|
365
|
+
cstdlib cstring ctime deque exception execution filesystem format forward_list
|
|
366
|
+
fstream functional future initializer_list iomanip ios iosfwd iostream istream
|
|
367
|
+
iterator limits list map memory mutex numeric optional ostream queue random
|
|
368
|
+
ranges ratio regex set span sstream stack stdexcept string string_view thread
|
|
369
|
+
tuple type_traits typeinfo unordered_map unordered_set utility valarray variant
|
|
370
|
+
vector`;
|
|
371
|
+
/**
|
|
372
|
+
Header names offered inside `#include <...>` in C.
|
|
373
|
+
*/
|
|
374
|
+
const cHeaders = words(cHeaderNames, "namespace");
|
|
375
|
+
/**
|
|
376
|
+
Header names offered inside `#include <...>` in C++.
|
|
377
|
+
*/
|
|
378
|
+
const cppHeaders = words(cppHeaderNames, "namespace");
|
|
379
|
+
// Objective-C adds these to C's keywords and types.
|
|
380
|
+
const objcKeywordNames = `self super in typeof nullable nonnull __block __weak __strong
|
|
381
|
+
__kindof __unsafe_unretained`;
|
|
382
|
+
const objcTypeNames = `id instancetype BOOL SEL Class IMP NSInteger NSUInteger CGFloat
|
|
383
|
+
NSRange NSComparisonResult NSTimeInterval unichar`;
|
|
384
|
+
const objcConstantNames = `nil Nil YES NO NSNotFound NSOrderedAscending NSOrderedSame
|
|
385
|
+
NSOrderedDescending`;
|
|
386
|
+
/**
|
|
387
|
+
Keywords, types and constants for Objective-C, including C's.
|
|
388
|
+
*/
|
|
389
|
+
const objcKeywords = [
|
|
390
|
+
...cKeywords,
|
|
391
|
+
...words(objcKeywordNames, "keyword"),
|
|
392
|
+
...words(objcTypeNames, "type"),
|
|
393
|
+
...words(objcConstantNames, "constant")
|
|
394
|
+
];
|
|
395
|
+
// The Foundation classes and functions that Exercism solutions use most.
|
|
396
|
+
const foundationClasses = `
|
|
397
|
+
NSObject NSString NSMutableString NSArray NSMutableArray NSDictionary
|
|
398
|
+
NSMutableDictionary NSSet NSMutableSet NSCountedSet NSOrderedSet NSNumber NSValue
|
|
399
|
+
NSNull NSData NSDate NSDateComponents NSDateFormatter NSCalendar NSTimeZone
|
|
400
|
+
NSLocale NSCharacterSet NSMutableCharacterSet NSScanner NSRegularExpression
|
|
401
|
+
NSTextCheckingResult NSPredicate NSSortDescriptor NSIndexSet NSMutableIndexSet
|
|
402
|
+
NSError NSException NSEnumerator NSNumberFormatter NSDecimalNumber
|
|
403
|
+
NSAttributedString NSProcessInfo NSBundle NSFileManager NSURL NSUUID`;
|
|
404
|
+
const foundationFunctions = `
|
|
405
|
+
NSLog NSMakeRange NSMaxRange NSLocationInRange NSStringFromClass
|
|
406
|
+
NSStringFromSelector NSSelectorFromString NSClassFromString NSStringFromRange
|
|
407
|
+
NSEqualRanges NSUnionRange NSIntersectionRange`;
|
|
408
|
+
const foundationConstants = `
|
|
409
|
+
NSIntegerMax NSIntegerMin NSUIntegerMax NSCaseInsensitiveSearch NSLiteralSearch
|
|
410
|
+
NSBackwardsSearch NSAnchoredSearch NSNumericSearch NSUTF8StringEncoding
|
|
411
|
+
NSRegularExpressionCaseInsensitive NSCalendarUnitYear NSCalendarUnitMonth
|
|
412
|
+
NSCalendarUnitDay NSCalendarUnitWeekday NSCalendarUnitHour NSCalendarUnitMinute
|
|
413
|
+
NSCalendarUnitSecond NSCalendarIdentifierGregorian`;
|
|
414
|
+
/**
|
|
415
|
+
The common classes, functions and constants of Foundation.
|
|
416
|
+
*/
|
|
417
|
+
const foundationNames = [
|
|
418
|
+
...words(foundationClasses, "class"),
|
|
419
|
+
...words(foundationFunctions, "function"),
|
|
420
|
+
...words(foundationConstants, "constant")
|
|
421
|
+
];
|
|
422
|
+
// The Foundation methods that Exercism solutions send most. A selector
|
|
423
|
+
// with arguments keeps its colons, and completing it inserts the first
|
|
424
|
+
// part with its colon.
|
|
425
|
+
const foundationSelectorNames = `
|
|
426
|
+
alloc init new copy mutableCopy description class isKindOfClass: isMemberOfClass:
|
|
427
|
+
respondsToSelector: isEqual: hash
|
|
428
|
+
length characterAtIndex: substringFromIndex: substringToIndex: substringWithRange:
|
|
429
|
+
stringByAppendingString: stringByAppendingFormat: stringWithFormat: stringWithString:
|
|
430
|
+
initWithFormat: initWithString: stringByReplacingOccurrencesOfString:withString:
|
|
431
|
+
stringByTrimmingCharactersInSet: componentsSeparatedByString:
|
|
432
|
+
componentsSeparatedByCharactersInSet: componentsJoinedByString: rangeOfString:
|
|
433
|
+
rangeOfCharacterFromSet: hasPrefix: hasSuffix: containsString: isEqualToString:
|
|
434
|
+
compare: caseInsensitiveCompare: uppercaseString lowercaseString capitalizedString
|
|
435
|
+
intValue integerValue doubleValue floatValue boolValue longLongValue
|
|
436
|
+
unsignedIntegerValue stringValue appendString: appendFormat: insertString:atIndex:
|
|
437
|
+
deleteCharactersInRange: reverseObjectEnumerator
|
|
438
|
+
count objectAtIndex: firstObject lastObject containsObject: indexOfObject:
|
|
439
|
+
arrayWithObjects: arrayWithArray: arrayWithCapacity: array addObject:
|
|
440
|
+
addObjectsFromArray: insertObject:atIndex: removeObject: removeObjectAtIndex:
|
|
441
|
+
removeLastObject removeAllObjects replaceObjectAtIndex:withObject:
|
|
442
|
+
exchangeObjectAtIndex:withObjectAtIndex: sortedArrayUsingSelector:
|
|
443
|
+
sortedArrayUsingComparator: sortUsingComparator: sortUsingSelector:
|
|
444
|
+
filteredArrayUsingPredicate: enumerateObjectsUsingBlock: arrayByAddingObject:
|
|
445
|
+
subarrayWithRange: valueForKey: valueForKeyPath:
|
|
446
|
+
objectForKey: setObject:forKey: removeObjectForKey: allKeys allValues
|
|
447
|
+
dictionaryWithObjects:forKeys: dictionaryWithDictionary: dictionary
|
|
448
|
+
enumerateKeysAndObjectsUsingBlock: keysSortedByValueUsingSelector:
|
|
449
|
+
setWithArray: setWithObjects: set member: unionSet: intersectSet: minusSet:
|
|
450
|
+
countForObject: allObjects
|
|
451
|
+
numberWithInt: numberWithInteger: numberWithDouble: numberWithBool:
|
|
452
|
+
numberWithUnsignedInteger: numberWithLongLong:
|
|
453
|
+
characterIsMember: letterCharacterSet decimalDigitCharacterSet
|
|
454
|
+
whitespaceCharacterSet whitespaceAndNewlineCharacterSet punctuationCharacterSet
|
|
455
|
+
alphanumericCharacterSet uppercaseLetterCharacterSet lowercaseLetterCharacterSet
|
|
456
|
+
characterSetWithCharactersInString: invertedSet
|
|
457
|
+
regularExpressionWithPattern:options:error: matchesInString:options:range:
|
|
458
|
+
numberOfMatchesInString:options:range: firstMatchInString:options:range:
|
|
459
|
+
stringByReplacingMatchesInString:options:range:withTemplate:
|
|
460
|
+
predicateWithFormat: predicateWithBlock: currentCalendar components:fromDate:
|
|
461
|
+
dateFromComponents: dateByAddingTimeInterval: dateWithTimeInterval:sinceDate:
|
|
462
|
+
timeIntervalSinceDate: dateFromString: stringFromDate: setDateFormat:
|
|
463
|
+
raise:format: exceptionWithName:reason:userInfo:`;
|
|
464
|
+
/**
|
|
465
|
+
Common Foundation selectors, offered after the receiver of a message.
|
|
466
|
+
*/
|
|
467
|
+
const foundationSelectors = words(foundationSelectorNames, "method");
|
|
468
|
+
// The `@` directives and literals.
|
|
469
|
+
const objcDirectiveNames = `
|
|
470
|
+
@interface @implementation @end @protocol @class @property @synthesize @dynamic
|
|
471
|
+
@optional @required @private @protected @public @package @import @selector
|
|
472
|
+
@encode @try @catch @finally @throw @autoreleasepool @synchronized @YES @NO`;
|
|
473
|
+
/**
|
|
474
|
+
The Objective-C `@` directives.
|
|
475
|
+
*/
|
|
476
|
+
const objcDirectives = words(objcDirectiveNames, "keyword");
|
|
477
|
+
const objcHeaderNames = `Foundation/Foundation.h`;
|
|
478
|
+
/**
|
|
479
|
+
Header names offered inside `#import <...>` and `#include <...>` in
|
|
480
|
+
Objective-C.
|
|
481
|
+
*/
|
|
482
|
+
const objcHeaders = [
|
|
483
|
+
...words(objcHeaderNames, "namespace"),
|
|
484
|
+
...cHeaders
|
|
485
|
+
];
|
|
486
|
+
|
|
487
|
+
const cache = new common.NodeWeakMap();
|
|
488
|
+
// Names declared directly inside one of these nodes are visible only
|
|
489
|
+
// inside it.
|
|
490
|
+
const ScopeNodes = new Set([
|
|
491
|
+
"Program", "CompoundStatement", "FunctionDefinition", "LambdaExpression",
|
|
492
|
+
"ForStatement", "ForRangeLoop", "IfStatement", "SwitchStatement", "WhileStatement",
|
|
493
|
+
"CatchClause", "FieldDeclarationList",
|
|
494
|
+
"MethodDefinition", "BlockExpression", "ForInStatement"
|
|
495
|
+
]);
|
|
496
|
+
// Inside these, a name is visible only after its declaration. Names at
|
|
497
|
+
// the top of the file and in a class body are offered everywhere, since
|
|
498
|
+
// a function can be declared in a header or defined lower down.
|
|
499
|
+
const OrderedScopes = new Set([
|
|
500
|
+
"CompoundStatement", "FunctionDefinition", "LambdaExpression", "ForStatement",
|
|
501
|
+
"ForRangeLoop", "IfStatement", "SwitchStatement", "WhileStatement", "CatchClause",
|
|
502
|
+
"MethodDefinition", "BlockExpression", "ForInStatement"
|
|
503
|
+
]);
|
|
504
|
+
// A namespace body is a CompoundStatement, but its names stay visible
|
|
505
|
+
// in the rest of the file, as they do in most Exercism solutions,
|
|
506
|
+
// which put everything in one namespace. The instance variables of an
|
|
507
|
+
// Objective-C class are visible in all of its methods, which may be in
|
|
508
|
+
// another part of the file.
|
|
509
|
+
function isScope(node) {
|
|
510
|
+
var _a;
|
|
511
|
+
if (!ScopeNodes.has(node.name))
|
|
512
|
+
return false;
|
|
513
|
+
let parent = (_a = node.node.parent) === null || _a === void 0 ? void 0 : _a.name;
|
|
514
|
+
if (node.name == "CompoundStatement" && parent == "NamespaceDefinition")
|
|
515
|
+
return false;
|
|
516
|
+
if (node.name == "FieldDeclarationList" && (parent == "ClassInterface" || parent == "ClassImplementation"))
|
|
517
|
+
return false;
|
|
518
|
+
return true;
|
|
519
|
+
}
|
|
520
|
+
const Declarators = new Set([
|
|
521
|
+
"PointerDeclarator", "ReferenceDeclarator", "ArrayDeclarator", "FunctionDeclarator",
|
|
522
|
+
"ParenthesizedDeclarator", "InitDeclarator", "StructuredBindingDeclarator"
|
|
523
|
+
]);
|
|
524
|
+
const NameNodes = new Set(["Identifier", "FieldIdentifier", "TypeIdentifier"]);
|
|
525
|
+
const TypeSpecifiers = new Set(["StructSpecifier", "ClassSpecifier", "UnionSpecifier", "EnumSpecifier"]);
|
|
526
|
+
// Find the names declared by a declarator such as `*p`, `arr[3]` or
|
|
527
|
+
// `f(int x)`. Only the first named child of each declarator holds the
|
|
528
|
+
// name. The rest are sizes, parameters and initial values.
|
|
529
|
+
function declaratorNames(node, type, def) {
|
|
530
|
+
if (NameNodes.has(node.name)) {
|
|
531
|
+
def(node, type);
|
|
532
|
+
}
|
|
533
|
+
else if (node.name == "StructuredBindingDeclarator") {
|
|
534
|
+
for (let ch = node.firstChild; ch; ch = ch.nextSibling)
|
|
535
|
+
if (ch.name == "Identifier")
|
|
536
|
+
def(ch, type);
|
|
537
|
+
}
|
|
538
|
+
else if (Declarators.has(node.name)) {
|
|
539
|
+
let isFunction = node.name == "FunctionDeclarator";
|
|
540
|
+
for (let ch = node.firstChild; ch; ch = ch.nextSibling) {
|
|
541
|
+
if (NameNodes.has(ch.name) || Declarators.has(ch.name)) {
|
|
542
|
+
declaratorNames(ch, isFunction ? "function" : type, def);
|
|
543
|
+
break;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// Call `declaratorNames` on the direct children of a declaration that
|
|
549
|
+
// are declarators. The type comes first, so a TypeIdentifier is a name
|
|
550
|
+
// only after it, as in `typedef int number;`. A constructor declaration
|
|
551
|
+
// such as `C(int v);` has no type at all.
|
|
552
|
+
function declaredNames(type) {
|
|
553
|
+
return (node, def) => {
|
|
554
|
+
let sawType = false;
|
|
555
|
+
for (let ch = node.node.firstChild; ch; ch = ch.nextSibling) {
|
|
556
|
+
if (TypeSpecifiers.has(ch.name))
|
|
557
|
+
gatherCompletions[ch.name](ch, def);
|
|
558
|
+
let isName = NameNodes.has(ch.name) && (sawType || ch.name != "TypeIdentifier");
|
|
559
|
+
if (isName || Declarators.has(ch.name)) {
|
|
560
|
+
declaratorNames(ch, ch.name == "TypeIdentifier" ? "type" : type, def);
|
|
561
|
+
}
|
|
562
|
+
else if (!sawType && !ch.type.isError && /^[A-Z]/.test(ch.name) && ch.name != "Attribute") {
|
|
563
|
+
sawType = true;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
// Parameter names inside a function declarator belong to the
|
|
567
|
+
// function, so the search stops here.
|
|
568
|
+
return true;
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function typeName(type) {
|
|
572
|
+
return (node, def) => {
|
|
573
|
+
// In `NS_ENUM(NSInteger, Kind)`, the second type is the new one.
|
|
574
|
+
let name = node.node.getChild("NS_ENUM") ? node.node.getChildren("TypeIdentifier").pop()
|
|
575
|
+
: node.node.getChild("TypeIdentifier");
|
|
576
|
+
if (name)
|
|
577
|
+
def(name, type);
|
|
578
|
+
// Enumerators of a plain `enum` are visible next to the enum. Those
|
|
579
|
+
// of `enum class` are not.
|
|
580
|
+
if (node.name == "EnumSpecifier" && !node.node.getChild("class") && !node.node.getChild("struct")) {
|
|
581
|
+
let list = node.node.getChild("EnumeratorList");
|
|
582
|
+
if (list)
|
|
583
|
+
for (let e of list.getChildren("Enumerator")) {
|
|
584
|
+
let id = e.getChild("Identifier");
|
|
585
|
+
if (id)
|
|
586
|
+
def(id, "constant");
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
return true;
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
// In `for (auto &item : items)`, the first name or declarator is the
|
|
593
|
+
// loop variable and the second name is the range.
|
|
594
|
+
function rangeLoopNames(node, def) {
|
|
595
|
+
for (let ch = node.firstChild; ch; ch = ch.nextSibling)
|
|
596
|
+
if (Declarators.has(ch.name) || ch.name == "Identifier") {
|
|
597
|
+
declaratorNames(ch, "variable", def);
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
const gatherCompletions = {
|
|
602
|
+
Declaration: declaredNames("variable"),
|
|
603
|
+
FieldDeclaration: declaredNames("property"),
|
|
604
|
+
ParameterDeclaration: declaredNames("variable"),
|
|
605
|
+
OptionalParameterDeclaration: declaredNames("variable"),
|
|
606
|
+
TypeDefinition: declaredNames("type"),
|
|
607
|
+
// The parser reads `int x{};` in a class body as a function with an
|
|
608
|
+
// empty body, so the name is a function only if it has parameters.
|
|
609
|
+
FunctionDefinition: declaredNames("variable"),
|
|
610
|
+
StructSpecifier: typeName("class"),
|
|
611
|
+
ClassSpecifier: typeName("class"),
|
|
612
|
+
UnionSpecifier: typeName("class"),
|
|
613
|
+
EnumSpecifier: typeName("enum"),
|
|
614
|
+
AliasDeclaration: (node, def) => {
|
|
615
|
+
let name = node.node.getChild("TypeIdentifier");
|
|
616
|
+
if (name)
|
|
617
|
+
def(name, "type");
|
|
618
|
+
return true;
|
|
619
|
+
},
|
|
620
|
+
TypeParameterDeclaration: (node, def) => {
|
|
621
|
+
let name = node.node.getChild("TypeIdentifier");
|
|
622
|
+
if (name)
|
|
623
|
+
def(name, "type");
|
|
624
|
+
return true;
|
|
625
|
+
},
|
|
626
|
+
// `using std::string;` makes `string` available on its own.
|
|
627
|
+
UsingDeclaration: (node, def) => {
|
|
628
|
+
let scoped = node.node.getChild("ScopedIdentifier");
|
|
629
|
+
let name = scoped === null || scoped === void 0 ? void 0 : scoped.getChild("Identifier");
|
|
630
|
+
if (name && !node.node.getChild("namespace"))
|
|
631
|
+
def(name, "type");
|
|
632
|
+
return true;
|
|
633
|
+
},
|
|
634
|
+
NamespaceDefinition: (node, def) => {
|
|
635
|
+
let name = node.node.getChild("Identifier");
|
|
636
|
+
if (name)
|
|
637
|
+
def(name, "namespace");
|
|
638
|
+
return false;
|
|
639
|
+
},
|
|
640
|
+
// Objective-C. A class name and its instance variables and properties
|
|
641
|
+
// are visible in the whole file. A method's parameters are visible in
|
|
642
|
+
// its body, but those of a method declaration are not visible at all.
|
|
643
|
+
ClassInterface: (node, def) => {
|
|
644
|
+
let name = node.node.getChild("TypeIdentifier");
|
|
645
|
+
if (name)
|
|
646
|
+
def(name, "class");
|
|
647
|
+
return false;
|
|
648
|
+
},
|
|
649
|
+
ClassImplementation: (node, def) => {
|
|
650
|
+
let name = node.node.getChild("TypeIdentifier");
|
|
651
|
+
if (name)
|
|
652
|
+
def(name, "class");
|
|
653
|
+
return false;
|
|
654
|
+
},
|
|
655
|
+
ProtocolDeclaration: (node, def) => {
|
|
656
|
+
for (let name of node.node.getChildren("TypeIdentifier"))
|
|
657
|
+
def(name, "interface");
|
|
658
|
+
return true;
|
|
659
|
+
},
|
|
660
|
+
ClassDeclaration: (node, def) => {
|
|
661
|
+
for (let name of node.node.getChildren("TypeIdentifier"))
|
|
662
|
+
def(name, "class");
|
|
663
|
+
return true;
|
|
664
|
+
},
|
|
665
|
+
// `@property NSString *name;` gives `name` and its instance variable `_name`.
|
|
666
|
+
PropertyDeclaration: (node, def) => {
|
|
667
|
+
declaredNames("property")(node, (name, type) => {
|
|
668
|
+
def(name, type);
|
|
669
|
+
def(name, "variable", "_");
|
|
670
|
+
});
|
|
671
|
+
return true;
|
|
672
|
+
},
|
|
673
|
+
MethodDeclaration: () => true,
|
|
674
|
+
KeywordDeclarator: (node, def) => {
|
|
675
|
+
let name = node.node.getChild("Identifier");
|
|
676
|
+
if (name)
|
|
677
|
+
def(name, "variable");
|
|
678
|
+
return true;
|
|
679
|
+
},
|
|
680
|
+
PreprocDirective: (node, def) => {
|
|
681
|
+
let first = node.node.firstChild;
|
|
682
|
+
if ((first === null || first === void 0 ? void 0 : first.name) == "#define") {
|
|
683
|
+
let name = node.node.getChild("Identifier");
|
|
684
|
+
if (name)
|
|
685
|
+
def(name, "constant");
|
|
686
|
+
}
|
|
687
|
+
return true;
|
|
688
|
+
},
|
|
689
|
+
__proto__: null
|
|
690
|
+
};
|
|
691
|
+
function getScope(doc, node) {
|
|
692
|
+
let cached = cache.get(node);
|
|
693
|
+
if (cached)
|
|
694
|
+
return cached;
|
|
695
|
+
let completions = [], top = true;
|
|
696
|
+
function def(node, type, prefix = "") {
|
|
697
|
+
let name = prefix + doc.sliceString(node.from, node.to);
|
|
698
|
+
completions.push({ option: { label: name, type }, at: node.from });
|
|
699
|
+
}
|
|
700
|
+
if (node.name == "ForRangeLoop" || node.name == "ForInStatement")
|
|
701
|
+
rangeLoopNames(node, def);
|
|
702
|
+
node.cursor(common.IterMode.IncludeAnonymous).iterate(node => {
|
|
703
|
+
if (top) {
|
|
704
|
+
top = false;
|
|
705
|
+
}
|
|
706
|
+
else if (node.name) {
|
|
707
|
+
let gather = gatherCompletions[node.name];
|
|
708
|
+
if (gather && gather(node, def) || isScope(node))
|
|
709
|
+
return false;
|
|
710
|
+
}
|
|
711
|
+
else if (node.to - node.from > 8192) {
|
|
712
|
+
// Allow caching for bigger internal nodes
|
|
713
|
+
for (let c of getScope(doc, node.node))
|
|
714
|
+
completions.push(c);
|
|
715
|
+
return false;
|
|
716
|
+
}
|
|
717
|
+
});
|
|
718
|
+
cache.set(node, completions);
|
|
719
|
+
return completions;
|
|
720
|
+
}
|
|
721
|
+
const Identifier = /^[\w$\xa1-][\w$\d\xa1-]*$/;
|
|
722
|
+
/**
|
|
723
|
+
Nodes inside which no completion is offered: strings, comments,
|
|
724
|
+
the names after `.` and `->`, and Objective-C selectors, which
|
|
725
|
+
have their own source.
|
|
726
|
+
*/
|
|
727
|
+
const dontComplete = [
|
|
728
|
+
"String", "RawString", "CharLiteral", "SystemLibString",
|
|
729
|
+
"LineComment", "BlockComment", "FieldIdentifier", "StatementIdentifier",
|
|
730
|
+
"SelectorName", "CategoryName", ".", "->", "::"
|
|
731
|
+
];
|
|
732
|
+
/**
|
|
733
|
+
Completion source that looks up the names declared in the file
|
|
734
|
+
(functions, types, variables, parameters, fields and macros), and
|
|
735
|
+
offers each one where it is in scope.
|
|
736
|
+
*/
|
|
737
|
+
const localCompletionSource = context => {
|
|
738
|
+
if (afterAccessor(context))
|
|
739
|
+
return null;
|
|
740
|
+
let inner = language.syntaxTree(context.state).resolveInner(context.pos, -1);
|
|
741
|
+
if (dontComplete.indexOf(inner.name) > -1)
|
|
742
|
+
return null;
|
|
743
|
+
let isWord = inner.name == "Identifier" || inner.name == "TypeIdentifier" ||
|
|
744
|
+
inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to));
|
|
745
|
+
if (!isWord && !context.explicit)
|
|
746
|
+
return null;
|
|
747
|
+
let options = [], seen = new Set();
|
|
748
|
+
for (let pos = inner; pos; pos = pos.parent) {
|
|
749
|
+
if (isScope(pos))
|
|
750
|
+
for (let { option, at } of getScope(context.state.doc, pos)) {
|
|
751
|
+
if (at >= context.pos && OrderedScopes.has(pos.name))
|
|
752
|
+
continue;
|
|
753
|
+
if (seen.has(option.label))
|
|
754
|
+
continue;
|
|
755
|
+
seen.add(option.label);
|
|
756
|
+
options.push(option);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
return {
|
|
760
|
+
options,
|
|
761
|
+
from: isWord ? inner.from : context.pos,
|
|
762
|
+
validFor: Identifier
|
|
763
|
+
};
|
|
764
|
+
};
|
|
765
|
+
function includeBefore(context) {
|
|
766
|
+
let line = context.state.doc.lineAt(context.pos);
|
|
767
|
+
return /^\s*#\s*(?:include|import)\s*[<"]([\w./]*)$/.exec(line.text.slice(0, context.pos - line.from));
|
|
768
|
+
}
|
|
769
|
+
function inInclude(context) {
|
|
770
|
+
return includeBefore(context) != null;
|
|
771
|
+
}
|
|
772
|
+
// True when the word being typed follows `.`, `->` or `::`, or is a
|
|
773
|
+
// header name in `#include`. Member and namespace names are handled by
|
|
774
|
+
// their own sources, or not at all.
|
|
775
|
+
function afterAccessor(context) {
|
|
776
|
+
if (inInclude(context))
|
|
777
|
+
return true;
|
|
778
|
+
let word = context.matchBefore(/\w*/);
|
|
779
|
+
let before = context.state.sliceDoc(Math.max(0, (word ? word.from : context.pos) - 3), word ? word.from : context.pos);
|
|
780
|
+
return /(\.|->|::)\s*$/.test(before);
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
Wrap a completion source so that it offers nothing inside strings
|
|
784
|
+
and comments, or after `.`, `->` or `::`.
|
|
785
|
+
*/
|
|
786
|
+
function generalSource(source) {
|
|
787
|
+
return context => {
|
|
788
|
+
let inner = language.syntaxTree(context.state).resolveInner(context.pos, -1);
|
|
789
|
+
for (let pos = inner; pos; pos = pos.parent)
|
|
790
|
+
if (dontComplete.indexOf(pos.name) > -1)
|
|
791
|
+
return null;
|
|
792
|
+
if (afterAccessor(context))
|
|
793
|
+
return null;
|
|
794
|
+
return source(context);
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
Completion source for the names in namespace `std`. It offers them
|
|
799
|
+
after `std::`, and anywhere names are completed when the file says
|
|
800
|
+
`using namespace std;`.
|
|
801
|
+
*/
|
|
802
|
+
function stdCompletionSource(names) {
|
|
803
|
+
return context => {
|
|
804
|
+
let line = context.state.doc.lineAt(context.pos);
|
|
805
|
+
let before = line.text.slice(0, context.pos - line.from);
|
|
806
|
+
let qualified = /\bstd\s*::\s*(\w*)$/.exec(before);
|
|
807
|
+
if (qualified) {
|
|
808
|
+
let inner = language.syntaxTree(context.state).resolveInner(context.pos, -1);
|
|
809
|
+
for (let pos = inner; pos; pos = pos.parent)
|
|
810
|
+
if (dontComplete.indexOf(pos.name) > -1 && pos.name != "::")
|
|
811
|
+
return null;
|
|
812
|
+
return { from: context.pos - qualified[1].length, options: names, validFor: /^\w*$/ };
|
|
813
|
+
}
|
|
814
|
+
if (!/\busing\s+namespace\s+std\s*;/.test(context.state.sliceDoc()))
|
|
815
|
+
return null;
|
|
816
|
+
return generalSource(context => {
|
|
817
|
+
let word = context.matchBefore(/\w+/);
|
|
818
|
+
if (!word && !context.explicit)
|
|
819
|
+
return null;
|
|
820
|
+
return { from: word ? word.from : context.pos, options: names, validFor: /^\w*$/ };
|
|
821
|
+
})(context);
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
Completion source for header names inside `#include <...>`.
|
|
826
|
+
*/
|
|
827
|
+
function headerCompletionSource(headers) {
|
|
828
|
+
return (context) => {
|
|
829
|
+
let m = includeBefore(context);
|
|
830
|
+
if (!m || !/<[\w./]*$/.test(m[0]))
|
|
831
|
+
return null;
|
|
832
|
+
return { from: context.pos - m[1].length, options: headers, validFor: /^[\w./]*$/ };
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
// Method heads declare selectors, so they get no selector completion.
|
|
836
|
+
const MethodHeads = new Set(["MethodDeclaration", "MethodDefinition", "PropertyAttribute"]);
|
|
837
|
+
// The selector of a method declared in the file, such as `initWithA:b:`.
|
|
838
|
+
function selectorOf(doc, method) {
|
|
839
|
+
let parts = method.getChildren("KeywordDeclarator");
|
|
840
|
+
if (!parts.length) {
|
|
841
|
+
let name = method.getChild("SelectorName");
|
|
842
|
+
return name ? doc.sliceString(name.from, name.to) : null;
|
|
843
|
+
}
|
|
844
|
+
return parts.map(p => {
|
|
845
|
+
let name = p.getChild("SelectorName");
|
|
846
|
+
return (name ? doc.sliceString(name.from, name.to) : "") + ":";
|
|
847
|
+
}).join("");
|
|
848
|
+
}
|
|
849
|
+
function fileSelectors(doc, tree) {
|
|
850
|
+
let found = [];
|
|
851
|
+
tree.cursor().iterate(node => {
|
|
852
|
+
if (node.name == "MethodDeclaration" || node.name == "MethodDefinition") {
|
|
853
|
+
let label = selectorOf(doc, node.node);
|
|
854
|
+
if (label)
|
|
855
|
+
found.push({ label, type: "method" });
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
});
|
|
859
|
+
return found;
|
|
860
|
+
}
|
|
861
|
+
// Completing `setObject:forKey:` inserts `setObject:`, so that the
|
|
862
|
+
// first argument comes next.
|
|
863
|
+
function firstPart(option) {
|
|
864
|
+
let colon = option.label.indexOf(":");
|
|
865
|
+
return colon < 0 || colon == option.label.length - 1 ? option : Object.assign(Object.assign({}, option), { apply: option.label.slice(0, colon + 1) });
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
Completion source for Objective-C selectors. Where a message names
|
|
869
|
+
its method, as in `[list add|`, it offers the given selectors and
|
|
870
|
+
the selectors of the methods declared in the file.
|
|
871
|
+
*/
|
|
872
|
+
function selectorCompletionSource(selectors) {
|
|
873
|
+
return context => {
|
|
874
|
+
let tree = language.syntaxTree(context.state);
|
|
875
|
+
let inner = tree.resolveInner(context.pos, -1);
|
|
876
|
+
if (inner.name != "SelectorName")
|
|
877
|
+
return null;
|
|
878
|
+
for (let pos = inner.parent; pos; pos = pos.parent)
|
|
879
|
+
if (MethodHeads.has(pos.name) || pos.name == "SelectorExpression")
|
|
880
|
+
return null;
|
|
881
|
+
let seen = new Set(), options = [];
|
|
882
|
+
for (let option of fileSelectors(context.state.doc, tree.topNode).concat(selectors)) {
|
|
883
|
+
if (seen.has(option.label))
|
|
884
|
+
continue;
|
|
885
|
+
seen.add(option.label);
|
|
886
|
+
options.push(firstPart(option));
|
|
887
|
+
}
|
|
888
|
+
return { from: inner.from, options, validFor: /^\w*$/ };
|
|
889
|
+
};
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
Completion source for the Objective-C `@` directives, offered when
|
|
893
|
+
the word being typed starts with `@`.
|
|
894
|
+
*/
|
|
895
|
+
function directiveCompletionSource(options) {
|
|
896
|
+
return context => {
|
|
897
|
+
let word = context.matchBefore(/@\w*/);
|
|
898
|
+
if (!word)
|
|
899
|
+
return null;
|
|
900
|
+
let inner = language.syntaxTree(context.state).resolveInner(context.pos, -1);
|
|
901
|
+
for (let pos = inner; pos; pos = pos.parent)
|
|
902
|
+
if (pos.name == "String" || pos.name == "LineComment" || pos.name == "BlockComment")
|
|
903
|
+
return null;
|
|
904
|
+
return { from: word.from, options, validFor: /^@\w*$/ };
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
Wrap a completion source so that it offers nothing when the word
|
|
909
|
+
being typed starts with `@`, where only directives make sense.
|
|
910
|
+
*/
|
|
911
|
+
function notAfterAt(source) {
|
|
912
|
+
return context => context.matchBefore(/@\w*/) ? null : source(context);
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
A language provider based on Exercism's fork of the [Lezer C++
|
|
917
|
+
parser](https://code.haverbeke.berlin/lezer/cpp), extended with
|
|
918
|
+
highlighting and indentation information.
|
|
919
|
+
*/
|
|
920
|
+
const cppLanguage = language.LRLanguage.define({
|
|
921
|
+
name: "cpp",
|
|
922
|
+
parser: lezerCpp.parser.configure({
|
|
923
|
+
props: [
|
|
924
|
+
language.indentNodeProp.add({
|
|
925
|
+
IfStatement: language.continuedIndent({ except: /^\s*({|else\b)/ }),
|
|
926
|
+
TryStatement: language.continuedIndent({ except: /^\s*({|catch)\b/ }),
|
|
927
|
+
LabeledStatement: language.flatIndent,
|
|
928
|
+
CaseStatement: context => context.baseIndent + context.unit,
|
|
929
|
+
BlockComment: () => null,
|
|
930
|
+
CompoundStatement: language.delimitedIndent({ closing: "}" }),
|
|
931
|
+
Statement: language.continuedIndent({ except: /^{/ }),
|
|
932
|
+
"MessageExpression ArrayLiteral": language.delimitedIndent({ closing: "]" }),
|
|
933
|
+
DictionaryLiteral: language.delimitedIndent({ closing: "}" })
|
|
934
|
+
}),
|
|
935
|
+
language.foldNodeProp.add({
|
|
936
|
+
"DeclarationList CompoundStatement EnumeratorList FieldDeclarationList InitializerList": language.foldInside,
|
|
937
|
+
"ArrayLiteral DictionaryLiteral": language.foldInside,
|
|
938
|
+
// An Objective-C class or protocol folds from the end of its
|
|
939
|
+
// first line to its `@end`.
|
|
940
|
+
"ClassInterface ClassImplementation ProtocolDeclaration"(tree, state) {
|
|
941
|
+
let end = tree.lastChild;
|
|
942
|
+
if (!end || end.name != "@end")
|
|
943
|
+
return null;
|
|
944
|
+
let from = state.doc.lineAt(tree.from).to;
|
|
945
|
+
return from < end.from ? { from, to: end.from } : null;
|
|
946
|
+
},
|
|
947
|
+
BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
|
|
948
|
+
})
|
|
949
|
+
]
|
|
950
|
+
}),
|
|
951
|
+
languageData: {
|
|
952
|
+
commentTokens: { line: "//", block: { open: "/*", close: "*/" } },
|
|
953
|
+
indentOnInput: /^\s*(?:case |default:|\{|\})$/,
|
|
954
|
+
closeBrackets: { stringPrefixes: ["L", "u", "U", "u8", "LR", "UR", "uR", "u8R", "R"] }
|
|
955
|
+
}
|
|
956
|
+
});
|
|
957
|
+
/**
|
|
958
|
+
Language support for C++. Includes
|
|
959
|
+
[snippet](https://codemirror.net/6/docs/ref/#lang-cpp.cppSnippets), keyword, standard library and
|
|
960
|
+
local name completion.
|
|
961
|
+
*/
|
|
962
|
+
function cpp() {
|
|
963
|
+
return new language.LanguageSupport(cppLanguage, [
|
|
964
|
+
cppLanguage.data.of({
|
|
965
|
+
autocomplete: generalSource(autocomplete.completeFromList(cppSnippets.concat(cppKeywords, cppGlobalTypes)))
|
|
966
|
+
}),
|
|
967
|
+
cppLanguage.data.of({ autocomplete: stdCompletionSource(stdNames) }),
|
|
968
|
+
cppLanguage.data.of({ autocomplete: headerCompletionSource(cppHeaders) }),
|
|
969
|
+
cppLanguage.data.of({ autocomplete: localCompletionSource })
|
|
970
|
+
]);
|
|
971
|
+
}
|
|
972
|
+
/**
|
|
973
|
+
Language support for C. It uses the C++ parser, which also parses
|
|
974
|
+
C, and completes C's keywords, standard library and
|
|
975
|
+
[snippets](https://codemirror.net/6/docs/ref/#lang-cpp.cSnippets) along with local names.
|
|
976
|
+
*/
|
|
977
|
+
function c() {
|
|
978
|
+
return new language.LanguageSupport(cppLanguage, [
|
|
979
|
+
cppLanguage.data.of({
|
|
980
|
+
autocomplete: generalSource(autocomplete.completeFromList(cSnippets.concat(cKeywords, cLibrary)))
|
|
981
|
+
}),
|
|
982
|
+
cppLanguage.data.of({ autocomplete: headerCompletionSource(cHeaders) }),
|
|
983
|
+
cppLanguage.data.of({ autocomplete: localCompletionSource })
|
|
984
|
+
]);
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
A language provider for Objective-C, using the parser's `objc`
|
|
988
|
+
dialect.
|
|
989
|
+
*/
|
|
990
|
+
const objcLanguage = cppLanguage.configure({ dialect: "objc" }, "objc");
|
|
991
|
+
/**
|
|
992
|
+
Language support for Objective-C. Includes C's keywords and
|
|
993
|
+
library, the Objective-C keywords, types and `@` directives, the
|
|
994
|
+
common Foundation classes, functions and methods,
|
|
995
|
+
[snippets](https://codemirror.net/6/docs/ref/#lang-cpp.objcSnippets), and local names.
|
|
996
|
+
*/
|
|
997
|
+
function objc() {
|
|
998
|
+
return new language.LanguageSupport(objcLanguage, [
|
|
999
|
+
objcLanguage.data.of({
|
|
1000
|
+
autocomplete: notAfterAt(generalSource(autocomplete.completeFromList(objcSnippets.concat(objcKeywords, cLibrary, foundationNames))))
|
|
1001
|
+
}),
|
|
1002
|
+
objcLanguage.data.of({ autocomplete: directiveCompletionSource(objcDirectiveSnippets.concat(objcDirectives)) }),
|
|
1003
|
+
objcLanguage.data.of({ autocomplete: selectorCompletionSource(foundationSelectors) }),
|
|
1004
|
+
objcLanguage.data.of({ autocomplete: headerCompletionSource(objcHeaders) }),
|
|
1005
|
+
objcLanguage.data.of({ autocomplete: localCompletionSource })
|
|
1006
|
+
]);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
exports.c = c;
|
|
1010
|
+
exports.cSnippets = cSnippets;
|
|
1011
|
+
exports.cpp = cpp;
|
|
1012
|
+
exports.cppLanguage = cppLanguage;
|
|
1013
|
+
exports.cppSnippets = cppSnippets;
|
|
1014
|
+
exports.localCompletionSource = localCompletionSource;
|
|
1015
|
+
exports.objc = objc;
|
|
1016
|
+
exports.objcLanguage = objcLanguage;
|
|
1017
|
+
exports.objcSnippets = objcSnippets;
|
|
1018
|
+
exports.selectorCompletionSource = selectorCompletionSource;
|