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