Line data Source code
1 : /*
2 : +----------------------------------------------------------------------+
3 : | LSParrot PHP LSP Extension |
4 : +----------------------------------------------------------------------+
5 : | Copyright (c) LSParrot GitHub Organization |
6 : +----------------------------------------------------------------------+
7 : | This source file is subject to the 0BSD license that is |
8 : | bundled with this package in the file LICENSE. |
9 : +----------------------------------------------------------------------+
10 : | Author: Go Kudo <zeriyoshi@gmail.com> |
11 : +----------------------------------------------------------------------+
12 : */
13 :
14 : #include "lsp_internal.h"
15 :
16 548 : static inline void lsp_symbol_index_header_init(lsp_symbol_index *region)
17 : {
18 : lsp_symbol_index_header *header;
19 :
20 548 : if (!region->available || !region->addr || region->size < sizeof(lsp_symbol_index_header)) {
21 0 : return;
22 : }
23 :
24 548 : header = (lsp_symbol_index_header *) region->addr;
25 548 : header->magic = LSP_SYMBOL_INDEX_MAGIC;
26 548 : header->reserved = 0;
27 548 : header->generation = 1;
28 548 : header->capacity = region->size;
29 548 : header->used = sizeof(lsp_symbol_index_header);
30 548 : header->symbol_count = 0;
31 548 : header->flags = 0;
32 : }
33 :
34 10588 : static inline zend_string *lsp_symbol_index_key(char kind, zend_string *fqcn)
35 : {
36 : zend_string *key;
37 10588 : const char *value = ZSTR_VAL(fqcn);
38 10588 : size_t i, length = ZSTR_LEN(fqcn);
39 :
40 : /* Index records are stored without a leading namespace separator, so a
41 : * fully-qualified probe such as "\App\Widget" must normalize to the same
42 : * key as "App\Widget". */
43 10588 : if (length > 0 && value[0] == '\\') {
44 0 : value++;
45 0 : length--;
46 : }
47 :
48 10588 : key = zend_string_alloc(length + 1, 0);
49 10588 : ZSTR_VAL(key)[0] = kind;
50 242604 : for (i = 0; i < length; i++) {
51 232016 : ZSTR_VAL(key)[i + 1] = (char) tolower((unsigned char) value[i]);
52 : }
53 10588 : ZSTR_VAL(key)[length + 1] = '\0';
54 :
55 10588 : return key;
56 : }
57 :
58 3596 : static inline void lsp_symbol_index_add_key(lsp_symbol_index *region, char kind, zend_string *fqcn, size_t record_offset)
59 : {
60 : zend_string *key;
61 : zval offset_zv;
62 :
63 3596 : if (!region->keys_initialized) {
64 0 : return;
65 : }
66 :
67 3596 : key = lsp_symbol_index_key(kind, fqcn);
68 3596 : ZVAL_LONG(&offset_zv, (zend_long) record_offset);
69 3596 : zend_hash_add(®ion->symbol_keys, key, &offset_zv);
70 3596 : zend_string_release(key);
71 : }
72 :
73 3816 : static inline bool lsp_symbol_index_has_key(lsp_symbol_index *region, char kind, zend_string *fqcn)
74 : {
75 : zend_string *key;
76 : bool exists;
77 :
78 3816 : if (!region->keys_initialized) {
79 0 : return false;
80 : }
81 :
82 3816 : key = lsp_symbol_index_key(kind, fqcn);
83 3816 : exists = zend_hash_exists(®ion->symbol_keys, key);
84 3816 : zend_string_release(key);
85 :
86 3816 : return exists;
87 : }
88 :
89 548 : extern void lsp_symbol_index_init(lsp_symbol_index *region, lsp_options *options)
90 : {
91 548 : memset(region, 0, sizeof(*region));
92 :
93 548 : if (options->symbol_index_size < sizeof(lsp_symbol_index_header) + 1024) {
94 0 : options->symbol_index_size = sizeof(lsp_symbol_index_header) + 1024;
95 : }
96 :
97 548 : region->size = options->symbol_index_size;
98 548 : region->addr = ecalloc(1, region->size);
99 548 : region->available = region->addr != NULL;
100 548 : zend_hash_init(®ion->symbol_keys, 1024, NULL, NULL, 0);
101 548 : region->keys_initialized = true;
102 548 : lsp_symbol_index_header_init(region);
103 548 : }
104 :
105 3598 : extern void lsp_symbol_index_table_invalidate(lsp_symbol_index *region)
106 : {
107 3598 : if (region->entries) {
108 124 : efree(region->entries);
109 124 : region->entries = NULL;
110 : }
111 :
112 3598 : if (region->segments) {
113 124 : efree(region->segments);
114 124 : region->segments = NULL;
115 : }
116 :
117 3598 : region->entry_count = 0;
118 3598 : region->segment_count = 0;
119 3598 : region->table_valid = false;
120 3598 : }
121 :
122 548 : extern void lsp_symbol_index_destroy(lsp_symbol_index *region)
123 : {
124 548 : if (region->keys_initialized) {
125 548 : zend_hash_destroy(®ion->symbol_keys);
126 : }
127 :
128 548 : lsp_symbol_index_table_invalidate(region);
129 :
130 548 : if (region->addr) {
131 548 : efree(region->addr);
132 : }
133 :
134 548 : memset(region, 0, sizeof(*region));
135 548 : }
136 :
137 546 : extern void lsp_symbol_index_reset(lsp_symbol_index *region)
138 : {
139 : lsp_symbol_index_header *header;
140 :
141 546 : if (!region->available || !region->addr) {
142 0 : return;
143 : }
144 :
145 546 : header = (lsp_symbol_index_header *) region->addr;
146 546 : header->magic = LSP_SYMBOL_INDEX_MAGIC;
147 546 : header->reserved = 0;
148 546 : header->generation++;
149 546 : header->capacity = region->size;
150 546 : header->used = sizeof(lsp_symbol_index_header);
151 546 : header->symbol_count = 0;
152 546 : header->flags = 0;
153 546 : if (region->keys_initialized) {
154 546 : zend_hash_clean(®ion->symbol_keys);
155 : }
156 :
157 546 : lsp_symbol_index_table_invalidate(region);
158 : }
159 :
160 7096 : extern bool lsp_path_value_contains_vendor(const char *path, size_t path_length)
161 : {
162 7096 : return lsp_path_value_contains_segment(path, path_length, "vendor");
163 : }
164 :
165 3948 : extern bool lsp_path_value_contains_analysis_helper(const char *path, size_t path_length)
166 : {
167 3948 : return lsp_path_value_contains_segment(path, path_length, ".lsparrot");
168 : }
169 :
170 3820 : extern bool lsp_symbol_index_add_symbol_kind(lsp_symbol_index *region, char kind, zend_string *fqcn, zend_string *path)
171 : {
172 : lsp_symbol_index_header *header;
173 : size_t need;
174 : char *cursor;
175 :
176 3820 : if (!region->available || !region->addr) {
177 0 : return false;
178 : }
179 :
180 3820 : header = (lsp_symbol_index_header *) region->addr;
181 3820 : if (header->magic != LSP_SYMBOL_INDEX_MAGIC) {
182 0 : return false;
183 : }
184 :
185 3820 : if (path && lsp_path_value_contains_analysis_helper(ZSTR_VAL(path), ZSTR_LEN(path))) {
186 4 : return false;
187 : }
188 :
189 3816 : if (lsp_symbol_index_has_key(region, kind, fqcn)) {
190 1884 : return false;
191 : }
192 :
193 1932 : need = 1 + ZSTR_LEN(fqcn) + 1 + (path ? ZSTR_LEN(path) : 0) + 1;
194 1932 : if (header->used + need > header->capacity) {
195 0 : return false;
196 : }
197 :
198 1932 : cursor = ((char *) region->addr) + header->used;
199 1932 : *cursor++ = kind;
200 1932 : memcpy(cursor, ZSTR_VAL(fqcn), ZSTR_LEN(fqcn));
201 1932 : cursor += ZSTR_LEN(fqcn);
202 1932 : *cursor++ = '\0';
203 :
204 1932 : if (path) {
205 1932 : memcpy(cursor, ZSTR_VAL(path), ZSTR_LEN(path));
206 1932 : cursor += ZSTR_LEN(path);
207 : }
208 :
209 1932 : *cursor++ = '\0';
210 1932 : lsp_symbol_index_add_key(region, kind, fqcn, header->used);
211 1932 : header->used += need;
212 1932 : header->symbol_count++;
213 1932 : lsp_symbol_index_table_invalidate(region);
214 :
215 1932 : return true;
216 : }
217 :
218 32480 : extern const char *lsp_symbol_entry_fqcn(lsp_symbol_index *region, const lsp_symbol_entry *entry)
219 : {
220 32480 : return ((const char *) region->addr) + entry->record_offset + 1;
221 : }
222 :
223 1100 : extern const char *lsp_symbol_entry_path(lsp_symbol_index *region, const lsp_symbol_entry *entry)
224 : {
225 1100 : return lsp_symbol_entry_fqcn(region, entry) + entry->fqcn_length + 1;
226 : }
227 :
228 : /* qsort(3) has no user-data parameter in C99, so the comparator reads the
229 : * region being sorted from this file-local pointer. The server is strictly
230 : * single-threaded, which makes this safe. */
231 : static lsp_symbol_index *lsp_symbol_sort_region = NULL;
232 :
233 13280 : static inline int lsp_symbol_segment_compare(const void *left, const void *right)
234 : {
235 13280 : const lsp_symbol_segment *a = (const lsp_symbol_segment *) left, *b = (const lsp_symbol_segment *) right;
236 : const char *sa, *sb;
237 : int result;
238 :
239 13280 : sa = lsp_symbol_entry_fqcn(lsp_symbol_sort_region, &lsp_symbol_sort_region->entries[a->entry_index]) + a->segment_offset;
240 13280 : sb = lsp_symbol_entry_fqcn(lsp_symbol_sort_region, &lsp_symbol_sort_region->entries[b->entry_index]) + b->segment_offset;
241 13280 : result = strcasecmp(sa, sb);
242 13280 : if (result != 0) {
243 13276 : return result;
244 : }
245 :
246 4 : if (a->entry_index != b->entry_index) {
247 4 : return a->entry_index < b->entry_index ? -1 : 1;
248 : }
249 :
250 0 : return a->segment_offset < b->segment_offset ? -1 : (a->segment_offset > b->segment_offset ? 1 : 0);
251 : }
252 :
253 264 : extern void lsp_symbol_index_table_ensure(lsp_symbol_index *region)
254 : {
255 : lsp_symbol_index_header *header;
256 : lsp_symbol_entry *entry;
257 : uint32_t i, j, segment_capacity;
258 : size_t fqcn_length, path_length;
259 : char *cursor, *end, *base, *fqcn, *path, kind;
260 :
261 264 : if (region->table_valid) {
262 96 : return;
263 : }
264 :
265 168 : lsp_symbol_index_table_invalidate(region);
266 168 : region->table_valid = true;
267 :
268 168 : if (!region->available || !region->addr) {
269 0 : return;
270 : }
271 :
272 168 : header = (lsp_symbol_index_header *) region->addr;
273 168 : if (header->magic != LSP_SYMBOL_INDEX_MAGIC || header->used > header->capacity || header->symbol_count == 0) {
274 44 : return;
275 : }
276 :
277 124 : base = (char *) region->addr;
278 124 : region->entries = safe_emalloc(header->symbol_count, sizeof(lsp_symbol_entry), 0);
279 124 : cursor = base + sizeof(lsp_symbol_index_header);
280 124 : end = base + header->used;
281 1292 : for (i = 0; i < header->symbol_count && cursor < end; i++) {
282 1168 : kind = *cursor++;
283 1168 : fqcn = cursor;
284 1168 : fqcn_length = strlen(fqcn);
285 1168 : path = fqcn + fqcn_length + 1;
286 1168 : if (path >= end) {
287 0 : break;
288 : }
289 :
290 1168 : path_length = strlen(path);
291 1168 : cursor = path + path_length + 1;
292 1168 : if (cursor > end) {
293 0 : break;
294 : }
295 :
296 1168 : if (kind == LSP_SYMBOL_TOMBSTONE) {
297 0 : continue;
298 : }
299 :
300 1168 : entry = ®ion->entries[region->entry_count++];
301 1168 : entry->record_offset = (uint32_t) ((fqcn - 1) - base);
302 1168 : entry->fqcn_length = (uint32_t) fqcn_length;
303 1168 : entry->path_length = (uint32_t) path_length;
304 1168 : entry->kind = (uint8_t) kind;
305 1168 : entry->flags = lsp_path_value_contains_vendor(path, path_length) ? LSP_SYMBOL_ENTRY_VENDOR : 0;
306 : }
307 :
308 124 : if (region->entry_count == 0) {
309 0 : return;
310 : }
311 :
312 124 : segment_capacity = region->entry_count * 2;
313 124 : region->segments = safe_emalloc(segment_capacity, sizeof(lsp_symbol_segment), 0);
314 1292 : for (i = 0; i < region->entry_count; i++) {
315 1168 : entry = ®ion->entries[i];
316 1168 : fqcn = (char *) lsp_symbol_entry_fqcn(region, entry);
317 18532 : for (j = 0; j < entry->fqcn_length; j++) {
318 17364 : if (j != 0 && fqcn[j - 1] != '\\' && fqcn[j - 1] != '_') {
319 14644 : continue;
320 : }
321 :
322 2720 : if (region->segment_count >= segment_capacity) {
323 72 : segment_capacity *= 2;
324 72 : region->segments = safe_erealloc(region->segments, segment_capacity, sizeof(lsp_symbol_segment), 0);
325 : }
326 :
327 2720 : region->segments[region->segment_count].entry_index = i;
328 2720 : region->segments[region->segment_count].segment_offset = j;
329 2720 : region->segment_count++;
330 : }
331 : }
332 :
333 124 : lsp_symbol_sort_region = region;
334 124 : qsort(region->segments, region->segment_count, sizeof(lsp_symbol_segment), lsp_symbol_segment_compare);
335 124 : lsp_symbol_sort_region = NULL;
336 : }
337 :
338 404 : extern void lsp_symbol_index_rebuild_keys(lsp_symbol_index *region)
339 : {
340 : lsp_symbol_index_header *header;
341 : zend_string *fqcn_string;
342 : char *cursor, *end, *base, *fqcn, *path, kind;
343 : uint32_t i;
344 : size_t fqcn_length, path_length, record_offset;
345 :
346 404 : if (!region->available || !region->addr || !region->keys_initialized) {
347 0 : return;
348 : }
349 :
350 404 : zend_hash_clean(®ion->symbol_keys);
351 404 : lsp_symbol_index_table_invalidate(region);
352 :
353 404 : header = (lsp_symbol_index_header *) region->addr;
354 404 : if (header->magic != LSP_SYMBOL_INDEX_MAGIC || header->used > header->capacity) {
355 0 : return;
356 : }
357 :
358 404 : base = (char *) region->addr;
359 404 : cursor = base + sizeof(lsp_symbol_index_header);
360 404 : end = base + header->used;
361 2068 : for (i = 0; i < header->symbol_count && cursor < end; i++) {
362 1664 : record_offset = (size_t) (cursor - base);
363 1664 : kind = *cursor++;
364 1664 : fqcn = cursor;
365 1664 : fqcn_length = strlen(fqcn);
366 1664 : path = fqcn + fqcn_length + 1;
367 1664 : if (path >= end) {
368 0 : break;
369 : }
370 :
371 1664 : path_length = strlen(path);
372 1664 : cursor = path + path_length + 1;
373 1664 : if (cursor > end) {
374 0 : break;
375 : }
376 :
377 1664 : if (kind == LSP_SYMBOL_TOMBSTONE) {
378 0 : continue;
379 : }
380 :
381 1664 : fqcn_string = zend_string_init(fqcn, fqcn_length, 0);
382 1664 : lsp_symbol_index_add_key(region, kind, fqcn_string, record_offset);
383 1664 : zend_string_release(fqcn_string);
384 : }
385 : }
386 :
387 16 : extern uint32_t lsp_symbol_index_remove_path(lsp_symbol_index *region, zend_string *path)
388 : {
389 : lsp_symbol_entry *entry;
390 : zend_string *fqcn_string, *key;
391 : const char *fqcn, *entry_path;
392 : char *base;
393 16 : uint32_t i, removed = 0;
394 :
395 16 : if (!region->available || !region->addr) {
396 0 : return 0;
397 : }
398 :
399 16 : lsp_symbol_index_table_ensure(region);
400 :
401 16 : base = (char *) region->addr;
402 20 : for (i = 0; i < region->entry_count; i++) {
403 4 : entry = ®ion->entries[i];
404 4 : if ((entry->flags & LSP_SYMBOL_ENTRY_DELETED) != 0) {
405 0 : continue;
406 : }
407 :
408 4 : entry_path = lsp_symbol_entry_path(region, entry);
409 4 : if (entry->path_length != ZSTR_LEN(path) || memcmp(entry_path, ZSTR_VAL(path), ZSTR_LEN(path)) != 0) {
410 0 : continue;
411 : }
412 :
413 : /* Tombstone the arena record (kept in place so the record walk stays
414 : * intact), drop the dedup/lookup key, and hide the derived entry. */
415 4 : fqcn = lsp_symbol_entry_fqcn(region, entry);
416 4 : if (region->keys_initialized) {
417 4 : fqcn_string = zend_string_init(fqcn, entry->fqcn_length, 0);
418 4 : key = lsp_symbol_index_key((char) entry->kind, fqcn_string);
419 4 : zend_hash_del(®ion->symbol_keys, key);
420 4 : zend_string_release(key);
421 4 : zend_string_release(fqcn_string);
422 : }
423 :
424 4 : base[entry->record_offset] = LSP_SYMBOL_TOMBSTONE;
425 4 : entry->flags |= LSP_SYMBOL_ENTRY_DELETED;
426 4 : removed++;
427 : }
428 :
429 16 : return removed;
430 : }
431 :
432 796 : extern const char *lsp_symbol_index_lookup(lsp_symbol_index *region, char expected_kind, zend_string *fqcn, char *found_kind, const char **stored_fqcn, size_t *path_length)
433 : {
434 : static const char class_like_kinds[] = { LSP_SYMBOL_CLASS, LSP_SYMBOL_INTERFACE, LSP_SYMBOL_TRAIT, LSP_SYMBOL_ENUM };
435 : lsp_symbol_index_header *header;
436 : zend_string *key;
437 : zval *offset_zv;
438 796 : const char *probe_kinds, *base, *stored, *path, *best_path = NULL;
439 796 : size_t probe_count, i, record_offset, best_offset = 0, stored_length;
440 : char single_kind[1];
441 :
442 796 : if (!region->available || !region->addr || !region->keys_initialized) {
443 0 : return NULL;
444 : }
445 :
446 796 : header = (lsp_symbol_index_header *) region->addr;
447 796 : if (header->magic != LSP_SYMBOL_INDEX_MAGIC || header->used > header->capacity) {
448 0 : return NULL;
449 : }
450 :
451 796 : if (expected_kind == LSP_SYMBOL_CLASS) {
452 792 : probe_kinds = class_like_kinds;
453 792 : probe_count = sizeof(class_like_kinds);
454 : } else {
455 4 : single_kind[0] = expected_kind;
456 4 : probe_kinds = single_kind;
457 4 : probe_count = 1;
458 : }
459 :
460 796 : base = (const char *) region->addr;
461 3968 : for (i = 0; i < probe_count; i++) {
462 3172 : key = lsp_symbol_index_key(probe_kinds[i], fqcn);
463 3172 : offset_zv = zend_hash_find(®ion->symbol_keys, key);
464 3172 : zend_string_release(key);
465 3172 : if (!offset_zv || Z_TYPE_P(offset_zv) != IS_LONG) {
466 2452 : continue;
467 : }
468 :
469 720 : record_offset = (size_t) Z_LVAL_P(offset_zv);
470 720 : if (record_offset + 1 >= header->used) {
471 0 : continue;
472 : }
473 :
474 : /* Keep the earliest arena record to preserve historical first-match
475 : * semantics when multiple class-like kinds share one FQCN. */
476 720 : if (best_path && record_offset >= best_offset) {
477 0 : continue;
478 : }
479 :
480 720 : stored = base + record_offset + 1;
481 720 : stored_length = strlen(stored);
482 720 : path = stored + stored_length + 1;
483 720 : if (path >= base + header->used) {
484 0 : continue;
485 : }
486 :
487 720 : best_path = path;
488 720 : best_offset = record_offset;
489 720 : if (found_kind) {
490 720 : *found_kind = base[record_offset];
491 : }
492 720 : if (stored_fqcn) {
493 8 : *stored_fqcn = stored;
494 : }
495 720 : if (path_length) {
496 720 : *path_length = strlen(path);
497 : }
498 : }
499 :
500 796 : return best_path;
501 : }
502 :
503 : static inline bool lsp_symbol_index_add_symbol(lsp_symbol_index *region, zend_string *fqcn, zend_string *path)
504 : {
505 : return lsp_symbol_index_add_symbol_kind(region, LSP_SYMBOL_CLASS, fqcn, path);
506 : }
507 :
508 45400 : extern const char *lsp_basename_from_fqcn(const char *fqcn, size_t length, size_t *label_length)
509 : {
510 : size_t i;
511 :
512 688092 : for (i = length; i > 0; i--) {
513 653484 : if (fqcn[i - 1] == '\\') {
514 10792 : *label_length = length - i;
515 10792 : return fqcn + i;
516 : }
517 : }
518 :
519 549804 : for (i = length; i > 0; i--) {
520 515572 : if (fqcn[i - 1] == '_') {
521 376 : *label_length = length - i;
522 376 : return fqcn + i;
523 : }
524 : }
525 :
526 34232 : *label_length = length;
527 :
528 34232 : return fqcn;
529 : }
530 :
531 18380 : extern bool lsp_token_is_class_like(zval *token)
532 : {
533 36440 : return lsp_token_name_equals(token, "T_CLASS") ||
534 36120 : lsp_token_name_equals(token, "T_INTERFACE") ||
535 54500 : lsp_token_name_equals(token, "T_TRAIT") ||
536 18056 : lsp_token_name_equals(token, "T_ENUM")
537 : ;
538 : }
539 :
540 772 : extern zend_string *lsp_next_string_token(HashTable *tokens, uint32_t start)
541 : {
542 : zval *token;
543 772 : uint32_t i, count = zend_hash_num_elements(tokens);
544 :
545 1540 : for (i = start; i < count; i++) {
546 1540 : token = zend_hash_index_find(tokens, i);
547 1540 : if (!token || Z_TYPE_P(token) != IS_ARRAY) {
548 0 : continue;
549 : }
550 :
551 1540 : if (lsp_token_name_equals(token, "T_STRING")) {
552 768 : return lsp_token_string(token, "text");
553 : }
554 :
555 772 : if (!lsp_token_name_equals(token, "T_WHITESPACE")) {
556 4 : return NULL;
557 : }
558 : }
559 :
560 0 : return NULL;
561 : }
562 :
563 0 : extern zend_string *lsp_next_function_name_token(HashTable *tokens, uint32_t start)
564 : {
565 : zend_string *text;
566 : zval *token;
567 0 : uint32_t i, count = zend_hash_num_elements(tokens);
568 :
569 0 : for (i = start; i < count; i++) {
570 0 : token = zend_hash_index_find(tokens, i);
571 0 : if (!token || Z_TYPE_P(token) != IS_ARRAY) {
572 0 : continue;
573 : }
574 :
575 0 : if (lsp_token_name_equals(token, "T_STRING")) {
576 0 : return lsp_token_string(token, "text");
577 : }
578 :
579 0 : if (lsp_token_name_equals(token, "T_WHITESPACE")) {
580 0 : continue;
581 : }
582 :
583 0 : if (lsp_token_name_equals(token, "CHAR")) {
584 0 : text = lsp_token_string(token, "text");
585 0 : if (text && ZSTR_LEN(text) == 1 && ZSTR_VAL(text)[0] == '&') {
586 0 : continue;
587 : }
588 : }
589 :
590 0 : if (lsp_token_name_equals(token, "T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG") ||
591 0 : lsp_token_name_equals(token, "T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG")
592 : ) {
593 0 : continue;
594 : }
595 :
596 0 : return NULL;
597 : }
598 :
599 0 : return NULL;
600 : }
601 :
602 748 : extern zval *lsp_next_function_name_token_ex(HashTable *tokens, uint32_t start, uint32_t *index)
603 : {
604 : zval *token;
605 748 : uint32_t i, count = zend_hash_num_elements(tokens);
606 :
607 1496 : for (i = start; i < count; i++) {
608 1496 : token = zend_hash_index_find(tokens, i);
609 1496 : if (!token || Z_TYPE_P(token) != IS_ARRAY) {
610 0 : continue;
611 : }
612 :
613 1496 : if (lsp_token_name_equals(token, "T_STRING")) {
614 748 : *index = i;
615 748 : return token;
616 : }
617 :
618 748 : if (lsp_token_name_equals(token, "T_WHITESPACE")) {
619 748 : continue;
620 : }
621 :
622 0 : if ((lsp_token_name_equals(token, "CHAR") && lsp_token_text_equals(token, "&")) ||
623 0 : lsp_token_name_equals(token, "T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG") ||
624 0 : lsp_token_name_equals(token, "T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG")
625 : ) {
626 0 : continue;
627 : }
628 :
629 0 : return NULL;
630 : }
631 :
632 0 : return NULL;
633 : }
634 :
635 764 : static inline bool lsp_completion_kind_needs_call_snippet(zend_long kind)
636 : {
637 764 : return kind == 2 || kind == 3;
638 : }
639 :
640 764 : extern void lsp_add_completion_item_ex(zval *items, zend_string *label, zend_long kind, zend_string *detail, const char *source)
641 : {
642 764 : const char *filter_text = ZSTR_VAL(label);
643 : zval item, data;
644 764 : size_t filter_text_length = ZSTR_LEN(label);
645 :
646 764 : array_init(&item);
647 764 : add_assoc_str(&item, "label", zend_string_copy(label));
648 764 : add_assoc_long(&item, "kind", kind);
649 764 : add_assoc_str(&item, "detail", zend_string_copy(detail));
650 764 : add_assoc_stringl(&item, "filterText", filter_text, filter_text_length);
651 :
652 764 : if (lsp_completion_kind_needs_call_snippet(kind)) {
653 564 : add_assoc_str(&item, "insertText", lsp_completion_call_snippet_for_detail(label, detail));
654 564 : add_assoc_long(&item, "insertTextFormat", 2);
655 : }
656 :
657 764 : array_init(&data);
658 764 : add_assoc_string(&data, "source", source);
659 764 : add_assoc_zval(&item, "data", &data);
660 764 : add_next_index_zval(items, &item);
661 764 : }
662 :
663 48 : extern void lsp_add_variable_completion_item_ex(zval *items, zend_string *label, zend_string *detail, const char *source, zend_string *text, size_t start_offset, size_t end_offset)
664 : {
665 : zval item, data, text_edit, range;
666 :
667 48 : array_init(&item);
668 48 : add_assoc_str(&item, "label", zend_string_copy(label));
669 48 : add_assoc_long(&item, "kind", 6);
670 48 : add_assoc_str(&item, "detail", zend_string_copy(detail));
671 48 : add_assoc_str(&item, "filterText", zend_string_copy(label));
672 48 : array_init(&text_edit);
673 48 : lsp_range_from_offsets(text, start_offset, end_offset, &range);
674 48 : add_assoc_zval(&text_edit, "range", &range);
675 48 : add_assoc_str(&text_edit, "newText", zend_string_copy(label));
676 48 : add_assoc_zval(&item, "textEdit", &text_edit);
677 48 : array_init(&data);
678 48 : add_assoc_string(&data, "source", source);
679 48 : add_assoc_zval(&item, "data", &data);
680 48 : add_next_index_zval(items, &item);
681 48 : }
682 :
683 24 : extern void lsp_add_completion_item(zval *items, zend_string *label, zend_long kind, zend_string *detail)
684 : {
685 24 : lsp_add_completion_item_ex(items, label, kind, detail, "lsparrot");
686 24 : }
687 :
688 : /* Same as lsp_add_completion_item, but records the item's FQCN so dedup can
689 : * tell same-short-name classes from different namespaces apart. */
690 4 : extern void lsp_add_completion_item_qualified(zval *items, zend_string *label, zend_long kind, zend_string *detail, zend_string *namespace_name)
691 : {
692 : zval item, data;
693 :
694 4 : array_init(&item);
695 4 : add_assoc_str(&item, "label", zend_string_copy(label));
696 4 : add_assoc_long(&item, "kind", kind);
697 4 : add_assoc_str(&item, "detail", zend_string_copy(detail));
698 4 : add_assoc_str(&item, "filterText", zend_string_copy(label));
699 :
700 4 : array_init(&data);
701 4 : add_assoc_string(&data, "source", "lsparrot");
702 4 : if (namespace_name && ZSTR_LEN(namespace_name) > 0) {
703 4 : add_assoc_str(&data, "qualifiedName", strpprintf(0, "%s\\%s", ZSTR_VAL(namespace_name), ZSTR_VAL(label)));
704 : } else {
705 0 : add_assoc_str(&data, "qualifiedName", zend_string_copy(label));
706 : }
707 4 : add_assoc_zval(&item, "data", &data);
708 4 : add_next_index_zval(items, &item);
709 4 : }
710 :
711 1640 : extern void lsp_add_keyword_completion(zval *items, const char *keyword, zend_string *prefix)
712 : {
713 : zval item;
714 :
715 1640 : if (!lsp_matches_prefix_literal(keyword, prefix)) {
716 1556 : return;
717 : }
718 :
719 84 : array_init(&item);
720 84 : add_assoc_string(&item, "label", keyword);
721 84 : add_assoc_long(&item, "kind", 14);
722 84 : add_assoc_string(&item, "detail", "keyword");
723 84 : add_next_index_zval(items, &item);
724 : }
725 :
726 180 : static inline bool lsp_completion_same_label(zval *left, zval *right)
727 : {
728 : const char *left_value, *right_value;
729 180 : zend_string *left_label = lsp_array_string(left, "label"), *right_label = lsp_array_string(right, "label"),
730 : *left_qualified_name, *right_qualified_name;
731 180 : zend_long left_kind = lsp_array_long(left, "kind", 0), right_kind = lsp_array_long(right, "kind", 0);
732 : zval *left_data, *right_data;
733 : size_t left_length, right_length;
734 :
735 180 : if (!left_label || !right_label) {
736 0 : return false;
737 : }
738 :
739 180 : if (left_kind != 0 && right_kind != 0 && left_kind != right_kind) {
740 0 : return false;
741 : }
742 :
743 180 : left_value = ZSTR_VAL(left_label);
744 180 : left_length = ZSTR_LEN(left_label);
745 180 : right_value = ZSTR_VAL(right_label);
746 180 : right_length = ZSTR_LEN(right_label);
747 :
748 180 : if (left_length > 0 && left_value[0] == '$') {
749 20 : left_value++;
750 20 : left_length--;
751 : }
752 :
753 180 : if (right_length > 0 && right_value[0] == '$') {
754 20 : right_value++;
755 20 : right_length--;
756 : }
757 :
758 180 : if (left_length != right_length || memcmp(left_value, right_value, left_length) != 0) {
759 0 : return false;
760 : }
761 :
762 : /* Pre-encoded entries carry qualifiedName at the top level; classic zval
763 : * items nest it under data. */
764 180 : left_qualified_name = lsp_array_string(left, "qualifiedName");
765 180 : right_qualified_name = lsp_array_string(right, "qualifiedName");
766 180 : if (!left_qualified_name) {
767 168 : left_data = lsp_array_find(left, "data");
768 168 : left_qualified_name = left_data && Z_TYPE_P(left_data) == IS_ARRAY ? lsp_array_string(left_data, "qualifiedName") : NULL;
769 : }
770 180 : if (!right_qualified_name) {
771 172 : right_data = lsp_array_find(right, "data");
772 172 : right_qualified_name = right_data && Z_TYPE_P(right_data) == IS_ARRAY ? lsp_array_string(right_data, "qualifiedName") : NULL;
773 : }
774 :
775 180 : if (left_qualified_name && right_qualified_name) {
776 8 : return zend_string_equals(left_qualified_name, right_qualified_name);
777 : }
778 :
779 : /* Class-like items where only one side carries an FQCN may name
780 : * different classes that merely share a short name; merging would
781 : * collapse them onto an arbitrary namespace. */
782 172 : if (left_qualified_name || right_qualified_name) {
783 4 : switch (left_kind != 0 ? left_kind : right_kind) {
784 0 : case 7: /* Class */
785 : case 8: /* Interface */
786 : case 9: /* Module (trait) */
787 : case 13: /* Enum */
788 0 : return false;
789 : }
790 : }
791 :
792 172 : return true;
793 : }
794 :
795 7532 : static inline bool lsp_completion_detail_starts_with(zend_string *detail, const char *prefix)
796 : {
797 7532 : size_t prefix_length = strlen(prefix);
798 :
799 7532 : return ZSTR_LEN(detail) >= prefix_length && memcmp(ZSTR_VAL(detail), prefix, prefix_length) == 0;
800 : }
801 :
802 : /* Detail-derived part of the completion ranking, shared between the classic
803 : * zval scorer and the pre-encoded item builder. */
804 1524 : static inline zend_long lsp_completion_detail_score(zend_string *detail)
805 : {
806 : zend_long score;
807 : size_t i;
808 :
809 1524 : score = (zend_long) ZSTR_LEN(detail);
810 1524 : if (lsp_completion_detail_starts_with(detail, "keyword")) {
811 0 : score -= 1000;
812 3028 : } else if (lsp_completion_detail_starts_with(detail, "variable ") ||
813 3004 : lsp_completion_detail_starts_with(detail, "function ") ||
814 1960 : lsp_completion_detail_starts_with(detail, "class ") ||
815 808 : lsp_completion_detail_starts_with(detail, "interface ") ||
816 696 : lsp_completion_detail_starts_with(detail, "trait ") ||
817 672 : lsp_completion_detail_starts_with(detail, "enum ") ||
818 324 : lsp_completion_detail_starts_with(detail, "property ")
819 : ) {
820 1216 : score -= 200;
821 : }
822 :
823 38284 : for (i = 0; i < ZSTR_LEN(detail); i++) {
824 36760 : switch (ZSTR_VAL(detail)[i]) {
825 820 : case '\\':
826 : case '<':
827 : case '>':
828 : case '|':
829 : case '&':
830 : case '{':
831 : case '}':
832 : case '[':
833 : case ']':
834 : case ':':
835 820 : score += 25;
836 820 : break;
837 : }
838 : }
839 :
840 1524 : if (strstr(ZSTR_VAL(detail), "array") != NULL || strstr(ZSTR_VAL(detail), "list") != NULL) {
841 24 : score += 75;
842 : }
843 :
844 1524 : if (strstr(ZSTR_VAL(detail), "non-empty") != NULL || strstr(ZSTR_VAL(detail), "positive-") != NULL) {
845 8 : score += 100;
846 : }
847 :
848 1524 : if (strstr(ZSTR_VAL(detail), "...") != NULL) {
849 200 : score += 25;
850 : }
851 :
852 1524 : return score;
853 : }
854 :
855 352 : static inline zend_long lsp_completion_type_score(zval *item)
856 : {
857 : zend_long score;
858 : zend_string *detail, *source, *sort_text;
859 : zval *data, *precomputed;
860 :
861 : /* Pre-encoded entries carry their score, computed at build time. */
862 352 : precomputed = lsp_array_find(item, "score");
863 352 : if (precomputed && Z_TYPE_P(precomputed) == IS_LONG) {
864 12 : return Z_LVAL_P(precomputed);
865 : }
866 :
867 340 : detail = lsp_array_string(item, "detail");
868 340 : sort_text = lsp_array_string(item, "sortText");
869 340 : data = lsp_array_find(item, "data");
870 340 : source = data && Z_TYPE_P(data) == IS_ARRAY ? lsp_array_string(data, "source") : NULL;
871 340 : score = 0;
872 :
873 340 : if (source && (zend_string_equals_literal(source, "phpstan") || zend_string_equals_literal(source, "psalm") || zend_string_equals_literal(source, "psalm-ls"))) {
874 248 : score += 10000;
875 : }
876 :
877 340 : if (sort_text && ZSTR_LEN(sort_text) >= 2 && ZSTR_VAL(sort_text)[1] == ':') {
878 0 : if (ZSTR_VAL(sort_text)[0] == '0') {
879 0 : score += 5000;
880 0 : } else if (ZSTR_VAL(sort_text)[0] == '1') {
881 0 : score -= 5000;
882 : }
883 : }
884 :
885 340 : if (!detail) {
886 0 : return score;
887 : }
888 :
889 340 : score += lsp_completion_detail_score(detail);
890 :
891 340 : return score;
892 : }
893 :
894 3100 : static inline zend_string *lsp_completion_dedup_bucket_key(zval *item)
895 : {
896 3100 : zend_string *label = lsp_array_string(item, "label");
897 : const char *value;
898 : size_t length;
899 :
900 3100 : if (!label) {
901 0 : return NULL;
902 : }
903 :
904 3100 : value = ZSTR_VAL(label);
905 3100 : length = ZSTR_LEN(label);
906 3100 : if (length > 0 && value[0] == '$') {
907 84 : value++;
908 84 : length--;
909 : }
910 :
911 3100 : return zend_string_init(value, length, 0);
912 : }
913 :
914 532 : extern void lsp_deduplicate_completion_items(zval *items)
915 : {
916 : HashTable label_buckets;
917 : zend_string *bucket_key;
918 : zval deduped, new_bucket, *item, *existing, *bucket, *index_zv, copy;
919 532 : zend_long next_index = 0;
920 : bool handled;
921 :
922 532 : if (Z_TYPE_P(items) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_P(items)) < 2) {
923 316 : return;
924 : }
925 :
926 : /* Items with different labels can never merge, so candidates are
927 : * bucketed by normalized label and the pairwise comparison only runs
928 : * within a bucket. This keeps the historical merge semantics while
929 : * turning the old O(n^2) full scan into O(n) for typical lists. */
930 216 : zend_hash_init(&label_buckets, 64, NULL, ZVAL_PTR_DTOR, 0);
931 216 : array_init(&deduped);
932 :
933 3316 : ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(items), item) {
934 3100 : handled = false;
935 :
936 3100 : if (Z_TYPE_P(item) != IS_ARRAY) {
937 0 : ZVAL_COPY(©, item);
938 0 : add_next_index_zval(&deduped, ©);
939 0 : next_index++;
940 0 : continue;
941 : }
942 :
943 3100 : bucket_key = lsp_completion_dedup_bucket_key(item);
944 3100 : bucket = bucket_key ? zend_hash_find(&label_buckets, bucket_key) : NULL;
945 :
946 3100 : if (bucket) {
947 184 : ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(bucket), index_zv) {
948 180 : existing = zend_hash_index_find(Z_ARRVAL(deduped), (zend_ulong) Z_LVAL_P(index_zv));
949 180 : if (!existing || Z_TYPE_P(existing) != IS_ARRAY || !lsp_completion_same_label(item, existing)) {
950 4 : continue;
951 : }
952 :
953 176 : if (lsp_completion_type_score(item) > lsp_completion_type_score(existing)) {
954 4 : zval_ptr_dtor(existing);
955 4 : ZVAL_COPY(existing, item);
956 : }
957 :
958 176 : handled = true;
959 176 : break;
960 : } ZEND_HASH_FOREACH_END();
961 : }
962 :
963 3100 : if (!handled) {
964 2924 : ZVAL_COPY(©, item);
965 2924 : add_next_index_zval(&deduped, ©);
966 :
967 2924 : if (bucket_key) {
968 2924 : if (!bucket) {
969 2920 : array_init(&new_bucket);
970 2920 : bucket = zend_hash_add(&label_buckets, bucket_key, &new_bucket);
971 : }
972 2924 : add_next_index_long(bucket, next_index);
973 : }
974 :
975 2924 : next_index++;
976 : }
977 :
978 3100 : if (bucket_key) {
979 3100 : zend_string_release(bucket_key);
980 : }
981 : } ZEND_HASH_FOREACH_END();
982 :
983 216 : zend_hash_destroy(&label_buckets);
984 216 : zval_ptr_dtor(items);
985 216 : ZVAL_COPY_VALUE(items, &deduped);
986 : }
987 :
988 : /* Assemble the completion response JSON directly: pre-encoded entries are
989 : * spliced verbatim, classic zval items are encoded individually. The result
990 : * is handed to the transport as a raw JSON payload, skipping the full
991 : * zval-tree encode of potentially thousands of items. */
992 504 : extern bool lsp_completion_attach_items(zval *return_value, zval *items)
993 : {
994 504 : smart_str json = {0};
995 : zend_string *fragment;
996 : zval *item, *incomplete;
997 504 : bool first = true, ok = true;
998 :
999 504 : incomplete = zend_hash_str_find(Z_ARRVAL_P(return_value), "isIncomplete", sizeof("isIncomplete") - 1);
1000 504 : smart_str_appendl(&json, "{\"isIncomplete\":", sizeof("{\"isIncomplete\":") - 1);
1001 504 : if (incomplete && Z_TYPE_P(incomplete) == IS_TRUE) {
1002 48 : smart_str_appendl(&json, "true", 4);
1003 : } else {
1004 456 : smart_str_appendl(&json, "false", 5);
1005 : }
1006 504 : smart_str_appendl(&json, ",\"items\":[", sizeof(",\"items\":[") - 1);
1007 :
1008 3600 : ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(items), item) {
1009 3096 : if (!first) {
1010 2616 : smart_str_appendc(&json, ',');
1011 : }
1012 :
1013 3096 : fragment = Z_TYPE_P(item) == IS_ARRAY ? lsp_array_string(item, "__json") : NULL;
1014 3096 : if (fragment) {
1015 1180 : smart_str_append(&json, fragment);
1016 1916 : } else if (php_json_encode(&json, item, PHP_JSON_UNESCAPED_SLASHES | PHP_JSON_UNESCAPED_UNICODE) != SUCCESS) {
1017 0 : ok = false;
1018 0 : break;
1019 : }
1020 :
1021 3096 : first = false;
1022 : } ZEND_HASH_FOREACH_END();
1023 :
1024 504 : if (!ok) {
1025 : /* Pathological data (e.g. invalid UTF-8 from an analyzer): fall back
1026 : * to attaching the structured items so the generic encoder reports
1027 : * the failure the same way it always has. */
1028 0 : smart_str_free(&json);
1029 0 : add_assoc_zval(return_value, "items", items);
1030 :
1031 0 : return false;
1032 : }
1033 :
1034 504 : smart_str_appendl(&json, "]}", 2);
1035 504 : smart_str_0(&json);
1036 :
1037 504 : zval_ptr_dtor(items);
1038 504 : zval_ptr_dtor(return_value);
1039 504 : array_init(return_value);
1040 504 : add_assoc_str(return_value, "__raw_json", json.s);
1041 :
1042 504 : return true;
1043 : }
1044 :
1045 2368 : static inline zend_long lsp_symbol_completion_kind(char kind)
1046 : {
1047 2368 : switch (kind) {
1048 2080 : case LSP_SYMBOL_CLASS:
1049 2080 : return 7;
1050 224 : case LSP_SYMBOL_INTERFACE:
1051 224 : return 8;
1052 0 : case LSP_SYMBOL_TRAIT:
1053 0 : return 9;
1054 48 : case LSP_SYMBOL_ENUM:
1055 48 : return 13;
1056 8 : case LSP_SYMBOL_FUNCTION:
1057 8 : return 3;
1058 8 : case LSP_SYMBOL_CONSTANT:
1059 8 : return 21;
1060 : }
1061 :
1062 0 : return 7;
1063 : }
1064 :
1065 864 : extern zend_long lsp_symbol_workspace_kind(char kind)
1066 : {
1067 864 : switch (kind) {
1068 240 : case LSP_SYMBOL_INTERFACE:
1069 240 : return 11;
1070 240 : case LSP_SYMBOL_ENUM:
1071 240 : return 10;
1072 16 : case LSP_SYMBOL_FUNCTION:
1073 16 : return 12;
1074 0 : case LSP_SYMBOL_CONSTANT:
1075 0 : return 14;
1076 : }
1077 :
1078 368 : return 5;
1079 : }
1080 :
1081 1184 : static inline const char *lsp_symbol_detail_prefix(char kind)
1082 : {
1083 1184 : switch (kind) {
1084 112 : case LSP_SYMBOL_INTERFACE:
1085 112 : return "interface ";
1086 0 : case LSP_SYMBOL_TRAIT:
1087 0 : return "trait ";
1088 24 : case LSP_SYMBOL_ENUM:
1089 24 : return "enum ";
1090 4 : case LSP_SYMBOL_FUNCTION:
1091 4 : return "function ";
1092 4 : case LSP_SYMBOL_CONSTANT:
1093 4 : return "constant ";
1094 1040 : case LSP_SYMBOL_CLASS:
1095 : default:
1096 1040 : return "class ";
1097 : }
1098 : }
1099 :
1100 376 : static inline bool lsp_symbol_kind_is_class_like(char kind)
1101 : {
1102 116 : return kind == LSP_SYMBOL_CLASS ||
1103 116 : kind == LSP_SYMBOL_INTERFACE ||
1104 492 : kind == LSP_SYMBOL_TRAIT ||
1105 : kind == LSP_SYMBOL_ENUM
1106 : ;
1107 : }
1108 :
1109 1184 : static inline const char *lsp_symbol_completion_label(char kind, const char *fqcn, size_t fqcn_length, size_t *label_length)
1110 : {
1111 : size_t i;
1112 :
1113 1184 : if (kind == LSP_SYMBOL_FUNCTION || kind == LSP_SYMBOL_CONSTANT) {
1114 84 : for (i = fqcn_length; i > 0; i--) {
1115 84 : if (fqcn[i - 1] == '\\') {
1116 8 : *label_length = fqcn_length - i;
1117 :
1118 8 : return fqcn + i;
1119 : }
1120 : }
1121 :
1122 0 : *label_length = fqcn_length;
1123 :
1124 0 : return fqcn;
1125 : }
1126 :
1127 1176 : return lsp_basename_from_fqcn(fqcn, fqcn_length, label_length);
1128 : }
1129 :
1130 3240 : static inline void lsp_offset_to_position(zend_string *text, size_t offset, zval *position)
1131 : {
1132 3240 : const char *value = ZSTR_VAL(text);
1133 3240 : zend_long line = 0;
1134 3240 : size_t i, line_start = 0,
1135 3240 : length = offset > ZSTR_LEN(text) ? ZSTR_LEN(text) : offset
1136 : ;
1137 :
1138 610880 : for (i = 0; i < length; i++) {
1139 607640 : if (value[i] == '\n') {
1140 28092 : line++;
1141 28092 : line_start = i + 1;
1142 : }
1143 : }
1144 :
1145 3240 : array_init(position);
1146 3240 : add_assoc_long(position, "line", line);
1147 3240 : add_assoc_long(position, "character", lsp_byte_offset_to_utf16_units(value, line_start, length));
1148 3240 : }
1149 :
1150 1620 : extern void lsp_range_from_offsets(zend_string *text, size_t start_offset, size_t end_offset, zval *range)
1151 : {
1152 : zval start, end;
1153 :
1154 1620 : array_init(range);
1155 1620 : lsp_offset_to_position(text, start_offset, &start);
1156 1620 : lsp_offset_to_position(text, end_offset, &end);
1157 1620 : add_assoc_zval(range, "start", &start);
1158 1620 : add_assoc_zval(range, "end", &end);
1159 1620 : }
1160 :
1161 232 : static inline bool lsp_symbol_fuzzy_match(const char *value, size_t value_length, const char *prefix, size_t prefix_length)
1162 : {
1163 : size_t value_index, prefix_index;
1164 :
1165 232 : if (prefix_length < 2 || value_length == 0) {
1166 0 : return false;
1167 : }
1168 :
1169 232 : prefix_index = 0;
1170 7296 : for (value_index = 0; value_index < value_length && prefix_index < prefix_length; value_index++) {
1171 7064 : if (tolower((unsigned char) value[value_index]) == tolower((unsigned char) prefix[prefix_index])) {
1172 640 : prefix_index++;
1173 : }
1174 : }
1175 :
1176 232 : return prefix_index == prefix_length;
1177 : }
1178 :
1179 1112 : static inline bool lsp_current_statement_starts_with_use(zend_string *text, size_t offset)
1180 : {
1181 1112 : const char *value = ZSTR_VAL(text);
1182 : size_t start, p;
1183 :
1184 1112 : if (offset > ZSTR_LEN(text)) {
1185 0 : offset = ZSTR_LEN(text);
1186 : }
1187 :
1188 1112 : start = offset;
1189 32676 : while (start > 0 && value[start - 1] != '\n' && value[start - 1] != ';' && value[start - 1] != '{' && value[start - 1] != '}') {
1190 31564 : start--;
1191 : }
1192 :
1193 1112 : p = start;
1194 5448 : while (p < offset && isspace((unsigned char) value[p])) {
1195 4336 : p++;
1196 : }
1197 :
1198 2204 : return p + sizeof("use") - 1 <= offset &&
1199 1116 : memcmp(value + p, "use", sizeof("use") - 1) == 0 &&
1200 4 : (p + sizeof("use") - 1 == offset || isspace((unsigned char) value[p + sizeof("use") - 1]))
1201 : ;
1202 : }
1203 :
1204 1560 : static inline bool lsp_namespace_token_is_name(zval *token)
1205 : {
1206 2196 : return lsp_token_name_equals(token, "T_STRING") ||
1207 636 : lsp_token_name_equals(token, "T_NAME_QUALIFIED") ||
1208 0 : lsp_token_name_equals(token, "T_NAME_FULLY_QUALIFIED") ||
1209 2196 : lsp_token_name_equals(token, "T_NAME_RELATIVE") ||
1210 0 : lsp_token_name_equals(token, "T_NS_SEPARATOR")
1211 : ;
1212 : }
1213 :
1214 1560 : static inline zend_string *lsp_document_namespace_from_tokens(HashTable *tokens, uint32_t start)
1215 : {
1216 : zend_string *text;
1217 : zval *token;
1218 1560 : smart_str namespace_name = {0};
1219 : uint32_t i, count;
1220 :
1221 1560 : count = zend_hash_num_elements(tokens);
1222 4704 : for (i = start; i < count; i++) {
1223 4704 : token = zend_hash_index_find(tokens, i);
1224 4704 : if (!token || Z_TYPE_P(token) != IS_ARRAY) {
1225 0 : continue;
1226 : }
1227 :
1228 4704 : if (lsp_token_name_equals(token, "T_WHITESPACE")) {
1229 1584 : continue;
1230 : }
1231 :
1232 3120 : if (lsp_token_is_char(token, ';') || lsp_token_is_char(token, '{')) {
1233 : break;
1234 : }
1235 :
1236 1560 : if (!lsp_namespace_token_is_name(token)) {
1237 0 : continue;
1238 : }
1239 :
1240 1560 : text = lsp_token_string(token, "text");
1241 1560 : if (!text) {
1242 0 : continue;
1243 : }
1244 :
1245 1560 : if (ZSTR_LEN(text) > 0 && ZSTR_VAL(text)[0] == '\\') {
1246 0 : smart_str_appendl(&namespace_name, ZSTR_VAL(text) + 1, ZSTR_LEN(text) - 1);
1247 : } else {
1248 1560 : smart_str_append(&namespace_name, text);
1249 : }
1250 : }
1251 :
1252 1560 : if (!namespace_name.s) {
1253 0 : return zend_empty_string;
1254 : }
1255 :
1256 1560 : smart_str_0(&namespace_name);
1257 :
1258 1560 : return namespace_name.s;
1259 : }
1260 :
1261 772 : extern zend_string *lsp_document_namespace(zend_string *text)
1262 : {
1263 : zval tokens_zv, *token;
1264 : HashTable *tokens;
1265 : zend_string *namespace_name;
1266 : uint32_t i, count;
1267 :
1268 772 : ZVAL_UNDEF(&tokens_zv);
1269 772 : lsp_lsparrot_tokens_to_zval(&tokens_zv, text);
1270 772 : if (Z_TYPE(tokens_zv) != IS_ARRAY) {
1271 0 : if (!Z_ISUNDEF(tokens_zv)) {
1272 0 : zval_ptr_dtor(&tokens_zv);
1273 : }
1274 :
1275 0 : return zend_empty_string;
1276 : }
1277 :
1278 772 : tokens = Z_ARRVAL(tokens_zv);
1279 772 : count = zend_hash_num_elements(tokens);
1280 772 : namespace_name = zend_empty_string;
1281 2640 : for (i = 0; i < count; i++) {
1282 2584 : token = zend_hash_index_find(tokens, i);
1283 2584 : if (!token || Z_TYPE_P(token) != IS_ARRAY || !lsp_token_name_equals(token, "T_NAMESPACE")) {
1284 1868 : continue;
1285 : }
1286 :
1287 716 : namespace_name = lsp_document_namespace_from_tokens(tokens, i + 1);
1288 716 : break;
1289 : }
1290 :
1291 772 : zval_ptr_dtor(&tokens_zv);
1292 :
1293 772 : return namespace_name;
1294 : }
1295 :
1296 : /* Namespace in effect at a byte offset. Files may declare several namespaces
1297 : * (semicolon or braced form); the one whose declaration most recently precedes
1298 : * the offset governs name resolution there. Falls back to the first namespace
1299 : * for offsets before any declaration, matching lsp_document_namespace. */
1300 896 : extern zend_string *lsp_document_namespace_at_ex(zend_string *text, size_t offset, bool *multiple)
1301 : {
1302 : zval tokens_zv, *token;
1303 : HashTable *tokens;
1304 : zend_string *namespace_name;
1305 : zend_long token_offset;
1306 : uint32_t i, count, namespace_count;
1307 : int64_t best_index, first_index;
1308 :
1309 896 : *multiple = false;
1310 :
1311 896 : ZVAL_UNDEF(&tokens_zv);
1312 896 : lsp_lsparrot_tokens_to_zval(&tokens_zv, text);
1313 896 : if (Z_TYPE(tokens_zv) != IS_ARRAY) {
1314 0 : if (!Z_ISUNDEF(tokens_zv)) {
1315 0 : zval_ptr_dtor(&tokens_zv);
1316 : }
1317 :
1318 0 : return zend_empty_string;
1319 : }
1320 :
1321 896 : tokens = Z_ARRVAL(tokens_zv);
1322 896 : count = zend_hash_num_elements(tokens);
1323 896 : namespace_count = 0;
1324 896 : best_index = -1;
1325 896 : first_index = -1;
1326 54572 : for (i = 0; i < count; i++) {
1327 53676 : token = zend_hash_index_find(tokens, i);
1328 53676 : if (!token || Z_TYPE_P(token) != IS_ARRAY || !lsp_token_name_equals(token, "T_NAMESPACE")) {
1329 52808 : continue;
1330 : }
1331 :
1332 868 : namespace_count++;
1333 868 : if (first_index < 0) {
1334 844 : first_index = (int64_t) i;
1335 : }
1336 :
1337 868 : token_offset = lsp_token_long(token, "offset", 0);
1338 868 : if (token_offset >= 0 && (size_t) token_offset <= offset) {
1339 860 : best_index = (int64_t) i;
1340 : }
1341 : }
1342 :
1343 896 : *multiple = namespace_count > 1;
1344 896 : if (best_index < 0) {
1345 52 : best_index = first_index;
1346 : }
1347 :
1348 896 : namespace_name = best_index < 0
1349 : ? zend_empty_string
1350 896 : : lsp_document_namespace_from_tokens(tokens, (uint32_t) best_index + 1)
1351 : ;
1352 896 : zval_ptr_dtor(&tokens_zv);
1353 :
1354 896 : return namespace_name;
1355 : }
1356 :
1357 0 : extern zend_string *lsp_document_namespace_at(zend_string *text, size_t offset)
1358 : {
1359 : bool multiple;
1360 :
1361 0 : return lsp_document_namespace_at_ex(text, offset, &multiple);
1362 : }
1363 :
1364 1184 : static inline bool lsp_symbol_has_namespace(const char *fqcn, size_t fqcn_length, const char **namespace_end)
1365 : {
1366 : size_t i;
1367 :
1368 17336 : for (i = fqcn_length; i > 0; i--) {
1369 16548 : if (fqcn[i - 1] == '\\') {
1370 396 : *namespace_end = fqcn + i - 1;
1371 :
1372 396 : return true;
1373 : }
1374 : }
1375 :
1376 788 : return false;
1377 : }
1378 :
1379 1184 : extern bool lsp_symbol_in_current_namespace(zend_string *current_namespace, char kind, const char *fqcn, size_t fqcn_length)
1380 : {
1381 : const char *namespace_end;
1382 : size_t namespace_length;
1383 :
1384 1184 : if (!lsp_symbol_has_namespace(fqcn, fqcn_length, &namespace_end)) {
1385 : /* Unqualified functions and constants fall back to the global
1386 : * namespace at runtime, so a global symbol is always reachable.
1387 : * Class names never fall back: inside a namespace a global class
1388 : * needs an import (or a leading backslash) to be reachable. */
1389 788 : if (kind == LSP_SYMBOL_FUNCTION || kind == LSP_SYMBOL_CONSTANT) {
1390 0 : return true;
1391 : }
1392 :
1393 788 : return ZSTR_LEN(current_namespace) == 0;
1394 : }
1395 :
1396 396 : namespace_length = namespace_end - fqcn;
1397 :
1398 452 : return ZSTR_LEN(current_namespace) == namespace_length &&
1399 56 : strncasecmp(ZSTR_VAL(current_namespace), fqcn, namespace_length) == 0
1400 : ;
1401 : }
1402 :
1403 64 : static inline uint32_t lsp_symbol_import_ast_kind(char kind)
1404 : {
1405 64 : if (kind == LSP_SYMBOL_FUNCTION) {
1406 8 : return ZEND_SYMBOL_FUNCTION;
1407 : }
1408 :
1409 56 : if (kind == LSP_SYMBOL_CONSTANT) {
1410 0 : return ZEND_SYMBOL_CONST;
1411 : }
1412 :
1413 56 : return ZEND_SYMBOL_CLASS;
1414 : }
1415 :
1416 0 : static inline bool lsp_import_name_equals(zend_string *name, char kind, const char *fqcn)
1417 : {
1418 0 : if (kind == LSP_SYMBOL_CONSTANT) {
1419 0 : return strcmp(ZSTR_VAL(name), fqcn) == 0;
1420 : }
1421 :
1422 0 : return strcasecmp(ZSTR_VAL(name), fqcn) == 0;
1423 : }
1424 :
1425 24 : static inline zend_string *lsp_import_full_name(zend_string *prefix, zend_string *name)
1426 : {
1427 24 : if (prefix && ZSTR_LEN(prefix) > 0) {
1428 0 : return strpprintf(0, "%s\\%s", ZSTR_VAL(prefix), ZSTR_VAL(name));
1429 : }
1430 :
1431 24 : return zend_string_copy(name);
1432 : }
1433 :
1434 0 : static inline bool lsp_use_statement_has_import(zend_ast *use_ast, zend_string *prefix, uint32_t target_kind, char symbol_kind, const char *fqcn)
1435 : {
1436 : zend_ast_list *list;
1437 : zend_ast *elem;
1438 : zend_string *name, *full_name;
1439 : uint32_t i, elem_kind;
1440 : bool found;
1441 :
1442 0 : if (!use_ast || use_ast->kind != ZEND_AST_USE || !zend_ast_is_list(use_ast)) {
1443 0 : return false;
1444 : }
1445 :
1446 0 : list = zend_ast_get_list(use_ast);
1447 0 : for (i = 0; i < list->children; i++) {
1448 0 : elem = list->child[i];
1449 0 : if (!elem || elem->kind != ZEND_AST_USE_ELEM) {
1450 0 : continue;
1451 : }
1452 :
1453 0 : elem_kind = elem->attr != 0 ? elem->attr : use_ast->attr;
1454 0 : if (elem_kind == 0) {
1455 0 : elem_kind = ZEND_SYMBOL_CLASS;
1456 : }
1457 0 : if (elem_kind != target_kind) {
1458 0 : continue;
1459 : }
1460 :
1461 0 : name = lsp_ast_string_value(elem->child[0]);
1462 0 : if (!name) {
1463 0 : continue;
1464 : }
1465 :
1466 0 : full_name = lsp_import_full_name(prefix, name);
1467 0 : found = lsp_import_name_equals(full_name, symbol_kind, fqcn);
1468 0 : zend_string_release(full_name);
1469 0 : if (found) {
1470 0 : return true;
1471 : }
1472 : }
1473 :
1474 0 : return false;
1475 : }
1476 :
1477 0 : static inline bool lsp_document_has_import_in_ast(zend_ast *ast, uint32_t target_kind, char symbol_kind, const char *fqcn)
1478 : {
1479 : zend_ast_list *list;
1480 : zend_string *prefix;
1481 : uint32_t i, count;
1482 :
1483 0 : if (!ast) {
1484 0 : return false;
1485 : }
1486 :
1487 0 : if (ast->kind == ZEND_AST_USE) {
1488 0 : return lsp_use_statement_has_import(ast, NULL, target_kind, symbol_kind, fqcn);
1489 : }
1490 :
1491 0 : if (ast->kind == ZEND_AST_GROUP_USE) {
1492 0 : prefix = lsp_ast_string_value(ast->child[0]);
1493 :
1494 0 : return lsp_use_statement_has_import(ast->child[1], prefix, target_kind, symbol_kind, fqcn);
1495 : }
1496 :
1497 0 : if (zend_ast_is_list(ast)) {
1498 0 : list = zend_ast_get_list(ast);
1499 0 : for (i = 0; i < list->children; i++) {
1500 0 : if (lsp_document_has_import_in_ast(list->child[i], target_kind, symbol_kind, fqcn)) {
1501 0 : return true;
1502 : }
1503 : }
1504 :
1505 0 : return false;
1506 : }
1507 :
1508 0 : if (zend_ast_is_special(ast) || php_ver_abstract.ast_is_opaque_node(ast->kind)) {
1509 0 : return false;
1510 : }
1511 :
1512 0 : count = zend_ast_get_num_children(ast);
1513 0 : for (i = 0; i < count; i++) {
1514 0 : if (lsp_document_has_import_in_ast(ast->child[i], target_kind, symbol_kind, fqcn)) {
1515 0 : return true;
1516 : }
1517 : }
1518 :
1519 0 : return false;
1520 : }
1521 :
1522 0 : extern bool lsp_document_has_import(zend_string *text, char kind, const char *fqcn)
1523 : {
1524 : zend_arena *ast_arena;
1525 : zend_ast *ast;
1526 : uint32_t target_kind;
1527 : bool found;
1528 :
1529 0 : if (!strstr(ZSTR_VAL(text), "use")) {
1530 0 : return false;
1531 : }
1532 :
1533 0 : ast = lsp_compile_string_to_ast_silent(text, ZSTR_EMPTY_ALLOC(), &ast_arena);
1534 0 : if (!ast) {
1535 0 : lsp_compiled_ast_destroy(ast, ast_arena);
1536 :
1537 0 : return false;
1538 : }
1539 :
1540 0 : target_kind = lsp_symbol_import_ast_kind(kind);
1541 0 : found = lsp_document_has_import_in_ast(ast, target_kind, kind, fqcn);
1542 0 : lsp_compiled_ast_destroy(ast, ast_arena);
1543 :
1544 0 : return found;
1545 : }
1546 :
1547 64 : static inline zend_string *lsp_import_set_key(uint32_t target_kind, const char *name, size_t length)
1548 : {
1549 : zend_string *key;
1550 : size_t i;
1551 :
1552 64 : key = zend_string_alloc(length + 2, 0);
1553 64 : ZSTR_VAL(key)[0] = (char) ('0' + (target_kind % 10));
1554 64 : ZSTR_VAL(key)[1] = ':';
1555 :
1556 64 : if (target_kind == ZEND_SYMBOL_CONST) {
1557 : /* Constant imports compare case-sensitively. */
1558 0 : memcpy(ZSTR_VAL(key) + 2, name, length);
1559 : } else {
1560 1496 : for (i = 0; i < length; i++) {
1561 1432 : ZSTR_VAL(key)[i + 2] = (char) tolower((unsigned char) name[i]);
1562 : }
1563 : }
1564 :
1565 64 : ZSTR_VAL(key)[length + 2] = '\0';
1566 :
1567 64 : return key;
1568 : }
1569 :
1570 : /* Key recording which short name (explicit alias or terminal segment) an
1571 : * import binds in the document, so completion can detect that adding a `use`
1572 : * for a same-named symbol from another namespace would conflict. */
1573 48 : static inline zend_string *lsp_import_alias_set_key(uint32_t target_kind, const char *name, size_t length)
1574 : {
1575 : zend_string *key;
1576 : size_t i;
1577 :
1578 48 : key = zend_string_alloc(length + 3, 0);
1579 48 : ZSTR_VAL(key)[0] = 'A';
1580 48 : ZSTR_VAL(key)[1] = (char) ('0' + (target_kind % 10));
1581 48 : ZSTR_VAL(key)[2] = ':';
1582 :
1583 48 : if (target_kind == ZEND_SYMBOL_CONST) {
1584 0 : memcpy(ZSTR_VAL(key) + 3, name, length);
1585 : } else {
1586 356 : for (i = 0; i < length; i++) {
1587 308 : ZSTR_VAL(key)[i + 3] = (char) tolower((unsigned char) name[i]);
1588 : }
1589 : }
1590 :
1591 48 : ZSTR_VAL(key)[length + 3] = '\0';
1592 :
1593 48 : return key;
1594 : }
1595 :
1596 : /* Reverse-lookup key: bound short name -> original-case FQCN. */
1597 36 : static inline zend_string *lsp_import_reverse_key(uint32_t target_kind, const char *name, size_t length)
1598 : {
1599 : zend_string *key;
1600 : size_t i;
1601 :
1602 36 : key = zend_string_alloc(length + 3, 0);
1603 36 : ZSTR_VAL(key)[0] = 'R';
1604 36 : ZSTR_VAL(key)[1] = (char) ('0' + (target_kind % 10));
1605 36 : ZSTR_VAL(key)[2] = ':';
1606 288 : for (i = 0; i < length; i++) {
1607 252 : ZSTR_VAL(key)[i + 3] = (char) tolower((unsigned char) name[i]);
1608 : }
1609 36 : ZSTR_VAL(key)[length + 3] = '\0';
1610 :
1611 36 : return key;
1612 : }
1613 :
1614 44 : static inline void lsp_import_terminal_segment(const char *name, size_t length, const char **segment, size_t *segment_length)
1615 : {
1616 : size_t i;
1617 :
1618 348 : for (i = length; i > 0; i--) {
1619 344 : if (name[i - 1] == '\\') {
1620 40 : *segment = name + i;
1621 40 : *segment_length = length - i;
1622 :
1623 40 : return;
1624 : }
1625 : }
1626 :
1627 4 : *segment = name;
1628 4 : *segment_length = length;
1629 : }
1630 :
1631 24 : static inline void lsp_collect_use_statement_imports(zend_ast *use_ast, zend_string *prefix, HashTable *imports)
1632 : {
1633 : zend_ast_list *list;
1634 : zend_ast *elem;
1635 : zend_string *name, *full_name, *key, *alias;
1636 : zval bound;
1637 : const char *alias_value;
1638 : size_t alias_length;
1639 : uint32_t i, elem_kind;
1640 :
1641 24 : if (!use_ast || use_ast->kind != ZEND_AST_USE || !zend_ast_is_list(use_ast)) {
1642 0 : return;
1643 : }
1644 :
1645 24 : list = zend_ast_get_list(use_ast);
1646 48 : for (i = 0; i < list->children; i++) {
1647 24 : elem = list->child[i];
1648 24 : if (!elem || elem->kind != ZEND_AST_USE_ELEM) {
1649 0 : continue;
1650 : }
1651 :
1652 24 : elem_kind = elem->attr != 0 ? elem->attr : use_ast->attr;
1653 24 : if (elem_kind == 0) {
1654 0 : elem_kind = ZEND_SYMBOL_CLASS;
1655 : }
1656 :
1657 24 : name = lsp_ast_string_value(elem->child[0]);
1658 24 : if (!name) {
1659 0 : continue;
1660 : }
1661 :
1662 24 : full_name = lsp_import_full_name(prefix, name);
1663 24 : alias = elem->child[1] ? lsp_ast_string_value(elem->child[1]) : NULL;
1664 24 : if (alias) {
1665 4 : alias_value = ZSTR_VAL(alias);
1666 4 : alias_length = ZSTR_LEN(alias);
1667 : } else {
1668 20 : lsp_import_terminal_segment(ZSTR_VAL(full_name), ZSTR_LEN(full_name), &alias_value, &alias_length);
1669 : }
1670 :
1671 : /* The exact-FQCN key records which short name the import binds, so
1672 : * completion can insert the alias instead of an unresolvable bare
1673 : * class name. */
1674 24 : key = lsp_import_set_key(elem_kind, ZSTR_VAL(full_name), ZSTR_LEN(full_name));
1675 24 : ZVAL_STR(&bound, zend_string_init(alias_value, alias_length, 0));
1676 24 : zend_hash_update(imports, key, &bound);
1677 24 : zend_string_release(key);
1678 :
1679 24 : key = lsp_import_alias_set_key(elem_kind, alias_value, alias_length);
1680 24 : zend_hash_add_empty_element(imports, key);
1681 24 : zend_string_release(key);
1682 :
1683 24 : key = lsp_import_reverse_key(elem_kind, alias_value, alias_length);
1684 24 : ZVAL_STR(&bound, zend_string_copy(full_name));
1685 24 : zend_hash_update(imports, key, &bound);
1686 24 : zend_string_release(key);
1687 24 : zend_string_release(full_name);
1688 : }
1689 : }
1690 :
1691 112 : static inline void lsp_collect_imports_in_ast(zend_ast *ast, HashTable *imports)
1692 : {
1693 : zend_ast_list *list;
1694 : zend_string *prefix;
1695 : uint32_t i, count;
1696 :
1697 112 : if (!ast) {
1698 16 : return;
1699 : }
1700 :
1701 96 : if (ast->kind == ZEND_AST_USE) {
1702 24 : lsp_collect_use_statement_imports(ast, NULL, imports);
1703 :
1704 24 : return;
1705 : }
1706 :
1707 72 : if (ast->kind == ZEND_AST_GROUP_USE) {
1708 0 : prefix = lsp_ast_string_value(ast->child[0]);
1709 0 : lsp_collect_use_statement_imports(ast->child[1], prefix, imports);
1710 :
1711 0 : return;
1712 : }
1713 :
1714 72 : if (zend_ast_is_list(ast)) {
1715 16 : list = zend_ast_get_list(ast);
1716 80 : for (i = 0; i < list->children; i++) {
1717 64 : lsp_collect_imports_in_ast(list->child[i], imports);
1718 : }
1719 :
1720 16 : return;
1721 : }
1722 :
1723 56 : if (zend_ast_is_special(ast) || php_ver_abstract.ast_is_opaque_node(ast->kind)) {
1724 40 : return;
1725 : }
1726 :
1727 16 : count = zend_ast_get_num_children(ast);
1728 48 : for (i = 0; i < count; i++) {
1729 32 : lsp_collect_imports_in_ast(ast->child[i], imports);
1730 : }
1731 : }
1732 :
1733 216 : static inline bool lsp_collect_import_token_is_ignored(zval *token)
1734 : {
1735 356 : return lsp_token_name_equals(token, "T_WHITESPACE") ||
1736 356 : lsp_token_name_equals(token, "T_COMMENT") ||
1737 140 : lsp_token_name_equals(token, "T_DOC_COMMENT")
1738 : ;
1739 : }
1740 :
1741 8 : static inline bool lsp_collect_import_token_is_name_part(zval *token)
1742 : {
1743 16 : return lsp_token_name_equals(token, "T_STRING") ||
1744 8 : lsp_token_name_equals(token, "T_NAME_QUALIFIED") ||
1745 0 : lsp_token_name_equals(token, "T_NAME_FULLY_QUALIFIED") ||
1746 16 : lsp_token_name_equals(token, "T_NAME_RELATIVE") ||
1747 0 : lsp_token_name_equals(token, "T_NS_SEPARATOR")
1748 : ;
1749 : }
1750 :
1751 4 : static inline void lsp_collect_import_candidate(HashTable *imports, uint32_t target_kind, smart_str *prefix, smart_str *name, zend_string *alias)
1752 : {
1753 : zend_string *key, *full_name;
1754 : zval bound;
1755 : const char *alias_value;
1756 : size_t alias_length;
1757 :
1758 4 : if (!name->s || ZSTR_LEN(name->s) == 0) {
1759 0 : return;
1760 : }
1761 :
1762 4 : smart_str_0(name);
1763 4 : if (prefix->s && ZSTR_LEN(prefix->s) > 0) {
1764 0 : smart_str_0(prefix);
1765 : /* The tokenized group prefix keeps its trailing namespace separator
1766 : * (`use App\{First};` lexes as "App\" + '{'), so only add one when
1767 : * it is missing. */
1768 0 : if (ZSTR_VAL(prefix->s)[ZSTR_LEN(prefix->s) - 1] == '\\') {
1769 0 : full_name = strpprintf(0, "%s%s", ZSTR_VAL(prefix->s), ZSTR_VAL(name->s));
1770 : } else {
1771 0 : full_name = strpprintf(0, "%s\\%s", ZSTR_VAL(prefix->s), ZSTR_VAL(name->s));
1772 : }
1773 : } else {
1774 4 : full_name = zend_string_copy(name->s);
1775 : }
1776 :
1777 4 : if (ZSTR_LEN(full_name) > 0 && ZSTR_VAL(full_name)[0] == '\\') {
1778 0 : zend_string *trimmed = zend_string_init(ZSTR_VAL(full_name) + 1, ZSTR_LEN(full_name) - 1, 0);
1779 0 : zend_string_release(full_name);
1780 0 : full_name = trimmed;
1781 : }
1782 :
1783 4 : if (alias) {
1784 0 : alias_value = ZSTR_VAL(alias);
1785 0 : alias_length = ZSTR_LEN(alias);
1786 : } else {
1787 4 : lsp_import_terminal_segment(ZSTR_VAL(full_name), ZSTR_LEN(full_name), &alias_value, &alias_length);
1788 : }
1789 :
1790 4 : key = lsp_import_set_key(target_kind, ZSTR_VAL(full_name), ZSTR_LEN(full_name));
1791 4 : ZVAL_STR(&bound, zend_string_init(alias_value, alias_length, 0));
1792 4 : zend_hash_update(imports, key, &bound);
1793 4 : zend_string_release(key);
1794 :
1795 4 : key = lsp_import_alias_set_key(target_kind, alias_value, alias_length);
1796 4 : zend_hash_add_empty_element(imports, key);
1797 4 : zend_string_release(key);
1798 :
1799 4 : key = lsp_import_reverse_key(target_kind, alias_value, alias_length);
1800 4 : ZVAL_STR(&bound, zend_string_copy(full_name));
1801 4 : zend_hash_update(imports, key, &bound);
1802 4 : zend_string_release(key);
1803 4 : zend_string_release(full_name);
1804 : }
1805 :
1806 : /* Token-level fallback used while the document does not parse (mid-edit
1807 : * documents are routinely syntactically invalid). Mirrors the use-statement
1808 : * shapes handled by the AST collector: plain, aliased, grouped, and
1809 : * function/const imports. */
1810 12 : static inline void lsp_document_collect_imports_from_tokens(zend_string *text, HashTable *imports)
1811 : {
1812 : zval tokens_zv, *token;
1813 : HashTable *tokens;
1814 12 : smart_str prefix = {0}, name = {0}, no_prefix = {0};
1815 : zend_string *alias, *token_text;
1816 : uint32_t i, count, target_kind;
1817 12 : bool in_use = false, in_group = false, reading_alias = false;
1818 :
1819 12 : ZVAL_UNDEF(&tokens_zv);
1820 12 : lsp_lsparrot_tokens_to_zval(&tokens_zv, text);
1821 12 : if (Z_TYPE(tokens_zv) != IS_ARRAY) {
1822 0 : if (!Z_ISUNDEF(tokens_zv)) {
1823 0 : zval_ptr_dtor(&tokens_zv);
1824 : }
1825 :
1826 0 : return;
1827 : }
1828 :
1829 12 : tokens = Z_ARRVAL(tokens_zv);
1830 12 : count = zend_hash_num_elements(tokens);
1831 12 : alias = NULL;
1832 12 : target_kind = ZEND_SYMBOL_CLASS;
1833 224 : for (i = 0; i < count; i++) {
1834 216 : token = zend_hash_index_find(tokens, i);
1835 216 : if (!token || Z_TYPE_P(token) != IS_ARRAY || lsp_collect_import_token_is_ignored(token)) {
1836 84 : continue;
1837 : }
1838 :
1839 132 : if (!in_use) {
1840 120 : if (lsp_token_is_class_like(token)) {
1841 4 : break;
1842 : }
1843 :
1844 116 : if (lsp_token_name_equals(token, "T_USE")) {
1845 8 : in_use = true;
1846 8 : in_group = false;
1847 8 : reading_alias = false;
1848 8 : alias = NULL;
1849 8 : target_kind = ZEND_SYMBOL_CLASS;
1850 8 : smart_str_free(&prefix);
1851 8 : memset(&prefix, 0, sizeof(prefix));
1852 8 : smart_str_free(&name);
1853 8 : memset(&name, 0, sizeof(name));
1854 : }
1855 :
1856 116 : continue;
1857 : }
1858 :
1859 12 : if (lsp_token_name_equals(token, "T_FUNCTION")) {
1860 0 : target_kind = ZEND_SYMBOL_FUNCTION;
1861 0 : continue;
1862 : }
1863 :
1864 12 : if (lsp_token_name_equals(token, "T_CONST")) {
1865 0 : target_kind = ZEND_SYMBOL_CONST;
1866 0 : continue;
1867 : }
1868 :
1869 12 : if (lsp_token_is_char(token, ';')) {
1870 4 : lsp_collect_import_candidate(imports, target_kind, &prefix, &name, alias);
1871 4 : smart_str_free(&name);
1872 4 : memset(&name, 0, sizeof(name));
1873 4 : in_use = false;
1874 4 : continue;
1875 : }
1876 :
1877 8 : if (lsp_token_is_char(token, '{')) {
1878 0 : if (name.s) {
1879 0 : smart_str_0(&name);
1880 0 : smart_str_append(&prefix, name.s);
1881 0 : smart_str_free(&name);
1882 0 : memset(&name, 0, sizeof(name));
1883 : }
1884 :
1885 0 : in_group = true;
1886 0 : alias = NULL;
1887 0 : reading_alias = false;
1888 0 : continue;
1889 : }
1890 :
1891 8 : if (lsp_token_is_char(token, ',') || lsp_token_is_char(token, '}')) {
1892 0 : lsp_collect_import_candidate(imports, target_kind, in_group ? &prefix : &no_prefix, &name, alias);
1893 0 : smart_str_free(&name);
1894 0 : memset(&name, 0, sizeof(name));
1895 0 : alias = NULL;
1896 0 : reading_alias = false;
1897 :
1898 0 : if (lsp_token_is_char(token, '}')) {
1899 0 : in_group = false;
1900 : }
1901 :
1902 0 : continue;
1903 : }
1904 :
1905 8 : if (lsp_token_name_equals(token, "T_AS")) {
1906 0 : reading_alias = true;
1907 0 : alias = NULL;
1908 0 : continue;
1909 : }
1910 :
1911 8 : if (reading_alias) {
1912 0 : if (lsp_collect_import_token_is_name_part(token)) {
1913 0 : alias = lsp_token_string(token, "text");
1914 0 : reading_alias = false;
1915 : }
1916 :
1917 0 : continue;
1918 : }
1919 :
1920 8 : if (lsp_collect_import_token_is_name_part(token)) {
1921 8 : token_text = lsp_token_string(token, "text");
1922 8 : if (token_text) {
1923 8 : smart_str_append(&name, token_text);
1924 : }
1925 : }
1926 : }
1927 :
1928 12 : smart_str_free(&prefix);
1929 12 : smart_str_free(&name);
1930 12 : zval_ptr_dtor(&tokens_zv);
1931 : }
1932 :
1933 116 : extern void lsp_document_collect_imports(zend_string *text, HashTable *imports)
1934 : {
1935 : zend_arena *ast_arena;
1936 : zend_ast *ast;
1937 :
1938 116 : if (!strstr(ZSTR_VAL(text), "use")) {
1939 100 : return;
1940 : }
1941 :
1942 28 : ast = lsp_compile_string_to_ast_silent(text, ZSTR_EMPTY_ALLOC(), &ast_arena);
1943 28 : if (!ast) {
1944 12 : lsp_compiled_ast_destroy(ast, ast_arena);
1945 12 : lsp_document_collect_imports_from_tokens(text, imports);
1946 :
1947 12 : return;
1948 : }
1949 :
1950 16 : lsp_collect_imports_in_ast(ast, imports);
1951 16 : lsp_compiled_ast_destroy(ast, ast_arena);
1952 : }
1953 :
1954 1128 : extern bool lsp_document_has_import_cached(lsp_document *document, char kind, const char *fqcn, size_t fqcn_length)
1955 : {
1956 : zend_string *key;
1957 : uint32_t target_kind;
1958 : bool exists;
1959 :
1960 1128 : lsp_document_derived_ensure(document);
1961 1128 : if (!document->derived_imports || zend_hash_num_elements(document->derived_imports) == 0) {
1962 1100 : return false;
1963 : }
1964 :
1965 28 : target_kind = lsp_symbol_import_ast_kind(kind);
1966 28 : key = lsp_import_set_key(target_kind, fqcn, fqcn_length);
1967 28 : exists = zend_hash_exists(document->derived_imports, key);
1968 28 : zend_string_release(key);
1969 :
1970 28 : return exists;
1971 : }
1972 :
1973 : /* Returns the short name the document's import of `fqcn` binds (the alias for
1974 : * `use X as Y`, the terminal segment otherwise), or NULL when not imported.
1975 : * The returned string is borrowed from the derived-import table. */
1976 64 : extern zend_string *lsp_document_import_bound_name(lsp_document *document, char kind, const char *fqcn, size_t fqcn_length)
1977 : {
1978 : zend_string *key;
1979 : zval *value;
1980 : uint32_t target_kind;
1981 :
1982 64 : lsp_document_derived_ensure(document);
1983 64 : if (!document->derived_imports || zend_hash_num_elements(document->derived_imports) == 0) {
1984 56 : return NULL;
1985 : }
1986 :
1987 8 : target_kind = lsp_symbol_import_ast_kind(kind);
1988 8 : key = lsp_import_set_key(target_kind, fqcn, fqcn_length);
1989 8 : value = zend_hash_find(document->derived_imports, key);
1990 8 : zend_string_release(key);
1991 :
1992 8 : return value && Z_TYPE_P(value) == IS_STRING ? Z_STR_P(value) : NULL;
1993 : }
1994 :
1995 : /* Reverse lookup: the FQCN whose import binds `name` for the given symbol
1996 : * kind (e.g. `use function App\helper;` binds "helper"). Returns a new
1997 : * string or NULL. */
1998 40 : extern zend_string *lsp_document_import_fqcn_for_bound_name(lsp_document *document, char kind, zend_string *name)
1999 : {
2000 40 : zend_string *key, *result = NULL;
2001 : zval *value;
2002 : uint32_t target_kind;
2003 :
2004 40 : lsp_document_derived_ensure(document);
2005 40 : if (!document->derived_imports || zend_hash_num_elements(document->derived_imports) == 0) {
2006 32 : return NULL;
2007 : }
2008 :
2009 8 : target_kind = lsp_symbol_import_ast_kind(kind);
2010 8 : key = lsp_import_reverse_key(target_kind, ZSTR_VAL(name), ZSTR_LEN(name));
2011 8 : value = zend_hash_find(document->derived_imports, key);
2012 8 : zend_string_release(key);
2013 :
2014 8 : if (value && Z_TYPE_P(value) == IS_STRING) {
2015 0 : result = zend_string_copy(Z_STR_P(value));
2016 : }
2017 :
2018 8 : return result;
2019 : }
2020 :
2021 1120 : extern bool lsp_document_import_binds_short_name(lsp_document *document, char kind, const char *fqcn, size_t fqcn_length)
2022 : {
2023 : zend_string *key;
2024 : const char *segment;
2025 : size_t segment_length;
2026 : uint32_t target_kind;
2027 : bool exists;
2028 :
2029 1120 : lsp_document_derived_ensure(document);
2030 1120 : if (!document->derived_imports || zend_hash_num_elements(document->derived_imports) == 0) {
2031 1100 : return false;
2032 : }
2033 :
2034 20 : lsp_import_terminal_segment(fqcn, fqcn_length, &segment, &segment_length);
2035 20 : target_kind = lsp_symbol_import_ast_kind(kind);
2036 20 : key = lsp_import_alias_set_key(target_kind, segment, segment_length);
2037 20 : exists = zend_hash_exists(document->derived_imports, key);
2038 20 : zend_string_release(key);
2039 :
2040 20 : return exists;
2041 : }
2042 :
2043 3232 : static inline bool lsp_line_trimmed_starts_with(const char *start, const char *end, const char *keyword)
2044 : {
2045 3232 : size_t keyword_length = strlen(keyword);
2046 :
2047 3364 : while (start < end && isspace((unsigned char) *start)) {
2048 132 : start++;
2049 : }
2050 :
2051 4832 : return (size_t) (end - start) >= keyword_length &&
2052 3556 : memcmp(start, keyword, keyword_length) == 0 &&
2053 324 : ((size_t) (end - start) == keyword_length || isspace((unsigned char) start[keyword_length]) || start[keyword_length] == '(')
2054 : ;
2055 : }
2056 :
2057 44 : static inline bool lsp_line_contains_char(const char *start, const char *end, char needle)
2058 : {
2059 1124 : while (start < end) {
2060 1120 : if (*start == needle) {
2061 40 : return true;
2062 : }
2063 :
2064 1080 : start++;
2065 : }
2066 :
2067 4 : return false;
2068 : }
2069 :
2070 120 : extern size_t lsp_import_insert_offset(zend_string *text, bool *after_existing_use)
2071 : {
2072 120 : const char *value = ZSTR_VAL(text), *line_start, *line_end;
2073 120 : size_t offset = 0, insert_offset = 0, next_offset;
2074 :
2075 120 : *after_existing_use = false;
2076 520 : while (offset < ZSTR_LEN(text)) {
2077 520 : line_start = value + offset;
2078 520 : line_end = memchr(line_start, '\n', ZSTR_LEN(text) - offset);
2079 :
2080 520 : if (!line_end) {
2081 32 : line_end = value + ZSTR_LEN(text);
2082 32 : next_offset = ZSTR_LEN(text);
2083 : } else {
2084 488 : next_offset = (size_t) (line_end - value) + 1;
2085 : }
2086 :
2087 920 : if (lsp_line_trimmed_starts_with(line_start, line_end, "<?php") ||
2088 796 : lsp_line_trimmed_starts_with(line_start, line_end, "declare") ||
2089 396 : lsp_line_trimmed_starts_with(line_start, line_end, "namespace")
2090 : ) {
2091 204 : insert_offset = next_offset;
2092 316 : } else if (lsp_line_trimmed_starts_with(line_start, line_end, "use") && lsp_line_contains_char(line_start, line_end, ';')) {
2093 40 : insert_offset = next_offset;
2094 40 : *after_existing_use = true;
2095 540 : } else if (lsp_line_trimmed_starts_with(line_start, line_end, "class") ||
2096 476 : lsp_line_trimmed_starts_with(line_start, line_end, "final") ||
2097 424 : lsp_line_trimmed_starts_with(line_start, line_end, "abstract") ||
2098 424 : lsp_line_trimmed_starts_with(line_start, line_end, "interface") ||
2099 424 : lsp_line_trimmed_starts_with(line_start, line_end, "trait") ||
2100 424 : lsp_line_trimmed_starts_with(line_start, line_end, "enum") ||
2101 212 : lsp_line_trimmed_starts_with(line_start, line_end, "function")
2102 : ) {
2103 : break;
2104 : }
2105 :
2106 444 : offset = next_offset;
2107 :
2108 444 : if (next_offset == ZSTR_LEN(text)) {
2109 44 : break;
2110 : }
2111 : }
2112 :
2113 120 : return insert_offset;
2114 : }
2115 :
2116 1116 : extern zend_string *lsp_symbol_import_text(char kind, const char *fqcn, bool compact)
2117 : {
2118 1116 : if (kind == LSP_SYMBOL_FUNCTION) {
2119 4 : return strpprintf(0, "%suse function %s;\n", compact ? "" : "\n", fqcn);
2120 : }
2121 :
2122 1112 : if (kind == LSP_SYMBOL_CONSTANT) {
2123 0 : return strpprintf(0, "%suse const %s;\n", compact ? "" : "\n", fqcn);
2124 : }
2125 :
2126 1112 : return strpprintf(0, "%suse %s;\n", compact ? "" : "\n", fqcn);
2127 : }
2128 :
2129 : /* ------------------------------------------------------------------------
2130 : * Pre-encoded completion items. Project-symbol candidates are the highest
2131 : * volume completion source (thousands per keystroke on broad prefixes); each
2132 : * one used to be built as a deeply nested zval array and JSON-encoded again
2133 : * at response time. Instead the item JSON is emitted once here, and a small
2134 : * carrier zval {__json, label, kind, score, qualifiedName} keeps exactly the
2135 : * fields deduplication needs. The response assembler splices the fragments.
2136 : * ------------------------------------------------------------------------ */
2137 :
2138 7032 : static inline void lsp_json_append_escaped(smart_str *out, const char *value, size_t length)
2139 : {
2140 : static const char hex_digits[] = "0123456789abcdef";
2141 : size_t i;
2142 : unsigned char c;
2143 :
2144 7032 : smart_str_appendc(out, '"');
2145 133000 : for (i = 0; i < length; i++) {
2146 125968 : c = (unsigned char) value[i];
2147 125968 : switch (c) {
2148 0 : case '"':
2149 0 : smart_str_appendl(out, "\\\"", 2);
2150 0 : break;
2151 1836 : case '\\':
2152 1836 : smart_str_appendl(out, "\\\\", 2);
2153 1836 : break;
2154 0 : case '\b':
2155 0 : smart_str_appendl(out, "\\b", 2);
2156 0 : break;
2157 0 : case '\f':
2158 0 : smart_str_appendl(out, "\\f", 2);
2159 0 : break;
2160 2212 : case '\n':
2161 2212 : smart_str_appendl(out, "\\n", 2);
2162 2212 : break;
2163 0 : case '\r':
2164 0 : smart_str_appendl(out, "\\r", 2);
2165 0 : break;
2166 0 : case '\t':
2167 0 : smart_str_appendl(out, "\\t", 2);
2168 0 : break;
2169 121920 : default:
2170 121920 : if (c < 0x20) {
2171 0 : smart_str_appendl(out, "\\u00", 4);
2172 0 : smart_str_appendc(out, hex_digits[(c >> 4) & 0xf]);
2173 0 : smart_str_appendc(out, hex_digits[c & 0xf]);
2174 : } else {
2175 121920 : smart_str_appendc(out, (char) c);
2176 : }
2177 121920 : break;
2178 : }
2179 : }
2180 7032 : smart_str_appendc(out, '"');
2181 7032 : }
2182 :
2183 4360 : static inline void lsp_json_append_position(smart_str *out, zend_string *text, size_t offset)
2184 : {
2185 4360 : const char *value = ZSTR_VAL(text);
2186 4360 : zend_long line = 0;
2187 4360 : size_t i, line_start = 0, length = offset > ZSTR_LEN(text) ? ZSTR_LEN(text) : offset;
2188 :
2189 455196 : for (i = 0; i < length; i++) {
2190 450836 : if (value[i] == '\n') {
2191 28072 : line++;
2192 28072 : line_start = i + 1;
2193 : }
2194 : }
2195 :
2196 4360 : smart_str_appendl(out, "{\"line\":", sizeof("{\"line\":") - 1);
2197 4360 : smart_str_append_long(out, line);
2198 4360 : smart_str_appendl(out, ",\"character\":", sizeof(",\"character\":") - 1);
2199 4360 : smart_str_append_long(out, lsp_byte_offset_to_utf16_units(value, line_start, length));
2200 4360 : smart_str_appendc(out, '}');
2201 4360 : }
2202 :
2203 2180 : static inline zend_string *lsp_range_json_from_offsets(zend_string *text, size_t start_offset, size_t end_offset)
2204 : {
2205 2180 : smart_str json = {0};
2206 :
2207 2180 : smart_str_appendl(&json, "{\"start\":", sizeof("{\"start\":") - 1);
2208 2180 : lsp_json_append_position(&json, text, start_offset);
2209 2180 : smart_str_appendl(&json, ",\"end\":", sizeof(",\"end\":") - 1);
2210 2180 : lsp_json_append_position(&json, text, end_offset);
2211 2180 : smart_str_appendc(&json, '}');
2212 2180 : smart_str_0(&json);
2213 :
2214 2180 : return json.s;
2215 : }
2216 :
2217 : typedef struct _lsp_symbol_item_ctx {
2218 : lsp_document *document;
2219 : zend_string *prefix;
2220 : zend_string *current_namespace;
2221 : zend_string *edit_range_json;
2222 : zend_string *import_range_json;
2223 : size_t offset;
2224 : bool import_after_use;
2225 : bool import_context;
2226 : bool prefix_is_qualified;
2227 : } lsp_symbol_item_ctx;
2228 :
2229 1112 : static inline void lsp_symbol_item_ctx_init(lsp_symbol_item_ctx *ctx, lsp_document *document, size_t offset, zend_string *prefix)
2230 : {
2231 1112 : size_t prefix_start = offset >= ZSTR_LEN(prefix) ? offset - ZSTR_LEN(prefix) : 0;
2232 :
2233 1112 : ctx->document = document;
2234 1112 : ctx->prefix = prefix;
2235 1112 : ctx->current_namespace = lsp_document_namespace_cached(document);
2236 1112 : ctx->edit_range_json = lsp_range_json_from_offsets(document->text, prefix_start, offset);
2237 1112 : ctx->import_range_json = NULL;
2238 1112 : ctx->offset = offset;
2239 1112 : ctx->import_after_use = false;
2240 1112 : ctx->import_context = lsp_current_statement_starts_with_use(document->text, offset);
2241 1112 : ctx->prefix_is_qualified = memchr(ZSTR_VAL(prefix), '\\', ZSTR_LEN(prefix)) != NULL;
2242 1112 : }
2243 :
2244 1112 : static inline void lsp_symbol_item_ctx_release(lsp_symbol_item_ctx *ctx)
2245 : {
2246 1112 : if (ctx->edit_range_json) {
2247 1112 : zend_string_release(ctx->edit_range_json);
2248 : }
2249 :
2250 1112 : if (ctx->import_range_json) {
2251 1068 : zend_string_release(ctx->import_range_json);
2252 : }
2253 1112 : }
2254 :
2255 1112 : static inline zend_string *lsp_symbol_item_ctx_import_range(lsp_symbol_item_ctx *ctx)
2256 : {
2257 : size_t insert_offset;
2258 :
2259 1112 : if (!ctx->import_range_json) {
2260 1068 : insert_offset = lsp_document_import_insert_offset_cached(ctx->document, &ctx->import_after_use);
2261 1068 : ctx->import_range_json = lsp_range_json_from_offsets(ctx->document->text, insert_offset, insert_offset);
2262 : }
2263 :
2264 1112 : return ctx->import_range_json;
2265 : }
2266 :
2267 1184 : static inline void lsp_add_project_symbol_completion_item(zval *items, lsp_symbol_item_ctx *ctx, char kind, const char *fqcn, size_t fqcn_length, const char *label_value, size_t label_length, const char *path, size_t path_length)
2268 : {
2269 1184 : smart_str json = {0};
2270 : zend_string *new_text, *import_text, *detail, *encoded, *bound_name;
2271 : zval entry;
2272 : zend_long score;
2273 : char sort_prefix;
2274 : bool call_snippet, needs_import, qualify_inline;
2275 :
2276 1184 : call_snippet = kind == LSP_SYMBOL_FUNCTION && !ctx->import_context;
2277 1184 : sort_prefix = lsp_path_value_contains_vendor(path, path_length) ? '1' : '0';
2278 1184 : detail = strpprintf(0, "%s%s", lsp_symbol_detail_prefix(kind), fqcn);
2279 :
2280 3548 : needs_import = !ctx->import_context &&
2281 1180 : !ctx->prefix_is_qualified &&
2282 3488 : !lsp_symbol_in_current_namespace(ctx->current_namespace, kind, fqcn, fqcn_length) &&
2283 1124 : !lsp_document_has_import_cached(ctx->document, kind, fqcn, fqcn_length)
2284 : ;
2285 :
2286 : /* If the document already binds this short name to a different symbol
2287 : * (another import or alias), adding a `use` would be a name clash;
2288 : * insert the fully qualified name instead. */
2289 1184 : qualify_inline = needs_import && lsp_document_import_binds_short_name(ctx->document, kind, fqcn, fqcn_length);
2290 1184 : if (qualify_inline) {
2291 4 : needs_import = false;
2292 : }
2293 :
2294 : /* A class imported under an alias (`use Lib\Widget as W`) is only
2295 : * reachable through the alias: label and inserted text must use it,
2296 : * or the completion produces an unresolvable bare class name. */
2297 1184 : if (!needs_import && !qualify_inline && !ctx->import_context && !ctx->prefix_is_qualified) {
2298 64 : bound_name = lsp_document_import_bound_name(ctx->document, kind, fqcn, fqcn_length);
2299 64 : if (bound_name && (ZSTR_LEN(bound_name) != label_length || strncasecmp(ZSTR_VAL(bound_name), label_value, label_length) != 0)) {
2300 4 : label_value = ZSTR_VAL(bound_name);
2301 4 : label_length = ZSTR_LEN(bound_name);
2302 : }
2303 : }
2304 :
2305 1184 : if (ctx->import_context || ctx->prefix_is_qualified) {
2306 4 : if (ZSTR_LEN(ctx->prefix) > 0 && ZSTR_VAL(ctx->prefix)[0] == '\\') {
2307 0 : new_text = strpprintf(0, "\\%s", fqcn);
2308 : } else {
2309 4 : new_text = zend_string_init(fqcn, fqcn_length, 0);
2310 : }
2311 1180 : } else if (qualify_inline) {
2312 4 : new_text = strpprintf(0, "\\%.*s", (int) fqcn_length, fqcn);
2313 : } else {
2314 1176 : new_text = zend_string_init(label_value, label_length, 0);
2315 : }
2316 :
2317 1184 : smart_str_appendl(&json, "{\"label\":", sizeof("{\"label\":") - 1);
2318 1184 : lsp_json_append_escaped(&json, label_value, label_length);
2319 1184 : smart_str_appendl(&json, ",\"kind\":", sizeof(",\"kind\":") - 1);
2320 1184 : smart_str_append_long(&json, lsp_symbol_completion_kind(kind));
2321 1184 : smart_str_appendl(&json, ",\"detail\":", sizeof(",\"detail\":") - 1);
2322 1184 : lsp_json_append_escaped(&json, ZSTR_VAL(detail), ZSTR_LEN(detail));
2323 1184 : smart_str_appendl(&json, ",\"filterText\":", sizeof(",\"filterText\":") - 1);
2324 1184 : lsp_json_append_escaped(&json, label_value, label_length);
2325 1184 : smart_str_appendl(&json, ",\"sortText\":\"", sizeof(",\"sortText\":\"") - 1);
2326 1184 : smart_str_appendc(&json, sort_prefix);
2327 1184 : smart_str_appendc(&json, ':');
2328 : /* Labels are identifier characters; reuse the escaper minus the quotes
2329 : * by emitting the already-safe label directly. Identifier characters
2330 : * never require JSON escaping. */
2331 1184 : smart_str_appendl(&json, label_value, label_length);
2332 1184 : smart_str_appendc(&json, '"');
2333 1184 : smart_str_appendl(&json, ",\"data\":{\"source\":\"lsparrot\",\"qualifiedName\":", sizeof(",\"data\":{\"source\":\"lsparrot\",\"qualifiedName\":") - 1);
2334 1184 : lsp_json_append_escaped(&json, fqcn, fqcn_length);
2335 1184 : smart_str_appendc(&json, '}');
2336 :
2337 1184 : if (call_snippet) {
2338 4 : smart_str_appendl(&json, ",\"insertTextFormat\":2", sizeof(",\"insertTextFormat\":2") - 1);
2339 : }
2340 :
2341 1184 : smart_str_appendl(&json, ",\"textEdit\":{\"range\":", sizeof(",\"textEdit\":{\"range\":") - 1);
2342 1184 : smart_str_append(&json, ctx->edit_range_json);
2343 1184 : smart_str_appendl(&json, ",\"newText\":", sizeof(",\"newText\":") - 1);
2344 :
2345 1184 : if (call_snippet) {
2346 4 : encoded = lsp_completion_call_snippet(new_text);
2347 4 : lsp_json_append_escaped(&json, ZSTR_VAL(encoded), ZSTR_LEN(encoded));
2348 4 : zend_string_release(encoded);
2349 : } else {
2350 1180 : lsp_json_append_escaped(&json, ZSTR_VAL(new_text), ZSTR_LEN(new_text));
2351 : }
2352 :
2353 1184 : smart_str_appendc(&json, '}');
2354 :
2355 1184 : if (needs_import) {
2356 1112 : smart_str_appendl(&json, ",\"additionalTextEdits\":[{\"range\":", sizeof(",\"additionalTextEdits\":[{\"range\":") - 1);
2357 1112 : smart_str_append(&json, lsp_symbol_item_ctx_import_range(ctx));
2358 1112 : import_text = lsp_symbol_import_text(kind, fqcn, ctx->import_after_use);
2359 1112 : smart_str_appendl(&json, ",\"newText\":", sizeof(",\"newText\":") - 1);
2360 1112 : lsp_json_append_escaped(&json, ZSTR_VAL(import_text), ZSTR_LEN(import_text));
2361 1112 : zend_string_release(import_text);
2362 1112 : smart_str_appendl(&json, "}]", 2);
2363 : }
2364 :
2365 1184 : smart_str_appendc(&json, '}');
2366 1184 : smart_str_0(&json);
2367 :
2368 1184 : score = (sort_prefix == '0' ? 5000 : -5000) + lsp_completion_detail_score(detail);
2369 :
2370 1184 : array_init(&entry);
2371 1184 : add_assoc_str(&entry, "__json", json.s);
2372 1184 : add_assoc_stringl(&entry, "label", label_value, label_length);
2373 1184 : add_assoc_long(&entry, "kind", lsp_symbol_completion_kind(kind));
2374 1184 : add_assoc_long(&entry, "score", score);
2375 1184 : add_assoc_stringl(&entry, "qualifiedName", fqcn, fqcn_length);
2376 1184 : add_next_index_zval(items, &entry);
2377 :
2378 1184 : zend_string_release(new_text);
2379 1184 : zend_string_release(detail);
2380 1184 : }
2381 :
2382 128 : static inline uint32_t lsp_symbol_segment_lower_bound(lsp_symbol_index *region, const char *prefix_value, size_t prefix_length)
2383 : {
2384 : const lsp_symbol_segment *segment;
2385 : const char *seg;
2386 128 : uint32_t lo = 0, hi = region->segment_count, mid;
2387 :
2388 540 : while (lo < hi) {
2389 412 : mid = lo + (hi - lo) / 2;
2390 412 : segment = ®ion->segments[mid];
2391 412 : seg = lsp_symbol_entry_fqcn(region, ®ion->entries[segment->entry_index]) + segment->segment_offset;
2392 412 : if (strncasecmp(seg, prefix_value, prefix_length) < 0) {
2393 160 : lo = mid + 1;
2394 : } else {
2395 252 : hi = mid;
2396 : }
2397 : }
2398 :
2399 128 : return lo;
2400 : }
2401 :
2402 132 : static inline void lsp_symbol_match_prefix(lsp_symbol_index *region, zend_string *prefix, uint8_t *matched)
2403 : {
2404 : const lsp_symbol_entry *entry;
2405 : const lsp_symbol_segment *segment;
2406 132 : const char *prefix_value = ZSTR_VAL(prefix), *seg;
2407 : uint32_t i;
2408 132 : size_t prefix_length = ZSTR_LEN(prefix);
2409 :
2410 132 : if (prefix_length > 0 && prefix_value[0] == '\\') {
2411 0 : prefix_value++;
2412 0 : prefix_length--;
2413 : }
2414 :
2415 132 : if (prefix_length == 0) {
2416 4 : memset(matched, 1, region->entry_count);
2417 :
2418 4 : return;
2419 : }
2420 :
2421 : /* Strict prefix matching at FQCN segment starts (offset 0, after a
2422 : * namespace separator, or after an underscore) via binary search over
2423 : * the sorted segment array. */
2424 284 : for (i = lsp_symbol_segment_lower_bound(region, prefix_value, prefix_length); i < region->segment_count; i++) {
2425 236 : segment = ®ion->segments[i];
2426 236 : seg = lsp_symbol_entry_fqcn(region, ®ion->entries[segment->entry_index]) + segment->segment_offset;
2427 236 : if (strncasecmp(seg, prefix_value, prefix_length) != 0) {
2428 80 : break;
2429 : }
2430 :
2431 156 : matched[segment->entry_index] = 1;
2432 : }
2433 :
2434 128 : if (prefix_length < 2) {
2435 0 : return;
2436 : }
2437 :
2438 : /* Fuzzy subsequence fallback for class-like symbols. A subsequence of
2439 : * the basename label is always a subsequence of the FQCN, so matching
2440 : * the FQCN alone preserves the historical label-or-FQCN semantics. */
2441 600 : for (i = 0; i < region->entry_count; i++) {
2442 472 : entry = ®ion->entries[i];
2443 472 : if (matched[i] || !lsp_symbol_kind_is_class_like((char) entry->kind)) {
2444 240 : continue;
2445 : }
2446 :
2447 232 : if (lsp_symbol_fuzzy_match(lsp_symbol_entry_fqcn(region, entry), entry->fqcn_length, prefix_value, prefix_length)) {
2448 56 : matched[i] = 1;
2449 : }
2450 : }
2451 : }
2452 :
2453 264 : static inline void lsp_add_project_symbol_completions_pass(lsp_server *server, zval *items, lsp_symbol_item_ctx *ctx, char filter_kind, bool class_like_only, bool vendor_symbols, const uint8_t *matched)
2454 : {
2455 : const char *label_value, *fqcn, *path;
2456 : const lsp_symbol_entry *entry;
2457 264 : lsp_symbol_index *region = &server->symbol_index;
2458 : uint32_t i;
2459 : size_t label_length;
2460 :
2461 1272 : for (i = 0; i < region->entry_count; i++) {
2462 1008 : if (!matched[i]) {
2463 528 : continue;
2464 : }
2465 :
2466 480 : entry = ®ion->entries[i];
2467 480 : if ((entry->flags & LSP_SYMBOL_ENTRY_DELETED) != 0 ||
2468 472 : ((entry->flags & LSP_SYMBOL_ENTRY_VENDOR) != 0) != vendor_symbols
2469 : ) {
2470 244 : continue;
2471 : }
2472 :
2473 236 : if (filter_kind != '\0' && (char) entry->kind != filter_kind) {
2474 8 : continue;
2475 : }
2476 :
2477 228 : if (class_like_only && !lsp_symbol_kind_is_class_like((char) entry->kind)) {
2478 24 : continue;
2479 : }
2480 :
2481 204 : fqcn = lsp_symbol_entry_fqcn(region, entry);
2482 204 : path = lsp_symbol_entry_path(region, entry);
2483 204 : label_value = lsp_symbol_completion_label((char) entry->kind, fqcn, entry->fqcn_length, &label_length);
2484 204 : lsp_add_project_symbol_completion_item(items, ctx, (char) entry->kind, fqcn, entry->fqcn_length, label_value, label_length, path, entry->path_length);
2485 : }
2486 264 : }
2487 :
2488 192 : static inline void lsp_add_project_symbol_completions_ex(lsp_server *server, zval *items, lsp_document *document, size_t offset, zend_string *prefix, char filter_kind, bool class_like_only)
2489 : {
2490 : lsp_symbol_item_ctx ctx;
2491 : uint8_t *matched;
2492 :
2493 192 : lsp_index_join_worker(server);
2494 192 : lsp_symbol_index_table_ensure(&server->symbol_index);
2495 192 : if (server->symbol_index.entry_count == 0) {
2496 60 : return;
2497 : }
2498 :
2499 132 : matched = ecalloc(server->symbol_index.entry_count, 1);
2500 132 : lsp_symbol_match_prefix(&server->symbol_index, prefix, matched);
2501 132 : lsp_symbol_item_ctx_init(&ctx, document, offset, prefix);
2502 132 : lsp_add_project_symbol_completions_pass(server, items, &ctx, filter_kind, class_like_only, false, matched);
2503 132 : lsp_add_project_symbol_completions_pass(server, items, &ctx, filter_kind, class_like_only, true, matched);
2504 132 : lsp_symbol_item_ctx_release(&ctx);
2505 132 : efree(matched);
2506 : }
2507 :
2508 164 : extern void lsp_add_project_symbol_completions(lsp_server *server, zval *items, lsp_document *document, size_t offset, zend_string *prefix)
2509 : {
2510 164 : lsp_add_project_symbol_completions_ex(server, items, document, offset, prefix, '\0', false);
2511 164 : }
2512 :
2513 20 : extern void lsp_add_project_class_like_completions(lsp_server *server, zval *items, lsp_document *document, size_t offset, zend_string *prefix)
2514 : {
2515 20 : lsp_add_project_symbol_completions_ex(server, items, document, offset, prefix, '\0', true);
2516 20 : }
2517 :
2518 8 : extern void lsp_add_project_symbol_kind_completions(lsp_server *server, zval *items, lsp_document *document, size_t offset, zend_string *prefix, char filter_kind)
2519 : {
2520 8 : lsp_add_project_symbol_completions_ex(server, items, document, offset, prefix, filter_kind, false);
2521 8 : }
2522 :
2523 980 : extern void lsp_add_class_like_symbol_completion_item(zval *items, lsp_document *document, size_t offset, zend_string *prefix, char kind, zend_string *fqcn)
2524 : {
2525 : lsp_symbol_item_ctx ctx;
2526 : const char *label_value;
2527 : size_t label_length;
2528 :
2529 980 : label_value = lsp_symbol_completion_label(kind, ZSTR_VAL(fqcn), ZSTR_LEN(fqcn), &label_length);
2530 980 : lsp_symbol_item_ctx_init(&ctx, document, offset, prefix);
2531 980 : lsp_add_project_symbol_completion_item(items, &ctx, kind, ZSTR_VAL(fqcn), ZSTR_LEN(fqcn), label_value, label_length, "", 0);
2532 980 : lsp_symbol_item_ctx_release(&ctx);
2533 980 : }
|