载入中...
搜索中...
未找到
LanguageServer.cpp
浏览该文件的文档.
4
5#include "common/Runtime.h"
7#include "scripts.h"
8
9#include <Poco/Dynamic/Var.h>
10#include <Poco/JSON/Array.h>
11#include <Poco/JSON/Object.h>
12#include <Poco/JSON/Parser.h>
13#include <Poco/JSON/Stringifier.h>
14
15#include <algorithm>
16#include <cctype>
17#include <cstdint>
18#include <filesystem>
19#include <fstream>
20#include <functional>
21#include <iostream>
22#include <iterator>
23#include <regex>
24#include <sstream>
25#include <unordered_map>
26#include <utility>
27
28namespace eve::dev {
29namespace {
30
31std::string stringify(const Poco::Dynamic::Var& value) {
32 std::ostringstream output;
33 Poco::JSON::Stringifier::stringify(value, output);
34 return output.str();
35}
36
37void writeFrame(std::ostream& output, const Poco::JSON::Object::Ptr& message) {
38 const std::string body = stringify(Poco::Dynamic::Var(message));
39 output << "Content-Length: " << body.size() << "\r\n\r\n" << body << std::flush;
40}
41
42bool readFrame(std::istream& input, std::string& body) {
43 std::string line;
44 size_t length = 0;
45 while (std::getline(input, line)) {
46 if (!line.empty() && line.back() == '\r') line.pop_back();
47 if (line.empty()) break;
48 constexpr std::string_view prefix = "Content-Length:";
49 if (line.rfind(prefix, 0) == 0) {
50 try {
51 length = static_cast<size_t>(std::stoull(line.substr(prefix.size())));
52 } catch (const std::exception&) {
53 return false;
54 }
55 }
56 }
57 if (length == 0 || !input) return false;
58 body.resize(length);
59 input.read(body.data(), static_cast<std::streamsize>(length));
60 return static_cast<size_t>(input.gcount()) == length;
61}
62
63Poco::JSON::Object::Ptr rpcResponse(const Poco::Dynamic::Var& id, const Poco::Dynamic::Var& result) {
64 Poco::JSON::Object::Ptr message = new Poco::JSON::Object();
65 message->set("jsonrpc", "2.0");
66 message->set("id", id);
67 message->set("result", result);
68 return message;
69}
70
71Poco::JSON::Object::Ptr rpcError(const Poco::Dynamic::Var& id, int code, std::string messageText) {
72 Poco::JSON::Object::Ptr error = new Poco::JSON::Object();
73 error->set("code", code);
74 error->set("message", std::move(messageText));
75 Poco::JSON::Object::Ptr message = new Poco::JSON::Object();
76 message->set("jsonrpc", "2.0");
77 message->set("id", id);
78 message->set("error", error);
79 return message;
80}
81
82int clampNonNegative(int value) { return value < 0 ? 0 : value; }
83
84Poco::JSON::Object::Ptr rangeObject(const lsp::Range& value) {
85 Poco::JSON::Object::Ptr start = new Poco::JSON::Object();
86 start->set("line", static_cast<int>(value.start.line));
87 start->set("character", static_cast<int>(value.start.character));
88 Poco::JSON::Object::Ptr end = new Poco::JSON::Object();
89 end->set("line", static_cast<int>(value.end.line));
90 end->set("character", static_cast<int>(value.end.character));
91 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
92 result->set("start", start);
93 result->set("end", end);
94 return result;
95}
96
97Poco::JSON::Object::Ptr locationObject(const lsp::Location& value) {
98 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
99 result->set("uri", value.uri);
100 result->set("range", rangeObject(value.range));
101 return result;
102}
103
104lsp::Range parseRange(const Poco::JSON::Object::Ptr& value) {
105 lsp::Range range;
106 if (!value) return range;
107 if (auto start = value->getObject("start")) {
108 range.start.line = static_cast<size_t>(clampNonNegative(start->optValue<int>("line", 0)));
109 range.start.character = static_cast<size_t>(clampNonNegative(start->optValue<int>("character", 0)));
110 }
111 if (auto end = value->getObject("end")) {
112 range.end.line = static_cast<size_t>(clampNonNegative(end->optValue<int>("line", 0)));
113 range.end.character = static_cast<size_t>(clampNonNegative(end->optValue<int>("character", 0)));
114 }
115 return range;
116}
117
118lsp::FormatOptions parseFormatOptions(const Poco::JSON::Object::Ptr& value) {
119 lsp::FormatOptions options;
120 if (!value) return options;
121 options.tabSize = static_cast<unsigned>(clampNonNegative(value->optValue<int>("tabSize", 4)));
122 options.insertSpaces = value->optValue<bool>("insertSpaces", true);
123 if (options.tabSize == 0) options.tabSize = 4;
124 return options;
125}
126
127Poco::JSON::Array::Ptr textEditsArray(const std::vector<lsp::TextEdit>& edits) {
128 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
129 for (const lsp::TextEdit& edit : edits) {
130 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
131 item->set("range", rangeObject(edit.location.range));
132 item->set("newText", edit.newText);
133 items->add(item);
134 }
135 return items;
136}
137
138Poco::JSON::Object::Ptr semanticTokensLegend() {
139 Poco::JSON::Array::Ptr types = new Poco::JSON::Array();
140 types->add("namespace");
141 types->add("class");
142 types->add("function");
143 types->add("method");
144 types->add("variable");
145 types->add("parameter");
146 types->add("property");
147 types->add("keyword");
148 Poco::JSON::Array::Ptr modifiers = new Poco::JSON::Array();
149 modifiers->add("declaration");
150 modifiers->add("readonly");
151 modifiers->add("defaultLibrary");
152 Poco::JSON::Object::Ptr legend = new Poco::JSON::Object();
153 legend->set("tokenTypes", types);
154 legend->set("tokenModifiers", modifiers);
155 return legend;
156}
157
158Poco::JSON::Array::Ptr semanticTokensData(const std::vector<lsp::SemanticToken>& tokens) {
159 Poco::JSON::Array::Ptr data = new Poco::JSON::Array();
160 uint32_t prevLine = 0;
161 uint32_t prevChar = 0;
162 for (const lsp::SemanticToken& token : tokens) {
163 const auto line = static_cast<uint32_t>(token.start.line);
164 const auto start = static_cast<uint32_t>(token.start.character);
165 const auto dLine = line - prevLine;
166 const auto dStart = dLine == 0 ? start - prevChar : start;
167 data->add(static_cast<int>(dLine));
168 data->add(static_cast<int>(dStart));
169 data->add(static_cast<int>(token.length));
170 data->add(static_cast<int>(token.type));
171 data->add(static_cast<int>(token.modifiers));
172 prevLine = line;
173 prevChar = start;
174 }
175 return data;
176}
177
178int completionKind(std::string_view kind) {
179 if (kind == "function" || kind == "async") return 3;
180 if (kind == "class") return 7;
181 if (kind == "module" || kind == "slot") return 9;
182 if (kind == "keyword") return 14;
183 if (kind == "const" || kind == "export") return 21;
184 return 6;
185}
186
187int symbolKind(std::string_view kind) {
188 if (kind == "function" || kind == "async") return 12;
189 if (kind == "class") return 5;
190 if (kind == "const") return 14;
191 return 13;
192}
193
194std::string percentDecode(std::string path) {
195 for (size_t cursor = 0; cursor + 2 < path.size();) {
196 if (path[cursor] != '%') {
197 ++cursor;
198 continue;
199 }
200 const auto hex = [](char value) -> int {
201 if (value >= '0' && value <= '9') return value - '0';
202 if (value >= 'a' && value <= 'f') return value - 'a' + 10;
203 if (value >= 'A' && value <= 'F') return value - 'A' + 10;
204 return -1;
205 };
206 const int high = hex(path[cursor + 1]);
207 const int low = hex(path[cursor + 2]);
208 if (high < 0 || low < 0) {
209 ++cursor;
210 continue;
211 }
212 path.replace(cursor, 3, 1, static_cast<char>((high << 4) | low));
213 ++cursor;
214 }
215 return path;
216}
217
218std::string pathFromFileUri(std::string_view uri) {
219 std::string path;
220 if (uri.rfind("file:///", 0) == 0)
221 path = std::string(uri.substr(8));
222 else if (uri.rfind("file://", 0) == 0)
223 path = std::string(uri.substr(7));
224 else
225 return {};
226 path = percentDecode(std::move(path));
227#if defined(_WIN32)
228 if (path.size() >= 3 && path[0] == '/' && std::isalpha(static_cast<unsigned char>(path[1])) != 0 && path[2] == ':')
229 path.erase(path.begin());
230#else
231 if (!path.empty() && path.front() != '/') path.insert(path.begin(), '/');
232#endif
233 return path;
234}
235
236struct CursorWord {
237 std::string word;
238 std::string qualifier;
239 bool memberAccess = false;
240};
241
242CursorWord wordAt(std::string_view source, size_t line, size_t character, bool prefix = false) {
243 const size_t offset = lsp::offsetAt(source, {line, character});
244 size_t begin = offset;
245 size_t end = offset;
246 while (begin > 0 && (std::isalnum(static_cast<unsigned char>(source[begin - 1])) != 0 || source[begin - 1] == '_'))
247 --begin;
248 while (end < source.size() && (std::isalnum(static_cast<unsigned char>(source[end])) != 0 || source[end] == '_'))
249 ++end;
250 CursorWord result;
251 result.word = std::string(source.substr(begin, (prefix ? offset : end) - begin));
252 size_t scan = begin;
253 if (result.word.empty() && offset > 0 && source[offset - 1] == '.') scan = offset;
254 while (scan > 0 && std::isspace(static_cast<unsigned char>(source[scan - 1])) != 0) --scan;
255 if (scan > 0 && source[scan - 1] == '.') {
256 result.memberAccess = true;
257 size_t qualEnd = scan - 1;
258 while (qualEnd > 0 && std::isspace(static_cast<unsigned char>(source[qualEnd - 1])) != 0) --qualEnd;
259 size_t qualBegin = qualEnd;
260 while (qualBegin > 0 &&
261 (std::isalnum(static_cast<unsigned char>(source[qualBegin - 1])) != 0 || source[qualBegin - 1] == '_'))
262 --qualBegin;
263 result.qualifier = std::string(source.substr(qualBegin, qualEnd - qualBegin));
264 }
265 return result;
266}
267
268int activeParameterAt(std::string_view source, size_t offset) {
269 int commas = 0;
270 size_t depth = 0;
271 for (size_t i = offset; i > 0; --i) {
272 const char value = source[i - 1];
273 if (value == ')') {
274 ++depth;
275 continue;
276 }
277 if (value == '(') {
278 if (depth == 0) return commas;
279 --depth;
280 continue;
281 }
282 if (value == ',' && depth == 0) ++commas;
283 if (value == '\n' && depth == 0) break;
284 }
285 return commas;
286}
287
288std::string calleeBeforeParen(std::string_view source, size_t offset) {
289 size_t i = offset;
290 while (i > 0) {
291 if (source[i - 1] == ')') {
292 size_t depth = 1;
293 --i;
294 while (i > 0 && depth > 0) {
295 --i;
296 if (source[i] == ')') ++depth;
297 else if (source[i] == '(')
298 --depth;
299 }
300 continue;
301 }
302 if (source[i - 1] == '(') {
303 size_t end = i - 1;
304 while (end > 0 && std::isspace(static_cast<unsigned char>(source[end - 1])) != 0) --end;
305 size_t begin = end;
306 while (begin > 0 &&
307 (std::isalnum(static_cast<unsigned char>(source[begin - 1])) != 0 || source[begin - 1] == '_'))
308 --begin;
309 return std::string(source.substr(begin, end - begin));
310 }
311 --i;
312 }
313 return {};
314}
315
316bool identifierStart(char value) { return std::isalpha(static_cast<unsigned char>(value)) != 0 || value == '_'; }
317bool identifierPart(char value) { return std::isalnum(static_cast<unsigned char>(value)) != 0 || value == '_'; }
318
319std::string trimTypeName(std::string_view value) {
320 size_t begin = 0;
321 while (begin < value.size() && std::isspace(static_cast<unsigned char>(value[begin])) != 0) ++begin;
322 size_t end = value.size();
323 while (end > begin && std::isspace(static_cast<unsigned char>(value[end - 1])) != 0) --end;
324 if (end > begin && value[end - 1] == '?') --end;
325 return std::string(value.substr(begin, end - begin));
326}
327
328bool isPrimitiveType(std::string_view type) {
329 return type.empty() || type == "dynamic" || type == "void" || type == "null" || type == "int" || type == "float" ||
330 type == "bool" || type == "string" || type.rfind("Array", 0) == 0 || type.rfind("Table", 0) == 0;
331}
332
333enum class ExprTokKind { Ident, Dot, LParen, RParen };
334
335struct ExprTok {
336 ExprTokKind kind = ExprTokKind::Ident;
337 std::string text;
338};
339
340std::vector<ExprTok> tokenizeExpr(std::string_view source, size_t begin, size_t end) {
341 std::vector<ExprTok> result;
342 for (size_t i = begin; i < end && i < source.size();) {
343 const char value = source[i];
344 const char next = i + 1 < source.size() ? source[i + 1] : 0;
345 if (std::isspace(static_cast<unsigned char>(value)) != 0) {
346 ++i;
347 continue;
348 }
349 if (value == '/' && next == '/') {
350 while (i < end && i < source.size() && source[i] != '\n') ++i;
351 continue;
352 }
353 if (value == '/' && next == '*') {
354 i += 2;
355 while (i + 1 < source.size() && i < end && !(source[i] == '*' && source[i + 1] == '/')) ++i;
356 i = std::min(i + 2, end);
357 continue;
358 }
359 if (value == '"' || value == '\'') {
360 const char quote = value;
361 ++i;
362 while (i < end && i < source.size() && source[i] != quote) {
363 if (source[i] == '\\' && i + 1 < source.size()) i += 2;
364 else
365 ++i;
366 }
367 if (i < end) ++i;
368 continue;
369 }
370 if (identifierStart(value)) {
371 size_t start = i++;
372 while (i < end && i < source.size() && identifierPart(source[i])) ++i;
373 result.push_back({ExprTokKind::Ident, std::string(source.substr(start, i - start))});
374 continue;
375 }
376 if (value == '.') {
377 result.push_back({ExprTokKind::Dot, "."});
378 ++i;
379 continue;
380 }
381 if (value == '(') {
382 result.push_back({ExprTokKind::LParen, "("});
383 ++i;
384 continue;
385 }
386 if (value == ')') {
387 result.push_back({ExprTokKind::RParen, ")"});
388 ++i;
389 continue;
390 }
391 ++i;
392 }
393 return result;
394}
395
396size_t skipCallTokens(const std::vector<ExprTok>& tokens, size_t index) {
397 if (index >= tokens.size() || tokens[index].kind != ExprTokKind::LParen) return index;
398 int depth = 0;
399 while (index < tokens.size()) {
400 if (tokens[index].kind == ExprTokKind::LParen) ++depth;
401 else if (tokens[index].kind == ExprTokKind::RParen) {
402 --depth;
403 ++index;
404 if (depth == 0) return index;
405 continue;
406 }
407 ++index;
408 }
409 return index;
410}
411
412using SlotClassMap = std::unordered_map<std::string, std::string>;
413
414bool moduleClass(std::string_view type, const SlotClassMap& slots) {
415 for (const auto& entry : slots)
416 if (entry.second == type) return true;
417 return false;
418}
419
420bool belongsToType(const script::BindingContract& contract, std::string_view type, const SlotClassMap& slots) {
421 if (!contract.scriptClass.empty()) return contract.scriptClass == type;
422 const auto slot = slots.find(contract.module);
423 return slot != slots.end() && slot->second == type;
424}
425
426std::string returnedScriptClass(const script::BindingContract& factory,
427 const script::BindingContractRegistry& bindings) {
428 auto returned = trimTypeName(factory.returnType);
429 if (isPrimitiveType(returned)) return {};
430 if (bindings.hasScriptClass(returned)) return returned;
431 // Generated factories can retain a native type name while their methods
432 // name the script class. Derive that relation from the same owned contracts.
433 std::string candidate;
434 for (const auto& method : bindings.snapshot()) {
435 if (method.module != factory.module || method.scriptClass.empty()) continue;
436 const auto separator = method.cppSymbol.rfind("::");
437 if (separator == std::string::npos || method.cppSymbol.substr(0, separator) != returned) continue;
438 if (!candidate.empty() && candidate != method.scriptClass) return {};
439 candidate = method.scriptClass;
440 }
441 return candidate;
442}
443
444std::string applyRootIdent(std::string_view name, bool called, const SlotClassMap& slots,
445 const script::BindingContractRegistry& bindings,
446 const std::function<std::string(std::string_view)>& localType) {
447 if (name == "eve") return called ? std::string{} : std::string{"eve"};
448 const auto slot = slots.find(std::string(name));
449 if (slot != slots.end()) return slot->second;
450 if (bindings.hasScriptClass(name) || moduleClass(name, slots)) return std::string(name);
451 return localType(name);
452}
453
454std::string applyMember(std::string type, std::string_view name, bool called,
455 const script::BindingContractRegistry& bindings, const SlotClassMap& slots) {
456 if (type == "eve") {
457 return bindings.hasScriptClass(name) || moduleClass(name, slots) ? std::string(name) : std::string{};
458 }
459 if (isPrimitiveType(type)) return {};
460 const script::BindingContract* contract = bindings.findMethod(type, name);
461 std::optional<script::BindingContract> moduleMethod;
462 if (!contract && moduleClass(type, slots)) {
463 for (const auto& method : bindings.snapshot()) {
464 if (method.method != name || !belongsToType(method, type, slots)) continue;
465 if (moduleMethod) return {};
466 moduleMethod = method;
467 }
468 if (moduleMethod) contract = &*moduleMethod;
469 }
470 if (contract == nullptr) return {};
471 if (!called) return type;
472 return returnedScriptClass(*contract, bindings);
473}
474
475std::string typeOfTokens(const std::vector<ExprTok>& tokens, const SlotClassMap& slots,
476 const script::BindingContractRegistry& bindings,
477 const std::function<std::string(std::string_view)>& localType) {
478 std::string type;
479 for (size_t i = 0; i < tokens.size();) {
480 if (tokens[i].kind == ExprTokKind::Dot) {
481 ++i;
482 continue;
483 }
484 if (tokens[i].kind != ExprTokKind::Ident) {
485 ++i;
486 continue;
487 }
488 const std::string name = tokens[i].text;
489 ++i;
490 const bool called = i < tokens.size() && tokens[i].kind == ExprTokKind::LParen;
491 if (called) i = skipCallTokens(tokens, i);
492 type = type.empty() ? applyRootIdent(name, called, slots, bindings, localType)
493 : applyMember(std::move(type), name, called, bindings, slots);
494 if (type.empty()) return {};
495 }
496 return type;
497}
498
499size_t statementStart(std::string_view source, size_t end) {
500 size_t i = end;
501 while (i > 0) {
502 const char value = source[i - 1];
503 if (value == '\n' || value == ';' || value == '{' || value == '}') break;
504 --i;
505 }
506 return i;
507}
508
509std::string inferAssignedType(std::string_view source, size_t offset, std::string_view name, const SlotClassMap& slots,
510 const script::BindingContractRegistry& bindings) {
511 size_t match = std::string::npos;
512 for (size_t i = 0; i + name.size() <= offset;) {
513 if (!identifierStart(source[i]) || source.compare(i, name.size(), name) != 0) {
514 ++i;
515 continue;
516 }
517 const size_t after = i + name.size();
518 if ((i > 0 && identifierPart(source[i - 1])) || (after < source.size() && identifierPart(source[after]))) {
519 ++i;
520 continue;
521 }
522 size_t cursor = after;
523 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
524 if (cursor < offset && source[cursor] == ':') {
525 ++cursor;
526 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
527 size_t typeEnd = cursor;
528 while (typeEnd < offset && (identifierPart(source[typeEnd]) || source[typeEnd] == '?' || source[typeEnd] == '.'))
529 ++typeEnd;
530 const std::string annotated = trimTypeName(source.substr(cursor, typeEnd - cursor));
531 if (bindings.hasScriptClass(annotated)) {
532 match = i;
533 i = typeEnd;
534 continue;
535 }
536 cursor = typeEnd;
537 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
538 }
539 const bool assign = cursor < offset && (source[cursor] == '=' ||
540 (source[cursor] == '<' && cursor + 1 < offset && source[cursor + 1] == '-'));
541 if (!assign || (source[cursor] == '=' && cursor + 1 < offset && source[cursor + 1] == '=')) {
542 ++i;
543 continue;
544 }
545 match = i;
546 i = cursor + 1;
547 }
548 if (match == std::string::npos) return {};
549 size_t cursor = match + name.size();
550 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
551 if (cursor < offset && source[cursor] == ':') {
552 ++cursor;
553 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
554 size_t typeEnd = cursor;
555 while (typeEnd < offset && identifierPart(source[typeEnd])) ++typeEnd;
556 const std::string annotated = trimTypeName(source.substr(cursor, typeEnd - cursor));
557 if (bindings.hasScriptClass(annotated)) return annotated;
558 cursor = typeEnd;
559 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
560 }
561 if (cursor < offset && source[cursor] == '<' && cursor + 1 < offset && source[cursor + 1] == '-') cursor += 2;
562 else if (cursor < offset && source[cursor] == '=')
563 ++cursor;
564 while (cursor < offset && std::isspace(static_cast<unsigned char>(source[cursor])) != 0) ++cursor;
565 size_t rhsEnd = cursor;
566 int depth = 0;
567 while (rhsEnd < offset) {
568 const char value = source[rhsEnd];
569 if (value == '(' || value == '[' || value == '{') ++depth;
570 else if (value == ')' || value == ']' || value == '}') {
571 if (depth == 0) break;
572 --depth;
573 } else if (depth == 0 && (value == ';' || value == '\n'))
574 break;
575 ++rhsEnd;
576 }
577 const auto noopLocal = [](std::string_view) { return std::string{}; };
578 return typeOfTokens(tokenizeExpr(source, cursor, rhsEnd), slots, bindings, noopLocal);
579}
580
581script::ScriptCompletion completionFromContract(const script::BindingContract& contract) {
582 std::string signature = contract.method + "(";
583 std::string insertion = contract.method + "(";
584 for (size_t i = 0; i < contract.parameters.size(); ++i) {
585 if (i != 0) {
586 signature += ", ";
587 insertion += ", ";
588 }
589 signature += contract.parameters[i].name + ": " + contract.parameters[i].type;
590 insertion += contract.parameters[i].name + ": ";
591 }
592 signature += ") -> " + contract.returnType;
593 insertion += ')';
594 return {contract.method, "function", std::move(signature), std::move(insertion)};
595}
596
597class ProjectDirectoryProvider final : public script::IScriptModuleProvider {
598public:
599 explicit ProjectDirectoryProvider(std::filesystem::path root)
600 : root_(std::filesystem::weakly_canonical(std::move(root))) {}
601
602 script::ScriptModuleStatus resolve(const script::ScriptModuleRequest& request, std::string& canonicalUri,
603 std::string& error) override {
607 }
608
609 script::ScriptModuleStatus load(std::string_view canonicalUri, script::ScriptModuleSource& source,
610 std::string& error) override {
611 constexpr std::string_view prefix = "game:/";
612 if (canonicalUri.rfind(prefix, 0) != 0) return script::ScriptModuleStatus::NotHandled;
613 const auto path = std::filesystem::weakly_canonical(root_ / std::string(canonicalUri.substr(prefix.size())));
614 const auto relative = path.lexically_relative(root_).generic_string();
615 if (relative.empty() || relative.rfind("..", 0) == 0) {
616 error = "module escapes the project root: " + std::string(canonicalUri);
618 }
619 std::ifstream input(path, std::ios::binary);
621 source.canonicalUri = std::string(canonicalUri);
622 source.utf8Source.assign(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());
623 source.debugOrigin = path.string();
625 }
626
627private:
628 std::filesystem::path root_;
629};
630
631std::vector<std::string> moduleNames(std::string_view source, const std::regex& pattern) {
632 const std::string owned(source);
633 std::vector<std::string> result;
634 for (std::sregex_iterator it(owned.begin(), owned.end(), pattern), end; it != end; ++it)
635 result.push_back((*it)[1].str());
636 return result;
637}
638
639} // namespace
640
642 explicit Impl(std::string root)
643 : root_(std::filesystem::absolute(std::move(root)).lexically_normal().string()),
644 runtime_(2048, ssq::Libs::ALL) {
645 runtime_.scriptModules().registerProvider(std::make_shared<ProjectDirectoryProvider>(std::filesystem::path(root_)),
646 100);
647 const std::string contract = module_list_content ? module_list_content : "";
648 const size_t split = contract.find("eve_module_contract");
649 static const std::regex slotPattern(R"(\bslot\s*=\s*[\"']([^\"']+)[\"'])");
650 static const std::regex namePattern(R"(\bname\s*=\s*[\"']([^\"']+)[\"'])");
651 static const std::regex slotClassPattern(
652 R"(\{\s*slot\s*=\s*[\"']([^\"']+)[\"']\s*,\s*cls\s*=\s*[\"']([^\"']+)[\"'])");
653 activeModules_ = moduleNames(contract.substr(0, split), slotPattern);
654 knownModules_ = moduleNames(
655 split == std::string::npos ? std::string_view{} : std::string_view(contract).substr(split), namePattern);
656 const std::string owned(contract.substr(0, split));
657 for (std::sregex_iterator it(owned.begin(), owned.end(), slotClassPattern), end; it != end; ++it)
658 slotClass_[(*it)[1].str()] = (*it)[2].str();
659 indexProject();
660 }
661
662 std::string canonicalUri(const std::string& uri) const {
663 if (uri.rfind("game:/", 0) == 0) return uri;
664 const std::string path = pathFromFileUri(uri);
665 if (path.empty()) return uri;
666 std::error_code error;
667 const auto relative = std::filesystem::path(path).lexically_normal().lexically_relative(
668 std::filesystem::path(root_).lexically_normal());
669 if (error || relative.empty() || *relative.begin() == "..") return uri;
670 return "game:/" + relative.generic_string();
671 }
672
673 std::string identity(std::string_view uri) const {
674 const std::string owned(uri);
675 const auto found = canonical_.find(owned);
676 return found == canonical_.end() ? canonicalUri(owned) : found->second;
677 }
678
679 const std::string* sourceFor(std::string_view uri) const {
680 const auto found = documents_.find(std::string(uri));
681 return found == documents_.end() ? nullptr : &found->second;
682 }
683
684 void update(const std::string& uri, std::string source) {
685 if (uri.empty()) return;
686 documents_[uri] = std::move(source);
689 try {
691 } catch (const std::exception&) {
692 }
693 }
694
695 void close(const std::string& uri) {
696 const auto canonical = canonical_.find(uri);
697 if (canonical != canonical_.end()) {
698 const std::filesystem::path path = pathForCanonical(canonical->second);
699 std::ifstream input(path, std::ios::binary);
700 if (input) {
701 std::string source{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
702 index_.update(canonical->second, fileUriFromPath(path.string()), std::move(source));
703 } else {
704 index_.remove(canonical->second);
705 }
706 }
707 documents_.erase(uri);
708 canonical_.erase(uri);
709 }
710
711 std::vector<script::ScriptDiagnostic> diagnostics(std::string_view uri) const {
712 const std::string owned(uri);
713 const std::string ident = identity(owned);
714 auto list = runtime_.scriptCompiler().diagnostics(ident);
715 const auto document = documents_.find(owned);
716 const bool isProjectConfig =
717 ident == "game:/config.nut" || (owned.size() >= 11 && owned.compare(owned.size() - 11, 11, "/config.nut") == 0);
718 if (document != documents_.end() && isProjectConfig) {
719 auto configDiagnostics = script::ScriptCompiler::validateProjectConfig(document->second, ident, knownModules_,
721 list.insert(list.end(), configDiagnostics.begin(), configDiagnostics.end());
722 }
723 return list;
724 }
725
726 std::vector<script::ScriptCompletion> complete(std::string_view uri, lsp::Position position) const {
727 const std::string* source = sourceFor(uri);
728 CursorWord cursor;
729 if (source) cursor = wordAt(*source, position.line, position.character, true);
730 const std::string ident = identity(uri);
731 std::vector<script::ScriptCompletion> result;
732 if (cursor.memberAccess) {
733 size_t wordBegin = 0;
734 if (source) {
735 const size_t offset = lsp::offsetAt(*source, position);
736 wordBegin = offset;
737 while (wordBegin > 0 && identifierPart((*source)[wordBegin - 1])) --wordBegin;
738 }
739 size_t dot = wordBegin;
740 if (source) {
741 while (dot > 0 && std::isspace(static_cast<unsigned char>((*source)[dot - 1])) != 0) --dot;
742 if (dot > 0 && (*source)[dot - 1] == '.') --dot;
743 }
744 const auto localType = [&](std::string_view name) -> std::string {
745 if (const auto unit = runtime_.scriptCompiler().metadata(ident)) {
746 for (const script::ScriptSymbolMetadata& symbol : unit->get().symbols) {
747 if (symbol.name != name) continue;
748 const std::string annotated = trimTypeName(symbol.erasedType);
749 if (runtime_.scriptCompiler().bindings().hasScriptClass(annotated)) return annotated;
750 }
751 }
752 return source ? inferAssignedType(*source, dot, name, slotClass_, runtime_.scriptCompiler().bindings())
753 : std::string{};
754 };
755 const std::string receiver =
756 source ? typeOfTokens(tokenizeExpr(*source, statementStart(*source, dot), dot), slotClass_,
757 runtime_.scriptCompiler().bindings(), localType)
758 : std::string{};
759 const std::string expectedClass = !receiver.empty()
760 ? receiver
761 : (slotClass_.count(cursor.qualifier) ? slotClass_.at(cursor.qualifier)
762 : cursor.qualifier);
763 if (expectedClass == "eve") {
764 std::unordered_map<std::string, bool> seen;
765 for (const auto& entry : slotClass_) {
766 const auto& scriptClass = entry.second;
767 if (scriptClass.rfind(cursor.word, 0) != 0 || !seen.emplace(scriptClass, true).second) continue;
768 result.push_back({scriptClass, "class", "eve." + scriptClass, scriptClass});
769 }
771 if (contract.scriptClass.empty() || contract.scriptClass.rfind(cursor.word, 0) != 0) continue;
772 if (!seen.emplace(contract.scriptClass, true).second) continue;
773 result.push_back({contract.scriptClass, "class", "eve." + contract.scriptClass, contract.scriptClass});
774 }
775 return result;
776 }
778 if (!belongsToType(contract, expectedClass, slotClass_)) continue;
779 if (contract.method.rfind(cursor.word, 0) != 0) continue;
780 result.push_back(completionFromContract(contract));
781 }
782 return result;
783 }
784
786 static constexpr const char* keywords[] = {"import", "export", "persist", "match", "async", "await",
787 "local", "function", "class", "const", "foreach", "return",
788 "if", "else", "while", "for", "switch", "case",
789 "break", "continue", "try", "catch", "throw", "null",
790 "true", "false", "this", "base", "typeof", "instanceof",
791 "resume", "yield", "clone", "delete"};
792 for (const char* keyword : keywords) {
793 if (std::string_view(keyword).rfind(cursor.word, 0) != 0) continue;
794 result.push_back({keyword, "keyword", "EveScript keyword", keyword});
795 }
796 for (const std::string& slot : activeModules_) {
797 if (slot.rfind(cursor.word, 0) != 0) continue;
798 const auto cls = slotClass_.find(slot);
799 result.push_back({slot, "slot", cls == slotClass_.end() ? "module slot" : cls->second, slot});
800 }
801 std::sort(result.begin(), result.end(), [](const script::ScriptCompletion& a, const script::ScriptCompletion& b) {
802 if (a.label != b.label) return a.label < b.label;
803 return a.kind < b.kind;
804 });
805 result.erase(std::unique(result.begin(), result.end(),
807 return a.label == b.label && a.kind == b.kind;
808 }),
809 result.end());
810 return result;
811 }
812
813 std::optional<script::ScriptHover> hover(std::string_view uri, lsp::Position position) const {
814 const std::string* source = sourceFor(uri);
815 if (!source) return std::nullopt;
816 const CursorWord cursor = wordAt(*source, position.line, position.character);
817 if (cursor.word.empty()) return std::nullopt;
818 const std::string ident = identity(uri);
819 if (auto value = runtime_.scriptCompiler().hover(ident, cursor.word)) return value;
820 const auto slot = slotClass_.find(cursor.word);
821 if (slot != slotClass_.end()) {
823 hover.symbol = cursor.word;
824 hover.markdown = "`" + cursor.word + "` — `" + slot->second + "` module slot";
825 return hover;
826 }
827 if (const auto location = index_.definition(ident, position)) {
829 hover.symbol = cursor.word;
830 hover.markdown = "`" + cursor.word + "` defined in `" + location->uri + "`";
831 return hover;
832 }
833 return std::nullopt;
834 }
835
836 std::optional<LanguageSignatureHelp> signatureHelp(std::string_view uri, lsp::Position position) const {
837 const std::string* source = sourceFor(uri);
838 if (!source) return std::nullopt;
839 size_t offset = 0;
840 for (size_t current = 0; current < position.line && offset < source->size(); ++current) {
841 const size_t newline = source->find('\n', offset);
842 offset = newline == std::string_view::npos ? source->size() : newline + 1;
843 }
844 offset = std::min(offset + position.character, source->size());
845 const std::string callee = calleeBeforeParen(*source, offset);
846 if (callee.empty()) return std::nullopt;
848 if (!contract) return std::nullopt;
850 help.activeParameter = activeParameterAt(*source, offset);
851 help.documentation = contract->documentationId;
852 help.label = contract->scriptClass + "." + contract->method + "(";
853 for (size_t i = 0; i < contract->parameters.size(); ++i) {
854 if (i != 0) help.label += ", ";
855 help.label += contract->parameters[i].name + ": " + contract->parameters[i].type;
856 help.parameters.push_back({contract->parameters[i].name + ": " + contract->parameters[i].type, {}});
857 }
858 help.label += ") -> " + contract->returnType;
859 if (help.activeParameter >= static_cast<int>(help.parameters.size()))
860 help.activeParameter = help.parameters.empty() ? 0 : static_cast<int>(help.parameters.size()) - 1;
861 return help;
862 }
863
864 std::filesystem::path pathForCanonical(std::string_view canonical) const {
865 constexpr std::string_view prefix = "game:/";
866 return canonical.rfind(prefix, 0) == 0
867 ? std::filesystem::path(root_) / std::string(canonical.substr(prefix.size()))
868 : std::filesystem::path{};
869 }
870
872 std::error_code error;
873 for (std::filesystem::recursive_directory_iterator it(root_, error), end; it != end && !error;
874 it.increment(error)) {
875 if (it->is_directory(error)) {
876 const std::string name = it->path().filename().string();
877 if (name == ".git" || name == "build" || name == "third-party") it.disable_recursion_pending();
878 continue;
879 }
880 if (!it->is_regular_file(error) || it->path().extension() != ".nut") continue;
881 std::ifstream input(it->path(), std::ios::binary);
882 if (!input) continue;
883 std::string source{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
884 const std::string uri = fileUriFromPath(it->path().string());
885 const auto relative = std::filesystem::relative(it->path(), std::filesystem::path(root_), error);
886 if (error || relative.empty() || relative.generic_string().rfind("..", 0) == 0) continue;
887 index_.update("game:/" + relative.generic_string(), uri, std::move(source));
888 }
889 }
890
891 std::string root_;
894 std::unordered_map<std::string, std::string> documents_;
895 std::unordered_map<std::string, std::string> canonical_;
896 std::vector<std::string> knownModules_;
897 std::vector<std::string> activeModules_;
898 std::unordered_map<std::string, std::string> slotClass_;
899 bool shutdown_ = false;
900};
901
902LanguageServer::LanguageServer(std::string projectRoot) : impl_(std::make_unique<Impl>(std::move(projectRoot))) {}
904
905const std::string& LanguageServer::projectRoot() const noexcept { return impl_->root_; }
906
907std::string LanguageServer::fileUriFromPath(std::string_view path) {
908 std::string generic = std::filesystem::absolute(std::filesystem::path(path)).lexically_normal().generic_string();
909 std::string encoded;
910 encoded.reserve(generic.size());
911 for (const char value : generic) {
912 if (value == ' ')
913 encoded += "%20";
914 else if (value == '#')
915 encoded += "%23";
916 else if (value == '%')
917 encoded += "%25";
918 else
919 encoded += value;
920 }
921 if (!encoded.empty() && encoded.front() != '/') encoded.insert(encoded.begin(), '/');
922 return "file://" + encoded;
923}
924
925void LanguageServer::openDocument(std::string uri, std::string text) { impl_->update(uri, std::move(text)); }
926void LanguageServer::changeDocument(std::string uri, std::string text) { impl_->update(uri, std::move(text)); }
927void LanguageServer::changeDocument(std::string uri, lsp::Range range, std::string text) {
928 auto found = impl_->documents_.find(uri);
929 if (found == impl_->documents_.end()) {
930 impl_->update(uri, std::move(text));
931 return;
932 }
934 impl_->update(uri, found->second);
935}
936void LanguageServer::closeDocument(std::string uri) { impl_->close(uri); }
937
938std::vector<script::ScriptDiagnostic> LanguageServer::diagnosticsFor(std::string_view uri) const {
939 return impl_->diagnostics(uri);
940}
941
942std::vector<script::ScriptCompletion> LanguageServer::complete(std::string_view uri, lsp::Position position) const {
943 return impl_->complete(uri, position);
944}
945
946std::optional<script::ScriptHover> LanguageServer::hover(std::string_view uri, lsp::Position position) const {
947 return impl_->hover(uri, position);
948}
949
950std::optional<lsp::Location> LanguageServer::definition(std::string_view uri, lsp::Position position) const {
951 return impl_->index_.definition(impl_->identity(uri), position);
952}
953
954std::vector<lsp::Location> LanguageServer::references(std::string_view uri, lsp::Position position,
955 bool includeDeclaration) const {
956 return impl_->index_.references(impl_->identity(uri), position, includeDeclaration);
957}
958
959std::optional<std::vector<lsp::TextEdit>> LanguageServer::rename(std::string_view uri, lsp::Position position,
960 std::string_view newName) const {
961 return impl_->index_.rename(impl_->identity(uri), position, newName);
962}
963
964std::vector<script::ScriptSymbolMetadata> LanguageServer::documentSymbols(std::string_view uri) const {
965 const auto metadata = impl_->runtime_.scriptCompiler().metadata(impl_->identity(uri));
966 return metadata ? metadata->get().symbols : std::vector<script::ScriptSymbolMetadata>{};
967}
968
969std::optional<LanguageSignatureHelp> LanguageServer::signatureHelp(std::string_view uri, lsp::Position position) const {
970 return impl_->signatureHelp(uri, position);
971}
972
973std::vector<lsp::TextEdit> LanguageServer::formatDocument(std::string_view uri, lsp::FormatOptions options,
974 const lsp::Range* range) const {
975 const std::string* source = impl_->sourceFor(uri);
976 if (!source) return {};
977 const std::string formatted = lsp::formatEveScript(*source, options);
978 lsp::TextEdit edit;
979 edit.location.uri = std::string(uri);
980 if (range != nullptr && lsp::lastLineIndex(formatted) == lsp::lastLineIndex(*source)) {
981 size_t startLine = range->start.line;
982 size_t endLine = range->end.line;
983 if (range->end.character == 0 && endLine > startLine) --endLine;
984 const std::string originalSpan = lsp::sliceLines(*source, startLine, endLine);
985 const std::string formattedSpan = lsp::sliceLines(formatted, startLine, endLine);
986 if (formattedSpan == originalSpan) return {};
987 edit.location.range = lsp::coveringLines(*source, startLine, endLine);
988 edit.newText = formattedSpan;
989 return {std::move(edit)};
990 }
991 if (formatted == *source) return {};
993 edit.newText = formatted;
994 return {std::move(edit)};
995}
996
997std::vector<lsp::FoldingRange> LanguageServer::foldingRanges(std::string_view uri) const {
998 const std::string* source = impl_->sourceFor(uri);
999 return source ? lsp::foldingRanges(*source) : std::vector<lsp::FoldingRange>{};
1000}
1001
1002std::vector<lsp::SemanticToken> LanguageServer::semanticTokens(std::string_view uri) const {
1003 std::vector<lsp::SemanticToken> tokens = impl_->index_.semanticTokens(impl_->identity(uri));
1004 const auto& bindings = impl_->runtime_.scriptCompiler().bindings();
1005 const auto metadata = impl_->runtime_.scriptCompiler().metadata(impl_->identity(uri));
1006 std::unordered_map<std::string, uint32_t> extra;
1007 if (metadata) {
1008 for (const script::ScriptSymbolMetadata& symbol : metadata->get().symbols) {
1009 if (symbol.kind == "class") extra[symbol.name] = lsp::SemanticTypes::Class;
1010 else if (symbol.kind == "function" || symbol.kind == "async")
1011 extra[symbol.name] = lsp::SemanticTypes::Function;
1012 }
1013 }
1015 if (token.type == lsp::SemanticTypes::Keyword) continue;
1017 if (bindings.hasScriptClass(token.name)) token.type = lsp::SemanticTypes::Class;
1018 continue;
1019 }
1020 if (impl_->slotClass_.count(token.name) != 0) {
1023 continue;
1024 }
1025 if (bindings.hasScriptClass(token.name)) {
1027 continue;
1028 }
1029 const auto found = extra.find(token.name);
1030 if (found != extra.end() && token.type == lsp::SemanticTypes::Variable) token.type = found->second;
1031 }
1032 return tokens;
1033}
1034
1035LspDispatch LanguageServer::handleMessage(std::string_view jsonBody, std::ostream& output) {
1036 Poco::JSON::Parser parser;
1037 Poco::JSON::Object::Ptr request;
1038 try {
1039 request = parser.parse(std::string(jsonBody)).extract<Poco::JSON::Object::Ptr>();
1040 } catch (const std::exception& error) {
1041 writeFrame(output, rpcError(Poco::Dynamic::Var(), -32700, error.what()));
1042 return LspDispatch::Continue;
1043 }
1044 if (!request) return LspDispatch::Continue;
1045 const std::string method = request->optValue<std::string>("method", "");
1046 const auto params = request->getObject("params");
1047 const bool hasId = request->has("id");
1048 const auto id = hasId ? request->get("id") : Poco::Dynamic::Var();
1049 const auto documentUri = [&]() -> std::string {
1050 if (!params) return {};
1051 auto document = params->getObject("textDocument");
1052 return document ? document->optValue<std::string>("uri", "") : std::string{};
1053 };
1054 const auto requestPosition = [&]() -> lsp::Position {
1055 auto position = params ? params->getObject("position") : nullptr;
1056 return position ? lsp::Position{static_cast<size_t>(clampNonNegative(position->optValue<int>("line", 0))),
1057 static_cast<size_t>(clampNonNegative(position->optValue<int>("character", 0)))}
1058 : lsp::Position{};
1059 };
1060
1061 const auto publishDiagnostics = [&](const std::string& uri) {
1062 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
1063 for (const script::ScriptDiagnostic& diagnostic : diagnosticsFor(uri)) {
1064 const int line = clampNonNegative(static_cast<int>(diagnostic.position.line) - 1);
1065 const int col = clampNonNegative(static_cast<int>(diagnostic.position.column) - 1);
1066 lsp::Range range{{static_cast<size_t>(line), static_cast<size_t>(col)},
1067 {static_cast<size_t>(line), static_cast<size_t>(col + 1)}};
1068 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1069 item->set("range", rangeObject(range));
1070 item->set("severity", diagnostic.severity == script::ScriptDiagnosticSeverity::Error ? 1 : 2);
1071 item->set("code", diagnostic.code);
1072 item->set("source", "evescript");
1073 item->set("message", diagnostic.message);
1074 items->add(item);
1075 }
1076 Poco::JSON::Object::Ptr diagParams = new Poco::JSON::Object();
1077 diagParams->set("uri", uri);
1078 diagParams->set("diagnostics", items);
1079 Poco::JSON::Object::Ptr notification = new Poco::JSON::Object();
1080 notification->set("jsonrpc", "2.0");
1081 notification->set("method", "textDocument/publishDiagnostics");
1082 notification->set("params", diagParams);
1083 writeFrame(output, notification);
1084 };
1085
1086 if (method == "initialize") {
1087 Poco::JSON::Object::Ptr sync = new Poco::JSON::Object();
1088 sync->set("openClose", true);
1089 sync->set("change", 2);
1090 Poco::JSON::Object::Ptr completion = new Poco::JSON::Object();
1091 completion->set("resolveProvider", false);
1092 Poco::JSON::Array::Ptr triggers = new Poco::JSON::Array();
1093 triggers->add(".");
1094 triggers->add(":");
1095 completion->set("triggerCharacters", triggers);
1096 Poco::JSON::Object::Ptr signature = new Poco::JSON::Object();
1097 Poco::JSON::Array::Ptr sigTriggers = new Poco::JSON::Array();
1098 sigTriggers->add("(");
1099 sigTriggers->add(",");
1100 signature->set("triggerCharacters", sigTriggers);
1101 Poco::JSON::Object::Ptr capabilities = new Poco::JSON::Object();
1102 capabilities->set("textDocumentSync", sync);
1103 capabilities->set("completionProvider", completion);
1104 capabilities->set("hoverProvider", true);
1105 capabilities->set("definitionProvider", true);
1106 capabilities->set("referencesProvider", true);
1107 capabilities->set("renameProvider", true);
1108 capabilities->set("documentSymbolProvider", true);
1109 capabilities->set("signatureHelpProvider", signature);
1110 capabilities->set("documentFormattingProvider", true);
1111 capabilities->set("documentRangeFormattingProvider", true);
1112 capabilities->set("foldingRangeProvider", true);
1113 Poco::JSON::Object::Ptr semantic = new Poco::JSON::Object();
1114 semantic->set("legend", semanticTokensLegend());
1115 semantic->set("full", true);
1116 semantic->set("range", false);
1117 capabilities->set("semanticTokensProvider", semantic);
1118 Poco::JSON::Object::Ptr diagnosticProvider = new Poco::JSON::Object();
1119 diagnosticProvider->set("interFileDependencies", true);
1120 diagnosticProvider->set("workspaceDiagnostics", false);
1121 capabilities->set("diagnosticProvider", diagnosticProvider);
1122 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
1123 result->set("capabilities", capabilities);
1124 Poco::JSON::Object::Ptr serverInfo = new Poco::JSON::Object();
1125 serverInfo->set("name", "evescript");
1126 serverInfo->set("version", "1");
1127 result->set("serverInfo", serverInfo);
1128 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(result)));
1129 } else if (method == "initialized" || method == "textDocument/didSave" || method.rfind("$/", 0) == 0) {
1130 return LspDispatch::Continue;
1131 } else if (method == "shutdown") {
1132 impl_->shutdown_ = true;
1133 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var()));
1134 } else if (method == "exit") {
1135 return LspDispatch::Exit;
1136 } else if (method == "textDocument/didOpen") {
1137 auto document = params ? params->getObject("textDocument") : nullptr;
1138 if (document) {
1139 const std::string uri = document->optValue<std::string>("uri", "");
1140 openDocument(uri, document->optValue<std::string>("text", ""));
1141 publishDiagnostics(uri);
1142 }
1143 } else if (method == "textDocument/didChange") {
1144 const std::string uri = documentUri();
1145 auto changes = params ? params->getArray("contentChanges") : nullptr;
1146 if (changes) {
1147 for (unsigned int index = 0; index < changes->size(); ++index) {
1148 auto change = changes->getObject(index);
1149 if (!change) continue;
1150 const std::string text = change->optValue<std::string>("text", "");
1151 if (change->has("range"))
1152 changeDocument(uri, parseRange(change->getObject("range")), text);
1153 else
1155 }
1156 if (changes->size() != 0) publishDiagnostics(uri);
1157 }
1158 } else if (method == "textDocument/didClose") {
1159 const std::string uri = documentUri();
1161 Poco::JSON::Object::Ptr diagParams = new Poco::JSON::Object();
1162 diagParams->set("uri", uri);
1163 diagParams->set("diagnostics", Poco::JSON::Array::Ptr(new Poco::JSON::Array()));
1164 Poco::JSON::Object::Ptr notification = new Poco::JSON::Object();
1165 notification->set("jsonrpc", "2.0");
1166 notification->set("method", "textDocument/publishDiagnostics");
1167 notification->set("params", diagParams);
1168 writeFrame(output, notification);
1169 } else if (method == "textDocument/completion") {
1170 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
1171 for (const script::ScriptCompletion& completion : complete(documentUri(), requestPosition())) {
1172 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1173 item->set("label", completion.label);
1174 item->set("detail", completion.detail);
1175 item->set("insertText", completion.insertText);
1176 item->set("kind", completionKind(completion.kind));
1177 items->add(item);
1178 }
1179 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(items)));
1180 } else if (method == "textDocument/hover") {
1181 const auto value = hover(documentUri(), requestPosition());
1182 if (!value) {
1183 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var()));
1184 } else {
1185 Poco::JSON::Object::Ptr contents = new Poco::JSON::Object();
1186 contents->set("kind", "markdown");
1187 contents->set("value", value->markdown);
1188 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
1189 result->set("contents", contents);
1190 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(result)));
1191 }
1192 } else if (method == "textDocument/definition") {
1193 const auto value = definition(documentUri(), requestPosition());
1194 writeFrame(output, rpcResponse(id, value ? Poco::Dynamic::Var(locationObject(*value)) : Poco::Dynamic::Var()));
1195 } else if (method == "textDocument/references") {
1196 bool includeDeclaration = false;
1197 if (auto context = params ? params->getObject("context") : nullptr)
1198 includeDeclaration = context->optValue<bool>("includeDeclaration", false);
1199 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
1200 for (const lsp::Location& location : references(documentUri(), requestPosition(), includeDeclaration))
1201 items->add(locationObject(location));
1202 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(items)));
1203 } else if (method == "textDocument/rename") {
1204 const std::string newName = params ? params->optValue<std::string>("newName", "") : std::string{};
1205 const auto edits = rename(documentUri(), requestPosition(), newName);
1206 if (!edits) {
1207 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var()));
1208 } else {
1209 Poco::JSON::Object::Ptr changes = new Poco::JSON::Object();
1210 std::unordered_map<std::string, Poco::JSON::Array::Ptr> byUri;
1211 for (const lsp::TextEdit& edit : *edits) {
1212 auto& list = byUri[edit.location.uri];
1213 if (!list) list = new Poco::JSON::Array();
1214 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1215 item->set("range", rangeObject(edit.location.range));
1216 item->set("newText", edit.newText);
1217 list->add(item);
1218 }
1219 for (const auto& [uri, list] : byUri) changes->set(uri, list);
1220 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
1221 result->set("changes", changes);
1222 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(result)));
1223 }
1224 } else if (method == "textDocument/documentSymbol") {
1225 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
1226 for (const script::ScriptSymbolMetadata& symbol : documentSymbols(documentUri())) {
1227 const int line = clampNonNegative(static_cast<int>(symbol.position.line) - 1);
1228 const int col = clampNonNegative(static_cast<int>(symbol.position.column) - 1);
1229 lsp::Range range{{static_cast<size_t>(line), static_cast<size_t>(col)},
1230 {static_cast<size_t>(line), static_cast<size_t>(col + symbol.name.size())}};
1231 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1232 item->set("name", symbol.name);
1233 item->set("detail", symbol.erasedType);
1234 item->set("kind", symbolKind(symbol.kind));
1235 item->set("range", rangeObject(range));
1236 item->set("selectionRange", rangeObject(range));
1237 items->add(item);
1238 }
1239 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(items)));
1240 } else if (method == "textDocument/signatureHelp") {
1241 const auto value = signatureHelp(documentUri(), requestPosition());
1242 if (!value) {
1243 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var()));
1244 } else {
1245 Poco::JSON::Array::Ptr parameters = new Poco::JSON::Array();
1246 for (const LanguageSignatureParameter& parameter : value->parameters) {
1247 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1248 item->set("label", parameter.label);
1249 parameters->add(item);
1250 }
1251 Poco::JSON::Object::Ptr signature = new Poco::JSON::Object();
1252 signature->set("label", value->label);
1253 signature->set("documentation", value->documentation);
1254 signature->set("parameters", parameters);
1255 Poco::JSON::Array::Ptr signatures = new Poco::JSON::Array();
1256 signatures->add(signature);
1257 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
1258 result->set("signatures", signatures);
1259 result->set("activeSignature", 0);
1260 result->set("activeParameter", value->activeParameter);
1261 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(result)));
1262 }
1263 } else if (method == "textDocument/formatting") {
1264 const auto options = parseFormatOptions(params ? params->getObject("options") : nullptr);
1265 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(textEditsArray(formatDocument(documentUri(), options)))));
1266 } else if (method == "textDocument/rangeFormatting") {
1267 const auto options = parseFormatOptions(params ? params->getObject("options") : nullptr);
1268 lsp::Range range = parseRange(params ? params->getObject("range") : nullptr);
1269 writeFrame(output,
1270 rpcResponse(id, Poco::Dynamic::Var(textEditsArray(formatDocument(documentUri(), options, &range)))));
1271 } else if (method == "textDocument/foldingRange") {
1272 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
1273 for (const lsp::FoldingRange& fold : foldingRanges(documentUri())) {
1274 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1275 item->set("startLine", static_cast<int>(fold.startLine));
1276 item->set("endLine", static_cast<int>(fold.endLine));
1277 if (!fold.kind.empty()) item->set("kind", fold.kind);
1278 items->add(item);
1279 }
1280 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(items)));
1281 } else if (method == "textDocument/semanticTokens/full") {
1282 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
1283 result->set("data", semanticTokensData(semanticTokens(documentUri())));
1284 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(result)));
1285 } else if (method == "textDocument/diagnostic") {
1286 Poco::JSON::Array::Ptr items = new Poco::JSON::Array();
1287 const std::string uri = documentUri();
1288 for (const script::ScriptDiagnostic& diagnostic : diagnosticsFor(uri)) {
1289 const int line = clampNonNegative(static_cast<int>(diagnostic.position.line) - 1);
1290 const int col = clampNonNegative(static_cast<int>(diagnostic.position.column) - 1);
1291 lsp::Range range{{static_cast<size_t>(line), static_cast<size_t>(col)},
1292 {static_cast<size_t>(line), static_cast<size_t>(col + 1)}};
1293 Poco::JSON::Object::Ptr item = new Poco::JSON::Object();
1294 item->set("range", rangeObject(range));
1295 item->set("severity", diagnostic.severity == script::ScriptDiagnosticSeverity::Error ? 1 : 2);
1296 item->set("code", diagnostic.code);
1297 item->set("source", "evescript");
1298 item->set("message", diagnostic.message);
1299 items->add(item);
1300 }
1301 Poco::JSON::Object::Ptr result = new Poco::JSON::Object();
1302 result->set("kind", "full");
1303 result->set("items", items);
1304 writeFrame(output, rpcResponse(id, Poco::Dynamic::Var(result)));
1305 } else if (hasId) {
1306 writeFrame(output, rpcError(id, -32601, "unsupported LSP method: " + method));
1307 }
1308 return LspDispatch::Continue;
1309}
1310
1311int LanguageServer::runStdio(std::istream& input, std::ostream& output) {
1312 std::string body;
1313 while (readFrame(input, body)) {
1314 if (handleMessage(body, output) == LspDispatch::Exit) return impl_->shutdown_ ? 0 : 1;
1315 }
1316 return impl_->shutdown_ ? 0 : 1;
1317}
1318
1319} // namespace eve::dev
Duration start
int root
Definition AnimSmr.cpp:119
Vec3 relative
Definition AnimSmr.cpp:164
std::string output
ActiveSource owned
std::size_t cursor
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
EnvironmentMetricContract contract
std::uint16_t method
EvpackChunkInput input
Definition Evpack.cpp:170
std::string pattern
std::string message
DiagnosticCode code
const GltfImportRequest & request
std::int32_t second
float length
size_t offset
Range range
char quote
std::array< float, 3 > position
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
std::string error
Definition Package.cpp:174
std::array< uint32_t, 9 > parameters
std::vector< ParticleBakeMaterial > bindings
std::string path
Definition PlayHost.cpp:111
std::string uri
std::string body
Object::Ptr value
std::string slot
std::string parameter
uint32_t semantic
bool found
unsigned line
std::vector< Signature > signatures
std::string text
std::string_view source
size_t begin
size_t end
std::string kind
std::vector< Token > tokens
double current
std::string string
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
const SquirrelValueOptions & options
Share string attribute map operations through the Windows Foundation DLL.
TacticalUnit * unit
std::uint32_t depth
uint32_t index
const VegetationPresetContext & context
uint64_t identity
EVENGINE_API_FOUNDATION public API.
Definition Runtime.h:189
ScriptId compileSource(std::string source, std::string sourceName="buffer")
Compiles script source without running it.
Definition Runtime.cpp:542
script::ScriptModuleResolver & scriptModules() noexcept
Script module provider registry and dependency resolver for this VM.
Definition Runtime.cpp:523
script::ScriptCompiler & scriptCompiler() noexcept
Unified EveScript compiler, metadata store, and binding contracts.
Definition Runtime.cpp:527
LanguageServer(std::string projectRoot)
const std::string & projectRoot() const noexcept
Absolute project root used to resolve game:/ URIs.
std::vector< script::ScriptSymbolMetadata > documentSymbols(std::string_view uri) const
std::optional< LanguageSignatureHelp > signatureHelp(std::string_view uri, lsp::Position position) const
void openDocument(std::string uri, std::string text)
static std::string fileUriFromPath(std::string_view path)
Converts an on-disk path to the file:// URI the server expects.
std::vector< script::ScriptDiagnostic > diagnosticsFor(std::string_view uri) const
std::optional< lsp::Location > definition(std::string_view uri, lsp::Position position) const
std::vector< lsp::FoldingRange > foldingRanges(std::string_view uri) const
Foldable brace, bracket, and block-comment ranges in an open document.
std::vector< script::ScriptCompletion > complete(std::string_view uri, lsp::Position position) const
std::optional< script::ScriptHover > hover(std::string_view uri, lsp::Position position) const
std::optional< std::vector< lsp::TextEdit > > rename(std::string_view uri, lsp::Position position, std::string_view newName) const
std::vector< lsp::Location > references(std::string_view uri, lsp::Position position, bool includeDeclaration) const
std::vector< lsp::SemanticToken > semanticTokens(std::string_view uri) const
Semantic highlight tokens for an open document (class / function / variable / …).
int runStdio(std::istream &input, std::ostream &output)
Stdio LSP host. Returns 0 after a clean shutdown.
std::vector< lsp::TextEdit > formatDocument(std::string_view uri, lsp::FormatOptions options={}, const lsp::Range *range=nullptr) const
Formats an open document (brace/bracket indent, trailing whitespace).
LspDispatch handleMessage(std::string_view jsonBody, std::ostream &output)
Dispatches one LSP JSON-RPC body and appends Content-Length frames.
void changeDocument(std::string uri, std::string text)
Replaces the whole document (full sync).
void closeDocument(std::string uri)
Cross-file semantic index for EveScript source modules.
void remove(std::string_view canonicalUri)
Removes one source unit from the index.
std::optional< Location > definition(std::string_view canonicalUri, Position position) const
Finds the declaration targeted by the identifier at a position.
void update(std::string canonicalUri, std::string clientUri, std::string source)
Adds or replaces one canonical source unit.
bool hasScriptClass(std::string_view scriptClass) const noexcept
True when generated contracts include this script class.
std::vector< BindingContract > snapshot() const
Returns a stable snapshot sorted by contract key.
const BindingContract * findMethod(std::string_view method) const noexcept
Finds a uniquely named method.
std::vector< ScriptDiagnostic > diagnostics(std::string_view canonicalUri) const
Returns the latest diagnostics for one source unit.
BindingContractRegistry & bindings() noexcept
Native binding contracts used by semantic checks and tools.
eve::OptionalRef< const ScriptMetadata > metadata(std::string_view canonicalUri) const noexcept
Borrows metadata for the most recent successful compilation.
static std::vector< ScriptDiagnostic > validateProjectConfig(std::string_view source, std::string_view canonicalUri, const std::vector< std::string > &knownModules, const std::vector< std::string > &activeModules)
Statically checks literal config module lists without executing config.nut.
std::optional< ScriptHover > hover(std::string_view canonicalUri, std::string_view symbol) const
Returns hover information for a script or native symbol.
std::vector< ScriptCompletion > completions(std::string_view canonicalUri, std::string_view prefix={}) const
Returns completion candidates from script metadata and native contracts.
ProviderId registerProvider(std::shared_ptr< IScriptModuleProvider > provider, int priority=0)
Registers a provider. Higher priorities are tried first.
static bool canonicalize(const ScriptModuleRequest &request, std::string &output, std::string &error)
Normalizes a logical module URI and rejects root traversal.
std::string qualifier
std::string word
bool memberAccess
constexpr uint32_t DefaultLibrary
constexpr uint32_t Variable
constexpr uint32_t Method
constexpr uint32_t Namespace
constexpr uint32_t Keyword
constexpr uint32_t Function
constexpr uint32_t Property
size_t offsetAt(std::string_view source, Position position) noexcept
Converts an LSP position into a UTF-8 byte offset (same contract as the rest of the server).
size_t lastLineIndex(std::string_view source) noexcept
Last 0-based line index (empty source is line 0).
std::string sliceLines(std::string_view source, size_t startLine, size_t endLineInclusive)
Source bytes for coveringLines of the same line span.
bool applyIncremental(std::string &source, const Range *range, std::string_view text)
Applies one LSP content change.
std::string formatEveScript(std::string_view source, const FormatOptions &options)
Indents EveScript by braces/brackets and trims trailing whitespace.
Range coveringLines(std::string_view source, size_t startLine, size_t endLineInclusive) noexcept
Half-open LSP range covering startLine through endLine inclusive. Ends at the start of the following ...
Range documentRange(std::string_view source) noexcept
Full-document range covering every character in source.
std::vector< FoldingRange > foldingRanges(std::string_view source)
Brace, bracket, and block-comment folds that span more than one line.
Files scan(const std::filesystem::path &root, const Files &previous, Object::Ptr stats)
Bounded filesystem scan. Parses only changed files; symlinks are excluded.
LspDispatch
Whether the stdio/JSON-RPC host should keep reading after one dispatch.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Result< std::string > stringify(const eve::Value &value)
Serialize the canonical owning Value as deterministic compact JSON.
Definition Json.cpp:605
ScriptModuleStatus
Result of asking a provider to resolve or load a script module.
WidgetDesc separator(std::string id)
Horizontal separator line.
Definition Widget.cpp:379
const char * module_list_content
EVEngine ECS 集成层:底层实现使用 sunxfancy/ECS.hpp https://github.com/sunxfancy/ECS.hpp
Definition ECS.h:21
std::unordered_map< std::string, std::string > canonical_
std::unordered_map< std::string, std::string > slotClass_
std::filesystem::path pathForCanonical(std::string_view canonical) const
std::unordered_map< std::string, std::string > documents_
std::string canonicalUri(const std::string &uri) const
const std::string * sourceFor(std::string_view uri) const
std::vector< script::ScriptDiagnostic > diagnostics(std::string_view uri) const
void update(const std::string &uri, std::string source)
std::optional< LanguageSignatureHelp > signatureHelp(std::string_view uri, lsp::Position position) const
std::string identity(std::string_view uri) const
std::vector< std::string > activeModules_
std::optional< script::ScriptHover > hover(std::string_view uri, lsp::Position position) const
std::vector< script::ScriptCompletion > complete(std::string_view uri, lsp::Position position) const
void close(const std::string &uri)
std::vector< std::string > knownModules_
Binding-contract signature shown while typing a call.
std::vector< LanguageSignatureParameter > parameters
One parameter in an LSP signature-help result.
One foldable region (0-based inclusive end line).
Editor formatting preferences from LSP FormattingOptions.
Location public API.
Position public API.
Range public API.
One identifier classified for editor semantic highlighting.
TextEdit public API.
Complete script-facing contract for a native function or method.
Tool-neutral completion item suitable for LSP, MCP, and editor adapters.
Stable structured diagnostic shared by Runtime, LSP, MCP, and editor tools.
Tool-neutral hover result for one script or binding symbol.
Erased source-level symbol retained for tooling.