Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions native/lib/ArithmeticChecking.h
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,11 @@ std::optional<ValueId> invokeArithmetic(Frame &frame, SourceSpan span, TokenKind
!requireGenericTraitProof(frame, *trait, genericTerm(operands[0]), span, terms))
return {};
const auto requirement = syntax_.traits[*trait].methods.front();
const auto method = conformance->methods.at(name(requirement.name));
const auto method = conformance->methods.find(name(requirement.name));
if (method == conformance->methods.end())
return {};
auto result = invoke(frame, span, requirement.name, arguments, expected, {}, nullptr, false,
method, operands);
method->second, operands);
if (result && genericContext(frame))
genericValueTerms_[*result] =
projectedGenericTerm(*trait, genericTerm(operands[0]), terms, "Output", node(*result).type);
Expand Down
2 changes: 1 addition & 1 deletion native/lib/GenericChecking.h
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ std::optional<FunctionId> specializeFunction(FunctionId declaration, GenericBind
key += "[" + genericTypeKey(found->second) + "]";
}
if (auto found = functionSpecializations_.find(key); found != functionSpecializations_.end())
return found->second;
return signatures_[found->second] ? std::optional<FunctionId>(found->second) : std::nullopt;
{
GenericScope scope(*this, std::make_shared<const GenericBindings>(bindings),
proofOwnerForFunction(declaration));
Expand Down
4 changes: 3 additions & 1 deletion native/lib/GenericNominals.h
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,9 @@ std::optional<std::size_t> specializeRecord(std::size_t declaration, GenericBind
}
label += "]";
if (auto found = recordSpecializations_.find(key); found != recordSpecializations_.end())
return found->second;
return recordStates_[found->second] == State::Failed
? std::nullopt
: std::optional<std::size_t>(found->second);
{
auto owner = std::make_shared<GenericProofOwner>();
owner->parameters = original.generics;
Expand Down
6 changes: 3 additions & 3 deletions native/lib/GenericProjections.h
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,10 @@ std::optional<ValueId> traitFunctionValue(Frame &frame, SourceSpan span, SourceS
signature->mutableParameters, signature->ownedParameters);
if (!type)
return {};
const auto target = conformance->methods.at(name(methodName));
if (!analyzeFunction(target))
const auto target = conformance->methods.find(name(methodName));
if (target == conformance->methods.end() || !analyzeFunction(target->second))
return {};
auto result = add(frame, *type, span, FunctionReference{target});
auto result = add(frame, *type, span, FunctionReference{target->second});
if (result && genericContext(frame)) {
auto term = concreteGenericTerm(*type);
for (std::size_t n = 0; n < method->parameters.size(); ++n)
Expand Down
13 changes: 9 additions & 4 deletions native/lib/Semantics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ class Checker {
}
}
registerSignatures();
genericRegistryReady_ = true;
if (diagnostics_.empty())
validateTraitImplementations();
if (diagnostics_.empty())
Expand Down Expand Up @@ -2387,10 +2388,12 @@ class Checker {
auto conformance = requireConformance(*display, genericValueType(type), site);
if (!conformance || !requireGenericTraitProof(frame, *display, genericTerm(value), site))
return {};
const auto method = conformance->methods.at("display");
const auto method = conformance->methods.find("display");
if (method == conformance->methods.end())
return {};
const auto methodName = syntax_.traits[*display].methods.front().name;
auto converted = invoke(frame, site, methodName, {arguments[index + 1]}, result, {},
nullptr, false, method, std::vector<ValueId>{value});
nullptr, false, method->second, std::vector<ValueId>{value});
if (!converted)
return {};
values[index] = *converted;
Expand Down Expand Up @@ -3494,12 +3497,14 @@ class Checker {
!requireGenericTraitProof(frame, *capability, genericTerm(*left), span) ||
!requireGenericTraitProof(frame, *capability, genericTerm(*right), span))
return {};
const auto method = conformance->methods.at("equal");
const auto method = conformance->methods.find("equal");
if (method == conformance->methods.end())
return {};
const auto token = syntax_.traits[*capability].methods.front().name;
ValueType result;
result.builtin = BuiltinValue::Bool;
auto value = invoke(frame, span, token, {comparison.left, comparison.right}, result, {},
nullptr, false, method, std::vector<ValueId>{*left, *right});
nullptr, false, method->second, std::vector<ValueId>{*left, *right});
if (!value || comparison.operation == ComparisonKind::Equal)
return value;
auto no = add(frame, result, span, BoolLiteral{false});
Expand Down
6 changes: 4 additions & 2 deletions native/lib/TraitChecking.h
Original file line number Diff line number Diff line change
Expand Up @@ -927,12 +927,14 @@ invokeTrait(Frame &frame, SourceSpan span, SourceSpan traitName, SourceSpan meth
return {};
}
}
const auto method = conformance->methods.at(name(methodName));
const auto method = conformance->methods.find(name(methodName));
if (method == conformance->methods.end())
return {};
ResolvedSourceToken methodToken{methodName, requirement->name, {}, {}};
methodToken.label = sourceFunctionLabel(*requirement);
rememberSourceToken(std::move(methodToken));
auto result = invoke(frame, span, methodName, arguments, expected, selection, checkedSelection,
spawned, method, std::move(operands));
spawned, method->second, std::move(operands));
if (result && genericContext(frame)) {
auto resultTerm = requirement->result
? instantiateGenericTerm(*requirement->result, node(*result).type, terms)
Expand Down
44 changes: 44 additions & 0 deletions native/lsp/RecoveryProtocolTests.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,50 @@ def install(marked):
# A separate broken declaration cannot swallow the queried body.
text, offset, pos, _ = install('fn broken():\n add(1,\n' + base + ' va|\n')
assert any(i['label']=='value' for i in client.completion(path,*pos)['result']['items'])
# A broken error signature in an importing module must publish S072 and never crash LSP queries.
iter_helper = folder / 'iter_helper.k'
iter_helper.write_text(
'from "std/iter" import Iterable, Iterator, iter, range\n'
'type Countdown:\n stop:i64\n'
'impl Iterable for Countdown:\n'
' type Item=i64\n type Error=never\n'
' fn iterator(values:Self)->Iterator[i64,never]:\n'
' return iter(range(values.stop,0,-1))\n'
'fn begin[S:Iterable](values:S)->Iterator[S.Item,S.Error]:\n'
' return iter(values)\n'
'export fn sub()->i64:\n'
' c=begin(Countdown {stop:3})\n'
' return 2\n'
)
version += 1
client.change(
path,
'from "./iter_helper.k" import sub\n'
'from "./helper.k" import add\n'
'fn brokenSig()->unit ! IoError:\n return ()\n'
'fn main()->i64:\n value=sub()\n return add(1,value)\n',
version,
)
sig_report = publications(client.barrier())[path.as_uri()]
assert any(d['code'] == 'S072' for d in sig_report['diagnostics']), sig_report
text, offset, pos, _ = install(
'from "./iter_helper.k" import sub\n'
'from "./helper.k" import add\n'
'fn brokenSig()->unit ! IoError:\n return ()\n'
'fn main():\n value=sub()\n add(1,va|\n'
)
assert client.signature(path, *pos)['result'] is None
assert client.completion(path, *pos)['result']['items'] == []
text, offset, pos, _ = install(
'from "std/io" import IoError\n'
'from "./iter_helper.k" import sub\n'
'from "./helper.k" import add\n'
'fn brokenSig()->unit ! IoError:\n return ()\n'
'fn main():\n value=sub()\n add(1,va|\n'
)
sig_hint = client.signature(path, *pos)['result']
assert sig_hint and sig_hint['activeParameter'] == 1, sig_hint
assert any(i['label'] == 'value' for i in client.completion(path, *pos)['result']['items'])
# Current imported fields and parameters participate; disk stays unchanged.
client.open(helper, helper_text, 1)
client.barrier()
Expand Down
10 changes: 10 additions & 0 deletions native/lsp/RecoveryTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@ int main() {
signature(prefix + " add(1,missing+va|\n", false);
signature(prefix + " missing(1,va|\n", false);
signature("fn broken():\n value=\n" + prefix + " add(1,va|\n");
const std::string traitRecovery =
"type Point:\n x:i64\n"
"trait Measure:\n type Output\n fn size(value:Self)->Self.Output\n"
"impl Measure for Point:\n type Output=i64\n fn size(value:Self)->i64:\n return value.x\n"
"fn readSize[M:Measure](item:M)->M.Output:\n return Measure.size(item)\n"
"fn brokenSignature()->unit ! MissingError:\n return ()\n" +
add +
"fn main():\n value=readSize(Point {x:2})\n fnPtr=Measure[Point].size\n total=fnPtr(Point {x:1})\n";
completion(traitRecovery + " va|\n", false);
signature(traitRecovery + " add(total,va|\n", false);
// Every recovery path must obey ordinary resource limits and stop making progress.
const auto invalid = std::make_shared<const SourceFile>(path, prefix + " add(1,values[va\n");
for (int budget = 0; budget < 5; ++budget) {
Expand Down
56 changes: 55 additions & 1 deletion native/tests/GenericsTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ void require(bool condition, const std::string &message) {
throw std::runtime_error(message);
}
CheckResult analyze(std::string source, SemanticLimits limits = {}) {
if (source.find("yield ") != std::string::npos || source.find("std/ops") != std::string::npos) {
if (source.find("yield ") != std::string::npos || source.find("std/ops") != std::string::npos ||
source.find("std/fmt") != std::string::npos || source.find("std/cmp") != std::string::npos) {
const SourceOverlay overlay{"generics.k", std::move(source)};
auto loaded = loadModules(overlay.path, {}, {}, {}, {&overlay, 1});
require(bool(loaded), "cannot load generator generic fixture");
Expand Down Expand Up @@ -744,6 +745,37 @@ int main(int argc, char **argv) {
[](const auto &d) { return d.code == "S082"; }),
"specialization limit did not fail closed");

bad("partial signature diagnostics still populate all five trait dispatch paths",
"from \"std/fmt\" import Display, format\n"
"from \"std/cmp\" import Equal\n"
"from \"std/ops\" import Add\n"
"type Meter:\n value:i64\n"
"trait Measure:\n type Output\n fn size(value:Self)->Self.Output\n"
"impl Measure for Meter:\n type Output=i64\n fn size(value:Self)->i64:\n return value.value\n"
"impl Display for Meter:\n fn display(value:Self)->String:\n return format(\"{}\",value.value)\n"
"impl Equal for Meter:\n fn equal(left:Self,right:Self)->bool:\n return left.value==right.value\n"
"impl Add[Meter] for Meter:\n type Output=Meter\n fn add(left:Self,right:Meter)->Meter:\n return Meter {value:left.value+right.value}\n"
"fn readSize[M:Measure](item:M)->M.Output:\n return Measure.size(item)\n"
"fn brokenSignature()->unit ! MissingError:\n return ()\n"
"fn main()->i64:\n"
" a=Meter {value:20}\n"
" b=Meter {value:22}\n"
" sum=a+b\n"
" same=sum==Meter {value:42}\n"
" text=format(\"{}\",sum)\n"
" fnPtr=Measure[Meter].size\n"
" if same:\n"
" return readSize(sum)+fnPtr(a)+length(text)\n"
" return 0\n",
"S072");
bad("repeated specialization of a broken generic signature fails cleanly",
"fn brokenGeneric[T](value:T)->UnknownResult:\n return value\n"
"fn main()->i64:\n"
" a=brokenGeneric(1)\n"
" b=brokenGeneric(1)\n"
" return 0\n",
"S003");

const auto root = std::filesystem::absolute(argv[1]);
std::filesystem::create_directories(root);
const auto write = [&](const char *name, const std::string &text) {
Expand Down Expand Up @@ -775,6 +807,28 @@ int main(int argc, char **argv) {
require(!orphan.ok() && std::ranges::any_of(orphan.diagnostics,
[](const auto &d) { return d.code == "S083"; }),
"foreign trait/type implementation accepted");
write("iter_sub.k", "from \"std/iter\" import Iterable, Iterator, iter, range\n"
"type Countdown:\n stop:i64\n"
"impl Iterable for Countdown:\n"
" type Item=i64\n type Error=never\n"
" fn iterator(values:Self)->Iterator[i64,never]:\n"
" return iter(range(values.stop,0,-1))\n"
"fn begin[S:Iterable](values:S)->Iterator[S.Item,S.Error]:\n"
" return iter(values)\n"
"export fn sub()->unit:\n"
" c=begin(Countdown {stop:3})\n"
" return ()\n");
write("iter_main.k", "from \"./iter_sub.k\" import sub\n"
"fn main()->unit ! IoError:\n"
" sub()\n"
" return ()\n");
loaded = loadModules((root / "iter_main.k").string());
require(bool(loaded), "partial-signature module load");
auto partialSig = check(std::move(*loaded));
require(!partialSig.ok() && !partialSig.module &&
std::ranges::any_of(partialSig.diagnostics,
[](const auto &d) { return d.code == "S072"; }),
"cross-module partial signature did not report S072 cleanly");
std::cout << "PASS module identities and implementation coherence\n";
} catch (const std::exception &error) {
std::cerr << "FAIL " << error.what() << '\n';
Expand Down
Loading