7#include <simplesquirrel/vm.hpp>
18#include <unordered_set>
23std::mutex compilerRegistryMutex;
24std::unordered_map<HSQUIRRELVM, ScriptCompiler*> compilerRegistry;
26std::string& namedArgumentChoicesBuffer() {
28 static thread_local std::string
buffer;
32std::string hashSource(std::string_view
source) {
33 uint64_t
hash = 1469598103934665603ull;
34 for (
const unsigned char c :
source) {
36 hash *= 1099511628211ull;
38 std::ostringstream
out;
43ScriptSourcePosition positionAt(std::string_view
source,
size_t offset) {
45 for (
size_t i = 0; i <
offset && i <
source.size(); ++i) {
56template <
typename Callback>
60 callback(*it,
static_cast<size_t>(it->position()));
63void appendUnique(std::vector<std::string>&
values, std::string
value) {
67std::string maskComments(std::string_view
source,
bool maskStrings =
false) {
70 bool lineComment =
false;
71 bool blockComment =
false;
72 for (
size_t i = 0; i <
result.size(); ++i) {
80 }
else if (blockComment) {
81 if (
c ==
'*' && next ==
'/') {
85 }
else if (
c !=
'\n') {
88 }
else if (
quote != 0) {
89 if (maskStrings &&
c !=
'\n')
result[i] =
' ';
90 if (
c ==
'\\' && next != 0) {
91 if (maskStrings && next !=
'\n')
result[i + 1] =
' ';
95 }
else if (
c ==
'"' ||
c ==
'\'') {
97 if (maskStrings)
result[i] =
' ';
98 }
else if (
c ==
'/' && next ==
'/') {
102 }
else if (
c ==
'/' && next ==
'*') {
111std::string trim(std::string_view
value) {
112 const size_t begin =
value.find_first_not_of(
" \t\r\n");
113 if (
begin == std::string_view::npos)
return {};
114 const size_t end =
value.find_last_not_of(
" \t\r\n");
118std::string attributeValue(std::string_view
value) {
126std::vector<std::string> splitArguments(std::string_view arguments) {
127 std::vector<std::string>
result;
130 for (
size_t i = 0; i <= arguments.size(); ++i) {
131 const char c = i == arguments.size() ?
',' : arguments[i];
132 if ((
c ==
'"' ||
c ==
'\'') && (i == 0 || arguments[i - 1] !=
'\\'))
134 if (
c ==
',' &&
quote == 0) {
143std::vector<std::string> typeChoices(std::string_view
type) {
144 std::vector<std::string>
result;
145 static const std::regex choicePattern(R
"([\"']([^\"']+)[\"'])");
146 forMatches(type, choicePattern, [&](const std::smatch& match,
size_t) { appendUnique(
result, match[1].str()); });
150std::string diagnosticCode(std::string_view
message) {
151 if (
message.find(
"not assignable") != std::string_view::npos)
return "EVE2002";
152 if (
message.find(
"outside the allowed choices") != std::string_view::npos)
return "EVE2101";
153 if (
message.find(
"named argument") != std::string_view::npos)
return "EVE2201";
154 if (
message.find(
"Binding Contract") != std::string_view::npos)
return "EVE2202";
155 if (
message.find(
"incompatible unit") != std::string_view::npos)
return "EVE2301";
156 if (
message.find(
"non-exhaustive match") != std::string_view::npos)
return "EVE2401";
157 if (
message.find(
"persist is only allowed") != std::string_view::npos)
return "EVE2501";
158 if (
message.find(
"await is only allowed") != std::string_view::npos)
return "EVE2601";
159 if (
message.find(
"cannot resolve") != std::string_view::npos)
return "EVE1101";
160 if (
message.find(
"escapes") != std::string_view::npos)
return "EVE1102";
161 if (
message.find(
"cyclic import") != std::string_view::npos)
return "EVE1103";
162 if (
message.find(
"export") != std::string_view::npos)
return "EVE1104";
163 if (
message.find(
"identity") != std::string_view::npos)
return "EVE1105";
167ScriptDiagnostic makeDiagnostic(std::string_view
error, std::string_view
uri) {
173 ScriptDiagnostic diagnostic;
174 diagnostic.code = diagnosticCode(
message);
175 diagnostic.message = std::move(
message);
177 diagnostic.position.line =
static_cast<uint32_t
>(std::max(
line, 1));
178 diagnostic.position.column =
static_cast<uint32_t
>(std::max(
column, 1));
179 if (diagnostic.code ==
"EVE2201") diagnostic.fix =
"check the parameter names and required arguments";
180 if (diagnostic.code ==
"EVE2401") diagnostic.fix =
"add the missing cases or an else arm";
181 if (diagnostic.code ==
"EVE2601") diagnostic.fix =
"mark the containing function async";
190 if (entry.generated.line > generated.line ||
191 (entry.generated.line == generated.line && entry.generated.column > generated.column))
193 result.
line = entry.original.line + (generated.line - entry.generated.line);
194 result.column = generated.line == entry.generated.line
195 ? entry.original.column + (generated.column - entry.generated.column)
204 if (entry.original.line > original.line ||
205 (entry.original.line == original.line && entry.original.column > original.column))
207 result.
line = entry.generated.line + (original.line - entry.original.line);
208 result.column = original.line == entry.original.line
209 ? entry.generated.column + (original.column - entry.original.column)
217bool sourceIdentityMatches(std::string_view registered, std::string_view requested) {
218 std::string
left(registered);
219 std::string
right(requested);
220 std::replace(
left.begin(),
left.end(),
'\\',
'/');
221 std::replace(
right.begin(),
right.end(),
'\\',
'/');
223 const size_t scheme =
left.find(
":/");
224 if (scheme != std::string::npos)
left.erase(0, scheme + 2);
230template <
typename Mapper>
231ScriptSourcePosition mapRegisteredPosition(std::string_view
source, ScriptSourcePosition
position, Mapper mapper) {
232 std::lock_guard lock(compilerRegistryMutex);
233 for (
const auto& [_,
compiler] : compilerRegistry) {
234 for (
const ScriptMetadata& metadata :
compiler->metadataSnapshot()) {
235 if (sourceIdentityMatches(metadata.canonicalUri,
source))
return mapper(metadata.sourceMap,
position);
244 std::string
result =
module;
256std::string jsonEscape(std::string_view
text) {
259 for (
unsigned char c :
text) {
261 case '"':
out +=
"\\\"";
break;
262 case '\\':
out +=
"\\\\";
break;
263 case '\n':
out +=
"\\n";
break;
264 case '\r':
out +=
"\\r";
break;
265 case '\t':
out +=
"\\t";
break;
269 std::snprintf(buf,
sizeof(buf),
"\\u%04x",
c);
272 out.push_back(
static_cast<char>(
c));
293std::string asciiLower(std::string_view
text) {
295 for (
char&
c :
out)
c = static_cast<char>(
std::tolower(static_cast<unsigned char>(
c)));
299std::vector<std::string> splitTokens(
const std::string& query) {
300 std::vector<std::string>
tokens;
305 if (std::isspace(
static_cast<unsigned char>(
c)) ||
c ==
'/' ||
c ==
'.') {
318int scoreContract(
const BindingContract&
contract,
const std::string& queryLower,
319 const std::vector<std::string>&
tokens) {
320 const std::string
key = asciiLower(
contract.key());
322 const std::string
cls = asciiLower(
contract.scriptClass);
323 const std::string
module = asciiLower(contract.module);
324 const std::string docs = asciiLower(
contract.documentationId);
325 const std::string hay =
key +
" " +
module + " " + cls + " " + method + " " + docs;
326 if (queryLower.empty())
return 1;
328 if (hay.find(
token) == std::string::npos)
return 0;
330 if (
key == queryLower)
return 200;
331 if (
cls +
"." +
method == queryLower)
return 180;
332 if (
method == queryLower)
return 150;
333 if (
method.rfind(queryLower, 0) == 0)
return 120;
334 if (
method.find(queryLower) != std::string::npos)
return 90;
335 if (
cls.find(queryLower) != std::string::npos)
return 75;
336 if (
key.find(queryLower) != std::string::npos)
return 70;
337 if (docs.find(queryLower) != std::string::npos)
return 50;
344 std::ostringstream json;
345 json <<
"{\"key\":\"" << jsonEscape(
key()) <<
"\",\"module\":\"" << jsonEscape(module) <<
"\",\"scriptClass\":\""
346 << jsonEscape(
scriptClass) <<
"\",\"method\":\"" << jsonEscape(
method) <<
"\",\"parameters\":[";
347 for (
size_t i = 0; i <
parameters.size(); ++i) {
349 if (i != 0) json <<
',';
350 json <<
"{\"name\":\"" << jsonEscape(
parameter.name) <<
"\",\"type\":\"" << jsonEscape(
parameter.type)
351 <<
"\",\"nullable\":" << (
parameter.nullable ?
"true" :
"false");
353 json <<
",\"default\":\"" << jsonEscape(*
parameter.scriptDefault) <<
'"';
356 json <<
",\"unit\":\"" << scriptUnitName(
parameter.unit) <<
'"';
359 json <<
",\"choices\":[";
361 if (
c != 0) json <<
',';
362 json <<
'"' << jsonEscape(
parameter.choices[
c]) <<
'"';
368 json <<
"],\"returnType\":\"" << jsonEscape(
returnType)
369 <<
"\",\"returnNullable\":" << (
returnNullable ?
"true" :
"false") <<
",\"ownership\":\""
371 for (
size_t i = 0; i <
platforms.size(); ++i) {
372 if (i != 0) json <<
',';
373 json <<
'"' << jsonEscape(
platforms[i]) <<
'"';
375 json <<
"],\"documentationId\":\"" << jsonEscape(
documentationId) <<
"\",\"source\":\"" << jsonEscape(
source)
376 <<
"\",\"cppSymbol\":\"" << jsonEscape(
cppSymbol) <<
"\",\"architecture\":";
379 json <<
"{\"status\":\"mapped\",\"schemaVersion\":1,\"cppSymbol\":\"" << jsonEscape(
cppSymbol)
380 <<
"\",\"implementationSource\":\"" << jsonEscape(mapping.implementationSource) <<
"\",\"stateOwner\":\""
381 << jsonEscape(mapping.stateOwner) <<
"\",\"ownerSource\":\"" << jsonEscape(mapping.ownerSource)
382 <<
"\",\"inputHash\":\"" << jsonEscape(mapping.inputHash)
383 <<
"\",\"evidence\":\"static-binding+reviewed-owner+test-reference\",\"limitations\":\""
384 << jsonEscape(mapping.limitations) <<
'"';
385 const auto writeArray = [&json](
const char*
name,
const std::vector<std::string>&
values) {
386 json <<
",\"" <<
name <<
"\":[";
388 if (
index != 0) json <<
',';
393 writeArray(
"writes", mapping.writes);
394 writeArray(
"tests", mapping.tests);
395 writeArray(
"reads", mapping.reads);
398 json <<
"{\"status\":\"unknown\",\"reason\":\"No reviewed owner mapping for this binding\"}";
400 json <<
",\"semantics\":";
402 json <<
"{\"schemaVersion\":1,\"factory\":\"" << jsonEscape(
semantics->factory) <<
"\",\"role\":\""
403 << jsonEscape(
semantics->role) <<
"\",\"resultClass\":\"" << jsonEscape(
semantics->resultClass)
404 <<
"\",\"identityArgument\":" <<
semantics->identityArgument
405 <<
",\"relatedArgument\":" <<
semantics->relatedArgument
406 <<
",\"schema\":" << (
semantics->schemaJson.empty() ?
"null" :
semantics->schemaJson) <<
'}';
420 return storage_->contracts.erase(std::string(
key)) != 0;
424 const auto found = storage_->contracts.find(std::string(
key));
425 return found == storage_->contracts.end() ? nullptr : &
found->second;
430 for (
const auto& [_,
contract] : storage_->contracts) {
432 if (
result !=
nullptr)
return nullptr;
439 std::string_view
method)
const noexcept {
441 for (
const auto& [_,
contract] : storage_->contracts) {
443 if (
result !=
nullptr)
return nullptr;
450 for (
const auto& [_,
contract] : storage_->contracts) {
451 if (
contract.scriptClass == scriptClass)
return true;
457 std::vector<BindingContract>
result;
458 result.reserve(storage_->contracts.size());
466 std::string_view classFilter,
size_t limit)
const {
469 const std::string queryLower = asciiLower(query);
470 const std::string moduleLower = asciiLower(moduleFilter);
471 const std::string classLower = asciiLower(classFilter);
472 const auto tokens = splitTokens(queryLower);
473 std::vector<BindingSearchHit> hits;
474 for (
const auto& [_,
contract] : storage_->contracts) {
475 if (!moduleLower.empty() && asciiLower(
contract.module) != moduleLower)
continue;
476 if (!classLower.empty() && asciiLower(
contract.scriptClass) != classLower)
continue;
478 if (
score <= 0)
continue;
482 if (a.score != b.score) return a.score > b.score;
483 return a.contract.key() < b.contract.key();
489void BindingContractRegistry::ensureUnique() {
490 if (storage_.use_count() != 1) storage_ = std::make_shared<Storage>(*storage_);
504 const SQInteger
top = sq_gettop(vm_->getHandle());
505 sq_pushroottable(vm_->getHandle());
506 sq_pushnull(vm_->getHandle());
507 while (SQ_SUCCEEDED(sq_next(vm_->getHandle(), -2))) {
508 if (sq_gettype(vm_->getHandle(), -2) == OT_STRING) {
509 const SQChar*
name =
nullptr;
510 if (SQ_SUCCEEDED(sq_getstring(vm_->getHandle(), -2, &
name)) &&
name !=
nullptr) nativeGlobals_.insert(
name);
512 sq_pop(vm_->getHandle(), 2);
514 sq_settop(vm_->getHandle(),
top);
516 std::lock_guard lock(compilerRegistryMutex);
517 compilerRegistry[vm_->getHandle()] =
this;
519 sq_setnamedargresolver(
522 const SQChar**
unit,
const SQChar**
choices, SQUserPointer user) ->
const SQChar* {
523 const auto& self = *static_cast<ScriptCompiler*>(user);
524 if (self.nativeGlobals_.find(callee) != self.nativeGlobals_.end()) return nullptr;
525 const BindingContract* contract = self.bindings_.findMethod(callee);
526 if (contract == nullptr || index < 0 || static_cast<size_t>(index) >= contract->parameters.size())
528 const BindingParameterContract& parameter = contract->parameters[static_cast<size_t>(index)];
529 if (type != nullptr) *type = parameter.type.c_str();
530 if (nullable != nullptr) *nullable = parameter.nullable ? SQTrue : SQFalse;
531 static const char* units[] = {nullptr,
"seconds",
"milliseconds",
"radians",
"degrees",
"pixels",
"meters"};
534 auto& choiceBuffer = namedArgumentChoicesBuffer();
535 choiceBuffer.clear();
536 for (
size_t i = 0; i <
parameter.choices.size(); ++i) {
537 if (i != 0) choiceBuffer +=
',';
540 *
choices = choiceBuffer.empty() ? nullptr : choiceBuffer.c_str();
545 sq_setannotationresolver(
547 [](
HSQUIRRELVM,
const SQChar* annotation, SQUserPointer user) -> SQBool {
548 const auto& names = static_cast<ScriptCompiler*>(user)->annotations_;
549 return names.find(annotation) == names.end() ? SQFalse : SQTrue;
554ScriptCompiler::~ScriptCompiler() {
556 std::lock_guard lock(compilerRegistryMutex);
557 compilerRegistry.erase(vm_->getHandle());
559 sq_setannotationresolver(vm_->getHandle(),
nullptr,
nullptr);
560 sq_setnamedargresolver(vm_->getHandle(),
nullptr,
nullptr);
563ssq::Script ScriptCompiler::compileSource(std::string_view
source, std::string_view sourceName) {
564 const std::string
uri(sourceName);
565 modules_->beginCompilation(
uri);
568 ssq::Script compiled = vm_->compileSource(std::string(
source).c_str(),
uri.c_str());
569 modules_->prepareDependencies(
uri);
570 next.dependencies = modules_->dependencies(
uri);
571 metadata_[
uri] = std::move(next);
572 refreshDependencyMetadata();
574 }
catch (
const std::exception&
error) {
575 const auto failure = modules_->takeCompilationFailure();
576 next.diagnostics.push_back(makeDiagnostic(failure ? *failure :
error.what(),
uri));
578 metadata_[
uri] = std::move(next);
579 throw std::runtime_error(*failure);
581 metadata_[
uri] = std::move(next);
586ssq::Script ScriptCompiler::compileFile(std::string_view
path) {
589 std::ifstream
input(
uri, std::ios::binary);
591 const std::string
source(std::istreambuf_iterator<char>(
input), {});
594 next.canonicalUri =
uri;
595 next.sourceMap.canonicalUri =
uri;
597 modules_->beginCompilation(
uri);
599 ssq::Script compiled = vm_->compileFile(
uri.c_str());
600 modules_->prepareDependencies(
uri);
601 next.dependencies = modules_->dependencies(
uri);
602 metadata_[
uri] = std::move(next);
603 refreshDependencyMetadata();
605 }
catch (
const std::exception&
error) {
606 const auto failure = modules_->takeCompilationFailure();
607 next.diagnostics.push_back(makeDiagnostic(failure ? *failure :
error.what(),
uri));
609 metadata_[
uri] = std::move(next);
610 throw std::runtime_error(*failure);
612 metadata_[
uri] = std::move(next);
618 const auto found = metadata_.find(std::string(canonicalUri));
623std::vector<ScriptMetadata> ScriptCompiler::metadataSnapshot()
const {
624 std::vector<ScriptMetadata>
result;
625 result.reserve(metadata_.size());
626 for (
const auto& [_, metadata] : metadata_)
result.push_back(metadata);
632void ScriptCompiler::refreshDependencyMetadata() {
633 for (
auto& [_, metadata] : metadata_) metadata.reverseDependencies.clear();
634 for (
const auto& [importer, metadata] : metadata_) {
635 for (
const std::string& dependency : metadata.dependencies) {
636 const auto found = metadata_.find(dependency);
637 if (
found != metadata_.end()) appendUnique(
found->second.reverseDependencies, importer);
640 for (
auto& [_, metadata] : metadata_)
641 std::sort(metadata.reverseDependencies.
begin(), metadata.reverseDependencies.
end());
647void ScriptCompiler::registerAnnotation(std::string
name) {
648 if (!
name.empty()) annotations_.insert(std::move(
name));
651bool ScriptCompiler::unregisterAnnotation(std::string_view
name) {
return annotations_.erase(std::string(
name)) != 0; }
653std::vector<ScriptCompletion> ScriptCompiler::completions(std::string_view canonicalUri,
654 std::string_view prefix)
const {
655 std::vector<ScriptCompletion>
result;
656 const auto matches = [prefix](std::string_view
value) {
return value.rfind(prefix, 0) == 0; };
657 if (
const auto unit = metadata(canonicalUri)) {
659 if (matches(symbol.name))
result.push_back({symbol.name, symbol.kind, symbol.erasedType, symbol.name});
661 for (
const std::string&
name :
unit->get().exports) {
662 const bool described = std::any_of(
result.begin(),
result.end(),
664 if (matches(
name) && !described)
result.push_back({
name,
"export",
"module export",
name});
668 if (!matches(
contract.method))
continue;
669 std::string signature =
contract.method +
"(";
670 std::string insertion =
contract.method +
"(";
671 for (
size_t i = 0; i <
contract.parameters.size(); ++i) {
676 signature +=
contract.parameters[i].name +
": " +
contract.parameters[i].type;
677 insertion +=
contract.parameters[i].name +
": ";
679 signature +=
") -> " +
contract.returnType;
681 result.push_back({
contract.method,
"function", std::move(signature), std::move(insertion)});
683 std::sort(
result.begin(),
result.end(), [](
const ScriptCompletion&
a,
const ScriptCompletion&
b) {
684 if (a.label != b.label) return a.label < b.label;
685 return a.kind < b.kind;
688 [](
const ScriptCompletion&
a,
const ScriptCompletion&
b) {
689 return a.label == b.label && a.kind == b.kind;
695std::optional<ScriptHover> ScriptCompiler::hover(std::string_view canonicalUri, std::string_view symbol)
const {
696 if (
const auto unit = metadata(canonicalUri)) {
698 if (candidate.name == symbol)
700 "`" + candidate.kind +
" " + candidate.name +
": " + candidate.erasedType +
"`",
705 std::string markdown =
"`" +
contract->method +
"(";
706 for (
size_t i = 0; i <
contract->parameters.size(); ++i) {
707 if (i != 0) markdown +=
", ";
708 markdown +=
contract->parameters[i].name +
": " +
contract->parameters[i].type;
710 markdown +=
") -> " +
contract->returnType +
"`";
711 if (!
contract->documentationId.empty()) markdown +=
"\n\n" +
contract->documentationId;
717std::vector<ScriptDiagnostic> ScriptCompiler::diagnostics(std::string_view canonicalUri)
const {
718 const auto unit = metadata(canonicalUri);
719 return unit ?
unit->get().diagnostics : std::vector<ScriptDiagnostic>{};
722bool ScriptCompiler::setSourceMap(std::string_view canonicalUri,
ScriptSourceMap sourceMap) {
723 const auto found = metadata_.find(std::string(canonicalUri));
724 if (
found == metadata_.end())
return false;
726 found->second.sourceMap = std::move(sourceMap);
746 std::lock_guard lock(compilerRegistryMutex);
747 const auto found = compilerRegistry.find(
vm);
753 const std::string
uri = sourceName ==
nullptr ?
"buffer" : sourceName;
756 const SQInteger
top = sq_gettop(
vm);
766 next.diagnostics.push_back(std::move(diagnostic));
772 }
catch (
const std::exception&
error) {
774 next.diagnostics.push_back(makeDiagnostic(
error.what(),
uri));
776 return sq_throwerror(
vm,
error.what());
778 next.dependencies =
compiler->modules_->dependencies(
uri);
780 compiler->refreshDependencyMetadata();
784std::vector<ScriptDiagnostic> ScriptCompiler::validateProjectConfig(std::string_view
source,
785 std::string_view canonicalUri,
786 const std::vector<std::string>& knownModules,
787 const std::vector<std::string>& activeModules) {
788 std::vector<ScriptDiagnostic>
result;
789 const std::string scanned = maskComments(
source);
790 static const std::regex listPattern(R
"(\b(modules|optionalModules)\s*=\s*\[([^\]]*)\])");
791 static const std::regex allowPattern(R
"(\ballowGlobals\s*=\s*\[([^\]]*)\])");
792 static const std::regex valuePattern(R
"([\"']([^\"']+)[\"'])");
793 static const std::unordered_set<std::string> knownAllowGlobals = {
"dofile",
"loadfile",
"compilestring"};
794 forMatches(scanned, listPattern, [&](
const std::smatch& list,
size_t listOffset) {
795 const bool required = list[1].str() ==
"modules";
796 const std::string
values = list[2].str();
797 forMatches(
values, valuePattern, [&](
const std::smatch&
value,
size_t valueOffset) {
799 const bool known = std::find(knownModules.begin(), knownModules.end(),
name) != knownModules.end();
800 const bool active = std::find(activeModules.begin(), activeModules.end(),
name) != activeModules.end();
803 diagnostic.
code = known ?
"EVE1002" :
"EVE1001";
804 diagnostic.
message = known ?
"required module is absent from the selected profile: " +
name
805 :
"config contains an unknown module root slot: " +
name;
807 diagnostic.
position = positionAt(
source, listOffset +
static_cast<size_t>(list.position(2)) + valueOffset);
809 diagnostic.
fix = known ?
"enable the module in the selected build profile"
810 :
"use a root slot from the generated Module Contract";
811 result.push_back(std::move(diagnostic));
814 forMatches(scanned, allowPattern, [&](
const std::smatch& list,
size_t listOffset) {
815 const std::string
values = list[1].str();
816 forMatches(
values, valuePattern, [&](
const std::smatch&
value,
size_t valueOffset) {
818 if (knownAllowGlobals.count(
name) != 0)
return;
820 diagnostic.
code =
"EVE1003";
821 diagnostic.
message =
"config.allowGlobals contains an unknown name: " +
name;
823 diagnostic.
position = positionAt(
source, listOffset +
static_cast<size_t>(list.position(1)) + valueOffset);
825 diagnostic.
fix =
"use one of: dofile, loadfile, compilestring";
826 result.push_back(std::move(diagnostic));
836 result.canonicalUri = std::string(canonicalUri);
837 result.providerOrigin = std::string(canonicalUri);
839 result.sourceMap.entries.push_back({{1, 1}, {1, 1}});
840 const std::string scanned = maskComments(
source);
841 const std::string
code = maskComments(
source,
true);
843 static const std::regex importPattern(
844 R
"(\bimport\s+(?:\*\s+as\s+[A-Za-z_]\w*|\{[^}]*\})\s+from\s+[\"']([^\"']+)[\"'])");
845 static const std::regex exportPattern(R
"(\bexport\s+(?:function|class|const)\s+([A-Za-z_]\w*))");
846 static const std::regex persistPattern(R
"(\bpersist\s+([A-Za-z_]\w*)\s*(?::[^=]+)?=)");
847 static const std::regex symbolPattern(R
"(\b(local|function|class)\s+([A-Za-z_]\w*)\s*(?::\s*([^=,\)\{\n]+))?)");
848 static const std::regex asyncPattern(R
"(\basync\s+function\s+([A-Za-z_]\w*))");
849 static const std::regex awaitPattern(R
"(\bawait\b)");
850 static const std::regex propertyPattern(
851 R
"(((?:[ \t]*@[A-Za-z_]\w*\([^\r\n]*\)[ \t]*\r?\n)+)[ \t]*([A-Za-z_]\w*)[ \t]*:[ \t]*([^=\r\n]+)[ \t]*=)");
852 static const std::regex annotationPattern(R
"(@([A-Za-z_]\w*)\(([^)]*)\))");
854 forMatches(scanned, importPattern, [&](const std::smatch& match,
size_t) {
855 appendUnique(
result.imports, match[1].str());
856 appendUnique(
result.moduleReferences, match[1].str());
858 forMatches(scanned, exportPattern,
859 [&](
const std::smatch& match,
size_t) { appendUnique(
result.exports, match[1].str()); });
860 forMatches(scanned, persistPattern, [&](
const std::smatch& match,
size_t offset) {
861 appendUnique(
result.persistRoots, match[1].str());
862 result.symbols.push_back({match[1].str(),
"persist",
"dynamic", positionAt(
source,
offset)});
864 forMatches(scanned, symbolPattern, [&](
const std::smatch& match,
size_t offset) {
865 result.symbols.push_back({match[2].str(), match[1].str(), match[3].matched ? match[3].str() :
"dynamic",
868 forMatches(scanned, asyncPattern,
869 [&](
const std::smatch& match,
size_t) { appendUnique(
result.asyncFunctions, match[1].str()); });
870 forMatches(
code, awaitPattern,
872 forMatches(scanned, propertyPattern, [&](
const std::smatch& match,
size_t offset) {
874 property.
name = match[2].str();
875 property.erasedType = trim(match[3].str());
876 property.position = positionAt(
source,
offset +
static_cast<size_t>(match.position(2)));
877 const std::string annotations = match[1].str();
878 forMatches(annotations, annotationPattern, [&](
const std::smatch& annotation,
size_t) {
879 const std::string
name = annotation[1].str();
880 const std::vector<std::string> args = splitArguments(annotation[2].str());
881 for (
size_t i = 0; i < args.size(); ++i) {
882 const size_t colon = args[i].find(
':');
883 if (i == 0 && colon == std::string::npos)
884 property.attributes[
name] = attributeValue(args[i]);
885 else if (colon != std::string::npos)
886 property.attributes[trim(std::string_view(args[i]).substr(0, colon))] =
887 attributeValue(std::string_view(args[i]).substr(colon + 1));
890 property.choices = typeChoices(property.
erasedType);
891 const auto editor =
property.attributes.find(
"editor");
892 if (editor != property.
attributes.end() && editor->second ==
"combo" && !property.
choices.empty()) {
894 for (
size_t i = 0; i <
property.choices.size(); ++i) {
896 options +=
property.choices[i];
898 property.attributes[
"options"] = std::move(
options);
900 result.properties.push_back(std::move(property));
std::unordered_map< std::string, QuestRuntime > entries
struct SQVM * HSQUIRRELVM
EnvironmentMetricContract contract
std::array< float, 3 > position
std::set< std::string > choices
onnx_detail::CompilerQueue compiler
std::unique_ptr< gpgpu::GpuBuffer > buffer
std::set< std::string > values
std::vector< Token > tokens
const SquirrelValueOptions & options
std::vector< UnitCandidate > units
const VegetationPresetContext & context
Registry consumed by compiler checks and tooling protocol adapters.
void registerContract(BindingContract contract)
Adds or atomically replaces a binding contract by key.
const BindingContract * find(std::string_view key) const noexcept
Finds a binding contract.
std::vector< BindingSearchHit > search(std::string_view query, std::string_view moduleFilter={}, std::string_view classFilter={}, size_t limit=20) const
Ranked substring/token search over keys, classes, methods and documentation ids.
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.
bool unregisterContract(std::string_view key)
Removes a binding contract.
Unified Runtime compiler facade for metadata, diagnostics, and module preparation.
ScriptCompiler(ssq::VM &vm, ScriptModuleResolver &modules)
Script compiler.
Owns providers, the static dependency graph, compiled closures, and module instances.
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
ScriptUnit
Unit attached to a binding parameter or return value.
ScriptErrorContext captureCompileError(HSQUIRRELVM vm)
Captures the last compilation error recorded by the VM.
const BindingContractRegistry & generatedBindingContracts()
Process-wide generated Binding Contracts for this linked engine build.
bool parseCompileError(const std::string &text, std::string *source, int *line, int *column, std::string *message)
Parses the ssq compile message "Compile error at source:line:column msg".
ScriptStructure analyzeScriptStructure(std::string_view source)
Parse named functions, lexical bindings and call/member/literal expressions.
EVENGINE_API_FOUNDATION void registerEngineBindingContracts(BindingContractRegistry ®istry)
Registers the build-generated contracts for every SimpleSquirrel binding.
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Complete script-facing contract for a native function or method.
std::string key() const
Stable lookup key in the form module/class.method.
std::string documentationId
std::optional< BindingSemanticContract > semantics
Engine-owned source semantics; never supplied by a project relation manifest.
std::vector< BindingParameterContract > parameters
std::string cppSymbol
Direct member target; empty for unresolved lambda/dynamic targets.
std::string source
Actual native registration location.
std::vector< std::string > platforms
std::optional< BindingArchitectureContract > architecture
Optional reviewed mapping; absence is explicitly reported as unknown.
std::string toJson() const
Compact JSON object for one contract (eve.binding-api item).
std::string threadAffinity
std::string std::string scriptClass
One native binding parameter visible to EveScript tools and named arguments.
Ranked Binding Contract hit from text search.
Tool-neutral completion item suitable for LSP, MCP, and editor adapters.
Stable structured diagnostic shared by Runtime, LSP, MCP, and editor tools.
ScriptSourcePosition position
Structured snapshot of a script error: message, throw site and stack.
Tool-neutral hover result for one script or binding symbol.
ScriptSourcePosition position
One generated-to-original mapping segment. Native syntax uses identity mappings.
Source map for a compiled script.
ScriptSourcePosition generatedPosition(ScriptSourcePosition original) const noexcept
Maps an original location to the nearest generated location.
ScriptSourcePosition originalPosition(ScriptSourcePosition generated) const noexcept
Maps a generated location back to the nearest original location.
Original EveScript source position. Lines and columns are one-based.