@exercism/codemirror-lang-php 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.
@@ -0,0 +1,52 @@
1
+ import { Language, LanguageSupport, LRLanguage } from '@codemirror/language';
2
+ import { Completion, CompletionSource } from '@codemirror/autocomplete';
3
+
4
+ /**
5
+ A collection of PHP-related [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
6
+ */
7
+ declare const snippets: readonly Completion[];
8
+
9
+ /**
10
+ Keywords, types and the most common built-in functions, classes,
11
+ interfaces and constants. These are offered outside strings and
12
+ comments, in places where a bare name can appear.
13
+ */
14
+ declare const builtins: readonly Completion[];
15
+
16
+ /**
17
+ Completion source that looks up names declared in the PHP file.
18
+ After `$this->`, it offers the class's methods and properties.
19
+ After `self::`, `static::`, `parent::` or the name of a class
20
+ declared in the file, it offers that class's static members. In
21
+ other places, it offers the variables in scope and the functions,
22
+ classes and constants declared in the file.
23
+ */
24
+ declare const localCompletionSource: CompletionSource;
25
+
26
+ /**
27
+ A language provider based on the [Lezer PHP
28
+ parser](https://code.haverbeke.berlin/lezer/php), extended with
29
+ highlighting and indentation information.
30
+ */
31
+ declare const phpLanguage: LRLanguage;
32
+ /**
33
+ PHP language support. Includes completion of keywords, common
34
+ built-in functions and classes, [snippets](https://codemirror.net/6/docs/ref/#lang-php.snippets),
35
+ and the names declared in the file.
36
+ */
37
+ declare function php(config?: {
38
+ /**
39
+ By default, the parser will treat content outside of `<?` and
40
+ `?>` markers as HTML. You can pass a different language here to
41
+ change that. Explicitly passing disables parsing of such content.
42
+ */
43
+ baseLanguage?: Language | null;
44
+ /**
45
+ By default, PHP parsing only starts at the first `<?` marker.
46
+ When you set this to true, it starts immediately at the start of
47
+ the document.
48
+ */
49
+ plain?: boolean;
50
+ }): LanguageSupport;
51
+
52
+ export { builtins, localCompletionSource, php, phpLanguage, snippets };
package/dist/index.js ADDED
@@ -0,0 +1,615 @@
1
+ import { parser } from '@exercism/lezer-php';
2
+ import { NodeWeakMap, IterMode, parseMixed } from '@lezer/common';
3
+ import { html } from '@codemirror/lang-html';
4
+ import { syntaxTree, LRLanguage, indentNodeProp, continuedIndent, delimitedIndent, foldNodeProp, foldInside, LanguageSupport } from '@codemirror/language';
5
+ import { snippetCompletion, completeFromList } from '@codemirror/autocomplete';
6
+
7
+ /**
8
+ A collection of PHP-related [snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
9
+ */
10
+ const snippets = [
11
+ /*@__PURE__*/snippetCompletion("function ${name}(${params}): ${type}\n{\n\t${}\n}", {
12
+ label: "function",
13
+ detail: "definition",
14
+ type: "keyword"
15
+ }),
16
+ /*@__PURE__*/snippetCompletion("fn(${params}) => ${}", {
17
+ label: "fn",
18
+ detail: "arrow function",
19
+ type: "keyword"
20
+ }),
21
+ /*@__PURE__*/snippetCompletion("public function ${name}(${params}): ${type}\n{\n\t${}\n}", {
22
+ label: "function",
23
+ detail: "public method",
24
+ type: "keyword"
25
+ }),
26
+ /*@__PURE__*/snippetCompletion("public function __construct(${params})\n{\n\t${}\n}", {
27
+ label: "__construct",
28
+ detail: "constructor",
29
+ type: "keyword"
30
+ }),
31
+ /*@__PURE__*/snippetCompletion("class ${name}\n{\n\t${}\n}", {
32
+ label: "class",
33
+ detail: "definition",
34
+ type: "keyword"
35
+ }),
36
+ /*@__PURE__*/snippetCompletion("interface ${name}\n{\n\t${}\n}", {
37
+ label: "interface",
38
+ detail: "definition",
39
+ type: "keyword"
40
+ }),
41
+ /*@__PURE__*/snippetCompletion("enum ${name}\n{\n\tcase ${};\n}", {
42
+ label: "enum",
43
+ detail: "definition",
44
+ type: "keyword"
45
+ }),
46
+ /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n}", {
47
+ label: "if",
48
+ detail: "block",
49
+ type: "keyword"
50
+ }),
51
+ /*@__PURE__*/snippetCompletion("if (${}) {\n\t${}\n} else {\n\t${}\n}", {
52
+ label: "if",
53
+ detail: "/ else block",
54
+ type: "keyword"
55
+ }),
56
+ /*@__PURE__*/snippetCompletion("foreach (${array} as ${value}) {\n\t${}\n}", {
57
+ label: "foreach",
58
+ detail: "loop",
59
+ type: "keyword"
60
+ }),
61
+ /*@__PURE__*/snippetCompletion("foreach (${array} as ${key} => ${value}) {\n\t${}\n}", {
62
+ label: "foreach",
63
+ detail: "key => value loop",
64
+ type: "keyword"
65
+ }),
66
+ /*@__PURE__*/snippetCompletion("for (${$i} = 0; ${$i} < ${end}; ${$i}++) {\n\t${}\n}", {
67
+ label: "for",
68
+ detail: "loop",
69
+ type: "keyword"
70
+ }),
71
+ /*@__PURE__*/snippetCompletion("while (${}) {\n\t${}\n}", {
72
+ label: "while",
73
+ detail: "loop",
74
+ type: "keyword"
75
+ }),
76
+ /*@__PURE__*/snippetCompletion("switch (${}) {\n\tcase ${}:\n\t\t${}\n\t\tbreak;\n\tdefault:\n\t\t${}\n}", {
77
+ label: "switch",
78
+ detail: "statement",
79
+ type: "keyword"
80
+ }),
81
+ /*@__PURE__*/snippetCompletion("match (${}) {\n\t${} => ${},\n\tdefault => ${},\n}", {
82
+ label: "match",
83
+ detail: "expression",
84
+ type: "keyword"
85
+ }),
86
+ /*@__PURE__*/snippetCompletion("try {\n\t${}\n} catch (${Exception} ${$e}) {\n\t${}\n}", {
87
+ label: "try",
88
+ detail: "/ catch block",
89
+ type: "keyword"
90
+ }),
91
+ /*@__PURE__*/snippetCompletion("throw new ${InvalidArgumentException}(${});", {
92
+ label: "throw",
93
+ detail: "exception",
94
+ type: "keyword"
95
+ }),
96
+ /*@__PURE__*/snippetCompletion("declare(strict_types=1);", {
97
+ label: "declare",
98
+ detail: "strict types",
99
+ type: "keyword"
100
+ })
101
+ ];
102
+
103
+ function list(names, type) {
104
+ return names.split(/\s+/).filter(n => n).map(label => ({ label, type }));
105
+ }
106
+ const keywords = /*@__PURE__*/list(`
107
+ abstract and as break case catch class clone const continue declare default do echo else elseif
108
+ enum extends final finally fn for foreach function global goto if implements include include_once
109
+ instanceof insteadof interface match namespace new or print private protected public readonly
110
+ require require_once return static switch throw trait try use var while xor yield
111
+ self parent true false null
112
+ `, "keyword");
113
+ const types = /*@__PURE__*/list(`
114
+ int float string bool array callable iterable object mixed void never
115
+ `, "type");
116
+ // Language constructs that look like function calls.
117
+ const constructs = /*@__PURE__*/list(`isset empty unset list array die exit`, "function");
118
+ // The functions that PHP solutions use most often: strings, arrays, maths,
119
+ // types, regular expressions and dates.
120
+ const functions = /*@__PURE__*/list(`
121
+ strlen str_split strrev strtolower strtoupper ucfirst lcfirst ucwords str_repeat str_pad
122
+ str_replace str_ireplace str_contains str_starts_with str_ends_with str_word_count substr
123
+ substr_count strpos stripos strrpos strstr strtr strcmp strcasecmp strncmp levenshtein
124
+ similar_text trim ltrim rtrim explode implode join sprintf printf vsprintf number_format
125
+ wordwrap nl2br htmlspecialchars ord chr bin2hex dechex hexdec bindec decbin octdec decoct
126
+ base_convert mb_strlen mb_substr mb_strtolower mb_strtoupper mb_str_split mb_str_pad
127
+ mb_convert_case ctype_digit ctype_alpha ctype_alnum ctype_upper ctype_lower ctype_space
128
+ ctype_punct preg_match preg_match_all preg_replace preg_replace_callback preg_split preg_quote
129
+ count array_map array_filter array_reduce array_walk array_sum array_product array_keys
130
+ array_values array_merge array_combine array_flip array_slice array_splice array_search
131
+ in_array array_key_exists array_key_first array_key_last array_unique array_reverse array_fill
132
+ array_fill_keys array_pad array_push array_pop array_shift array_unshift array_count_values
133
+ array_diff array_diff_key array_intersect array_intersect_key array_chunk array_column
134
+ array_rand array_is_list array_find array_any array_all range compact extract sort rsort
135
+ usort uasort uksort ksort krsort asort arsort shuffle iterator_to_array min max abs floor
136
+ ceil round intdiv fmod pow sqrt log exp pi random_int rand mt_rand intval floatval strval
137
+ boolval settype gettype get_debug_type is_int is_float is_string is_bool is_array
138
+ is_numeric is_null is_callable is_object is_iterable var_dump print_r var_export
139
+ json_encode json_decode serialize unserialize function_exists method_exists
140
+ property_exists class_exists get_class get_object_vars call_user_func
141
+ call_user_func_array func_get_args spl_object_id uniqid str_shuffle time date mktime
142
+ strtotime checkdate microtime hrtime
143
+ `, "function");
144
+ const classes = /*@__PURE__*/list(`
145
+ Exception ErrorException Error TypeError ValueError ArgumentCountError ArithmeticError
146
+ DivisionByZeroError InvalidArgumentException LogicException RuntimeException
147
+ DomainException LengthException OutOfRangeException OutOfBoundsException RangeException
148
+ UnexpectedValueException OverflowException UnderflowException BadFunctionCallException
149
+ BadMethodCallException DateTime DateTimeImmutable DateInterval DatePeriod DateTimeZone
150
+ ArrayObject ArrayIterator SplStack SplQueue SplObjectStorage SplFixedArray
151
+ SplPriorityQueue SplMinHeap SplMaxHeap SplDoublyLinkedList Generator Closure stdClass
152
+ WeakMap
153
+ `, "class");
154
+ const interfaces = /*@__PURE__*/list(`
155
+ Throwable DateTimeInterface Iterator IteratorAggregate Traversable Countable ArrayAccess
156
+ Stringable JsonSerializable UnitEnum BackedEnum
157
+ `, "interface");
158
+ const constants = /*@__PURE__*/list(`
159
+ PHP_EOL PHP_INT_MAX PHP_INT_MIN PHP_INT_SIZE PHP_FLOAT_EPSILON PHP_FLOAT_MAX PHP_FLOAT_MIN
160
+ PHP_VERSION M_PI M_E M_SQRT2 INF NAN E_ALL SORT_REGULAR SORT_NUMERIC SORT_STRING SORT_FLAG_CASE
161
+ COUNT_RECURSIVE ARRAY_FILTER_USE_KEY ARRAY_FILTER_USE_BOTH STR_PAD_LEFT STR_PAD_RIGHT
162
+ STR_PAD_BOTH PREG_SPLIT_NO_EMPTY PREG_SPLIT_DELIM_CAPTURE PREG_SET_ORDER PREG_PATTERN_ORDER
163
+ JSON_PRETTY_PRINT JSON_THROW_ON_ERROR MB_CASE_TITLE PHP_ROUND_HALF_UP PHP_ROUND_HALF_DOWN
164
+ PHP_ROUND_HALF_EVEN
165
+ `, "constant");
166
+ /**
167
+ Keywords, types and the most common built-in functions, classes,
168
+ interfaces and constants. These are offered outside strings and
169
+ comments, in places where a bare name can appear.
170
+ */
171
+ const builtins = /*@__PURE__*/keywords.concat(types, constructs, functions, classes, interfaces, constants);
172
+ /**
173
+ PHP's superglobal variables. They are visible in every scope.
174
+ */
175
+ const superglobals = /*@__PURE__*/list(`
176
+ $GLOBALS $_SERVER $_GET $_POST $_FILES $_COOKIE $_SESSION $_REQUEST $_ENV
177
+ `, "variable");
178
+
179
+ const word = /[\w\x80-￿]*/.source;
180
+ const validFor = /*@__PURE__*/new RegExp(`^\\$?${word}$`);
181
+ // Nodes that start a new scope for variables. PHP variables belong to the
182
+ // whole function (or the whole file at the top level), so blocks don't count.
183
+ const FunctionScopes = /*@__PURE__*/new Set(["FunctionDefinition", "MethodDeclaration", "FunctionExpression"]);
184
+ // Nodes that the variable collector doesn't enter, because their variables
185
+ // belong to another scope.
186
+ const SkipForVariables = /*@__PURE__*/new Set([
187
+ "FunctionDefinition", "MethodDeclaration", "FunctionExpression", "ArrowFunction",
188
+ "ClassDeclaration", "InterfaceDeclaration", "TraitDeclaration", "EnumDeclaration",
189
+ "DeclarationList", "ClassMemberName"
190
+ ]);
191
+ const ClassLike = /*@__PURE__*/new Set([
192
+ "ClassDeclaration", "InterfaceDeclaration", "TraitDeclaration", "EnumDeclaration"
193
+ ]);
194
+ // A `Name` directly inside one of these is the name being defined.
195
+ const DefinitionParents = /*@__PURE__*/new Set([
196
+ "ClassDeclaration", "InterfaceDeclaration", "TraitDeclaration", "EnumDeclaration",
197
+ "FunctionDefinition", "MethodDeclaration", "EnumCase", "VariableDeclarator",
198
+ "NamespaceName", "LabelStatement", "GotoStatement", "NamedArgument"
199
+ ]);
200
+ const NoCompletion = /*@__PURE__*/new Set([
201
+ "String", "HeredocString", "ShellExpression", "LineComment", "BlockComment", "Text",
202
+ "EscapeSequence", "PhpOpen", "PhpClose"
203
+ ]);
204
+ const variableCache = /*@__PURE__*/new NodeWeakMap();
205
+ const globalCache = /*@__PURE__*/new NodeWeakMap();
206
+ /**
207
+ Works out what kind of name can go at the cursor. It returns null
208
+ inside strings and comments, in the names of definitions, and
209
+ where nothing has been typed (unless completion was started
210
+ explicitly).
211
+ */
212
+ function phpCompletionContext(context) {
213
+ let { state, pos } = context;
214
+ let node = syntaxTree(state).resolveInner(pos, -1);
215
+ if (!inCode(node))
216
+ return null;
217
+ let line = state.doc.lineAt(pos);
218
+ let before = state.sliceDoc(Math.max(line.from, pos - 300), pos);
219
+ let member = new RegExp(`(\\$?${word})\\s*\\??->\\s*(${word})$`).exec(before);
220
+ if (member)
221
+ return { kind: "member", from: pos - member[2].length, node, target: member[1] };
222
+ let scoped = new RegExp(`(${word})\\s*::\\s*(\\$?${word})$`).exec(before);
223
+ if (scoped)
224
+ return { kind: "static", from: pos - scoped[2].length, node, target: scoped[1] };
225
+ if (/\b(function|class|interface|trait|enum|namespace|const|goto)\s+&?\s*\w*$/i.test(before))
226
+ return null;
227
+ if (/(^|[^\w$])(case)\s+\w*$/.test(before) && inEnumBody(node))
228
+ return null;
229
+ if (node.name == "Name" && node.parent && DefinitionParents.has(node.parent.name))
230
+ return null;
231
+ if (node.name == "VariableName" && node.parent && /Parameter$/.test(node.parent.name))
232
+ return null;
233
+ let typed = new RegExp(`\\$?${word}$`).exec(before)[0];
234
+ if (/^\$?\d/.test(typed))
235
+ return null;
236
+ if (!typed && !context.explicit)
237
+ return null;
238
+ return { kind: typed[0] == "$" ? "variable" : "name", from: pos - typed.length, node };
239
+ }
240
+ function inCode(node) {
241
+ var _a;
242
+ for (let cur = node; cur; cur = cur.parent) {
243
+ if (cur.name == "Interpolation")
244
+ return true;
245
+ if (cur.name == "VariableName" && ((_a = cur.parent) === null || _a === void 0 ? void 0 : _a.name) == "String")
246
+ return true;
247
+ if (NoCompletion.has(cur.name))
248
+ return false;
249
+ }
250
+ return true;
251
+ }
252
+ function inEnumBody(node) {
253
+ for (let cur = node; cur; cur = cur.parent) {
254
+ if (cur.name == "EnumBody")
255
+ return true;
256
+ if (cur.name == "Block")
257
+ return false;
258
+ }
259
+ return false;
260
+ }
261
+ function variablesIn(state, scope) {
262
+ let cached = variableCache.get(scope);
263
+ if (cached)
264
+ return cached;
265
+ let found = [], top = true;
266
+ scope.cursor(IterMode.IncludeAnonymous).iterate(node => {
267
+ if (top) {
268
+ top = false;
269
+ return;
270
+ }
271
+ if (SkipForVariables.has(node.name))
272
+ return false;
273
+ if (node.name == "VariableName")
274
+ found.push({ label: state.sliceDoc(node.from, node.to), type: "variable", from: node.from });
275
+ });
276
+ variableCache.set(scope, found);
277
+ return found;
278
+ }
279
+ function paramsOf(state, fn) {
280
+ let found = [];
281
+ let params = fn.getChild("ParamList");
282
+ if (params)
283
+ for (let p = params.firstChild; p; p = p.nextSibling) {
284
+ let name = p.getChild("VariableName");
285
+ if (name)
286
+ found.push({ label: state.sliceDoc(name.from, name.to), type: "variable", from: name.from });
287
+ }
288
+ return found;
289
+ }
290
+ function isStatic(node) {
291
+ return node.getChild("static") != null;
292
+ }
293
+ /**
294
+ Collects the variables in scope at `node`: the parameters and
295
+ variables of the enclosing function (or of the top level of the
296
+ file), the parameters of any arrow functions around it, `$this`
297
+ inside methods, and the superglobals.
298
+ */
299
+ function variablesAt(state, node) {
300
+ let found = [], inMethod = false, closed = false;
301
+ for (let cur = node; cur; cur = cur.parent) {
302
+ if (cur.name == "MethodDeclaration" && !isStatic(cur))
303
+ inMethod = true;
304
+ if (closed)
305
+ continue;
306
+ if (cur.name == "ArrowFunction") {
307
+ found = found.concat(paramsOf(state, cur));
308
+ }
309
+ else if (FunctionScopes.has(cur.name)) {
310
+ found = found.concat(variablesIn(state, cur));
311
+ closed = true;
312
+ }
313
+ else if (!cur.parent) {
314
+ found = found.concat(variablesIn(state, cur));
315
+ }
316
+ }
317
+ let options = [];
318
+ if (inMethod)
319
+ options.push({ label: "$this", type: "variable" });
320
+ for (let v of found)
321
+ if (v.from != node.from || v.label != state.sliceDoc(node.from, node.to))
322
+ options.push(v);
323
+ return options.concat(superglobals);
324
+ }
325
+ function nameOf(state, node) {
326
+ let name = node === null || node === void 0 ? void 0 : node.getChild("Name");
327
+ return name ? state.sliceDoc(name.from, name.to) : null;
328
+ }
329
+ /**
330
+ Collects the functions, classes, interfaces, traits, enums and
331
+ constants declared anywhere in the file, and the names imported
332
+ with `use`.
333
+ */
334
+ function globalNames(state, top) {
335
+ let cached = globalCache.get(top);
336
+ if (cached)
337
+ return cached;
338
+ let found = [];
339
+ let add = (node, type) => {
340
+ if (node)
341
+ found.push({ label: state.sliceDoc(node.from, node.to), type });
342
+ };
343
+ top.cursor().iterate(ref => {
344
+ var _a, _b;
345
+ let node = ref.node;
346
+ switch (node.name) {
347
+ case "ClassDeclaration":
348
+ case "TraitDeclaration":
349
+ add(node.getChild("Name"), "class");
350
+ break;
351
+ case "InterfaceDeclaration":
352
+ add(node.getChild("Name"), "interface");
353
+ break;
354
+ case "EnumDeclaration":
355
+ add(node.getChild("Name"), "enum");
356
+ break;
357
+ case "FunctionDefinition":
358
+ add(node.getChild("Name"), "function");
359
+ break;
360
+ case "ConstDeclaration":
361
+ if (((_a = node.parent) === null || _a === void 0 ? void 0 : _a.name) != "DeclarationList" && ((_b = node.parent) === null || _b === void 0 ? void 0 : _b.name) != "EnumBody")
362
+ for (let d of node.getChildren("VariableDeclarator"))
363
+ add(d.getChild("Name"), "constant");
364
+ return false;
365
+ case "NamespaceUseDeclaration":
366
+ node.cursor().iterate(inner => {
367
+ var _a;
368
+ if (inner.name == "Name") {
369
+ let name = ((_a = inner.node.parent) === null || _a === void 0 ? void 0 : _a.name) == "QualifiedName" ? inner.node.parent : inner.node;
370
+ let after = name.nextSibling;
371
+ // In `use A\B as C`, only `C` is the imported name.
372
+ if (!(after && after.name == "as"))
373
+ add(inner.node, "class");
374
+ }
375
+ });
376
+ return false;
377
+ }
378
+ });
379
+ globalCache.set(top, found);
380
+ return found;
381
+ }
382
+ function findClass(top, state, name) {
383
+ let result = null;
384
+ top.cursor().iterate(ref => {
385
+ var _a;
386
+ if (result)
387
+ return false;
388
+ if (ClassLike.has(ref.name) && ((_a = nameOf(state, ref.node)) === null || _a === void 0 ? void 0 : _a.toLowerCase()) == name.toLowerCase()) {
389
+ result = ref.node;
390
+ return false;
391
+ }
392
+ });
393
+ return result;
394
+ }
395
+ function enclosingClass(node) {
396
+ for (let cur = node; cur; cur = cur.parent) {
397
+ if (ClassLike.has(cur.name))
398
+ return cur;
399
+ if (cur.name == "NewExpression" && cur.getChild("DeclarationList"))
400
+ return cur;
401
+ }
402
+ return null;
403
+ }
404
+ function parentClassName(state, cls) {
405
+ let base = cls.getChild("BaseClause");
406
+ let name = base === null || base === void 0 ? void 0 : base.lastChild;
407
+ return name ? state.sliceDoc(name.from, name.to).replace(/^.*\\/, "") : null;
408
+ }
409
+ /**
410
+ Collects the members of a class, along with the ones it gets from
411
+ a parent class or traits declared in the same file. With
412
+ `scoped` set, it gives what can follow `::` (static properties
413
+ with their `$`, constants, enum cases and methods). Without it, it
414
+ gives what can follow `->` (properties without their `$`, and
415
+ methods).
416
+ */
417
+ function membersOf(state, top, cls, scoped, seen = []) {
418
+ var _a;
419
+ if (seen.some(s => s.from == cls.from && s.to == cls.to))
420
+ return [];
421
+ seen.push(cls);
422
+ let options = [];
423
+ let text = (n) => state.sliceDoc(n.from, n.to);
424
+ let prop = (n) => ({ label: scoped ? text(n) : text(n).slice(1), type: "property" });
425
+ let body = cls.getChild("DeclarationList") || cls.getChild("EnumBody");
426
+ if (!body)
427
+ return options;
428
+ let inherit = (name) => {
429
+ let other = name && findClass(top, state, name);
430
+ if (other)
431
+ options = options.concat(membersOf(state, top, other, scoped, seen));
432
+ };
433
+ for (let m = body.firstChild; m; m = m.nextSibling) {
434
+ if (m.name == "MethodDeclaration") {
435
+ let name = m.getChild("Name");
436
+ if (!name)
437
+ continue;
438
+ options.push({ label: text(name), type: "method" });
439
+ if (!scoped && text(name).toLowerCase() == "__construct")
440
+ for (let p of ((_a = m.getChild("ParamList")) === null || _a === void 0 ? void 0 : _a.getChildren("PropertyParameter")) || []) {
441
+ let v = p.getChild("VariableName");
442
+ if (v)
443
+ options.push(prop(v));
444
+ }
445
+ }
446
+ else if (m.name == "PropertyDeclaration") {
447
+ if (isStatic(m) != scoped)
448
+ continue;
449
+ for (let d of m.getChildren("VariableDeclarator")) {
450
+ let v = d.getChild("VariableName");
451
+ if (v)
452
+ options.push(prop(v));
453
+ }
454
+ }
455
+ else if (m.name == "ConstDeclaration" && scoped) {
456
+ for (let d of m.getChildren("VariableDeclarator")) {
457
+ let n = d.getChild("Name");
458
+ if (n)
459
+ options.push({ label: text(n), type: "constant" });
460
+ }
461
+ }
462
+ else if (m.name == "EnumCase" && scoped) {
463
+ let n = m.getChild("Name");
464
+ if (n)
465
+ options.push({ label: text(n), type: "enum" });
466
+ }
467
+ else if (m.name == "UseDeclaration") {
468
+ m.cursor().iterate(inner => {
469
+ if (inner.name == "UseList")
470
+ return false;
471
+ if (inner.name == "Name")
472
+ inherit(text(inner.node));
473
+ });
474
+ }
475
+ }
476
+ inherit(parentClassName(state, cls));
477
+ if (scoped)
478
+ options.push({ label: "class", type: "keyword" });
479
+ return options;
480
+ }
481
+ function dedupe(options) {
482
+ let seen = new Set(), result = [];
483
+ for (let o of options)
484
+ if (!seen.has(o.label)) {
485
+ seen.add(o.label);
486
+ result.push(o);
487
+ }
488
+ return result;
489
+ }
490
+ /**
491
+ Completion source that looks up names declared in the PHP file.
492
+ After `$this->`, it offers the class's methods and properties.
493
+ After `self::`, `static::`, `parent::` or the name of a class
494
+ declared in the file, it offers that class's static members. In
495
+ other places, it offers the variables in scope and the functions,
496
+ classes and constants declared in the file.
497
+ */
498
+ const localCompletionSource = context => {
499
+ let cx = phpCompletionContext(context);
500
+ if (!cx)
501
+ return null;
502
+ let { state } = context;
503
+ let top = syntaxTree(state).topNode;
504
+ let options = [];
505
+ if (cx.kind == "member") {
506
+ let cls = cx.target == "$this" ? enclosingClass(cx.node) : null;
507
+ if (!cls)
508
+ return null;
509
+ options = membersOf(state, top, cls, false);
510
+ }
511
+ else if (cx.kind == "static") {
512
+ let target = cx.target.toLowerCase(), cls = null;
513
+ if (target == "self" || target == "static") {
514
+ cls = enclosingClass(cx.node);
515
+ }
516
+ else if (target == "parent") {
517
+ let own = enclosingClass(cx.node), name = own && parentClassName(state, own);
518
+ cls = name ? findClass(top, state, name) : null;
519
+ }
520
+ else {
521
+ cls = findClass(top, state, cx.target);
522
+ }
523
+ if (!cls)
524
+ return null;
525
+ options = membersOf(state, top, cls, true);
526
+ }
527
+ else if (cx.kind == "variable") {
528
+ options = variablesAt(state, cx.node);
529
+ }
530
+ else {
531
+ options = globalNames(state, top);
532
+ if (cx.from == context.pos)
533
+ options = options.concat(variablesAt(state, cx.node));
534
+ }
535
+ return { options: dedupe(options), from: cx.from, validFor };
536
+ };
537
+ /**
538
+ Wraps a completion source so that it only runs where a bare name
539
+ (one without a `$`, `->` or `::` before it) can go.
540
+ */
541
+ function ifBareName(source) {
542
+ return context => {
543
+ let cx = phpCompletionContext(context);
544
+ return cx && cx.kind == "name" ? source(context) : null;
545
+ };
546
+ }
547
+
548
+ /**
549
+ A language provider based on the [Lezer PHP
550
+ parser](https://code.haverbeke.berlin/lezer/php), extended with
551
+ highlighting and indentation information.
552
+ */
553
+ const phpLanguage = /*@__PURE__*/LRLanguage.define({
554
+ name: "php",
555
+ parser: /*@__PURE__*/parser.configure({
556
+ props: [
557
+ /*@__PURE__*/indentNodeProp.add({
558
+ IfStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|else\b|elseif\b|endif\b)/ }),
559
+ TryStatement: /*@__PURE__*/continuedIndent({ except: /^\s*({|catch\b|finally\b)/ }),
560
+ SwitchBody: context => {
561
+ let after = context.textAfter, closed = /^\s*\}/.test(after), isCase = /^\s*(case|default)\b/.test(after);
562
+ return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
563
+ },
564
+ ColonBlock: cx => cx.baseIndent + cx.unit,
565
+ "Block EnumBody DeclarationList": /*@__PURE__*/delimitedIndent({ closing: "}" }),
566
+ ArrowFunction: cx => cx.baseIndent + cx.unit,
567
+ "String BlockComment": () => null,
568
+ Statement: /*@__PURE__*/continuedIndent({ except: /^({|end(for|foreach|switch|while)\b)/ })
569
+ }),
570
+ /*@__PURE__*/foldNodeProp.add({
571
+ "Block EnumBody DeclarationList SwitchBody ArrayExpression ValueList": foldInside,
572
+ ColonBlock(tree) { return { from: tree.from + 1, to: tree.to }; },
573
+ BlockComment(tree) { return { from: tree.from + 2, to: tree.to - 2 }; }
574
+ })
575
+ ]
576
+ }),
577
+ languageData: {
578
+ commentTokens: { block: { open: "/*", close: "*/" }, line: "//" },
579
+ indentOnInput: /^\s*(?:case |default:|end(?:if|for(?:each)?|switch|while)|else(?:if)?|\{|\})$/,
580
+ wordChars: "$",
581
+ closeBrackets: { stringPrefixes: ["b", "B"] }
582
+ }
583
+ });
584
+ /**
585
+ PHP language support. Includes completion of keywords, common
586
+ built-in functions and classes, [snippets](https://codemirror.net/6/docs/ref/#lang-php.snippets),
587
+ and the names declared in the file.
588
+ */
589
+ function php(config = {}) {
590
+ let support = [], base;
591
+ if (config.baseLanguage === null) ;
592
+ else if (config.baseLanguage) {
593
+ base = config.baseLanguage;
594
+ }
595
+ else {
596
+ let htmlSupport = html({ matchClosingTags: false });
597
+ support.push(htmlSupport.support);
598
+ base = htmlSupport.language;
599
+ }
600
+ let lang = phpLanguage.configure({
601
+ wrap: base && parseMixed(node => {
602
+ if (!node.type.isTop)
603
+ return null;
604
+ return {
605
+ parser: base.parser,
606
+ overlay: node => node.name == "Text"
607
+ };
608
+ }),
609
+ top: config.plain ? "Program" : "Template"
610
+ });
611
+ support.push(lang.data.of({ autocomplete: ifBareName(completeFromList(snippets.concat(builtins))) }), lang.data.of({ autocomplete: localCompletionSource }));
612
+ return new LanguageSupport(lang, support);
613
+ }
614
+
615
+ export { builtins, localCompletionSource, php, phpLanguage, snippets };