LCOV - code coverage report
Current view: top level - ext - lsp_server_documents.c (source / functions) Coverage Total Hit
Test: Extension code coverage Lines: 90.6 % 588 533
Test Date: 2026-07-13 00:58:38 Functions: 100.0 % 46 46

            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              : extern void lsp_document_analyze(lsp_document *document);
      17              : 
      18              : /* Completion cache keys embed ":uri:version:", so entries for older versions
      19              :  * can never hit again and are dropped on every change. Type cache keys are
      20              :  * deliberately version-less (an expression's analyzer type survives typing),
      21              :  * so they are only evicted on save/close. */
      22           40 : extern void lsp_server_evict_document_caches(lsp_server *server, zend_string *uri, bool include_type_cache)
      23              : {
      24              :         zend_string *key, *needle;
      25              : 
      26           40 :         if (include_type_cache) {
      27              :                 /* didSave/didClose: drop the semantic-token delta snapshot too. */
      28           16 :                 lsp_semantic_tokens_cache_evict(uri);
      29              :         }
      30              : 
      31           40 :         needle = strpprintf(0, ":%s:", ZSTR_VAL(uri));
      32              : 
      33           40 :         ZEND_HASH_FOREACH_STR_KEY(&server->completion_cache, key) {
      34            0 :                 if (key && strstr(ZSTR_VAL(key), ZSTR_VAL(needle))) {
      35            0 :                         zend_hash_del(&server->completion_cache, key);
      36              :                 }
      37              :         } ZEND_HASH_FOREACH_END();
      38              : 
      39           40 :         if (include_type_cache) {
      40           16 :                 ZEND_HASH_FOREACH_STR_KEY(&server->type_cache, key) {
      41            0 :                         if (key && strstr(ZSTR_VAL(key), ZSTR_VAL(needle))) {
      42            0 :                                 zend_hash_del(&server->type_cache, key);
      43              :                         }
      44              :                 } ZEND_HASH_FOREACH_END();
      45              :         }
      46              : 
      47           40 :         zend_string_release(needle);
      48           40 : }
      49              : 
      50          564 : extern lsp_document *lsp_document_open_or_change(lsp_server *server, zend_string *uri, zend_long version, zend_string *text)
      51              : {
      52              :         lsp_document *document;
      53          564 :         zval *existing = zend_hash_find(&server->documents, uri), ptr;
      54              : 
      55          564 :         if (existing) {
      56           24 :                 document = (lsp_document *) Z_PTR_P(existing);
      57           24 :                 zend_string_release(document->text);
      58           24 :                 document->text = zend_string_copy(text);
      59           24 :                 document->version = version;
      60           24 :                 lsp_document_analyze(document);
      61           24 :                 lsp_server_evict_document_caches(server, uri, false);
      62              : 
      63           24 :                 return document;
      64              :         }
      65              : 
      66          540 :         document = ecalloc(1, sizeof(lsp_document));
      67          540 :         document->uri = zend_string_copy(uri);
      68          540 :         document->path = lsp_uri_to_path(uri);
      69          540 :         document->text = zend_string_copy(text);
      70          540 :         document->version = version;
      71          540 :         ZVAL_UNDEF(&document->lsparrot);
      72          540 :         lsp_document_analyze(document);
      73              : 
      74          540 :         ZVAL_PTR(&ptr, document);
      75          540 :         zend_hash_update(&server->documents, uri, &ptr);
      76              : 
      77          540 :         return document;
      78              : }
      79              : 
      80          928 : extern lsp_document *lsp_document_from_uri(lsp_server *server, zend_string *uri)
      81              : {
      82              :         lsp_document *document;
      83              :         zend_string *path, *text;
      84          928 :         zval *existing = zend_hash_find(&server->documents, uri);
      85              : 
      86          928 :         if (existing) {
      87          924 :                 return (lsp_document *) Z_PTR_P(existing);
      88              :         }
      89              : 
      90            4 :         path = lsp_uri_to_path(uri);
      91            4 :         text = lsp_read_file(path);
      92            4 :         document = lsp_document_open_or_change(server, uri, 0, text);
      93              : 
      94            4 :         if (text != zend_empty_string) {
      95            4 :                 zend_string_release(text);
      96              :         }
      97              : 
      98            4 :         zend_string_release(path);
      99              : 
     100            4 :         return document;
     101              : }
     102              : 
     103         4648 : static inline void lsp_protocol_write_frame(const char *body, size_t length)
     104              : {
     105         4648 :         fprintf(stdout, "Content-Length: %zu\r\n\r\n", length);
     106         4648 :         fwrite(body, 1, length, stdout);
     107         4648 :         fflush(stdout);
     108         4648 : }
     109              : 
     110         4144 : static inline void lsp_protocol_write(zval *payload)
     111              : {
     112         4144 :         const char *fallback = "{\"jsonrpc\":\"2.0\",\"error\":{\"code\":-32603,\"message\":\"Failed to encode response\"}}";
     113         4144 :         smart_str json = {0};
     114              : 
     115         4144 :         if (php_json_encode(&json, payload, PHP_JSON_UNESCAPED_SLASHES | PHP_JSON_UNESCAPED_UNICODE) == SUCCESS && json.s) {
     116         4144 :                 smart_str_0(&json);
     117         4144 :                 lsp_protocol_write_frame(ZSTR_VAL(json.s), ZSTR_LEN(json.s));
     118         4144 :                 smart_str_free(&json);
     119              : 
     120         4144 :                 return;
     121              :         }
     122              : 
     123            0 :         lsp_protocol_write_frame(fallback, strlen(fallback));
     124            0 :         smart_str_free(&json);
     125              : }
     126              : 
     127              : /* Responses whose result was pre-encoded by the handler (completion lists)
     128              :  * are spliced into the envelope without re-encoding. */
     129         2180 : static inline bool lsp_protocol_respond_raw(zval *id, zval *result)
     130              : {
     131         2180 :         smart_str json = {0};
     132              :         zend_string *raw;
     133              : 
     134         2180 :         if (!result || Z_TYPE_P(result) != IS_ARRAY || zend_hash_num_elements(Z_ARRVAL_P(result)) != 1) {
     135         1388 :                 return false;
     136              :         }
     137              : 
     138          792 :         raw = lsp_array_string(result, "__raw_json");
     139          792 :         if (!raw) {
     140          288 :                 return false;
     141              :         }
     142              : 
     143          504 :         smart_str_appendl(&json, "{\"jsonrpc\":\"2.0\",\"id\":", sizeof("{\"jsonrpc\":\"2.0\",\"id\":") - 1);
     144              : 
     145          504 :         if (id) {
     146          504 :                 if (php_json_encode(&json, id, PHP_JSON_UNESCAPED_SLASHES | PHP_JSON_UNESCAPED_UNICODE) != SUCCESS) {
     147            0 :                         smart_str_free(&json);
     148              : 
     149            0 :                         return false;
     150              :                 }
     151              :         } else {
     152            0 :                 smart_str_appendl(&json, "null", 4);
     153              :         }
     154              : 
     155          504 :         smart_str_appendl(&json, ",\"result\":", sizeof(",\"result\":") - 1);
     156          504 :         smart_str_append(&json, raw);
     157          504 :         smart_str_appendc(&json, '}');
     158          504 :         smart_str_0(&json);
     159          504 :         lsp_protocol_write_frame(ZSTR_VAL(json.s), ZSTR_LEN(json.s));
     160          504 :         smart_str_free(&json);
     161              : 
     162          504 :         return true;
     163              : }
     164              : 
     165         2180 : extern void lsp_protocol_respond(zval *id, zval *result)
     166              : {
     167              :         zval payload, id_copy, result_copy;
     168              : 
     169         2180 :         if (lsp_protocol_respond_raw(id, result)) {
     170          504 :                 return;
     171              :         }
     172              : 
     173         1676 :         array_init(&payload);
     174         1676 :         add_assoc_string(&payload, "jsonrpc", "2.0");
     175              : 
     176         1676 :         if (id) {
     177         1676 :                 ZVAL_COPY(&id_copy, id);
     178         1676 :                 add_assoc_zval(&payload, "id", &id_copy);
     179              :         } else {
     180            0 :                 add_assoc_null(&payload, "id");
     181              :         }
     182              : 
     183         1676 :         ZVAL_COPY(&result_copy, result);
     184         1676 :         add_assoc_zval(&payload, "result", &result_copy);
     185         1676 :         lsp_protocol_write(&payload);
     186         1676 :         zval_ptr_dtor(&payload);
     187              : }
     188              : 
     189           12 : extern void lsp_protocol_error(zval *id, int code, const char *message)
     190              : {
     191              :         zval payload, error, id_copy;
     192              : 
     193           12 :         array_init(&payload);
     194           12 :         add_assoc_string(&payload, "jsonrpc", "2.0");
     195              : 
     196           12 :         if (id) {
     197           12 :                 ZVAL_COPY(&id_copy, id);
     198           12 :                 add_assoc_zval(&payload, "id", &id_copy);
     199              :         } else {
     200            0 :                 add_assoc_null(&payload, "id");
     201              :         }
     202              : 
     203           12 :         array_init(&error);
     204           12 :         add_assoc_long(&error, "code", code);
     205           12 :         add_assoc_string(&error, "message", message);
     206           12 :         add_assoc_zval(&payload, "error", &error);
     207           12 :         lsp_protocol_write(&payload);
     208           12 :         zval_ptr_dtor(&payload);
     209           12 : }
     210              : 
     211         2456 : extern void lsp_protocol_notify(const char *method, zval *params)
     212              : {
     213              :         zval payload, params_copy, empty_params;
     214              : 
     215         2456 :         array_init(&payload);
     216         2456 :         add_assoc_string(&payload, "jsonrpc", "2.0");
     217         2456 :         add_assoc_string(&payload, "method", method);
     218              : 
     219         2456 :         if (params) {
     220         2456 :                 ZVAL_COPY(&params_copy, params);
     221         2456 :                 add_assoc_zval(&payload, "params", &params_copy);
     222              :         } else {
     223            0 :                 array_init(&empty_params);
     224            0 :                 add_assoc_zval(&payload, "params", &empty_params);
     225              :         }
     226              : 
     227         2456 :         lsp_protocol_write(&payload);
     228         2456 :         zval_ptr_dtor(&payload);
     229         2456 : }
     230              : 
     231         1204 : extern void lsp_analyzer_project_status(const char *analyzer, const char *state, const char *message, zend_string *project_root)
     232              : {
     233              :         zval params;
     234              : 
     235         1204 :         array_init(&params);
     236         1204 :         add_assoc_string(&params, "analyzer", analyzer);
     237         1204 :         add_assoc_string(&params, "state", state);
     238         1204 :         add_assoc_string(&params, "message", message);
     239              : 
     240         1204 :         if (project_root) {
     241          256 :                 add_assoc_str(&params, "projectRoot", zend_string_copy(project_root));
     242              :         }
     243              : 
     244         1204 :         lsp_protocol_notify("lsparrot.php/analyzerStatus", &params);
     245         1204 :         zval_ptr_dtor(&params);
     246         1204 : }
     247              : 
     248          948 : extern void lsp_analyzer_status(const char *analyzer, const char *state, const char *message)
     249              : {
     250          948 :         lsp_analyzer_project_status(analyzer, state, message, NULL);
     251          948 : }
     252              : 
     253           68 : static inline const char *lsp_analyzer_finished_message(const char *analyzer)
     254              : {
     255           68 :         if (strcmp(analyzer, "phpstan") == 0) {
     256           44 :                 return "PHPStan diagnostics finished.";
     257              :         }
     258              : 
     259           24 :         return "Psalm diagnostics finished.";
     260              : }
     261              : 
     262              : static inline void lsp_reap_analyzer_job(lsp_server *server, lsp_analyzer_job *job, const char *analyzer);
     263              : 
     264         6208 : extern void lsp_reap_analyzer_job_table(lsp_server *server, HashTable *jobs, const char *analyzer)
     265              : {
     266              :         lsp_analyzer_job *job;
     267              :         zval *value;
     268              : 
     269         6720 :         ZEND_HASH_FOREACH_VAL(jobs, value) {
     270          512 :                 if (Z_TYPE_P(value) != IS_PTR) {
     271            0 :                         continue;
     272              :                 }
     273              : 
     274          512 :                 job = (lsp_analyzer_job *) Z_PTR_P(value);
     275          512 :                 lsp_reap_analyzer_job(server, job, analyzer);
     276              :         } ZEND_HASH_FOREACH_END();
     277         6208 : }
     278              : 
     279          512 : static inline void lsp_reap_analyzer_job(lsp_server *server, lsp_analyzer_job *job, const char *analyzer)
     280              : {
     281          512 :         zend_string *project_root = NULL, *output_file = NULL;
     282          512 :         int status = 0;
     283              : 
     284          512 :         if (!job->running || !lsp_process_id_valid(job->pid)) {
     285          444 :                 return;
     286              :         }
     287              : 
     288          319 :         if (!lsp_process_wait_nonblocking(job->pid, &status)) {
     289          251 :                 return;
     290              :         }
     291              : 
     292           68 :         if (job->project_root) {
     293           68 :                 project_root = zend_string_copy(job->project_root);
     294              :         }
     295              : 
     296           68 :         if (job->cache_file) {
     297           68 :                 output_file = zend_string_copy(job->cache_file);
     298              :         }
     299              : 
     300           68 :         lsp_analyzer_job_clear(job);
     301              : 
     302           68 :         if (project_root) {
     303           68 :                 lsp_analyzer_project_status(analyzer, "idle", lsp_analyzer_finished_message(analyzer), project_root);
     304              :         } else {
     305            0 :                 lsp_analyzer_status(analyzer, "idle", lsp_analyzer_finished_message(analyzer));
     306              :         }
     307              : 
     308           68 :         if (project_root) {
     309           68 :                 lsp_analyzer_project_finished(server, analyzer, project_root, output_file);
     310           68 :                 zend_string_release(project_root);
     311              :         }
     312              : 
     313           68 :         if (output_file) {
     314           68 :                 zend_string_release(output_file);
     315              :         }
     316              : }
     317              : 
     318              : /* A deferred type query finished in the resident runner: parse the output
     319              :  * with the analyzer that started it and publish the result into the type
     320              :  * cache so the next completion/hover request picks it up. */
     321            4 : extern void lsp_analyzer_deferred_type_completed(lsp_server *server, zval *descriptor, zend_string *output)
     322              : {
     323              :         zend_string *analyzer, *cache_key, *analysis_file, *expression, *type;
     324              :         zend_long marker_line;
     325              :         zval cache_value;
     326              : 
     327            4 :         analyzer = lsp_array_string(descriptor, "analyzer");
     328            4 :         cache_key = lsp_array_string(descriptor, "cacheKey");
     329            4 :         analysis_file = lsp_array_string(descriptor, "analysisFile");
     330            4 :         expression = lsp_array_string(descriptor, "expression");
     331            4 :         marker_line = lsp_array_long(descriptor, "markerLine", 0);
     332              : 
     333            4 :         type = NULL;
     334            4 :         if (output && analyzer) {
     335            4 :                 if (zend_string_equals_literal(analyzer, "phpstan")) {
     336            4 :                         type = lsp_phpstan_parse_type_output(output, analysis_file, marker_line);
     337            0 :                 } else if (zend_string_equals_literal(analyzer, "psalm")) {
     338            0 :                         type = lsp_psalm_parse_type_output(output, expression, marker_line);
     339              :                 }
     340              :         }
     341              : 
     342            4 :         if (lsp_type_is_unhelpful(type)) {
     343            0 :                 if (type) {
     344            0 :                         zend_string_release(type);
     345              :                 }
     346            0 :                 type = NULL;
     347              :         }
     348              : 
     349            4 :         if (cache_key) {
     350            4 :                 if (type) {
     351            4 :                         ZVAL_STR_COPY(&cache_value, type);
     352              :                 } else {
     353            0 :                         ZVAL_FALSE(&cache_value);
     354              :                 }
     355            4 :                 zend_hash_update(&server->type_cache, cache_key, &cache_value);
     356              :         }
     357              : 
     358            4 :         if (type) {
     359            4 :                 zend_string_release(type);
     360              :         }
     361              : 
     362            4 :         if (analysis_file) {
     363            4 :                 VCWD_UNLINK(ZSTR_VAL(analysis_file));
     364              :         }
     365            4 : }
     366              : 
     367         3104 : extern void lsp_reap_analyzer_jobs(lsp_server *server)
     368              : {
     369         3104 :         lsp_index_poll_worker(server);
     370         3104 :         lsp_reap_analyzer_job_table(server, &server->phpstan_jobs, "phpstan");
     371         3104 :         lsp_reap_analyzer_job_table(server, &server->psalm_jobs, "psalm");
     372         3104 :         lsp_psalm_ls_pump(server, 0.0);
     373         3104 :         lsp_runner_pump_pending(server);
     374         3104 :         lsp_runner_reap_idle_sessions(server);
     375         3104 :         lsp_reap_analyzer_completion_jobs();
     376         3104 : }
     377              : 
     378            4 : static inline void lsp_window_show_message(zend_long type, const char *message)
     379              : {
     380              :         zval params;
     381              : 
     382            4 :         array_init(&params);
     383            4 :         add_assoc_long(&params, "type", type);
     384            4 :         add_assoc_string(&params, "message", message);
     385            4 :         lsp_protocol_notify("window/showMessage", &params);
     386            4 :         zval_ptr_dtor(&params);
     387            4 : }
     388              : 
     389            4 : extern void lsp_analyzer_unavailable(const char *analyzer, const char *label)
     390              : {
     391              :         zend_string *message;
     392              :         zval params;
     393              : 
     394            4 :         message = strpprintf(0, "%s is not installed; falling back to LSParrot Engine.", label);
     395              : 
     396            4 :         array_init(&params);
     397            4 :         add_assoc_string(&params, "analyzer", analyzer);
     398            4 :         add_assoc_string(&params, "state", "error");
     399            4 :         add_assoc_str(&params, "message", zend_string_copy(message));
     400            4 :         add_assoc_string(&params, "missingAnalyzer", analyzer);
     401            4 :         lsp_protocol_notify("lsparrot.php/analyzerStatus", &params);
     402            4 :         zval_ptr_dtor(&params);
     403            4 :         lsp_window_show_message(1, ZSTR_VAL(message));
     404            4 :         zend_string_release(message);
     405            4 : }
     406              : 
     407          548 : static inline void lsp_active_driver(lsp_server *server, const char **driver, const char **label)
     408              : {
     409          548 :         if (server->phpstan_enabled && server->psalm_enabled) {
     410           20 :                 *driver = "lsparrot+phpstan+psalm";
     411           20 :                 *label = "LSParrot Engine + PHPStan + Psalm";
     412              : 
     413           20 :                 return;
     414              :         }
     415              : 
     416          528 :         if (server->phpstan_enabled) {
     417           92 :                 *driver = "lsparrot+phpstan";
     418           92 :                 *label = "LSParrot Engine + PHPStan";
     419              : 
     420           92 :                 return;
     421              :         }
     422              : 
     423          436 :         if (server->psalm_enabled) {
     424           28 :                 *driver = "lsparrot+psalm";
     425           28 :                 *label = "LSParrot Engine + Psalm";
     426              : 
     427           28 :                 return;
     428              :         }
     429              : 
     430          408 :         *driver = "lsparrot";
     431          408 :         *label = "LSParrot Engine";
     432              : }
     433              : 
     434          548 : extern void lsp_driver_status(lsp_server *server)
     435              : {
     436              :         const char *driver, *label;
     437              :         zend_string *message;
     438              :         zval params;
     439              : 
     440          548 :         lsp_active_driver(server, &driver, &label);
     441          548 :         message = strpprintf(0, "Using %s analyzer.", label);
     442              : 
     443          548 :         array_init(&params);
     444          548 :         add_assoc_string(&params, "analyzer", "driver");
     445          548 :         add_assoc_string(&params, "state", "idle");
     446          548 :         add_assoc_string(&params, "driver", driver);
     447          548 :         add_assoc_string(&params, "label", label);
     448          548 :         add_assoc_str(&params, "message", message);
     449          548 :         lsp_protocol_notify("lsparrot.php/analyzerStatus", &params);
     450          548 :         zval_ptr_dtor(&params);
     451          548 : }
     452              : 
     453          104 : static inline const char *lsp_analyzer_project_state_name(zend_long state)
     454              : {
     455          104 :         switch (state) {
     456           60 :                 case LSP_ANALYZER_PROJECT_READY:
     457           60 :                         return "ready";
     458           20 :                 case LSP_ANALYZER_PROJECT_RUNNING:
     459           20 :                         return "running";
     460            0 :                 case LSP_ANALYZER_PROJECT_PENDING:
     461            0 :                         return "pending";
     462           24 :                 case LSP_ANALYZER_PROJECT_ERROR:
     463           24 :                         return "error";
     464              :         }
     465              : 
     466            0 :         return "unknown";
     467              : }
     468              : 
     469          348 : static inline void lsp_add_analyzer_project_states(zval *target, HashTable *projects)
     470              : {
     471              :         zend_long state;
     472              :         zend_string *project_root;
     473              :         zval states, *state_zv;
     474              : 
     475          348 :         array_init(&states);
     476              : 
     477          452 :         ZEND_HASH_FOREACH_STR_KEY_VAL(projects, project_root, state_zv) {
     478          104 :                 if (!project_root || Z_TYPE_P(state_zv) != IS_LONG) {
     479            0 :                         continue;
     480              :                 }
     481          104 :                 state = Z_LVAL_P(state_zv);
     482          104 :                 add_assoc_string(&states, ZSTR_VAL(project_root), lsp_analyzer_project_state_name(state));
     483              :         } ZEND_HASH_FOREACH_END();
     484              : 
     485          348 :         add_assoc_zval(target, "projects", &states);
     486          348 : }
     487              : 
     488          348 : static inline void lsp_add_analyzer_status_entry(zval *target, const char *name, bool enabled, bool running, HashTable *projects)
     489              : {
     490              :         zval entry;
     491              : 
     492          348 :         array_init(&entry);
     493          348 :         add_assoc_bool(&entry, "enabled", enabled);
     494          348 :         add_assoc_bool(&entry, "running", running);
     495          348 :         lsp_add_analyzer_project_states(&entry, projects);
     496          348 :         add_assoc_zval(target, name, &entry);
     497          348 : }
     498              : 
     499          116 : static inline void lsp_add_perf_stats(lsp_server *server, zval *target)
     500              : {
     501              :         lsp_perf_counter *counter;
     502              :         zend_string *method;
     503              :         zval stats, entry;
     504              : 
     505          116 :         array_init(&stats);
     506              : 
     507          396 :         ZEND_HASH_FOREACH_STR_KEY_PTR(&server->perf_stats, method, counter) {
     508          280 :                 if (!method || !counter) {
     509            0 :                         continue;
     510              :                 }
     511              : 
     512          280 :                 array_init(&entry);
     513          280 :                 add_assoc_long(&entry, "count", (zend_long) counter->count);
     514          280 :                 add_assoc_double(&entry, "totalMs", counter->total_seconds * 1000.0);
     515          280 :                 add_assoc_double(&entry, "maxMs", counter->max_seconds * 1000.0);
     516          280 :                 add_assoc_double(&entry, "avgMs", counter->count > 0 ? (counter->total_seconds * 1000.0) / (double) counter->count : 0.0);
     517          280 :                 add_assoc_zval(&stats, ZSTR_VAL(method), &entry);
     518              :         } ZEND_HASH_FOREACH_END();
     519              : 
     520          116 :         add_assoc_zval(target, "performance", &stats);
     521          116 : }
     522              : 
     523          116 : extern void lsp_server_status(lsp_server *server, zval *return_value)
     524              : {
     525          116 :         lsp_symbol_index_header *header = NULL;
     526          116 :         zend_long memory_limit = PG(memory_limit);
     527              :         zval memory, symbol_index, processes, analyzers;
     528          116 :         uint32_t symbol_count = 0;
     529          116 :         size_t memory_current, memory_peak, symbol_index_used = 0, symbol_index_capacity = server->symbol_index.size;
     530              : 
     531          116 :         memory_current = zend_memory_usage(true);
     532          116 :         memory_peak = zend_memory_peak_usage(true);
     533              : 
     534          116 :         lsp_reap_analyzer_jobs(server);
     535              : 
     536          116 :         if (server->symbol_index.available && server->symbol_index.addr) {
     537          116 :                 header = (lsp_symbol_index_header *) server->symbol_index.addr;
     538          116 :                 if (header->magic == LSP_SYMBOL_INDEX_MAGIC && header->used <= header->capacity) {
     539          116 :                         symbol_index_used = header->used;
     540          116 :                         symbol_index_capacity = header->capacity;
     541          116 :                         symbol_count = header->symbol_count;
     542              :                 }
     543              :         }
     544              : 
     545          116 :         array_init(return_value);
     546              : 
     547          116 :         array_init(&memory);
     548              : 
     549          116 :         if (memory_peak < memory_current) {
     550          116 :                 memory_peak = memory_current;
     551              :         }
     552              : 
     553          116 :         add_assoc_long(&memory, "current", (zend_long) memory_current);
     554          116 :         add_assoc_long(&memory, "peak", (zend_long) memory_peak);
     555          116 :         add_assoc_long(&memory, "max", memory_limit > 0 ? memory_limit : 0);
     556          116 :         add_assoc_zval(return_value, "memory", &memory);
     557              : 
     558          116 :         array_init(&symbol_index);
     559          116 :         add_assoc_bool(&symbol_index, "available", server->symbol_index.available);
     560          116 :         add_assoc_bool(&symbol_index, "indexing", server->index_worker_running);
     561          116 :         add_assoc_long(&symbol_index, "used", (zend_long) symbol_index_used);
     562          116 :         add_assoc_long(&symbol_index, "max", (zend_long) symbol_index_capacity);
     563          116 :         add_assoc_long(&symbol_index, "symbols", symbol_count);
     564          116 :         add_assoc_zval(return_value, "symbolIndex", &symbol_index);
     565              : 
     566          116 :         array_init(&processes);
     567          116 :         add_assoc_long(&processes, "active", lsp_active_process_count(server));
     568          116 :         add_assoc_long(&processes, "configured", server->options.worker_count);
     569          116 :         add_assoc_bool(&processes, "phpstanRunning", lsp_analyzer_job_table_running(&server->phpstan_jobs));
     570          116 :         add_assoc_bool(&processes, "psalmRunning", lsp_analyzer_job_table_running(&server->psalm_jobs));
     571          116 :         add_assoc_zval(return_value, "processes", &processes);
     572              : 
     573          116 :         array_init(&analyzers);
     574          116 :         lsp_add_analyzer_status_entry(&analyzers, "phpstan", server->phpstan_enabled, lsp_analyzer_job_table_running(&server->phpstan_jobs), &server->phpstan_projects);
     575          116 :         lsp_add_analyzer_status_entry(&analyzers, "psalm", server->psalm_enabled, lsp_analyzer_job_table_running(&server->psalm_jobs), &server->psalm_projects);
     576          116 :         lsp_add_analyzer_status_entry(&analyzers, "psalm-ls", server->psalm_ls_enabled, false, &server->psalm_ls_project_states);
     577          116 :         add_assoc_zval(return_value, "analyzers", &analyzers);
     578              : 
     579          116 :         lsp_runner_status(server, return_value);
     580          116 :         lsp_add_perf_stats(server, return_value);
     581          116 : }
     582              : 
     583              : /* ------------------------------------------------------------------------
     584              :  * Non-blocking transport: a poll(2)-driven receive buffer feeding a pending
     585              :  * message queue. While waiting for client input the server keeps pumping
     586              :  * analyzer jobs, so diagnostics are published as soon as they are ready
     587              :  * instead of on the next client message. The queue also enables
     588              :  * $/cancelRequest support and coalescing of bursty didChange notifications.
     589              :  * Windows falls back to the historical blocking reader (no queue lookahead).
     590              :  * ------------------------------------------------------------------------ */
     591              : 
     592              : static smart_str lsp_rx_buffer = {0};
     593              : static size_t lsp_rx_offset = 0;
     594              : static bool lsp_rx_eof = false;
     595              : static zval lsp_pending_messages;
     596              : static uint32_t lsp_pending_head = 0;
     597              : static bool lsp_pending_initialized = false;
     598              : static HashTable lsp_cancelled_ids;
     599              : static bool lsp_cancelled_initialized = false;
     600              : 
     601         8078 : static inline void lsp_transport_ensure_initialized(void)
     602              : {
     603         8078 :         if (!lsp_pending_initialized) {
     604          548 :                 array_init(&lsp_pending_messages);
     605          548 :                 lsp_pending_initialized = true;
     606              :         }
     607              : 
     608         8078 :         if (!lsp_cancelled_initialized) {
     609          548 :                 zend_hash_init(&lsp_cancelled_ids, 8, NULL, NULL, 0);
     610          548 :                 lsp_cancelled_initialized = true;
     611              :         }
     612         8078 : }
     613              : 
     614          548 : extern void lsp_transport_shutdown(void)
     615              : {
     616          548 :         smart_str_free(&lsp_rx_buffer);
     617          548 :         lsp_rx_offset = 0;
     618          548 :         lsp_rx_eof = false;
     619              : 
     620          548 :         if (lsp_pending_initialized) {
     621          548 :                 zval_ptr_dtor(&lsp_pending_messages);
     622          548 :                 lsp_pending_initialized = false;
     623              :         }
     624          548 :         lsp_pending_head = 0;
     625              : 
     626          548 :         if (lsp_cancelled_initialized) {
     627          548 :                 zend_hash_destroy(&lsp_cancelled_ids);
     628          548 :                 lsp_cancelled_initialized = false;
     629              :         }
     630          548 : }
     631              : 
     632         2856 : static inline void lsp_rx_compact(void)
     633              : {
     634              :         size_t remaining;
     635              : 
     636         2856 :         if (!lsp_rx_buffer.s || lsp_rx_offset == 0) {
     637            0 :                 return;
     638              :         }
     639              : 
     640         2856 :         remaining = ZSTR_LEN(lsp_rx_buffer.s) - lsp_rx_offset;
     641         2856 :         if (remaining > 0) {
     642         2514 :                 memmove(ZSTR_VAL(lsp_rx_buffer.s), ZSTR_VAL(lsp_rx_buffer.s) + lsp_rx_offset, remaining);
     643              :         }
     644              : 
     645         2856 :         ZSTR_LEN(lsp_rx_buffer.s) = remaining;
     646         2856 :         lsp_rx_offset = 0;
     647              : }
     648              : 
     649              : typedef enum _lsp_frame_result {
     650              :         LSP_FRAME_INCOMPLETE = 0, /* need more bytes before anything can parse */
     651              :         LSP_FRAME_MESSAGE,        /* a message was produced */
     652              :         LSP_FRAME_SKIPPED,        /* a bad frame was consumed; try the next one */
     653              : } lsp_frame_result;
     654              : 
     655              : /* Parse one complete Content-Length framed message from the receive buffer.
     656              :  * Accepts both \r\n and bare \n header line endings. Distinguishes "not
     657              :  * enough bytes yet" from "consumed a malformed/undecodable frame" so frames
     658              :  * queued behind a bad one are still drained. */
     659         7946 : static inline lsp_frame_result lsp_transport_parse_frame(zval *message)
     660              : {
     661         7946 :         const char *data, *line_start, *line_end, *headers_end = NULL;
     662              :         char *body;
     663         7946 :         size_t available, content_length = 0, header_size;
     664         7946 :         bool has_length = false;
     665              : 
     666         7946 :         if (!lsp_rx_buffer.s) {
     667          548 :                 return LSP_FRAME_INCOMPLETE;
     668              :         }
     669              : 
     670         7398 :         data = ZSTR_VAL(lsp_rx_buffer.s) + lsp_rx_offset;
     671         7398 :         available = ZSTR_LEN(lsp_rx_buffer.s) - lsp_rx_offset;
     672         7398 :         line_start = data;
     673              : 
     674        10378 :         while ((size_t) (line_start - data) < available) {
     675         6304 :                 line_end = memchr(line_start, '\n', available - (line_start - data));
     676         6304 :                 if (!line_end) {
     677            0 :                         return LSP_FRAME_INCOMPLETE;
     678              :                 }
     679              : 
     680         6304 :                 if (line_start == line_end || (line_end - line_start == 1 && line_start[0] == '\r')) {
     681         3324 :                         headers_end = line_end + 1;
     682         3324 :                         break;
     683              :                 }
     684              : 
     685         2980 :                 if ((size_t) (line_end - line_start) > sizeof("Content-Length:") - 1 &&
     686         2980 :                         strncasecmp(line_start, "Content-Length:", sizeof("Content-Length:") - 1) == 0
     687              :                 ) {
     688         2980 :                         content_length = (size_t) strtoull(line_start + sizeof("Content-Length:") - 1, NULL, 10);
     689         2980 :                         has_length = true;
     690              :                 }
     691              : 
     692         2980 :                 line_start = line_end + 1;
     693              :         }
     694              : 
     695         7398 :         if (!headers_end || !has_length || content_length == 0) {
     696         4418 :                 if (headers_end) {
     697              :                         /* Skip a malformed frame header so the stream can resynchronize. */
     698          344 :                         lsp_rx_offset += headers_end - data;
     699              : 
     700          344 :                         return LSP_FRAME_SKIPPED;
     701              :                 }
     702              : 
     703         4074 :                 return LSP_FRAME_INCOMPLETE;
     704              :         }
     705              : 
     706         2980 :         header_size = headers_end - data;
     707         2980 :         if (available < header_size + content_length) {
     708          124 :                 return LSP_FRAME_INCOMPLETE;
     709              :         }
     710              : 
     711              :         /* The JSON scanner requires a NUL sentinel at body[length]; the framed
     712              :          * body sits mid-buffer followed by the next frame, so decode from a
     713              :          * terminated copy. */
     714         2856 :         body = emalloc(content_length + 1);
     715         2856 :         memcpy(body, headers_end, content_length);
     716         2856 :         body[content_length] = '\0';
     717         2856 :         ZVAL_UNDEF(message);
     718         2856 :         php_json_decode_ex(message, body, content_length, PHP_JSON_OBJECT_AS_ARRAY, 512);
     719         2856 :         efree(body);
     720         2856 :         lsp_rx_offset += header_size + content_length;
     721         2856 :         lsp_rx_compact();
     722              : 
     723         2856 :         if (Z_TYPE_P(message) != IS_ARRAY) {
     724            0 :                 if (!Z_ISUNDEF_P(message)) {
     725            0 :                         zval_ptr_dtor(message);
     726              :                 }
     727            0 :                 ZVAL_UNDEF(message);
     728              : 
     729            0 :                 return LSP_FRAME_SKIPPED;
     730              :         }
     731              : 
     732         2856 :         return LSP_FRAME_MESSAGE;
     733              : }
     734              : 
     735         4746 : static inline void lsp_transport_drain_frames(void)
     736              : {
     737              :         lsp_frame_result parsed;
     738              :         zval message;
     739              : 
     740         4746 :         lsp_transport_ensure_initialized();
     741         7946 :         while ((parsed = lsp_transport_parse_frame(&message)) != LSP_FRAME_INCOMPLETE) {
     742         3200 :                 if (parsed == LSP_FRAME_MESSAGE) {
     743         2856 :                         add_next_index_zval(&lsp_pending_messages, &message);
     744              :                 }
     745              :         }
     746         4746 : }
     747              : 
     748              : #if defined(_WIN32)
     749              : static inline int lsp_transport_fill_from_pipe(HANDLE handle, double timeout_seconds)
     750              : {
     751              :         char chunk[8192];
     752              :         DWORD available, n, wait_ms, wanted;
     753              :         double deadline, now, remaining;
     754              : 
     755              :         deadline = lsp_now_seconds() + timeout_seconds;
     756              :         for (;;) {
     757              :                 available = 0;
     758              :                 if (!PeekNamedPipe(handle, NULL, 0, NULL, &available, NULL)) {
     759              :                         lsp_rx_eof = true;
     760              : 
     761              :                         return -1;
     762              :                 }
     763              : 
     764              :                 if (available > 0) {
     765              :                         wanted = available < sizeof(chunk) ? available : (DWORD) sizeof(chunk);
     766              :                         n = 0;
     767              :                         if (!ReadFile(handle, chunk, wanted, &n, NULL)) {
     768              :                                 lsp_rx_eof = true;
     769              : 
     770              :                                 return -1;
     771              :                         }
     772              : 
     773              :                         if (n == 0) {
     774              :                                 lsp_rx_eof = true;
     775              : 
     776              :                                 return -1;
     777              :                         }
     778              : 
     779              :                         smart_str_appendl(&lsp_rx_buffer, chunk, (size_t) n);
     780              : 
     781              :                         return 1;
     782              :                 }
     783              : 
     784              :                 if (timeout_seconds == 0.0) {
     785              :                         return 0;
     786              :                 }
     787              : 
     788              :                 now = lsp_now_seconds();
     789              :                 if (now >= deadline) {
     790              :                         return 0;
     791              :                 }
     792              : 
     793              :                 remaining = deadline - now;
     794              :                 wait_ms = (DWORD) (remaining * 1000.0);
     795              :                 if (wait_ms == 0) {
     796              :                         wait_ms = 1;
     797              :                 }
     798              :                 if (wait_ms > 10) {
     799              :                         wait_ms = 10;
     800              :                 }
     801              : 
     802              :                 Sleep(wait_ms);
     803              :         }
     804              : }
     805              : 
     806              : static inline int lsp_transport_fill(double timeout_seconds)
     807              : {
     808              :         char chunk[8192];
     809              :         HANDLE handle;
     810              :         size_t n;
     811              : 
     812              :         if (lsp_rx_eof) {
     813              :                 return -1;
     814              :         }
     815              : 
     816              :         handle = GetStdHandle(STD_INPUT_HANDLE);
     817              :         if (timeout_seconds >= 0.0 &&
     818              :                 handle != NULL &&
     819              :                 handle != INVALID_HANDLE_VALUE &&
     820              :                 GetFileType(handle) == FILE_TYPE_PIPE
     821              :         ) {
     822              :                 return lsp_transport_fill_from_pipe(handle, timeout_seconds);
     823              :         }
     824              : 
     825              :         n = fread(chunk, 1, sizeof(chunk), stdin);
     826              :         if (n == 0) {
     827              :                 lsp_rx_eof = true;
     828              : 
     829              :                 return -1;
     830              :         }
     831              : 
     832              :         smart_str_appendl(&lsp_rx_buffer, chunk, n);
     833              : 
     834              :         return 1;
     835              : }
     836              : #else
     837         1418 : static inline int lsp_transport_fill(double timeout_seconds)
     838              : {
     839              :         struct pollfd pfd;
     840              :         char chunk[65536];
     841              :         ssize_t n;
     842              :         int timeout_ms, result;
     843              : 
     844         1418 :         if (lsp_rx_eof) {
     845            0 :                 return -1;
     846              :         }
     847              : 
     848         1418 :         pfd.fd = STDIN_FILENO;
     849         1418 :         pfd.events = POLLIN;
     850         1418 :         pfd.revents = 0;
     851         1418 :         timeout_ms = timeout_seconds < 0 ? -1 : (int) (timeout_seconds * 1000.0);
     852              : 
     853         1418 :         result = poll(&pfd, 1, timeout_ms);
     854         1418 :         if (result == 0) {
     855          136 :                 return 0;
     856              :         }
     857              : 
     858         1282 :         if (result < 0) {
     859            0 :                 return errno == EINTR ? 0 : -1;
     860              :         }
     861              : 
     862         1282 :         if ((pfd.revents & (POLLIN | POLLHUP | POLLERR)) == 0) {
     863            0 :                 return 0;
     864              :         }
     865              : 
     866         1282 :         n = read(STDIN_FILENO, chunk, sizeof(chunk));
     867         1282 :         if (n > 0) {
     868          806 :                 smart_str_appendl(&lsp_rx_buffer, chunk, (size_t) n);
     869              : 
     870          806 :                 return 1;
     871              :         }
     872              : 
     873          476 :         if (n == 0 || (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
     874          476 :                 lsp_rx_eof = true;
     875              : 
     876          476 :                 return -1;
     877              :         }
     878              : 
     879            0 :         return 0;
     880              : }
     881              : #endif
     882              : 
     883         1418 : static inline bool lsp_server_has_background_work(lsp_server *server)
     884              : {
     885         1116 :         return server->index_worker_running ||
     886         2169 :                 lsp_analyzer_job_table_running(&server->phpstan_jobs) ||
     887         1053 :                 lsp_analyzer_job_table_running(&server->psalm_jobs) ||
     888         1053 :                 server->phpstan_completion_job.running ||
     889         2106 :                 server->psalm_completion_job.running ||
     890         3587 :                 zend_hash_num_elements(&server->psalm_ls_projects) > 0 ||
     891          957 :                 lsp_runner_pending_count(server) > 0
     892              :         ;
     893              : }
     894              : 
     895         2208 : static inline zend_string *lsp_request_id_key(zval *id)
     896              : {
     897         2208 :         if (!id) {
     898            0 :                 return NULL;
     899              :         }
     900              : 
     901         2208 :         if (Z_TYPE_P(id) == IS_LONG) {
     902         2208 :                 return strpprintf(0, "i:" ZEND_LONG_FMT, Z_LVAL_P(id));
     903              :         }
     904              : 
     905            0 :         if (Z_TYPE_P(id) == IS_STRING) {
     906            0 :                 return strpprintf(0, "s:%s", Z_STRVAL_P(id));
     907              :         }
     908              : 
     909            0 :         return NULL;
     910              : }
     911              : 
     912         7477 : static inline bool lsp_message_method_equals(zval *message, const char *method)
     913              : {
     914         7477 :         zend_string *value = lsp_array_string(message, "method");
     915              : 
     916         7477 :         return value && php_ver_abstract.string_equals_cstr(value, method, strlen(method));
     917              : }
     918              : 
     919            4 : static inline void lsp_register_cancellation(zval *message)
     920              : {
     921              :         zend_string *key;
     922            4 :         zval *params = lsp_array_find(message, "params"), *id;
     923              : 
     924            4 :         if (!params || Z_TYPE_P(params) != IS_ARRAY) {
     925            0 :                 return;
     926              :         }
     927              : 
     928            4 :         id = zend_hash_str_find(Z_ARRVAL_P(params), "id", sizeof("id") - 1);
     929            4 :         key = lsp_request_id_key(id);
     930            4 :         if (!key) {
     931            0 :                 return;
     932              :         }
     933              : 
     934            4 :         lsp_transport_ensure_initialized();
     935            4 :         zend_hash_add_empty_element(&lsp_cancelled_ids, key);
     936            4 :         zend_string_release(key);
     937              : }
     938              : 
     939         2192 : static inline bool lsp_pending_take_cancellation(zend_string *id_key)
     940              : {
     941              :         zend_string *queued_key;
     942              :         zval *message, *params, *queued_id, null_zv;
     943              :         uint32_t i, count;
     944              :         bool matched;
     945              : 
     946         2192 :         if (!lsp_pending_initialized) {
     947            0 :                 return false;
     948              :         }
     949              : 
     950         2192 :         count = zend_hash_num_elements(Z_ARRVAL(lsp_pending_messages));
     951         6785 :         for (i = lsp_pending_head; i < count; i++) {
     952         4597 :                 message = zend_hash_index_find(Z_ARRVAL(lsp_pending_messages), i);
     953         4597 :                 if (!message || Z_TYPE_P(message) != IS_ARRAY || !lsp_message_method_equals(message, "$/cancelRequest")) {
     954         4585 :                         continue;
     955              :                 }
     956              : 
     957           12 :                 params = lsp_array_find(message, "params");
     958           12 :                 queued_id = params && Z_TYPE_P(params) == IS_ARRAY
     959           12 :                         ? zend_hash_str_find(Z_ARRVAL_P(params), "id", sizeof("id") - 1)
     960           12 :                         : NULL
     961              :                 ;
     962           12 :                 queued_key = lsp_request_id_key(queued_id);
     963           12 :                 if (!queued_key) {
     964            0 :                         continue;
     965              :                 }
     966              : 
     967           12 :                 matched = zend_string_equals(queued_key, id_key);
     968           12 :                 zend_string_release(queued_key);
     969           12 :                 if (matched) {
     970              :                         /* Consume the queued cancellation so it cannot linger. */
     971            4 :                         ZVAL_NULL(&null_zv);
     972            4 :                         zend_hash_index_update(Z_ARRVAL(lsp_pending_messages), i, &null_zv);
     973              : 
     974            4 :                         return true;
     975              :                 }
     976              :         }
     977              : 
     978         2188 :         return false;
     979              : }
     980              : 
     981         2192 : extern bool lsp_protocol_request_is_cancelled(zval *id)
     982              : {
     983              :         zend_string *key;
     984              :         bool cancelled;
     985              : 
     986         2192 :         key = lsp_request_id_key(id);
     987         2192 :         if (!key) {
     988            0 :                 return false;
     989              :         }
     990              : 
     991         2192 :         cancelled = false;
     992         2192 :         if (lsp_cancelled_initialized && zend_hash_exists(&lsp_cancelled_ids, key)) {
     993            0 :                 zend_hash_del(&lsp_cancelled_ids, key);
     994            0 :                 cancelled = true;
     995              :         }
     996              : 
     997         2192 :         if (!cancelled) {
     998         2192 :                 cancelled = lsp_pending_take_cancellation(key);
     999              :         }
    1000              : 
    1001         2192 :         zend_string_release(key);
    1002              : 
    1003         2192 :         return cancelled;
    1004              : }
    1005              : 
    1006              : /* True when a newer didChange (or didClose) for the same document is already
    1007              :  * queued with no request in between: the current change's diagnostics would
    1008              :  * be immediately superseded, so the caller may skip publishing them. */
    1009           24 : extern bool lsp_protocol_queue_supersedes_change(zend_string *uri)
    1010              : {
    1011              :         zend_string *queued_uri;
    1012              :         zval *message, *params, *td;
    1013              :         uint32_t i, count;
    1014              : 
    1015           24 :         if (!lsp_pending_initialized) {
    1016            0 :                 return false;
    1017              :         }
    1018              : 
    1019           24 :         count = zend_hash_num_elements(Z_ARRVAL(lsp_pending_messages));
    1020           36 :         for (i = lsp_pending_head; i < count; i++) {
    1021           36 :                 message = zend_hash_index_find(Z_ARRVAL(lsp_pending_messages), i);
    1022           36 :                 if (!message || Z_TYPE_P(message) != IS_ARRAY) {
    1023            0 :                         continue;
    1024              :                 }
    1025              : 
    1026           36 :                 if (zend_hash_str_exists(Z_ARRVAL_P(message), "id", sizeof("id") - 1)) {
    1027           20 :                         return false;
    1028              :                 }
    1029              : 
    1030           16 :                 if (!lsp_message_method_equals(message, "textDocument/didChange") &&
    1031           12 :                         !lsp_message_method_equals(message, "textDocument/didClose")
    1032              :                 ) {
    1033           12 :                         continue;
    1034              :                 }
    1035              : 
    1036            4 :                 params = lsp_array_find(message, "params");
    1037            4 :                 td = params ? lsp_array_find(params, "textDocument") : NULL;
    1038            4 :                 queued_uri = td ? lsp_array_string(td, "uri") : NULL;
    1039            4 :                 if (queued_uri && zend_string_equals(queued_uri, uri)) {
    1040            4 :                         return true;
    1041              :                 }
    1042              :         }
    1043              : 
    1044            0 :         return false;
    1045              : }
    1046              : 
    1047         4746 : static inline bool lsp_pending_pop(zval *message)
    1048              : {
    1049              :         zval *head;
    1050              :         uint32_t count;
    1051              : 
    1052         4746 :         if (!lsp_pending_initialized) {
    1053            0 :                 return false;
    1054              :         }
    1055              : 
    1056         4746 :         count = zend_hash_num_elements(Z_ARRVAL(lsp_pending_messages));
    1057         4750 :         while (lsp_pending_head < count) {
    1058         2856 :                 head = zend_hash_index_find(Z_ARRVAL(lsp_pending_messages), lsp_pending_head);
    1059         2856 :                 lsp_pending_head++;
    1060              : 
    1061         2856 :                 if (!head || Z_TYPE_P(head) != IS_ARRAY) {
    1062            4 :                         continue;
    1063              :                 }
    1064              : 
    1065         2852 :                 ZVAL_COPY(message, head);
    1066              : 
    1067         2852 :                 if (lsp_pending_head >= count) {
    1068          690 :                         zend_hash_clean(Z_ARRVAL(lsp_pending_messages));
    1069          690 :                         lsp_pending_head = 0;
    1070              :                 }
    1071              : 
    1072         2852 :                 return true;
    1073              :         }
    1074              : 
    1075         1894 :         if (count > 0) {
    1076            0 :                 zend_hash_clean(Z_ARRVAL(lsp_pending_messages));
    1077            0 :                 lsp_pending_head = 0;
    1078              :         }
    1079              : 
    1080         1894 :         return false;
    1081              : }
    1082              : 
    1083         3328 : extern bool lsp_protocol_next_message(lsp_server *server, zval *message)
    1084              : {
    1085              :         double timeout;
    1086              :         int filled;
    1087              : 
    1088         3328 :         lsp_transport_ensure_initialized();
    1089              : 
    1090              :         for (;;) {
    1091         4746 :                 lsp_transport_drain_frames();
    1092              : 
    1093         4746 :                 if (lsp_pending_pop(message)) {
    1094              :                         /* Track cancellations as soon as they pass through the queue. */
    1095         2852 :                         if (lsp_message_method_equals(message, "$/cancelRequest")) {
    1096            4 :                                 lsp_register_cancellation(message);
    1097              :                         }
    1098              : 
    1099         2852 :                         return true;
    1100              :                 }
    1101              : 
    1102         1894 :                 if (lsp_rx_eof) {
    1103          476 :                         return false;
    1104              :                 }
    1105              : 
    1106              :                 /* SIGTERM: stop as if the client had sent exit; teardown still
    1107              :                  * runs so caches persist and children are stopped cleanly. */
    1108         1418 :                 if (lsp_terminate_requested()) {
    1109            0 :                         return false;
    1110              :                 }
    1111              : 
    1112         1418 :                 timeout = lsp_server_has_background_work(server) ? 0.05 : -1.0;
    1113         1418 :                 filled = lsp_transport_fill(timeout);
    1114         1418 :                 if (filled == 0) {
    1115              :                         /* Idle tick: reap finished analyzers and pump the Psalm LS
    1116              :                          * proxy so diagnostics reach the client without waiting for
    1117              :                          * the next request. */
    1118          136 :                         lsp_reap_analyzer_jobs(server);
    1119              :                 }
    1120              :         }
    1121              : }
    1122              : 
    1123          576 : extern void lsp_document_analyze(lsp_document *document)
    1124              : {
    1125          576 :         if (!Z_ISUNDEF(document->lsparrot)) {
    1126           36 :                 zval_ptr_dtor(&document->lsparrot);
    1127           36 :                 ZVAL_UNDEF(&document->lsparrot);
    1128              :         }
    1129              : 
    1130          576 :         lsp_document_derived_invalidate(document);
    1131          576 :         lsp_lsparrot_parse_to_zval_ex(&document->lsparrot, document->text, document->uri, false);
    1132          576 : }
    1133              : 
    1134         1116 : extern void lsp_document_derived_invalidate(lsp_document *document)
    1135              : {
    1136         1116 :         if (document->derived_namespace) {
    1137          116 :                 if (document->derived_namespace != zend_empty_string) {
    1138           76 :                         zend_string_release(document->derived_namespace);
    1139              :                 }
    1140          116 :                 document->derived_namespace = NULL;
    1141              :         }
    1142              : 
    1143         1116 :         if (document->derived_imports) {
    1144          116 :                 zend_hash_destroy(document->derived_imports);
    1145          116 :                 efree(document->derived_imports);
    1146          116 :                 document->derived_imports = NULL;
    1147              :         }
    1148              : 
    1149         1116 :         document->derived_import_insert_offset = 0;
    1150         1116 :         document->derived_import_after_use = false;
    1151         1116 :         document->derived_valid = false;
    1152         1116 : }
    1153              : 
    1154         4556 : extern void lsp_document_derived_ensure(lsp_document *document)
    1155              : {
    1156         4556 :         if (document->derived_valid) {
    1157         4440 :                 return;
    1158              :         }
    1159              : 
    1160          116 :         document->derived_namespace = lsp_document_namespace(document->text);
    1161          116 :         document->derived_imports = emalloc(sizeof(HashTable));
    1162          116 :         zend_hash_init(document->derived_imports, 8, NULL, ZVAL_PTR_DTOR, 0);
    1163          116 :         lsp_document_collect_imports(document->text, document->derived_imports);
    1164          116 :         document->derived_import_insert_offset = lsp_import_insert_offset(document->text, &document->derived_import_after_use);
    1165          116 :         document->derived_valid = true;
    1166              : }
    1167              : 
    1168         1136 : extern zend_string *lsp_document_namespace_cached(lsp_document *document)
    1169              : {
    1170         1136 :         lsp_document_derived_ensure(document);
    1171              : 
    1172         1136 :         return document->derived_namespace;
    1173              : }
    1174              : 
    1175         1068 : extern size_t lsp_document_import_insert_offset_cached(lsp_document *document, bool *after_existing_use)
    1176              : {
    1177         1068 :         lsp_document_derived_ensure(document);
    1178         1068 :         *after_existing_use = document->derived_import_after_use;
    1179              : 
    1180         1068 :         return document->derived_import_insert_offset;
    1181              : }
    1182              : 
    1183         2844 : extern void lsp_perf_stats_record(lsp_server *server, zend_string *method, double elapsed_seconds)
    1184              : {
    1185              :         lsp_perf_counter *counter, fresh;
    1186              : 
    1187         2844 :         counter = zend_hash_find_ptr(&server->perf_stats, method);
    1188         2844 :         if (!counter) {
    1189         2444 :                 memset(&fresh, 0, sizeof(fresh));
    1190         2444 :                 counter = zend_hash_add_mem(&server->perf_stats, method, &fresh, sizeof(fresh));
    1191         2444 :                 if (!counter) {
    1192            0 :                         return;
    1193              :                 }
    1194              :         }
    1195              : 
    1196         2844 :         counter->count++;
    1197         2844 :         counter->total_seconds += elapsed_seconds;
    1198         2844 :         if (elapsed_seconds > counter->max_seconds) {
    1199         2022 :                 counter->max_seconds = elapsed_seconds;
    1200              :         }
    1201              : }
        

Generated by: LCOV version 2.0-1