feat(pbs): add concrete generic structs and free functions
This commit is contained in:
+37
-3
@@ -29,12 +29,20 @@ public final class PbsContractTypes {
|
||||
private final List<PbsAst.ImplementsDecl> implementations = new ArrayList<>();
|
||||
private final Set<String> reported = new HashSet<>();
|
||||
private final DiagnosticSink diagnostics;
|
||||
private final PbsInstantiationBudget sharedBudget;
|
||||
private long keyChars;
|
||||
private int work;
|
||||
private boolean failed;
|
||||
private PbsAst.TopDecl activeDeclaration;
|
||||
|
||||
public PbsContractTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, DiagnosticSink diagnostics) {
|
||||
this(ast, supplemental, diagnostics, new PbsInstantiationBudget(diagnostics));
|
||||
}
|
||||
|
||||
public PbsContractTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, DiagnosticSink diagnostics,
|
||||
PbsInstantiationBudget sharedBudget) {
|
||||
this.diagnostics = diagnostics;
|
||||
this.sharedBudget = sharedBudget;
|
||||
supplemental.forEach(this::index);
|
||||
ast.topDecls().forEach(this::index);
|
||||
for (var imported : ast.imports()) for (var item : imported.items()) {
|
||||
@@ -45,7 +53,7 @@ public final class PbsContractTypes {
|
||||
}
|
||||
}
|
||||
|
||||
private void index(PbsAst.TopDecl declaration) {
|
||||
public void index(PbsAst.TopDecl declaration) {
|
||||
if (declaration instanceof PbsAst.TypeBindingDecl binding) {
|
||||
index(binding.declaration());
|
||||
declarations.put(binding.name(), binding.declaration());
|
||||
@@ -77,6 +85,8 @@ public final class PbsContractTypes {
|
||||
if (type == null) return "void";
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE) {
|
||||
var declaration = declaration(type);
|
||||
var origin = applicationOrigin(declaration);
|
||||
if (origin != null) return origin.display();
|
||||
var name = switch (declaration) {
|
||||
case PbsAst.ContractDecl c -> c.name();
|
||||
case PbsAst.StructDecl s -> s.name();
|
||||
@@ -127,6 +137,8 @@ public final class PbsContractTypes {
|
||||
case GROUP -> { return key(type.inner(), depth + 1); }
|
||||
case SIMPLE -> {
|
||||
var declaration = declaration(type);
|
||||
var origin = applicationOrigin(declaration);
|
||||
if (origin != null && type.arguments().isEmpty()) return origin.key();
|
||||
head = declaration == null ? type.name() : nominal(declaration);
|
||||
for (var argument : type.arguments()) children.add(key(argument, depth + 1));
|
||||
}
|
||||
@@ -150,13 +162,25 @@ public final class PbsContractTypes {
|
||||
// Length framing prevents ambiguity between nested constructors and nominal names.
|
||||
var result = head + "[" + children.stream().map(s -> s.length() + ":" + s).collect(Collectors.joining()) + "]";
|
||||
keyChars += result.length(); keys.put(type, result);
|
||||
sharedBudget.store(type.span(), result.length());
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String nominal(PbsAst.TopDecl declaration) {
|
||||
public static String nominal(PbsAst.TopDecl declaration) {
|
||||
var origin = applicationOrigin(declaration);
|
||||
if (origin != null) return origin.key();
|
||||
return "pbs:" + declaration.getClass().getSimpleName() + ":" + declaration.span().getFileId().getId() + ":" + declaration.span().getStart();
|
||||
}
|
||||
|
||||
public static PbsAst.ApplicationOrigin applicationOrigin(PbsAst.TopDecl declaration) {
|
||||
return switch (declaration) {
|
||||
case PbsAst.StructDecl s -> s.applicationOrigin();
|
||||
case PbsAst.ContractDecl c -> c.applicationOrigin();
|
||||
case PbsAst.FunctionDecl f -> f.applicationOrigin();
|
||||
case null, default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public Instance resolve(PbsAst.TypeRef type) {
|
||||
if (failed) return null;
|
||||
var template = template(type);
|
||||
@@ -169,6 +193,7 @@ public final class PbsContractTypes {
|
||||
var cached = instances.get(key);
|
||||
if (cached != null) return cached;
|
||||
if (instances.size() >= MAX_INSTANCES) throw expansion(type.span(), "Contract instance graph exceeds Registry type limit");
|
||||
sharedBudget.instance(type.span());
|
||||
var bindings = new LinkedHashMap<String, PbsAst.TypeRef>();
|
||||
for (int i = 0; i < template.typeParameters().size(); i++) bindings.put(template.typeParameters().get(i).name(), type.arguments().get(i));
|
||||
var signatures = ReadOnlyList.wrap(template.signatures().stream().map(s -> PbsTypeSubstitution.substitute(s, bindings)).toList());
|
||||
@@ -186,6 +211,7 @@ public final class PbsContractTypes {
|
||||
public void validate(PbsAst.File ast) {
|
||||
try {
|
||||
for (var declaration : ast.topDecls()) {
|
||||
activeDeclaration = declaration;
|
||||
if (declaration instanceof PbsAst.ContractDecl contract) {
|
||||
var parameters = new HashSet<String>();
|
||||
for (var parameter : contract.typeParameters()) if (!parameters.add(parameter.name()))
|
||||
@@ -199,6 +225,10 @@ public final class PbsContractTypes {
|
||||
}
|
||||
expand();
|
||||
validateImplementations(ast);
|
||||
} catch (PbsInstantiationBudget.Exhausted failure) {
|
||||
failed = true;
|
||||
pending.clear();
|
||||
error("E_SEM_CONTRACT_EXPANSION", "Contract expansion exceeds bounded generic analysis", ast.span());
|
||||
} catch (ExpansionFailure failure) {
|
||||
failed = true;
|
||||
pending.clear();
|
||||
@@ -284,6 +314,8 @@ public final class PbsContractTypes {
|
||||
return returnKey(type, 0);
|
||||
}
|
||||
|
||||
public String resultKey(PbsAst.TypeRef type) { return returnKey(type); }
|
||||
|
||||
private String returnKey(PbsAst.TypeRef type, int depth) {
|
||||
type = unwrap(type);
|
||||
if (type != null && type.kind() == PbsAst.TypeRefKind.NAMED_TUPLE && type.fields().size() == 1) type = type.fields().getFirst().typeRef();
|
||||
@@ -304,6 +336,7 @@ public final class PbsContractTypes {
|
||||
public List<Instance> instances() { return List.copyOf(instances.values()); }
|
||||
|
||||
private void budget(Span span, int depth) {
|
||||
sharedBudget.visit(span, depth);
|
||||
if (depth > MAX_DEPTH || ++work > MAX_WORK) throw expansion(span, "Contract expansion exceeds bounded type analysis; recursive applications may expand indefinitely");
|
||||
}
|
||||
|
||||
@@ -313,7 +346,8 @@ public final class PbsContractTypes {
|
||||
}
|
||||
|
||||
private void error(String code, String message, Span span) {
|
||||
if (reported.add(code + ":" + span + ":" + message)) Diagnostics.error(diagnostics, code, message, span);
|
||||
if (reported.add(code + ":" + span + ":" + message)) Diagnostics.error(
|
||||
activeDeclaration == null ? diagnostics : PbsGenericDiagnostics.forDeclaration(activeDeclaration, diagnostics), code, message, span);
|
||||
}
|
||||
|
||||
private static PbsAst.TypeRef unwrap(PbsAst.TypeRef type) {
|
||||
|
||||
+15
-6
@@ -127,7 +127,7 @@ public final class PbsFrontendCompiler {
|
||||
|
||||
public IRBackendFile compileParsedFile(
|
||||
final FileId fileId,
|
||||
final PbsAst.File ast,
|
||||
final PbsAst.File sourceAst,
|
||||
final DiagnosticSink diagnostics,
|
||||
final SourceKind sourceKind,
|
||||
final ModuleId moduleId,
|
||||
@@ -140,6 +140,14 @@ public final class PbsFrontendCompiler {
|
||||
final ReadOnlyList<ImportedGlobalSurface> importedGlobals,
|
||||
final IRReservedMetadata importedReservedMetadata,
|
||||
final Map<String, IRGlobalVisibility> declaredGlobalVisibilityByName) {
|
||||
final PbsAst.File ast;
|
||||
if (PbsGenericInstantiation.needed(sourceAst)) {
|
||||
var before = diagnostics.errorCount();
|
||||
var prepared = new PbsGenericInstantiation(java.util.List.of(new PbsGenericInstantiation.Source(sourceAst,
|
||||
supplementalTopDecls == null ? ReadOnlyList.empty() : supplementalTopDecls)), diagnostics, feSurfaceContext).prepare();
|
||||
if (diagnostics.errorCount() > before) return IRBackendFile.empty(fileId);
|
||||
ast = prepared.files().get(fileId);
|
||||
} else ast = sourceAst;
|
||||
final var effectiveModuleId = moduleId == null ? ModuleId.none() : moduleId;
|
||||
final var effectiveModulePool = modulePool == null ? ReadOnlyList.<ModuleReference>empty() : modulePool;
|
||||
final var effectiveNameTable = nameTable == null ? new NameTable() : nameTable;
|
||||
@@ -161,15 +169,16 @@ public final class PbsFrontendCompiler {
|
||||
final var effectiveDeclaredGlobalVisibilityByName = declaredGlobalVisibilityByName == null
|
||||
? Map.<String, IRGlobalVisibility>of()
|
||||
: Map.copyOf(declaredGlobalVisibilityByName);
|
||||
final var diagnosticView = PbsGenericDiagnostics.forFile(ast, effectiveSupplementalTopDecls, diagnostics);
|
||||
final var semanticsErrorBaseline = diagnostics.errorCount();
|
||||
new PbsDeclarationSemanticsValidator(effectiveNameTable).validate(
|
||||
ast,
|
||||
sourceKind,
|
||||
effectiveModuleId,
|
||||
effectiveImportedGlobals,
|
||||
diagnostics);
|
||||
flowSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, effectiveFESurfaceContext, diagnostics);
|
||||
lifecycleSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, diagnostics);
|
||||
diagnosticView);
|
||||
flowSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, effectiveFESurfaceContext, diagnosticView);
|
||||
lifecycleSemanticsValidator.validate(ast, effectiveSupplementalTopDecls, diagnosticView);
|
||||
if (diagnostics.errorCount() > semanticsErrorBaseline) {
|
||||
return IRBackendFile.empty(fileId);
|
||||
}
|
||||
@@ -178,7 +187,7 @@ public final class PbsFrontendCompiler {
|
||||
ast,
|
||||
sourceKind,
|
||||
hostAdmissionContext,
|
||||
diagnostics);
|
||||
diagnosticView);
|
||||
if (reservedMetadata == null) {
|
||||
return IRBackendFile.empty(fileId);
|
||||
}
|
||||
@@ -200,7 +209,7 @@ public final class PbsFrontendCompiler {
|
||||
mergeReservedMetadata(reservedMetadata, effectiveImportedReservedMetadata),
|
||||
effectiveNameTable,
|
||||
effectiveFESurfaceContext,
|
||||
diagnostics,
|
||||
diagnosticView,
|
||||
effectiveImportedCallables);
|
||||
if (diagnostics.errorCount() > loweringErrorBaseline) {
|
||||
return IRBackendFile.empty(fileId);
|
||||
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import java.util.*;
|
||||
|
||||
/** First-order symbolic overlap checking; never enumerates only the used applications. */
|
||||
final class PbsGenericCoherence {
|
||||
private record Term(String head, List<Term> children, boolean variable) {}
|
||||
private final PbsGenericInstantiation context;
|
||||
PbsGenericCoherence(PbsGenericInstantiation context, DiagnosticSink diagnostics) { this.context = context; }
|
||||
|
||||
void validate(List<PbsAst.ImplementsDecl> rules) {
|
||||
var valid = new ArrayList<PbsAst.ImplementsDecl>();
|
||||
for (var rule : rules) {
|
||||
context.budget().visit(rule.span(), 0);
|
||||
var owner = context.declaration(rule.ownerType());
|
||||
var target = context.declaration(rule.contractType());
|
||||
if (!(target instanceof PbsAst.ContractDecl contract)) {
|
||||
context.error("IMPLEMENTATION", "Implementation target must resolve to a contract", rule.contractType().span());
|
||||
continue;
|
||||
}
|
||||
if (!rule.typeParameters().isEmpty()) {
|
||||
var names = new HashSet<>(rule.typeParameters().stream().map(PbsAst.TypeParameter::name).toList());
|
||||
var arguments = rule.ownerType().arguments();
|
||||
var bound = new HashSet<String>();
|
||||
boolean ownerValid = owner instanceof PbsAst.StructDecl s && !s.typeParameters().isEmpty()
|
||||
&& s.typeParameters().size() == arguments.size();
|
||||
for (var argument : arguments) ownerValid &= argument.kind() == PbsAst.TypeRefKind.SIMPLE &&
|
||||
argument.arguments().isEmpty() && names.contains(argument.name()) && bound.add(argument.name());
|
||||
ownerValid &= bound.equals(names) && names.size() == rule.typeParameters().size();
|
||||
if (!ownerValid) {
|
||||
context.error("OWNER", "Generic implements must bind each parameter exactly once through a direct generic struct owner", rule.ownerType().span());
|
||||
continue;
|
||||
}
|
||||
if (!context.sameModule(rule.span(), owner.span())) {
|
||||
context.error("OWNER_MODULE", "Generic implements must belong to the module declaring its owner", rule.span());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (contract.typeParameters().size() != rule.contractType().arguments().size()) {
|
||||
context.error("ARITY", "Implementation target has incorrect contract arity", rule.contractType().span());
|
||||
continue;
|
||||
}
|
||||
var bindings = new HashMap<String, PbsAst.TypeRef>();
|
||||
for (int i = 0; i < contract.typeParameters().size(); i++) bindings.put(contract.typeParameters().get(i).name(), rule.contractType().arguments().get(i));
|
||||
for (var signature : contract.signatures()) {
|
||||
var expected = PbsTypeSubstitution.substitute(signature, bindings);
|
||||
var count = rule.methods().stream().filter(m -> matches(m, expected)).count();
|
||||
if (count != 1) context.error("SIGNATURE", "Implementation must supply exactly one matching "+signature.name(), rule.span());
|
||||
}
|
||||
if (rule.methods().size() != contract.signatures().size()) context.error("SIGNATURE", "Implementation must be complete with no extra methods", rule.span());
|
||||
valid.add(rule);
|
||||
}
|
||||
for (int i = 0; i < valid.size(); i++) for (int j = 0; j < i; j++) {
|
||||
var left = valid.get(i); var right = valid.get(j);
|
||||
context.budget().visit(left.span(), 0);
|
||||
var substitutions = new HashMap<String, Term>();
|
||||
if (unify(term(left.ownerType(), left, 0), term(right.ownerType(), right, 0), substitutions, left.span(), 0)
|
||||
&& unify(term(left.contractType(), left, 0), term(right.contractType(), right, 0), substitutions, left.span(), 0))
|
||||
context.error("OVERLAP", "Overlapping implementations can produce the same concrete owner/contract pair; conflicting declaration at "+right.span(), left.span());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matches(PbsAst.FunctionDecl method, PbsAst.FunctionSignature expected) {
|
||||
if (!method.name().equals(expected.name()) || method.parameters().size() != expected.parameters().size()
|
||||
|| (method.returnKind() == PbsAst.ReturnKind.RESULT) != (expected.returnKind() == PbsAst.ReturnKind.RESULT)
|
||||
|| !context.resultKey(method.returnType()).equals(context.resultKey(expected.returnType()))
|
||||
|| !context.key(method.resultErrorType()).equals(context.key(expected.resultErrorType()))) return false;
|
||||
for (int i = 0; i < method.parameters().size(); i++)
|
||||
if (!context.key(method.parameters().get(i).typeRef()).equals(context.key(expected.parameters().get(i).typeRef()))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private Term term(PbsAst.TypeRef type, PbsAst.ImplementsDecl rule, int depth) {
|
||||
if (type == null) return new Term("void", List.of(), false);
|
||||
context.budget().visit(type.span(), depth);
|
||||
if (type.kind() == PbsAst.TypeRefKind.GROUP) return term(type.inner(), rule, depth+1);
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE) {
|
||||
for (int i = 0; i < rule.typeParameters().size(); i++) if (rule.typeParameters().get(i).name().equals(type.name()))
|
||||
return new Term(PbsContractTypes.nominal(rule)+":"+i, List.of(), true);
|
||||
}
|
||||
var children = new ArrayList<Term>();
|
||||
for (var argument : type.arguments()) children.add(term(argument, rule, depth+1));
|
||||
for (var field : type.fields()) children.add(term(field.typeRef(), rule, depth+1));
|
||||
if (type.inner() != null) children.add(term(type.inner(), rule, depth+1));
|
||||
var declaration = context.declaration(type);
|
||||
var head = type.kind() == PbsAst.TypeRefKind.SIMPLE ? declaration == null ? type.name() : PbsContractTypes.nominal(declaration) : type.kind().name();
|
||||
context.budget().store(type.span(), 32L + head.length());
|
||||
return new Term(head, List.copyOf(children), false);
|
||||
}
|
||||
|
||||
private Term dereference(Term term, Map<String, Term> substitutions, Span site) {
|
||||
while (term.variable() && substitutions.containsKey(term.head())) {
|
||||
context.budget().visit(site, 0); term = substitutions.get(term.head());
|
||||
}
|
||||
return term;
|
||||
}
|
||||
private boolean occurs(String variable, Term term, Map<String, Term> substitutions, Span site, int depth) {
|
||||
context.budget().visit(site, depth);
|
||||
term = dereference(term, substitutions, site);
|
||||
if (term.variable()) return variable.equals(term.head());
|
||||
for (var child : term.children()) if (occurs(variable, child, substitutions, site, depth+1)) return true;
|
||||
return false;
|
||||
}
|
||||
private boolean unify(Term a, Term b, Map<String, Term> substitutions, Span site, int depth) {
|
||||
context.budget().visit(site, depth);
|
||||
a = dereference(a, substitutions, site); b = dereference(b, substitutions, site);
|
||||
if (a.variable() && b.variable() && a.head().equals(b.head())) return true;
|
||||
if (a.variable()) {
|
||||
if (occurs(a.head(), b, substitutions, site, depth+1)) return false;
|
||||
substitutions.put(a.head(), b); return true;
|
||||
}
|
||||
if (b.variable()) return unify(b, a, substitutions, site, depth+1);
|
||||
if (!a.head().equals(b.head()) || a.children().size() != b.children().size()) return false;
|
||||
for (int i = 0; i < a.children().size(); i++) if (!unify(a.children().get(i), b.children().get(i), substitutions, site, depth+1)) return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
/** Presents source applications and retains both ends of specialization diagnostics. */
|
||||
public final class PbsGenericDiagnostics extends DiagnosticSink {
|
||||
private final DiagnosticSink delegate;
|
||||
private final PbsAst.ApplicationOrigin origin;
|
||||
private final Map<String, String> names;
|
||||
|
||||
private PbsGenericDiagnostics(DiagnosticSink delegate, PbsAst.ApplicationOrigin origin, Map<String, String> names) {
|
||||
this.delegate = delegate; this.origin = origin; this.names = names;
|
||||
}
|
||||
public static DiagnosticSink forDeclaration(PbsAst.TopDecl declaration, DiagnosticSink sink) {
|
||||
var origin = PbsContractTypes.applicationOrigin(declaration);
|
||||
return forOrigin(origin, sink);
|
||||
}
|
||||
public static DiagnosticSink forOrigin(PbsAst.ApplicationOrigin origin, DiagnosticSink sink) {
|
||||
return origin == null ? sink : new PbsGenericDiagnostics(sink, origin, Map.of());
|
||||
}
|
||||
public static DiagnosticSink forFile(PbsAst.File file, ReadOnlyList<PbsAst.TopDecl> supplemental, DiagnosticSink sink) {
|
||||
var names = new LinkedHashMap<String, String>();
|
||||
var declarations = new ArrayList<>(file.topDecls().asList());
|
||||
if (supplemental != null) declarations.addAll(supplemental.asList());
|
||||
for (var declaration : declarations) {
|
||||
if (declaration instanceof PbsAst.TypeBindingDecl b) declaration = b.declaration();
|
||||
var origin = PbsContractTypes.applicationOrigin(declaration);
|
||||
if (origin != null) names.put(PbsGenericInstantiation.name(declaration), origin.display());
|
||||
}
|
||||
return names.isEmpty() ? sink : new PbsGenericDiagnostics(sink, null, names);
|
||||
}
|
||||
@Override public DiagnosticSink report(Diagnostic diagnostic) {
|
||||
var message = diagnostic.getMessage();
|
||||
for (var entry : names.entrySet()) message = message.replace(entry.getKey(), entry.getValue());
|
||||
var related = new ArrayList<>(diagnostic.getRelated().asList());
|
||||
if (origin != null) {
|
||||
var chain = origin.chain().stream().limit(4).collect(java.util.stream.Collectors.joining(" -> "));
|
||||
if (origin.chain().size() > 4) chain += " -> ... -> "+origin.display();
|
||||
message += " (instantiating "+chain+")";
|
||||
related.add(new RelatedSpan("Generic declaration "+origin.display(), origin.declaration().span()));
|
||||
related.add(new RelatedSpan("Application requested here", origin.requestedAt()));
|
||||
}
|
||||
delegate.report(new Diagnostic(diagnostic.getSeverity(), diagnostic.getCode(), diagnostic.getPhase(),
|
||||
diagnostic.getTemplateId(), diagnostic.getPlaceholders(), message, diagnostic.getSpan(), related));
|
||||
return this;
|
||||
}
|
||||
@Override public Collection<Diagnostic> asCollection() { return delegate.asCollection(); }
|
||||
@Override public int errorCount() { return delegate.errorCount(); }
|
||||
@Override public int warningCount() { return delegate.warningCount(); }
|
||||
@Override public boolean hasErrors() { return delegate.hasErrors(); }
|
||||
@Override public boolean hasWarnings() { return delegate.hasWarnings(); }
|
||||
}
|
||||
+685
@@ -0,0 +1,685 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.ast.PbsAstRewriter;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.diagnostics.Diagnostics;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Definition-scoped, anchored specialization. All output is ordinary concrete PBS AST. */
|
||||
public final class PbsGenericInstantiation {
|
||||
public record Source(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> visible, Object module) {
|
||||
public Source(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> visible) { this(ast, visible, ast.span().getFileId()); }
|
||||
}
|
||||
public record Prepared(Map<FileId, PbsAst.File> files, Map<FileId, Set<PbsAst.TopDecl>> dependencies, Map<Span, String> resolutions) {}
|
||||
private record Request(PbsAst.TopDecl template, ReadOnlyList<PbsAst.TypeRef> arguments, String name,
|
||||
PbsAst.ApplicationOrigin origin, List<String> chain) {}
|
||||
|
||||
private final DiagnosticSink diagnostics;
|
||||
private final PbsInstantiationBudget budget;
|
||||
private final PbsContractTypes types;
|
||||
private final Map<FileId, Map<String, List<PbsAst.TopDecl>>> scopes = new HashMap<>();
|
||||
private final Map<FileId, Object> modules = new HashMap<>();
|
||||
private final Map<FileId, List<PbsAst.TopDecl>> concrete = new LinkedHashMap<>();
|
||||
private final Map<FileId, Set<PbsAst.TopDecl>> dependencies = new HashMap<>();
|
||||
private final Map<Span, String> resolutions = new HashMap<>();
|
||||
private final Map<FileId, Map<String, PbsAst.TopDecl>> argumentBindings = new HashMap<>();
|
||||
private final Map<String, Request> instances = new LinkedHashMap<>();
|
||||
private final ArrayDeque<Request> pending = new ArrayDeque<>();
|
||||
private final List<PbsAst.ImplementsDecl> rules = new ArrayList<>();
|
||||
private final List<Source> sources;
|
||||
private final Map<String, PbsAst.TopDecl> anchors = new LinkedHashMap<>();
|
||||
private final Set<String> requiredShapes = new LinkedHashSet<>();
|
||||
private boolean symbolicProbe;
|
||||
private final p.studio.compiler.messages.FESurfaceContext surface;
|
||||
|
||||
public PbsGenericInstantiation(List<Source> sources, DiagnosticSink diagnostics) {
|
||||
this(sources, diagnostics, p.studio.compiler.messages.FESurfaceContext.empty());
|
||||
}
|
||||
public PbsGenericInstantiation(List<Source> sources, DiagnosticSink diagnostics, p.studio.compiler.messages.FESurfaceContext surface) {
|
||||
this(sources, diagnostics, surface, null);
|
||||
}
|
||||
private PbsGenericInstantiation(List<Source> sources, DiagnosticSink diagnostics,
|
||||
p.studio.compiler.messages.FESurfaceContext surface, PbsInstantiationBudget sharedBudget) {
|
||||
this.sources = sources;
|
||||
this.surface = surface == null ? p.studio.compiler.messages.FESurfaceContext.empty() : surface;
|
||||
this.diagnostics = diagnostics;
|
||||
budget = sharedBudget == null ? new PbsInstantiationBudget(diagnostics) : sharedBudget;
|
||||
var declarations = new ArrayList<PbsAst.TopDecl>();
|
||||
for (var source : sources) {
|
||||
var file = source.ast().span().getFileId();
|
||||
modules.put(file, source.module());
|
||||
scopes.put(file, new HashMap<>());
|
||||
concrete.put(file, new ArrayList<>());
|
||||
for (var d : source.visible()) { declarations.add(d); bind(file, name(d), d); }
|
||||
for (var d : source.ast().topDecls()) { declarations.add(d); bind(file, name(d), d); }
|
||||
}
|
||||
var first = sources.getFirst().ast();
|
||||
types = new PbsContractTypes(new PbsAst.File(ReadOnlyList.empty(), ReadOnlyList.wrap(declarations), first.span()),
|
||||
ReadOnlyList.empty(), diagnostics, budget);
|
||||
for (var source : sources) for (var d : source.visible()) if (d instanceof PbsAst.TypeBindingDecl b) types.index(b);
|
||||
for (var source : sources) for (var d : source.ast().topDecls()) {
|
||||
if (d instanceof PbsAst.ImplementsDecl rule && rules.stream().noneMatch(r -> r.span().equals(rule.span()))) rules.add(rule);
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean needed(PbsAst.File file) {
|
||||
return file.topDecls().stream().anyMatch(d -> !(d instanceof PbsAst.ContractDecl) && !parameters(d).isEmpty());
|
||||
}
|
||||
|
||||
private void bind(FileId file, String name, PbsAst.TopDecl declaration) {
|
||||
if (declaration instanceof PbsAst.TypeBindingDecl b) { name = b.name(); declaration = b.declaration(); }
|
||||
if (name == null) return;
|
||||
var list = scopes.computeIfAbsent(file, ignored -> new HashMap<>()).computeIfAbsent(name, ignored -> new ArrayList<>());
|
||||
var bound = declaration;
|
||||
if (list.stream().noneMatch(d -> d == bound || d.span().equals(bound.span()))) list.add(declaration);
|
||||
}
|
||||
|
||||
public List<PbsAst.TopDecl> lookup(String name, Span site) {
|
||||
return scopes.getOrDefault(site.getFileId(), Map.of()).getOrDefault(name, List.of());
|
||||
}
|
||||
|
||||
public PbsAst.TopDecl declaration(PbsAst.TypeRef type) { return types.declaration(type); }
|
||||
public String key(PbsAst.TypeRef type) { return types.key(type); }
|
||||
public String resultKey(PbsAst.TypeRef type) { return types.resultKey(type); }
|
||||
private String signatureKey(PbsAst.FunctionDecl f) {
|
||||
return f.parameters().stream().map(p -> key(p.typeRef())).collect(Collectors.joining(",")) + "->" +
|
||||
resultKey(f.returnType()) + (f.returnKind() == PbsAst.ReturnKind.RESULT ? "!"+key(f.resultErrorType()) : "");
|
||||
}
|
||||
public PbsInstantiationBudget budget() { return budget; }
|
||||
public boolean sameModule(Span a, Span b) { return Objects.equals(modules.get(a.getFileId()), modules.get(b.getFileId())); }
|
||||
|
||||
public Prepared prepare() {
|
||||
try {
|
||||
validateDeclarations();
|
||||
for (var source : sources) {
|
||||
var output = concrete.get(source.ast().span().getFileId());
|
||||
var rewrite = new ConcreteRewriter(Map.of(), null, List.of());
|
||||
for (var d : source.ast().topDecls()) {
|
||||
if (!parameters(d).isEmpty()) continue;
|
||||
output.add(rewrite.declaration(d));
|
||||
}
|
||||
}
|
||||
while (!pending.isEmpty()) {
|
||||
var request = pending.removeFirst(); budget.origin(request.origin());
|
||||
try { materialize(request); } finally { budget.origin(null); }
|
||||
}
|
||||
} catch (PbsInstantiationBudget.Exhausted exhausted) {
|
||||
pending.clear();
|
||||
}
|
||||
var files = new LinkedHashMap<FileId, PbsAst.File>();
|
||||
for (var source : sources) {
|
||||
var file = source.ast().span().getFileId();
|
||||
for (var binding : argumentBindings.getOrDefault(file, Map.of()).entrySet()) {
|
||||
var original = binding.getValue();
|
||||
var resolved = concrete.getOrDefault(original.span().getFileId(), List.of()).stream()
|
||||
.filter(d -> d.getClass() == original.getClass() && d.span().equals(original.span())
|
||||
&& PbsContractTypes.applicationOrigin(d) == null).findFirst().orElse(original);
|
||||
concrete.get(file).add(new PbsAst.TypeBindingDecl(binding.getKey(), resolved, source.ast().span()));
|
||||
}
|
||||
files.put(file, new PbsAst.File(source.ast().imports(), ReadOnlyList.wrap(concrete.get(file)), source.ast().span()));
|
||||
}
|
||||
return new Prepared(Map.copyOf(files), dependencies, Map.copyOf(resolutions));
|
||||
}
|
||||
|
||||
private void validateDeclarations() {
|
||||
for (var source : sources) {
|
||||
var duplicates = new HashMap<String, PbsAst.FunctionDecl>();
|
||||
for (var d : source.ast().topDecls()) {
|
||||
validateSelfPositions(d);
|
||||
var names = new HashSet<String>();
|
||||
for (var p : parameters(d)) if (!names.add(p.name())) error("PARAMETER", "Duplicate type parameter " + p.name(), p.span());
|
||||
if (d instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) {
|
||||
if (f.lifecycleMarker() != PbsAst.LifecycleMarker.NONE) error("LIFECYCLE", "Lifecycle functions cannot declare type parameters", f.span());
|
||||
var env = new HashMap<String, PbsAst.TypeRef>();
|
||||
for (int i = 0; i < f.typeParameters().size(); i++) env.put(f.typeParameters().get(i).name(), PbsAst.TypeRef.simple("$parameter"+i, f.span()));
|
||||
var signature = new PbsAstRewriter() {
|
||||
@Override public PbsAst.TypeRef type(PbsAst.TypeRef t) {
|
||||
return t != null && t.kind() == PbsAst.TypeRefKind.SIMPLE && env.containsKey(t.name()) ? env.get(t.name()) : super.type(t);
|
||||
}
|
||||
}.function(f);
|
||||
var duplicateKey = f.name()+"#"+f.typeParameters().size()+"#"+signatureKey(signature);
|
||||
if (duplicates.putIfAbsent(duplicateKey, f) != null) error("DUPLICATE", "Generic overloads differ only by parameter renaming: " + f.name(), f.span());
|
||||
}
|
||||
if (d instanceof PbsAst.StructDecl s) for (var m : s.methods()) rejectMethodParameters(m);
|
||||
if (d instanceof PbsAst.ServiceDecl s) for (var m : s.methods()) rejectMethodParameters(m);
|
||||
if (d instanceof PbsAst.ImplementsDecl i) for (var m : i.methods()) rejectMethodParameters(m);
|
||||
}
|
||||
}
|
||||
validateRules();
|
||||
// Symbolic checking is independent of which concrete applications are requested.
|
||||
new PbsGenericTemplateValidator(this, diagnostics).validate(sources);
|
||||
if (!diagnostics.hasErrors()) validateSymbolicBodies();
|
||||
}
|
||||
|
||||
private void rejectMethodParameters(PbsAst.FunctionDecl method) {
|
||||
if (!method.typeParameters().isEmpty()) error("METHOD", "Methods cannot declare their own type parameters", method.span());
|
||||
}
|
||||
|
||||
private void validateSelfPositions(PbsAst.TopDecl declaration) {
|
||||
new PbsAstRewriter() {
|
||||
private boolean allowed;
|
||||
private boolean owner;
|
||||
@Override public PbsAst.TopDecl declaration(PbsAst.TopDecl d) {
|
||||
boolean previous = owner;
|
||||
owner = d instanceof PbsAst.StructDecl || d instanceof PbsAst.ServiceDecl;
|
||||
try { return super.declaration(d); } finally { owner = previous; }
|
||||
}
|
||||
@Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) {
|
||||
boolean previous = allowed; allowed = owner;
|
||||
try { return super.function(f); } finally { allowed = previous; }
|
||||
}
|
||||
@Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) {
|
||||
boolean previous = allowed; allowed = owner;
|
||||
try { return super.constructor(c); } finally { allowed = previous; }
|
||||
}
|
||||
@Override public PbsAst.TypeRef type(PbsAst.TypeRef t) {
|
||||
if (t != null && t.kind() == PbsAst.TypeRefKind.SELF && !allowed)
|
||||
Diagnostics.error(diagnostics, "E_SEM_INVALID_SELF_CONTEXT", "Self requires a struct/service method or constructor", t.span());
|
||||
return super.type(t);
|
||||
}
|
||||
}.declaration(declaration);
|
||||
}
|
||||
|
||||
public static ReadOnlyList<PbsAst.TypeParameter> parameters(PbsAst.TopDecl d) {
|
||||
return switch (d) {
|
||||
case PbsAst.StructDecl s -> s.typeParameters();
|
||||
case PbsAst.ContractDecl c -> c.typeParameters();
|
||||
case PbsAst.FunctionDecl f -> f.typeParameters();
|
||||
case PbsAst.ImplementsDecl i -> i.typeParameters();
|
||||
case null, default -> ReadOnlyList.empty();
|
||||
};
|
||||
}
|
||||
|
||||
public static String name(PbsAst.TopDecl d) {
|
||||
return switch (d) {
|
||||
case PbsAst.StructDecl s -> s.name();
|
||||
case PbsAst.ContractDecl c -> c.name();
|
||||
case PbsAst.FunctionDecl f -> f.name();
|
||||
case PbsAst.ServiceDecl s -> s.name();
|
||||
case PbsAst.BuiltinTypeDecl b -> b.name();
|
||||
case PbsAst.HostDecl h -> h.name();
|
||||
case PbsAst.EnumDecl e -> e.name();
|
||||
case PbsAst.ErrorDecl e -> e.name();
|
||||
case PbsAst.GlobalDecl g -> g.name();
|
||||
case PbsAst.ConstDecl c -> c.name();
|
||||
case PbsAst.TypeBindingDecl b -> b.name();
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
public static String nominalBinding(PbsAst.TopDecl declaration) { return "$nominal$"+PbsContractTypes.nominal(declaration); }
|
||||
|
||||
private PbsAst.TypeRef canonicalArgument(PbsAst.TypeRef argument, Span definition) {
|
||||
return new PbsAstRewriter() {
|
||||
@Override public PbsAst.TypeRef type(PbsAst.TypeRef t) {
|
||||
if (t == null) return null;
|
||||
var rewritten = super.type(t);
|
||||
var d = types.declaration(t);
|
||||
if (t.kind() != PbsAst.TypeRefKind.SIMPLE || d == null || PbsContractTypes.applicationOrigin(d) != null) return rewritten;
|
||||
var alias = nominalBinding(d);
|
||||
types.index(new PbsAst.TypeBindingDecl(alias, d, definition));
|
||||
var file = concrete.containsKey(definition.getFileId()) ? definition.getFileId() : sources.getFirst().ast().span().getFileId();
|
||||
argumentBindings.computeIfAbsent(file, ignored -> new LinkedHashMap<>()).put(alias, d);
|
||||
dependency(definition, d);
|
||||
return PbsAst.TypeRef.simple(alias, t.span());
|
||||
}
|
||||
}.type(argument);
|
||||
}
|
||||
|
||||
private Request request(PbsAst.TopDecl template, ReadOnlyList<PbsAst.TypeRef> arguments, Span site, List<String> chain, String callableName) {
|
||||
if (parameters(template).size() != arguments.size()) {
|
||||
error("ARITY", name(template)+" requires "+parameters(template).size()+" explicit type argument(s)", site);
|
||||
return null;
|
||||
}
|
||||
var application = PbsAst.TypeRef.applied(name(template), arguments, template.span());
|
||||
var applicationKey = template instanceof PbsAst.FunctionDecl ? PbsContractTypes.nominal(template)+"["+
|
||||
arguments.stream().map(types::key).map(k -> k.length()+":"+k).collect(Collectors.joining())+"]" : types.key(application);
|
||||
var existing = instances.get(applicationKey);
|
||||
if (existing != null) { dependency(site, template); resolutions.put(site, existing.name()); return existing; }
|
||||
budget.visit(site, chain.size()); budget.instance(site); budget.store(site, applicationKey.length());
|
||||
var display = name(template)+"<"+arguments.stream().map(types::display).collect(Collectors.joining(", "))+">";
|
||||
arguments = PbsAstRewriter.map(arguments, a -> canonicalArgument(a, template.span()));
|
||||
var instanceName = callableName == null ? "$generic$"+applicationKey : callableName;
|
||||
var path = new ArrayList<>(chain); path.add(display);
|
||||
var origin = new PbsAst.ApplicationOrigin(template, arguments, applicationKey, display, site, ReadOnlyList.wrap(path));
|
||||
var request = new Request(template, arguments, instanceName, origin, List.copyOf(path));
|
||||
instances.put(applicationKey, request); // Anchor before any field, signature or body is traversed.
|
||||
resolutions.put(site, instanceName);
|
||||
PbsAst.TopDecl anchor = switch (template) {
|
||||
case PbsAst.StructDecl s -> new PbsAst.StructDecl(instanceName, ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(), s.hasBody(), s.attributes(), origin, s.span());
|
||||
case PbsAst.ContractDecl c -> new PbsAst.ContractDecl(instanceName, ReadOnlyList.empty(), ReadOnlyList.empty(), c.attributes(), origin, c.span());
|
||||
default -> null;
|
||||
};
|
||||
if (anchor != null) { types.index(anchor); scopes.values().forEach(scope -> scope.put(instanceName, List.of(anchor))); }
|
||||
if (anchor != null) anchors.put(instanceName, anchor);
|
||||
pending.addLast(request);
|
||||
dependency(site, template);
|
||||
return request;
|
||||
}
|
||||
|
||||
private void dependency(Span use, PbsAst.TopDecl template) {
|
||||
dependencies.computeIfAbsent(use.getFileId(), ignored -> new LinkedHashSet<>()).add(template);
|
||||
}
|
||||
|
||||
private Map<String, PbsAst.TypeRef> environment(PbsAst.TopDecl template, ReadOnlyList<PbsAst.TypeRef> arguments) {
|
||||
var result = new LinkedHashMap<String, PbsAst.TypeRef>();
|
||||
for (int i = 0; i < parameters(template).size(); i++) result.put(parameters(template).get(i).name(), arguments.get(i));
|
||||
return Map.copyOf(result);
|
||||
}
|
||||
|
||||
private void materialize(Request request) {
|
||||
var template = request.template();
|
||||
var rewrite = new ConcreteRewriter(environment(template, request.arguments()),
|
||||
template instanceof PbsAst.StructDecl ? PbsAst.TypeRef.simple(request.name(), template.span()) : null, request.chain());
|
||||
var instance = concreteDeclaration(request, rewrite);
|
||||
concrete.getOrDefault(template.span().getFileId(), concrete.values().iterator().next()).add(instance);
|
||||
types.index(instance);
|
||||
anchors.put(request.name(), instance);
|
||||
scopes.values().forEach(scope -> scope.put(request.name(), List.of(instance)));
|
||||
if (instance instanceof PbsAst.StructDecl s) {
|
||||
checkCollisions(s.methods(), request);
|
||||
checkCollisions(PbsAstRewriter.map(s.ctors(), c -> new PbsAst.FunctionDecl(c.name(), c.parameters(),
|
||||
PbsAst.ReturnKind.EXPLICIT_UNIT, PbsAst.TypeRef.unit(c.span()), null, ReadOnlyList.empty(),
|
||||
PbsAst.LifecycleMarker.NONE, c.body(), c.span())), request);
|
||||
if (symbolicProbe) return;
|
||||
for (var rule : rules) if (!rule.typeParameters().isEmpty() && types.declaration(rule.ownerType()) == template) {
|
||||
var bindings = new LinkedHashMap<String, PbsAst.TypeRef>();
|
||||
for (int i = 0; i < rule.ownerType().arguments().size(); i++) bindings.put(rule.ownerType().arguments().get(i).name(), request.arguments().get(i));
|
||||
var ruleRewrite = new ConcreteRewriter(bindings, PbsAst.TypeRef.simple(request.name(), rule.span()), request.chain());
|
||||
ruleRewrite.implicitLocals = Map.of(rule.binderName(), PbsAst.TypeRef.simple(request.name(), rule.span()));
|
||||
var implementation = new PbsAst.ImplementsDecl(ReadOnlyList.empty(), ruleRewrite.type(rule.contractType()),
|
||||
PbsAst.TypeRef.simple(request.name(), rule.ownerType().span()), rule.binderName(),
|
||||
PbsAstRewriter.map(rule.methods(), ruleRewrite::function), rule.span());
|
||||
concrete.getOrDefault(rule.span().getFileId(), concrete.values().iterator().next()).add(implementation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private PbsAst.TopDecl concreteDeclaration(Request request, ConcreteRewriter rewrite) {
|
||||
var d = rewrite.declaration(request.template());
|
||||
return switch (d) {
|
||||
case PbsAst.StructDecl s -> new PbsAst.StructDecl(request.name(), ReadOnlyList.empty(), s.fields(), s.methods(), s.ctors(), s.hasBody(), s.attributes(), request.origin(), s.span());
|
||||
case PbsAst.ContractDecl c -> new PbsAst.ContractDecl(request.name(), ReadOnlyList.empty(), c.signatures(), c.attributes(), request.origin(), c.span());
|
||||
case PbsAst.FunctionDecl f -> new PbsAst.FunctionDecl(request.name(), ReadOnlyList.empty(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.lifecycleMarker(), f.body(), request.origin(), f.span());
|
||||
default -> throw new IllegalStateException("Unexpected generic declaration");
|
||||
};
|
||||
}
|
||||
|
||||
/** Validate control flow, constructors and ordinary operations with opaque symbolic witnesses.
|
||||
* Dependencies contribute shapes only: expanding families remain an application-time concern. */
|
||||
private void validateSymbolicBodies() {
|
||||
for (var source : sources) for (var template : source.ast().topDecls()) {
|
||||
if (!(template instanceof PbsAst.StructDecl || template instanceof PbsAst.FunctionDecl || template instanceof PbsAst.ImplementsDecl)
|
||||
|| parameters(template).isEmpty()) continue;
|
||||
budget.visit(template.span(), 0);
|
||||
var symbolicDiagnostics = DiagnosticSink.empty();
|
||||
var probe = new PbsGenericInstantiation(sources, symbolicDiagnostics, surface, budget);
|
||||
probe.symbolicProbe = true;
|
||||
var witnesses = new ArrayList<PbsAst.TopDecl>();
|
||||
var arguments = new ArrayList<PbsAst.TypeRef>();
|
||||
var presentation = new LinkedHashMap<String, String>();
|
||||
for (int i = 0; i < parameters(template).size(); i++) {
|
||||
var parameter = parameters(template).get(i);
|
||||
var name = "$symbol$"+PbsContractTypes.nominal(template)+":"+i;
|
||||
var witness = new PbsAst.StructDecl(name, ReadOnlyList.empty(), ReadOnlyList.empty(), ReadOnlyList.empty(), false, ReadOnlyList.empty(), parameter.span());
|
||||
witnesses.add(witness); probe.types.index(witness);
|
||||
arguments.add(PbsAst.TypeRef.simple(name, parameter.span()));
|
||||
presentation.put(name, parameter.name()); presentation.put(nominalBinding(witness), parameter.name());
|
||||
}
|
||||
String callableName = null;
|
||||
if (template instanceof PbsAst.FunctionDecl f) {
|
||||
var candidates = probe.lookup(f.name(), f.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl && parameters(d).size() == f.typeParameters().size()).toList();
|
||||
callableName = probe.functionGroup(candidates, ReadOnlyList.wrap(arguments));
|
||||
}
|
||||
Request request = null;
|
||||
List<PbsAst.TopDecl> current;
|
||||
if (template instanceof PbsAst.ImplementsDecl rule) {
|
||||
var env = probe.environment(rule, ReadOnlyList.wrap(arguments));
|
||||
var rewrite = probe.new ConcreteRewriter(env, null, List.of());
|
||||
var owner = rewrite.type(rule.ownerType());
|
||||
rewrite = probe.new ConcreteRewriter(env, owner, List.of());
|
||||
rewrite.implicitLocals = Map.of(rule.binderName(), owner);
|
||||
var target = rewrite.type(rule.contractType());
|
||||
probe.requiredShapes.add(target.name());
|
||||
var methods = PbsAstRewriter.map(rule.methods(), rewrite::function);
|
||||
current = List.of(new PbsAst.ImplementsDecl(ReadOnlyList.empty(), target, owner, rule.binderName(), methods, rule.span()));
|
||||
} else {
|
||||
request = probe.request(template, ReadOnlyList.wrap(arguments), template.span(), List.of(), callableName);
|
||||
if (request == null) continue;
|
||||
probe.pending.remove(request);
|
||||
probe.materialize(request);
|
||||
current = probe.concrete.values().stream().flatMap(Collection::stream).toList();
|
||||
}
|
||||
var supplemental = new ArrayList<PbsAst.TopDecl>(witnesses);
|
||||
var visible = new ArrayList<PbsAst.TopDecl>(source.visible().asList());
|
||||
visible.addAll(source.ast().topDecls().asList());
|
||||
var shapeKeys = new HashSet<String>();
|
||||
for (var declaration : visible) {
|
||||
String alias = null;
|
||||
if (declaration instanceof PbsAst.TypeBindingDecl b) { alias = b.name(); declaration = b.declaration(); }
|
||||
if (!parameters(declaration).isEmpty() || declaration instanceof PbsAst.ImplementsDecl) continue;
|
||||
var shape = probe.shapeRewriter(Map.of(), declaration instanceof PbsAst.StructDecl || declaration instanceof PbsAst.ServiceDecl
|
||||
? PbsAst.TypeRef.simple(name(declaration), declaration.span()) : null).declaration(declaration);
|
||||
if (shape instanceof PbsAst.FunctionDecl f && alias != null) shape = new PbsAst.FunctionDecl(alias, f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.lifecycleMarker(), f.body(), f.span());
|
||||
else if (alias != null) shape = new PbsAst.TypeBindingDecl(alias, shape, declaration.span());
|
||||
var shapeKey = name(shape)+":"+shape.span();
|
||||
if (shapeKeys.add(shapeKey)) supplemental.add(shape);
|
||||
}
|
||||
while (!probe.pending.isEmpty()) {
|
||||
var dependency = probe.pending.removeFirst();
|
||||
if (dependency == request) continue;
|
||||
var fullShape = dependency.template() instanceof PbsAst.FunctionDecl || probe.requiredShapes.contains(dependency.name());
|
||||
var shape = fullShape ? probe.concreteDeclaration(dependency, probe.shapeRewriter(
|
||||
probe.environment(dependency.template(), dependency.arguments()), PbsAst.TypeRef.simple(dependency.name(), dependency.template().span())))
|
||||
: probe.anchors.get(dependency.name());
|
||||
if (shape != null) { supplemental.add(shape); probe.types.index(shape); }
|
||||
}
|
||||
for (var bindings : probe.argumentBindings.values()) for (var binding : bindings.entrySet())
|
||||
supplemental.add(new PbsAst.TypeBindingDecl(binding.getKey(), binding.getValue(), template.span()));
|
||||
var ast = new PbsAst.File(source.ast().imports(), ReadOnlyList.wrap(current), source.ast().span());
|
||||
var supplementalList = ReadOnlyList.wrap(supplemental);
|
||||
new p.studio.compiler.pbs.semantics.PbsDeclarationSemanticsValidator(new p.studio.compiler.source.tables.NameTable()).validate(ast, symbolicDiagnostics);
|
||||
new p.studio.compiler.pbs.semantics.PbsFlowSemanticsValidator().validate(ast, supplementalList, surface, symbolicDiagnostics);
|
||||
for (var diagnostic : symbolicDiagnostics) if (diagnostic.getSeverity().isError()) {
|
||||
var message = diagnostic.getMessage();
|
||||
for (var entry : presentation.entrySet()) message = message.replace(entry.getKey(), entry.getValue());
|
||||
Diagnostics.error(diagnostics, diagnostic.getCode(), message, diagnostic.getSpan());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ConcreteRewriter shapeRewriter(Map<String, PbsAst.TypeRef> bindings, PbsAst.TypeRef owner) {
|
||||
return new ConcreteRewriter(bindings, owner, List.of()) {
|
||||
@Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) {
|
||||
return new PbsAst.FunctionDecl(f.name(), f.typeParameters(), map(f.parameters(), this::parameter), f.returnKind(), type(f.returnType()),
|
||||
type(f.resultErrorType()), f.attributes(), f.lifecycleMarker(), new PbsAst.Block(ReadOnlyList.empty(), null, f.body().span()), f.applicationOrigin(), f.span());
|
||||
}
|
||||
@Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) {
|
||||
return new PbsAst.CtorDecl(c.name(), map(c.parameters(), this::parameter), new PbsAst.Block(ReadOnlyList.empty(), null, c.body().span()), c.span());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private String functionGroup(List<PbsAst.TopDecl> candidates, ReadOnlyList<PbsAst.TypeRef> arguments) {
|
||||
return "$generic$fn$"+candidates.stream().map(PbsContractTypes::nominal).sorted().collect(Collectors.joining("$"))+
|
||||
"["+arguments.stream().map(types::key).map(k -> k.length()+":"+k).collect(Collectors.joining())+"]";
|
||||
}
|
||||
|
||||
private void checkCollisions(ReadOnlyList<PbsAst.FunctionDecl> methods, Request request) {
|
||||
var signatures = new HashMap<String, PbsAst.FunctionDecl>();
|
||||
for (var method : methods) {
|
||||
var shape = method.name()+":"+signatureKey(method);
|
||||
var previous = signatures.putIfAbsent(shape, method);
|
||||
if (previous != null) error("COLLISION", "Overloads collapse in "+request.origin().display()+": "+method.name()+
|
||||
"; declarations at "+previous.span()+" and "+method.span(), request.origin().requestedAt());
|
||||
}
|
||||
}
|
||||
|
||||
private void validateRules() {
|
||||
// Implemented below using bounded symbolic owner/target unification, independent of requested applications.
|
||||
new PbsGenericCoherence(this, diagnostics).validate(rules);
|
||||
}
|
||||
|
||||
private class ConcreteRewriter extends PbsAstRewriter {
|
||||
private final Map<String, PbsAst.TypeRef> bindings;
|
||||
private final PbsAst.TypeRef self;
|
||||
private final List<String> chain;
|
||||
private Map<String, PbsAst.TypeRef> locals = new HashMap<>();
|
||||
private Map<String, PbsAst.TypeRef> implicitLocals = Map.of();
|
||||
private PbsAst.TypeRef result;
|
||||
private PbsAst.TypeRef blockExpected;
|
||||
|
||||
private ConcreteRewriter(Map<String, PbsAst.TypeRef> bindings, PbsAst.TypeRef self, List<String> chain) {
|
||||
this.bindings = Map.copyOf(bindings); this.self = self; this.chain = chain;
|
||||
}
|
||||
|
||||
@Override public PbsAst.TopDecl declaration(PbsAst.TopDecl d) {
|
||||
if (self == null && (d instanceof PbsAst.StructDecl || d instanceof PbsAst.ServiceDecl))
|
||||
return new ConcreteRewriter(bindings, PbsAst.TypeRef.simple(name(d), d.span()), chain).declaration(d);
|
||||
return super.declaration(d);
|
||||
}
|
||||
|
||||
@Override public PbsAst.TypeRef type(PbsAst.TypeRef t) {
|
||||
if (t == null) return null;
|
||||
budget.visit(t.span(), chain.size());
|
||||
budget.store(t.span(), 64);
|
||||
if (t.kind() == PbsAst.TypeRefKind.SELF && self != null) return self;
|
||||
if (t.kind() == PbsAst.TypeRefKind.SIMPLE && bindings.containsKey(t.name())) {
|
||||
if (!t.arguments().isEmpty()) error("PARAMETER", "Type parameter cannot be applied", t.span());
|
||||
return bindings.get(t.name());
|
||||
}
|
||||
var rewritten = super.type(t);
|
||||
var declaration = types.declaration(rewritten);
|
||||
if (rewritten.kind() == PbsAst.TypeRefKind.SIMPLE && declaration != null && !parameters(declaration).isEmpty()) {
|
||||
var request = request(declaration, rewritten.arguments(), t.span(), chain, null);
|
||||
return request == null ? PbsAst.TypeRef.error(t.span()) : PbsAst.TypeRef.simple(request.name(), t.span());
|
||||
}
|
||||
return rewritten;
|
||||
}
|
||||
|
||||
@Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) {
|
||||
var previousLocals = locals; var previousResult = result;
|
||||
locals = new HashMap<>(implicitLocals);
|
||||
f.parameters().forEach(p -> locals.put(p.name(), type(p.typeRef())));
|
||||
result = type(f.returnType());
|
||||
try { return super.function(f); }
|
||||
finally { locals = previousLocals; result = previousResult; }
|
||||
}
|
||||
|
||||
@Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) {
|
||||
var previous = locals; var oldResult = result;
|
||||
locals = new HashMap<>();
|
||||
c.parameters().forEach(p -> locals.put(p.name(), type(p.typeRef())));
|
||||
result = null;
|
||||
try { return super.constructor(c); }
|
||||
finally { locals = previous; result = oldResult; }
|
||||
}
|
||||
|
||||
@Override public PbsAst.Block block(PbsAst.Block b) {
|
||||
if (b == null) return null;
|
||||
var previous = locals; locals = new HashMap<>(locals);
|
||||
try { return new PbsAst.Block(map(b.statements(), this::statement), expression(b.tailExpression(), blockExpected), b.span()); }
|
||||
finally { locals = previous; }
|
||||
}
|
||||
|
||||
@Override public PbsAst.Statement statement(PbsAst.Statement s) {
|
||||
budget.visit(s.span(), chain.size()); budget.store(s.span(), 64);
|
||||
if (s instanceof PbsAst.LetStatement l) {
|
||||
var expected = type(l.explicitType());
|
||||
var value = expression(l.initializer(), expected);
|
||||
locals.put(l.name(), expected == null ? infer(value) : expected);
|
||||
return new PbsAst.LetStatement(l.isConst(), l.name(), l.nameSpan(), expected, value, l.span());
|
||||
}
|
||||
if (s instanceof PbsAst.ReturnStatement r) return new PbsAst.ReturnStatement(expression(r.value(), result), r.span());
|
||||
if (s instanceof PbsAst.AssignStatement a) {
|
||||
var target = a.target().expression();
|
||||
var expected = target == null ? locals.get(a.target().rootName()) : infer(target);
|
||||
return new PbsAst.AssignStatement(a.target(), a.operator(), expression(a.value(), expected), a.span());
|
||||
}
|
||||
return super.statement(s);
|
||||
}
|
||||
|
||||
@Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) {
|
||||
if (e != null) { budget.visit(e.span(), chain.size()); budget.store(e.span(), 64); }
|
||||
if (e instanceof PbsAst.CallExpr c) {
|
||||
var callee = expression(c.callee());
|
||||
var signatures = callableSignatures(callee);
|
||||
var candidates = signatures.stream().filter(s -> s.parameters().size() == c.arguments().size()).toList();
|
||||
var arguments = new ArrayList<PbsAst.Expression>();
|
||||
for (int i = 0; i < c.arguments().size(); i++) arguments.add(expression(c.arguments().get(i),
|
||||
candidates.size() == 1 ? candidates.getFirst().parameters().get(i).typeRef() : null));
|
||||
return new PbsAst.CallExpr(callee, ReadOnlyList.wrap(arguments), c.span());
|
||||
}
|
||||
if (e instanceof PbsAst.ApplyExpr a) {
|
||||
var callee = expression(a.callee());
|
||||
var signatures = callableSignatures(callee);
|
||||
PbsAst.TypeRef argumentType = null;
|
||||
if (signatures.size() == 1) {
|
||||
var parameters = signatures.getFirst().parameters();
|
||||
argumentType = parameters.size() == 1 ? parameters.getFirst().typeRef()
|
||||
: PbsAst.TypeRef.namedTuple(map(parameters, p -> new PbsAst.NamedTypeField(p.name(), p.typeRef(), p.span())), a.span());
|
||||
}
|
||||
return new PbsAst.ApplyExpr(callee, expression(a.argument(), argumentType), a.span());
|
||||
}
|
||||
if (e instanceof PbsAst.LambdaExpr l) {
|
||||
var previous = locals; var oldResult = result;
|
||||
locals = new HashMap<>(locals);
|
||||
for (var p : l.parameters()) locals.put(p.name(), type(p.typeRef()));
|
||||
result = type(l.returnType());
|
||||
try { return super.expression(e, expected); }
|
||||
finally { locals = previous; result = oldResult; }
|
||||
}
|
||||
if (e instanceof PbsAst.SomeExpr s) return new PbsAst.SomeExpr(expression(s.value(),
|
||||
expected != null && expected.kind() == PbsAst.TypeRefKind.OPTIONAL ? expected.inner() : null), s.span());
|
||||
if (e instanceof PbsAst.OkExpr o) return new PbsAst.OkExpr(expression(o.value(), expected), o.span());
|
||||
if (e instanceof PbsAst.TupleExpr t && expected != null && expected.kind() == PbsAst.TypeRefKind.NAMED_TUPLE
|
||||
&& t.items().size() == expected.fields().size()) {
|
||||
var items = new ArrayList<PbsAst.TupleItem>();
|
||||
for (int i = 0; i < t.items().size(); i++) { var item = t.items().get(i);
|
||||
items.add(new PbsAst.TupleItem(item.label(), expression(item.expression(), expected.fields().get(i).typeRef()), item.span())); }
|
||||
return new PbsAst.TupleExpr(ReadOnlyList.wrap(items), t.span());
|
||||
}
|
||||
if (e instanceof PbsAst.BlockExpr || e instanceof PbsAst.IfExpr || e instanceof PbsAst.SwitchExpr || e instanceof PbsAst.HandleExpr) {
|
||||
var previous = blockExpected; blockExpected = expected;
|
||||
try { return super.expression(e, expected); } finally { blockExpected = previous; }
|
||||
}
|
||||
if (e instanceof PbsAst.IdentifierExpr i && i.applied()) {
|
||||
if (locals.containsKey(i.name())) {
|
||||
error("FUNCTION_ARGUMENTS", "Type arguments apply only to named generic free functions", i.span());
|
||||
return i;
|
||||
}
|
||||
var arguments = map(i.typeArguments(), this::type);
|
||||
var candidates = lookup(i.name(), i.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl &&
|
||||
!parameters(d).isEmpty() && parameters(d).size() == arguments.size()).toList();
|
||||
if (candidates.isEmpty()) { error("FUNCTION_ARITY", "No generic free function "+i.name()+" accepts "+arguments.size()+" type argument(s)", i.span()); return i; }
|
||||
var group = functionGroup(candidates, arguments);
|
||||
var signatures = new HashSet<String>();
|
||||
for (var candidate : candidates) {
|
||||
var request = request(candidate, arguments, i.span(), chain, group);
|
||||
if (request == null) continue;
|
||||
var original = (PbsAst.FunctionDecl) candidate;
|
||||
var env = environment(candidate, arguments);
|
||||
var substituted = new PbsAst.FunctionDecl(original.name(), map(original.parameters(), p ->
|
||||
new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span())), original.returnKind(),
|
||||
PbsTypeSubstitution.substitute(original.returnType(), env), PbsTypeSubstitution.substitute(original.resultErrorType(), env),
|
||||
original.attributes(), original.lifecycleMarker(), original.body(), original.span());
|
||||
var signature = signatureKey(substituted);
|
||||
if (!signatures.add(signature)) error("COLLISION", "Generic overload signatures collapse in "+i.name(), i.span());
|
||||
}
|
||||
return new PbsAst.IdentifierExpr(group, i.span());
|
||||
}
|
||||
if (e instanceof PbsAst.IdentifierExpr i && !i.applied() && !locals.containsKey(i.name())) {
|
||||
var functions = lookup(i.name(), i.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl).toList();
|
||||
if (!functions.isEmpty() && functions.stream().allMatch(d -> !parameters(d).isEmpty()))
|
||||
error("FUNCTION_ARGUMENTS", "Generic function "+i.name()+" requires explicit type arguments", i.span());
|
||||
}
|
||||
if (e instanceof PbsAst.NewExpr n && !n.typeName().equals("array")) {
|
||||
var raw = PbsAst.TypeRef.simple(n.typeName(), n.span());
|
||||
var declaration = types.declaration(raw);
|
||||
if (bindings.containsKey(n.typeName())) { error("CONSTRUCTION", "A type parameter has no implicit constructor", n.span()); return n; }
|
||||
if (declaration instanceof PbsAst.StructDecl s && !s.typeParameters().isEmpty()) {
|
||||
var applied = n.explicitType();
|
||||
if (applied == null) {
|
||||
var context = expected;
|
||||
while (context != null && context.kind() == PbsAst.TypeRefKind.GROUP) context = context.inner();
|
||||
var target = context == null ? null : types.declaration(context);
|
||||
var origin = PbsContractTypes.applicationOrigin(target);
|
||||
if (origin != null && origin.declaration() == declaration) applied = PbsAst.TypeRef.applied(n.typeName(), origin.arguments(), n.span());
|
||||
else if (context != null && target == declaration && !context.arguments().isEmpty()) applied = context;
|
||||
else { error("CONTEXT", "Construction of "+n.typeName()+" requires explicit arguments or an expected application", n.span()); return n; }
|
||||
}
|
||||
var concreteType = type(applied);
|
||||
if (symbolicProbe) requiredShapes.add(concreteType.name());
|
||||
var fields = constructorParameters(concreteType, n.ctorName());
|
||||
var arguments = new ArrayList<PbsAst.Expression>();
|
||||
for (int i = 0; i < n.arguments().size(); i++) arguments.add(expression(n.arguments().get(i),
|
||||
fields.size() == n.arguments().size() ? fields.get(i).typeRef() : null));
|
||||
return new PbsAst.NewExpr(concreteType.name(), n.ctorName(), ReadOnlyList.wrap(arguments), null, false, n.span());
|
||||
}
|
||||
}
|
||||
return super.expression(e, expected);
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef infer(PbsAst.Expression e) {
|
||||
return switch (e) {
|
||||
case PbsAst.IdentifierExpr i -> locals.get(i.name());
|
||||
case PbsAst.ThisExpr t -> self;
|
||||
case PbsAst.NewExpr n -> n.explicitType() != null ? n.explicitType() : PbsAst.TypeRef.simple(n.typeName(), n.span());
|
||||
case PbsAst.GroupExpr g -> infer(g.expression());
|
||||
case PbsAst.CallExpr c -> { var callables = callableSignatures(c.callee()); yield callables.size() == 1 ? callables.getFirst().returnType() : null; }
|
||||
case PbsAst.MemberExpr m -> {
|
||||
var receiver = infer(m.receiver());
|
||||
if (symbolicProbe && receiver != null) requiredShapes.add(receiver.name());
|
||||
var declaration = types.declaration(receiver);
|
||||
var origin = PbsContractTypes.applicationOrigin(declaration);
|
||||
if (origin != null) declaration = origin.declaration();
|
||||
if (declaration instanceof PbsAst.StructDecl s) {
|
||||
var field = s.fields().stream().filter(f -> f.name().equals(m.memberName())).findFirst();
|
||||
yield field.isEmpty() ? null : origin == null ? field.get().typeRef()
|
||||
: new ConcreteRewriter(environment(s, origin.arguments()), receiver, chain).type(field.get().typeRef());
|
||||
}
|
||||
yield null;
|
||||
}
|
||||
case null, default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private List<PbsAst.FunctionSignature> callableSignatures(PbsAst.Expression expression) {
|
||||
if (expression instanceof PbsAst.IdentifierExpr i) {
|
||||
var local = locals.get(i.name());
|
||||
if (local != null && local.kind() == PbsAst.TypeRefKind.FN) return List.of(new PbsAst.FunctionSignature(i.name(),
|
||||
map(local.fields(), f -> new PbsAst.Parameter(f.label(), f.typeRef(), f.span())), PbsAst.ReturnKind.PLAIN,
|
||||
local.inner(), null, ReadOnlyList.empty(), i.span()));
|
||||
var requests = instances.values().stream().filter(r -> r.name().equals(i.name()) && r.template() instanceof PbsAst.FunctionDecl).toList();
|
||||
if (!requests.isEmpty()) return requests.stream().map(r -> {
|
||||
var f = (PbsAst.FunctionDecl)r.template();
|
||||
return new ConcreteRewriter(environment(f, r.arguments()), null, r.chain()).signature(signature(f));
|
||||
}).toList();
|
||||
return lookup(i.name(), i.span()).stream().filter(d -> d instanceof PbsAst.FunctionDecl && parameters(d).isEmpty())
|
||||
.map(d -> signature((PbsAst.FunctionDecl)d)).toList();
|
||||
}
|
||||
if (expression instanceof PbsAst.MemberExpr member) {
|
||||
var receiver = infer(member.receiver());
|
||||
if (symbolicProbe && receiver != null) requiredShapes.add(receiver.name());
|
||||
var d = types.declaration(receiver);
|
||||
if (d == null && member.receiver() instanceof PbsAst.IdentifierExpr i)
|
||||
d = lookup(i.name(), i.span()).stream().findFirst().orElse(null);
|
||||
var origin = PbsContractTypes.applicationOrigin(d);
|
||||
if (origin != null) d = origin.declaration();
|
||||
var signatures = switch (d) {
|
||||
case PbsAst.StructDecl s -> s.methods().stream().map(this::signature).toList();
|
||||
case PbsAst.ServiceDecl s -> s.methods().stream().map(this::signature).toList();
|
||||
case PbsAst.ContractDecl c -> c.signatures().asList();
|
||||
case PbsAst.HostDecl h -> h.signatures().asList();
|
||||
case PbsAst.BuiltinTypeDecl b -> b.signatures().asList();
|
||||
case null, default -> List.<PbsAst.FunctionSignature>of();
|
||||
};
|
||||
var rewrite = origin == null ? this : new ConcreteRewriter(environment(d, origin.arguments()), receiver, chain);
|
||||
return signatures.stream().filter(s -> s.name().equals(member.memberName())).map(rewrite::signature).toList();
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private PbsAst.FunctionSignature signature(PbsAst.FunctionDecl f) {
|
||||
return new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span());
|
||||
}
|
||||
private ReadOnlyList<PbsAst.Parameter> constructorParameters(PbsAst.TypeRef owner, String constructor) {
|
||||
var d = types.declaration(owner);
|
||||
var origin = PbsContractTypes.applicationOrigin(d);
|
||||
if (origin != null) d = origin.declaration();
|
||||
if (!(d instanceof PbsAst.StructDecl s)) return ReadOnlyList.empty();
|
||||
var rewrite = origin == null ? this : new ConcreteRewriter(environment(s, origin.arguments()), owner, chain);
|
||||
if (constructor == null) return map(s.fields(), f -> new PbsAst.Parameter(f.name(), rewrite.type(f.typeRef()), f.span()));
|
||||
var candidates = s.ctors().stream().filter(c -> c.name().equals(constructor)).toList();
|
||||
return candidates.size() == 1 ? map(candidates.getFirst().parameters(), rewrite::parameter) : ReadOnlyList.empty();
|
||||
}
|
||||
}
|
||||
|
||||
void error(String suffix, String message, Span span) { Diagnostics.error(diagnostics, "E_SEM_GENERIC_"+suffix, message, span); }
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.ast.PbsAstRewriter;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
/** Checks template capabilities in their definition environment, before concrete specialization. */
|
||||
final class PbsGenericTemplateValidator {
|
||||
private static final Set<String> BUILTINS = Set.of("int", "long", "float", "bool", "str", "Addressable");
|
||||
private record Callable(ReadOnlyList<PbsAst.Parameter> parameters, PbsAst.TypeRef result) {}
|
||||
private final PbsGenericInstantiation context;
|
||||
PbsGenericTemplateValidator(PbsGenericInstantiation context, DiagnosticSink diagnostics) { this.context = context; }
|
||||
|
||||
void validate(List<PbsGenericInstantiation.Source> sources) {
|
||||
for (var source : sources) for (var d : source.ast().topDecls()) {
|
||||
if (PbsGenericInstantiation.parameters(d).isEmpty()) continue;
|
||||
var body = new SymbolicBody(d);
|
||||
body.declaration(d);
|
||||
}
|
||||
}
|
||||
|
||||
private final class SymbolicBody extends PbsAstRewriter {
|
||||
private final Set<String> parameters;
|
||||
private final PbsAst.TypeRef owner;
|
||||
private Map<String, PbsAst.TypeRef> locals = new HashMap<>();
|
||||
private final IdentityHashMap<PbsAst.Expression, PbsAst.TypeRef> inferred = new IdentityHashMap<>();
|
||||
private PbsAst.TypeRef result;
|
||||
private boolean selfAllowed;
|
||||
|
||||
SymbolicBody(PbsAst.TopDecl template) {
|
||||
parameters = new HashSet<>(PbsGenericInstantiation.parameters(template).stream().map(PbsAst.TypeParameter::name).toList());
|
||||
owner = switch (template) {
|
||||
case PbsAst.StructDecl s -> PbsAst.TypeRef.applied(s.name(), map(s.typeParameters(), p -> PbsAst.TypeRef.simple(p.name(), p.span())), s.span());
|
||||
case PbsAst.ImplementsDecl i -> i.ownerType();
|
||||
default -> null;
|
||||
};
|
||||
if (template instanceof PbsAst.ImplementsDecl i) locals.put(i.binderName(), i.ownerType());
|
||||
}
|
||||
|
||||
@Override public PbsAst.TypeRef type(PbsAst.TypeRef t) {
|
||||
if (t == null) return null;
|
||||
context.budget().visit(t.span(), 0);
|
||||
if (t.kind() == PbsAst.TypeRefKind.SELF && !selfAllowed)
|
||||
context.error("SELF", "Self is only valid in existing owner method/constructor scopes", t.span());
|
||||
if (t.kind() == PbsAst.TypeRefKind.ARRAY && t.inner() != null &&
|
||||
(t.inner().kind() == PbsAst.TypeRefKind.OPTIONAL || t.inner().kind() == PbsAst.TypeRefKind.UNIT))
|
||||
context.error("POSITION", "Array elements must be non-optional value types", t.span());
|
||||
if (t.kind() == PbsAst.TypeRefKind.SIMPLE) {
|
||||
if (parameters.contains(t.name())) {
|
||||
if (!t.arguments().isEmpty()) context.error("PARAMETER", "Type parameter cannot be applied", t.span());
|
||||
} else {
|
||||
var declaration = context.declaration(t);
|
||||
if (declaration == null && !BUILTINS.contains(t.name())) context.error("PARAMETER", "Unresolved type or undeclared parameter "+t.name(), t.span());
|
||||
else if (declaration != null && PbsGenericInstantiation.parameters(declaration).size() != t.arguments().size())
|
||||
context.error("ARITY", "Type application requires the declaration's exact explicit arity", t.span());
|
||||
}
|
||||
}
|
||||
return super.type(t);
|
||||
}
|
||||
|
||||
@Override public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) {
|
||||
var previous = locals; var oldResult = result;
|
||||
var previousSelf = selfAllowed; selfAllowed = owner != null;
|
||||
locals = new HashMap<>(locals);
|
||||
for (var p : f.parameters()) locals.put(p.name(), p.typeRef());
|
||||
result = f.returnType();
|
||||
try { return super.function(f); }
|
||||
finally { locals = previous; result = oldResult; selfAllowed = previousSelf; }
|
||||
}
|
||||
|
||||
@Override public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) {
|
||||
var previous = locals;
|
||||
var previousSelf = selfAllowed; selfAllowed = owner != null;
|
||||
locals = new HashMap<>(locals);
|
||||
for (var p : c.parameters()) locals.put(p.name(), p.typeRef());
|
||||
try { return super.constructor(c); }
|
||||
finally { locals = previous; selfAllowed = previousSelf; }
|
||||
}
|
||||
|
||||
@Override public PbsAst.Block block(PbsAst.Block b) {
|
||||
var previous = locals; locals = new HashMap<>(locals);
|
||||
try { return super.block(b); } finally { locals = previous; }
|
||||
}
|
||||
|
||||
@Override public PbsAst.Statement statement(PbsAst.Statement s) {
|
||||
if (s instanceof PbsAst.LetStatement l) {
|
||||
var actual = infer(l.initializer(), l.explicitType());
|
||||
checkCompatible(actual, l.explicitType(), l.span());
|
||||
locals.put(l.name(), l.explicitType() == null ? actual : l.explicitType());
|
||||
} else if (s instanceof PbsAst.ReturnStatement r) checkCompatible(infer(r.value(), result), result, r.span());
|
||||
else if (s instanceof PbsAst.AssignStatement a) {
|
||||
var target = a.target().expression() == null ? locals.get(a.target().rootName()) : infer(a.target().expression(), null);
|
||||
checkCompatible(infer(a.value(), target), target, a.span());
|
||||
if (a.operator() != PbsAst.AssignOperator.ASSIGN && symbolic(target)) capability(a.span());
|
||||
}
|
||||
return super.statement(s);
|
||||
}
|
||||
|
||||
@Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) {
|
||||
if (e == null) return null;
|
||||
infer(e, expected);
|
||||
if (e instanceof PbsAst.LambdaExpr l) {
|
||||
var previous = locals; var oldResult = result;
|
||||
locals = new HashMap<>(locals);
|
||||
for (var p : l.parameters()) locals.put(p.name(), p.typeRef());
|
||||
result = l.returnType();
|
||||
try { return super.expression(e, expected); }
|
||||
finally { locals = previous; result = oldResult; }
|
||||
}
|
||||
return super.expression(e, expected);
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef infer(PbsAst.Expression e, PbsAst.TypeRef expected) {
|
||||
if (e == null) return null;
|
||||
if (inferred.containsKey(e)) return inferred.get(e);
|
||||
context.budget().visit(e.span(), 0);
|
||||
var type = inferBody(e, expected);
|
||||
inferred.put(e, type);
|
||||
return type;
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef inferBody(PbsAst.Expression e, PbsAst.TypeRef expected) {
|
||||
return switch (e) {
|
||||
case PbsAst.IdentifierExpr i -> {
|
||||
if (locals.containsKey(i.name())) {
|
||||
if (i.applied()) context.error("FUNCTION", "Only a generic free function accepts type arguments", i.span());
|
||||
yield locals.get(i.name());
|
||||
}
|
||||
var candidates = functions(i);
|
||||
if (candidates.size() == 1) {
|
||||
var callable = candidates.getFirst();
|
||||
yield PbsAst.TypeRef.function(map(callable.parameters(), p -> new PbsAst.NamedTypeField(null, p.typeRef(), p.span())), callable.result(), i.span());
|
||||
}
|
||||
yield null;
|
||||
}
|
||||
case PbsAst.ThisExpr t -> owner;
|
||||
case PbsAst.IntLiteralExpr i -> PbsAst.TypeRef.simple("int", e.span());
|
||||
case PbsAst.FloatLiteralExpr f -> PbsAst.TypeRef.simple("float", e.span());
|
||||
case PbsAst.BoolLiteralExpr b -> PbsAst.TypeRef.simple("bool", e.span());
|
||||
case PbsAst.StringLiteralExpr s -> PbsAst.TypeRef.simple("str", e.span());
|
||||
case PbsAst.BoundedLiteralExpr b -> PbsAst.TypeRef.simple("int", e.span());
|
||||
case PbsAst.NewExpr n -> {
|
||||
if (parameters.contains(n.typeName())) capability(n.span());
|
||||
var result = n.explicitType() == null ? expected == null ? PbsAst.TypeRef.simple(n.typeName(), n.span()) : expected : n.explicitType();
|
||||
var d = context.declaration(result);
|
||||
if (d != null && !PbsGenericInstantiation.parameters(d).isEmpty() && result.arguments().isEmpty())
|
||||
context.error("CONTEXT", "Generic construction requires an expected application or explicit type arguments", n.span());
|
||||
if (d instanceof PbsAst.StructDecl s) {
|
||||
var env = bindings(s, result);
|
||||
var expectedParameters = n.ctorName() == null ? map(s.fields(), f -> new PbsAst.Parameter(f.name(), PbsTypeSubstitution.substitute(f.typeRef(), env), f.span()))
|
||||
: s.ctors().stream().filter(c -> c.name().equals(n.ctorName())).findFirst().map(c ->
|
||||
map(c.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span()))).orElse(ReadOnlyList.empty());
|
||||
checkArguments(n.arguments(), List.of(new Callable(expectedParameters, result)), n.span());
|
||||
}
|
||||
yield result;
|
||||
}
|
||||
case PbsAst.MemberExpr m -> {
|
||||
var receiver = infer(m.receiver(), null);
|
||||
if (symbolic(receiver)) { capability(m.span()); yield null; }
|
||||
var d = context.declaration(receiver);
|
||||
if (d instanceof PbsAst.StructDecl s) {
|
||||
var env = bindings(s, receiver);
|
||||
var field = s.fields().stream().filter(f -> f.name().equals(m.memberName())).findFirst();
|
||||
if (field.isPresent()) yield PbsTypeSubstitution.substitute(field.get().typeRef(), env);
|
||||
}
|
||||
if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY && m.memberName().equals("length")) yield PbsAst.TypeRef.simple("long", m.span());
|
||||
yield null;
|
||||
}
|
||||
case PbsAst.CallExpr c -> {
|
||||
var candidates = callables(c.callee());
|
||||
yield checkArguments(c.arguments(), candidates, c.span());
|
||||
}
|
||||
case PbsAst.ApplyExpr a -> {
|
||||
var candidates = callables(a.callee());
|
||||
var args = a.argument() instanceof PbsAst.TupleExpr t ? map(t.items(), PbsAst.TupleItem::expression)
|
||||
: a.argument() instanceof PbsAst.UnitExpr ? ReadOnlyList.<PbsAst.Expression>empty() : ReadOnlyList.wrap(List.of(a.argument()));
|
||||
yield checkArguments(args, candidates, a.span());
|
||||
}
|
||||
case PbsAst.BinaryExpr b -> {
|
||||
var left = infer(b.left(), null); var right = infer(b.right(), null);
|
||||
if (containsParameter(left) || containsParameter(right)) capability(b.span());
|
||||
yield Set.of("==", "!=", "<", ">", "<=", ">=", "and", "or", "&&", "||").contains(b.operator())
|
||||
? PbsAst.TypeRef.simple("bool", b.span()) : left;
|
||||
}
|
||||
case PbsAst.UnaryExpr u -> { var value = infer(u.expression(), null); if (containsParameter(value)) capability(u.span()); yield value; }
|
||||
case PbsAst.IndexExpr i -> {
|
||||
var receiver = infer(i.receiver(), null);
|
||||
yield receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY ? PbsAst.TypeRef.optional(receiver.inner(), i.span()) : null;
|
||||
}
|
||||
case PbsAst.GroupExpr g -> infer(g.expression(), expected);
|
||||
case PbsAst.SomeExpr s -> { var value = infer(s.value(), expected == null ? null : expected.inner()); yield value == null ? null : PbsAst.TypeRef.optional(value, s.span()); }
|
||||
case PbsAst.NoneExpr n -> expected;
|
||||
case PbsAst.ElseExpr x -> { var optional = infer(x.optionalExpression(), null); yield optional == null ? infer(x.fallbackExpression(), expected) : optional.inner(); }
|
||||
case PbsAst.AsExpr a -> { if (symbolic(infer(a.expression(), null))) capability(a.span()); yield a.contractType(); }
|
||||
case PbsAst.TupleExpr t -> PbsAst.TypeRef.namedTuple(map(t.items(), i -> new PbsAst.NamedTypeField(i.label(), infer(i.expression(), null), i.span())), t.span());
|
||||
case PbsAst.LambdaExpr l -> l.functionType();
|
||||
case PbsAst.ArrayLiteralExpr a -> a.elements().isEmpty() ? expected : PbsAst.TypeRef.array(infer(a.elements().getFirst(), null), a.span());
|
||||
case PbsAst.BlockExpr b -> b.block().tailExpression() == null ? expected : infer(b.block().tailExpression(), expected);
|
||||
case PbsAst.IfExpr i -> expected;
|
||||
case PbsAst.SwitchExpr s -> expected;
|
||||
case PbsAst.HandleExpr h -> expected;
|
||||
case PbsAst.PropagateExpr p -> { var value = infer(p.expression(), null); yield value == null ? null : value.inner(); }
|
||||
case PbsAst.OkExpr o -> infer(o.value(), expected);
|
||||
case PbsAst.ErrExpr x -> expected;
|
||||
case PbsAst.UnitExpr u -> PbsAst.TypeRef.unit(u.span());
|
||||
};
|
||||
}
|
||||
|
||||
private List<Callable> functions(PbsAst.IdentifierExpr identifier) {
|
||||
var result = new ArrayList<Callable>();
|
||||
boolean genericSeen = false;
|
||||
for (var d : context.lookup(identifier.name(), identifier.span())) {
|
||||
if (!(d instanceof PbsAst.FunctionDecl f)) continue;
|
||||
genericSeen |= !f.typeParameters().isEmpty();
|
||||
if (identifier.applied() == f.typeParameters().isEmpty()) continue;
|
||||
if (identifier.applied() && f.typeParameters().size() != identifier.typeArguments().size()) continue;
|
||||
var env = new HashMap<String, PbsAst.TypeRef>();
|
||||
for (int i = 0; i < f.typeParameters().size(); i++) env.put(f.typeParameters().get(i).name(), identifier.typeArguments().get(i));
|
||||
result.add(new Callable(map(f.parameters(), p -> new PbsAst.Parameter(p.name(), PbsTypeSubstitution.substitute(p.typeRef(), env), p.span())),
|
||||
PbsTypeSubstitution.substitute(f.returnType(), env)));
|
||||
}
|
||||
if (result.isEmpty() && (genericSeen || identifier.applied())) context.error("FUNCTION_ARITY", "Generic free-function references require explicit arguments of exact arity", identifier.span());
|
||||
return result;
|
||||
}
|
||||
|
||||
private List<Callable> callables(PbsAst.Expression callee) {
|
||||
if (callee instanceof PbsAst.IdentifierExpr i && !locals.containsKey(i.name())) return functions(i);
|
||||
if (callee instanceof PbsAst.MemberExpr m) {
|
||||
var receiver = infer(m.receiver(), null);
|
||||
if (symbolic(receiver)) { capability(m.span()); return List.of(); }
|
||||
var d = context.declaration(receiver);
|
||||
if (d == null && m.receiver() instanceof PbsAst.IdentifierExpr i) d = context.lookup(i.name(), i.span()).stream().findFirst().orElse(null);
|
||||
var signatures = new ArrayList<PbsAst.FunctionSignature>();
|
||||
if (d instanceof PbsAst.ContractDecl c) signatures.addAll(c.signatures().asList());
|
||||
if (d instanceof PbsAst.StructDecl s) for (var f : s.methods()) signatures.add(signature(f));
|
||||
if (d instanceof PbsAst.ServiceDecl s) for (var f : s.methods()) signatures.add(signature(f));
|
||||
if (d instanceof PbsAst.HostDecl h) signatures.addAll(h.signatures().asList());
|
||||
if (d instanceof PbsAst.BuiltinTypeDecl b) signatures.addAll(b.signatures().asList());
|
||||
var env = bindings(d, receiver);
|
||||
var methods = signatures.stream().filter(s -> s.name().equals(m.memberName())).map(s -> {
|
||||
var substituted = PbsTypeSubstitution.substitute(s, env); return new Callable(substituted.parameters(), substituted.returnType());
|
||||
}).toList();
|
||||
if (!methods.isEmpty()) return methods;
|
||||
}
|
||||
var type = infer(callee, null);
|
||||
if (type != null && type.kind() == PbsAst.TypeRefKind.FN) return List.of(new Callable(map(type.fields(), f -> new PbsAst.Parameter(f.label(), f.typeRef(), f.span())), type.inner()));
|
||||
return List.of();
|
||||
}
|
||||
private PbsAst.FunctionSignature signature(PbsAst.FunctionDecl f) {
|
||||
return new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span());
|
||||
}
|
||||
private Map<String, PbsAst.TypeRef> bindings(PbsAst.TopDecl declaration, PbsAst.TypeRef applied) {
|
||||
var result = new HashMap<String, PbsAst.TypeRef>();
|
||||
if (applied != null && PbsGenericInstantiation.parameters(declaration).size() == applied.arguments().size())
|
||||
for (int i = 0; i < applied.arguments().size(); i++) result.put(PbsGenericInstantiation.parameters(declaration).get(i).name(), applied.arguments().get(i));
|
||||
return result;
|
||||
}
|
||||
private PbsAst.TypeRef checkArguments(ReadOnlyList<PbsAst.Expression> arguments, List<Callable> candidates, Span site) {
|
||||
var actual = arguments.stream().map(a -> infer(a, null)).toList();
|
||||
var arity = candidates.stream().filter(c -> c.parameters().size() == actual.size()).toList();
|
||||
var matches = arity.stream().filter(c -> {
|
||||
for (int i = 0; i < actual.size(); i++) if (!compatible(actual.get(i), c.parameters().get(i).typeRef())) return false;
|
||||
return true;
|
||||
}).toList();
|
||||
if (matches.isEmpty() && actual.stream().anyMatch(this::containsParameter)) context.error("SYMBOLIC_CALL", "No callable accepts these symbolic arguments in the definition scope", site);
|
||||
return matches.size() == 1 ? matches.getFirst().result() : null;
|
||||
}
|
||||
private boolean compatible(PbsAst.TypeRef actual, PbsAst.TypeRef expected) {
|
||||
if (actual != null && actual.kind() == PbsAst.TypeRefKind.SELF) actual = owner;
|
||||
if (expected != null && expected.kind() == PbsAst.TypeRefKind.SELF) expected = owner;
|
||||
if (actual == null || expected == null || (!containsParameter(actual) && !containsParameter(expected))) return true;
|
||||
return context.key(actual).equals(context.key(expected));
|
||||
}
|
||||
private void checkCompatible(PbsAst.TypeRef actual, PbsAst.TypeRef expected, Span site) {
|
||||
if (!compatible(actual, expected)) context.error("SYMBOLIC_TYPE", "Value does not match the declared symbolic type", site);
|
||||
}
|
||||
private boolean symbolic(PbsAst.TypeRef t) { return t != null && t.kind() == PbsAst.TypeRefKind.SIMPLE && parameters.contains(t.name()); }
|
||||
private boolean containsParameter(PbsAst.TypeRef t) {
|
||||
if (t == null) return false;
|
||||
if (symbolic(t) || containsParameter(t.inner())) return true;
|
||||
return t.arguments().stream().anyMatch(this::containsParameter) || t.fields().stream().anyMatch(f -> containsParameter(f.typeRef()));
|
||||
}
|
||||
private void capability(Span site) { context.error("CAPABILITY", "This operation is not justified for an unconstrained type parameter", site); }
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.diagnostics.Diagnostics;
|
||||
|
||||
/** One budget for the interacting type, callable and coherence graphs. Provider limits remain unchanged. */
|
||||
public final class PbsInstantiationBudget {
|
||||
public static final int MAX_DEPTH = 256;
|
||||
public static final int MAX_INSTANCES = 65_536;
|
||||
private static final int MAX_WORK = 1_048_576;
|
||||
private static final long MAX_STORAGE = 64L * 1024 * 1024;
|
||||
private final DiagnosticSink diagnostics;
|
||||
private long storage;
|
||||
private int work;
|
||||
private int instances;
|
||||
private p.studio.compiler.pbs.ast.PbsAst.ApplicationOrigin origin;
|
||||
|
||||
public PbsInstantiationBudget(DiagnosticSink diagnostics) { this.diagnostics = diagnostics; }
|
||||
public void origin(p.studio.compiler.pbs.ast.PbsAst.ApplicationOrigin origin) { this.origin = origin; }
|
||||
public void visit(Span span, int depth) {
|
||||
if (depth > MAX_DEPTH || ++work > MAX_WORK) fail(span, "Generic expansion exceeds bounded analysis depth/work");
|
||||
}
|
||||
public void instance(Span span) {
|
||||
visit(span, 0);
|
||||
if (++instances > MAX_INSTANCES) fail(span, "Generic application graph exceeds the type/callable budget");
|
||||
}
|
||||
public void store(Span span, long size) {
|
||||
if (size < 0 || size > MAX_STORAGE - storage) fail(span, "Generic identity/substitution storage budget exceeded");
|
||||
storage += size;
|
||||
}
|
||||
private void fail(Span span, String message) {
|
||||
Diagnostics.error(PbsGenericDiagnostics.forOrigin(origin, diagnostics), "E_SEM_GENERIC_EXPANSION", message, span);
|
||||
throw new Exhausted();
|
||||
}
|
||||
public static final class Exhausted extends RuntimeException {
|
||||
public Exhausted() { super(null, null, false, false); }
|
||||
}
|
||||
}
|
||||
+55
-1
@@ -136,6 +136,7 @@ public final class PbsAst {
|
||||
|
||||
public record FunctionDecl(
|
||||
String name,
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
ReadOnlyList<Parameter> parameters,
|
||||
ReturnKind returnKind,
|
||||
TypeRef returnType,
|
||||
@@ -143,17 +144,39 @@ public final class PbsAst {
|
||||
ReadOnlyList<Attribute> attributes,
|
||||
LifecycleMarker lifecycleMarker,
|
||||
Block body,
|
||||
ApplicationOrigin applicationOrigin,
|
||||
Span span) implements TopDecl {
|
||||
public FunctionDecl(String name, ReadOnlyList<TypeParameter> typeParameters, ReadOnlyList<Parameter> parameters,
|
||||
ReturnKind returnKind, TypeRef returnType, TypeRef resultErrorType, ReadOnlyList<Attribute> attributes,
|
||||
LifecycleMarker lifecycleMarker, Block body, Span span) {
|
||||
this(name, typeParameters, parameters, returnKind, returnType, resultErrorType, attributes, lifecycleMarker, body, null, span);
|
||||
}
|
||||
public FunctionDecl(String name, ReadOnlyList<Parameter> parameters, ReturnKind returnKind,
|
||||
TypeRef returnType, TypeRef resultErrorType, ReadOnlyList<Attribute> attributes,
|
||||
LifecycleMarker lifecycleMarker, Block body, Span span) {
|
||||
this(name, ReadOnlyList.empty(), parameters, returnKind, returnType, resultErrorType, attributes, lifecycleMarker, body, span);
|
||||
}
|
||||
}
|
||||
|
||||
public record StructDecl(
|
||||
String name,
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
ReadOnlyList<StructField> fields,
|
||||
ReadOnlyList<FunctionDecl> methods,
|
||||
ReadOnlyList<CtorDecl> ctors,
|
||||
boolean hasBody,
|
||||
ReadOnlyList<Attribute> attributes,
|
||||
ApplicationOrigin applicationOrigin,
|
||||
Span span) implements TopDecl {
|
||||
public StructDecl(String name, ReadOnlyList<TypeParameter> typeParameters, ReadOnlyList<StructField> fields,
|
||||
ReadOnlyList<FunctionDecl> methods, ReadOnlyList<CtorDecl> ctors, boolean hasBody,
|
||||
ReadOnlyList<Attribute> attributes, Span span) {
|
||||
this(name, typeParameters, fields, methods, ctors, hasBody, attributes, null, span);
|
||||
}
|
||||
public StructDecl(String name, ReadOnlyList<StructField> fields, ReadOnlyList<FunctionDecl> methods,
|
||||
ReadOnlyList<CtorDecl> ctors, boolean hasBody, ReadOnlyList<Attribute> attributes, Span span) {
|
||||
this(name, ReadOnlyList.empty(), fields, methods, ctors, hasBody, attributes, span);
|
||||
}
|
||||
}
|
||||
|
||||
public record ContractDecl(
|
||||
@@ -161,7 +184,12 @@ public final class PbsAst {
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
ReadOnlyList<FunctionSignature> signatures,
|
||||
ReadOnlyList<Attribute> attributes,
|
||||
ApplicationOrigin applicationOrigin,
|
||||
Span span) implements TopDecl {
|
||||
public ContractDecl(String name, ReadOnlyList<TypeParameter> typeParameters, ReadOnlyList<FunctionSignature> signatures,
|
||||
ReadOnlyList<Attribute> attributes, Span span) {
|
||||
this(name, typeParameters, signatures, attributes, null, span);
|
||||
}
|
||||
public ContractDecl(String name, ReadOnlyList<FunctionSignature> signatures,
|
||||
ReadOnlyList<Attribute> attributes, Span span) {
|
||||
this(name, ReadOnlyList.empty(), signatures, attributes, span);
|
||||
@@ -170,6 +198,14 @@ public final class PbsAst {
|
||||
|
||||
public record TypeParameter(String name, Span span) {}
|
||||
|
||||
/** Logical application identity and source provenance; never a runtime template descriptor. */
|
||||
public record ApplicationOrigin(TopDecl declaration, ReadOnlyList<TypeRef> arguments, String key,
|
||||
String display, Span requestedAt, ReadOnlyList<String> chain) {
|
||||
public ApplicationOrigin(TopDecl declaration, ReadOnlyList<TypeRef> arguments, String key, String display, Span requestedAt) {
|
||||
this(declaration, arguments, key, display, requestedAt, ReadOnlyList.wrap(java.util.List.of(display)));
|
||||
}
|
||||
}
|
||||
|
||||
/** Imported lexical binding; retains the original declaration and the importing source scope. */
|
||||
public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {}
|
||||
|
||||
@@ -232,16 +268,22 @@ public final class PbsAst {
|
||||
}
|
||||
|
||||
public record ImplementsDecl(
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
TypeRef contractType,
|
||||
String ownerName,
|
||||
TypeRef ownerType,
|
||||
String binderName,
|
||||
ReadOnlyList<FunctionDecl> methods,
|
||||
Span span) implements TopDecl {
|
||||
public ImplementsDecl(TypeRef contractType, String ownerName, String binderName,
|
||||
ReadOnlyList<FunctionDecl> methods, Span span) {
|
||||
this(ReadOnlyList.empty(), contractType, TypeRef.simple(ownerName, span), binderName, methods, span);
|
||||
}
|
||||
public ImplementsDecl(String contractName, String ownerName, String binderName,
|
||||
ReadOnlyList<FunctionDecl> methods, Span span) {
|
||||
this(TypeRef.simple(contractName, span), ownerName, binderName, methods, span);
|
||||
}
|
||||
public String contractName() { return contractType.surface(); }
|
||||
public String ownerName() { return ownerType.surface(); }
|
||||
}
|
||||
|
||||
public record InvalidDecl(
|
||||
@@ -498,7 +540,10 @@ public final class PbsAst {
|
||||
|
||||
public record IdentifierExpr(
|
||||
String name,
|
||||
ReadOnlyList<TypeRef> typeArguments,
|
||||
boolean applied,
|
||||
Span span) implements Expression {
|
||||
public IdentifierExpr(String name, Span span) { this(name, ReadOnlyList.empty(), false, span); }
|
||||
}
|
||||
|
||||
public record IntLiteralExpr(
|
||||
@@ -754,17 +799,26 @@ public final class PbsAst {
|
||||
public record BarrelFunctionItem(
|
||||
Visibility visibility,
|
||||
String name,
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
ReadOnlyList<TypeRef> parameterTypes,
|
||||
ReturnKind returnKind,
|
||||
TypeRef returnType,
|
||||
TypeRef resultErrorType,
|
||||
Span span) implements BarrelItem {
|
||||
public BarrelFunctionItem(Visibility visibility, String name, ReadOnlyList<TypeRef> parameterTypes,
|
||||
ReturnKind returnKind, TypeRef returnType, TypeRef resultErrorType, Span span) {
|
||||
this(visibility, name, ReadOnlyList.empty(), parameterTypes, returnKind, returnType, resultErrorType, span);
|
||||
}
|
||||
}
|
||||
|
||||
public record BarrelStructItem(
|
||||
Visibility visibility,
|
||||
String name,
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
Span span) implements BarrelItem {
|
||||
public BarrelStructItem(Visibility visibility, String name, Span span) {
|
||||
this(visibility, name, ReadOnlyList.empty(), span);
|
||||
}
|
||||
}
|
||||
|
||||
public record BarrelContractItem(
|
||||
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package p.studio.compiler.pbs.ast;
|
||||
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.function.Function;
|
||||
|
||||
/** Exhaustive, source-preserving structural rewrite of all executable type positions. */
|
||||
public class PbsAstRewriter {
|
||||
public static <A, B> ReadOnlyList<B> map(ReadOnlyList<A> values, Function<A, B> transform) {
|
||||
return ReadOnlyList.wrap(values.stream().map(transform).toList());
|
||||
}
|
||||
|
||||
public PbsAst.TypeRef type(PbsAst.TypeRef t) {
|
||||
if (t == null) return null;
|
||||
return new PbsAst.TypeRef(t.kind(), t.name(), map(t.fields(), f ->
|
||||
new PbsAst.NamedTypeField(f.label(), type(f.typeRef()), f.span())), type(t.inner()), map(t.arguments(), this::type), t.span());
|
||||
}
|
||||
|
||||
public PbsAst.Parameter parameter(PbsAst.Parameter p) { return new PbsAst.Parameter(p.name(), type(p.typeRef()), p.span()); }
|
||||
public PbsAst.FunctionSignature signature(PbsAst.FunctionSignature s) {
|
||||
return new PbsAst.FunctionSignature(s.name(), map(s.parameters(), this::parameter), s.returnKind(), type(s.returnType()),
|
||||
type(s.resultErrorType()), s.attributes(), s.span());
|
||||
}
|
||||
public PbsAst.FunctionDecl function(PbsAst.FunctionDecl f) {
|
||||
return new PbsAst.FunctionDecl(f.name(), f.typeParameters(), map(f.parameters(), this::parameter), f.returnKind(), type(f.returnType()),
|
||||
type(f.resultErrorType()), f.attributes(), f.lifecycleMarker(), block(f.body()), f.applicationOrigin(), f.span());
|
||||
}
|
||||
public PbsAst.CtorDecl constructor(PbsAst.CtorDecl c) {
|
||||
return new PbsAst.CtorDecl(c.name(), map(c.parameters(), this::parameter), block(c.body()), c.span());
|
||||
}
|
||||
public PbsAst.TopDecl declaration(PbsAst.TopDecl d) {
|
||||
return switch (d) {
|
||||
case PbsAst.FunctionDecl f -> function(f);
|
||||
case PbsAst.StructDecl s -> new PbsAst.StructDecl(s.name(), s.typeParameters(), map(s.fields(), f ->
|
||||
new PbsAst.StructField(f.name(), type(f.typeRef()), f.isPublic(), f.isMutable(), f.span())),
|
||||
map(s.methods(), this::function), map(s.ctors(), this::constructor), s.hasBody(), s.attributes(), s.applicationOrigin(), s.span());
|
||||
case PbsAst.ContractDecl c -> new PbsAst.ContractDecl(c.name(), c.typeParameters(), map(c.signatures(), this::signature), c.attributes(), c.applicationOrigin(), c.span());
|
||||
case PbsAst.ImplementsDecl i -> new PbsAst.ImplementsDecl(i.typeParameters(), type(i.contractType()), type(i.ownerType()),
|
||||
i.binderName(), map(i.methods(), this::function), i.span());
|
||||
case PbsAst.ServiceDecl s -> new PbsAst.ServiceDecl(s.name(), map(s.methods(), this::function),
|
||||
map(s.constants(), c -> (PbsAst.ConstDecl) declaration(c)), s.attributes(), s.span());
|
||||
case PbsAst.HostDecl h -> new PbsAst.HostDecl(h.name(), map(h.signatures(), this::signature), h.attributes(), h.span());
|
||||
case PbsAst.BuiltinTypeDecl b -> new PbsAst.BuiltinTypeDecl(b.name(), map(b.fields(), f ->
|
||||
new PbsAst.BuiltinFieldDecl(f.name(), type(f.typeRef()), f.isPublic(), f.attributes(), f.span())),
|
||||
map(b.signatures(), this::signature), b.attributes(), b.span());
|
||||
case PbsAst.GlobalDecl g -> new PbsAst.GlobalDecl(g.name(), type(g.explicitType()), expression(g.initializer(), type(g.explicitType())), g.span());
|
||||
case PbsAst.ConstDecl c -> new PbsAst.ConstDecl(c.name(), type(c.explicitType()), expression(c.initializer(), type(c.explicitType())), c.attributes(), c.span());
|
||||
case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span());
|
||||
case PbsAst.EnumDecl e -> e;
|
||||
case PbsAst.ErrorDecl e -> e;
|
||||
case PbsAst.InvalidDecl i -> i;
|
||||
};
|
||||
}
|
||||
public PbsAst.File file(PbsAst.File f) { return new PbsAst.File(f.imports(), map(f.topDecls(), this::declaration), f.span()); }
|
||||
public PbsAst.Block block(PbsAst.Block b) {
|
||||
return b == null ? null : new PbsAst.Block(map(b.statements(), this::statement), expression(b.tailExpression()), b.span());
|
||||
}
|
||||
public PbsAst.Statement statement(PbsAst.Statement s) {
|
||||
return switch (s) {
|
||||
case PbsAst.LetStatement l -> new PbsAst.LetStatement(l.isConst(), l.name(), l.nameSpan(), type(l.explicitType()),
|
||||
expression(l.initializer(), type(l.explicitType())), l.span());
|
||||
case PbsAst.AssignStatement a -> new PbsAst.AssignStatement(new PbsAst.LValue(a.target().rootName(), a.target().pathSegments(),
|
||||
a.target().span(), expression(a.target().expression())), a.operator(), expression(a.value()), a.span());
|
||||
case PbsAst.ReturnStatement r -> new PbsAst.ReturnStatement(expression(r.value()), r.span());
|
||||
case PbsAst.IfStatement i -> new PbsAst.IfStatement(expression(i.condition()), block(i.thenBlock()),
|
||||
i.elseIf() == null ? null : (PbsAst.IfStatement) statement(i.elseIf()), block(i.elseBlock()), i.span(), i.bindingName(), i.bindingSpan());
|
||||
case PbsAst.ForStatement f -> new PbsAst.ForStatement(f.iteratorName(), type(f.iteratorType()), expression(f.fromExpression()),
|
||||
expression(f.untilExpression()), expression(f.stepExpression()), block(f.body()), f.span());
|
||||
case PbsAst.WhileStatement w -> new PbsAst.WhileStatement(expression(w.condition()), block(w.body()), w.span());
|
||||
case PbsAst.ExpressionStatement e -> new PbsAst.ExpressionStatement(expression(e.expression()), e.span());
|
||||
case PbsAst.BreakStatement b -> b;
|
||||
case PbsAst.ContinueStatement c -> c;
|
||||
};
|
||||
}
|
||||
public PbsAst.Expression expression(PbsAst.Expression e) { return expression(e, null); }
|
||||
public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) {
|
||||
if (e == null) return null;
|
||||
return switch (e) {
|
||||
case PbsAst.IdentifierExpr i -> new PbsAst.IdentifierExpr(i.name(), map(i.typeArguments(), this::type), i.applied(), i.span());
|
||||
case PbsAst.NewExpr n -> new PbsAst.NewExpr(n.typeName(), n.ctorName(), map(n.arguments(), this::expression), type(n.explicitType()), n.diamond(), n.span());
|
||||
case PbsAst.LambdaExpr l -> new PbsAst.LambdaExpr(l.captures(), map(l.parameters(), this::parameter), type(l.returnType()), block(l.body()), l.span());
|
||||
case PbsAst.UnaryExpr u -> new PbsAst.UnaryExpr(u.operator(), expression(u.expression()), u.span());
|
||||
case PbsAst.BinaryExpr b -> new PbsAst.BinaryExpr(b.operator(), expression(b.left()), expression(b.right()), b.span());
|
||||
case PbsAst.ApplyExpr a -> new PbsAst.ApplyExpr(expression(a.callee()), expression(a.argument()), a.span());
|
||||
case PbsAst.CallExpr c -> new PbsAst.CallExpr(expression(c.callee()), map(c.arguments(), this::expression), c.span());
|
||||
case PbsAst.MemberExpr m -> new PbsAst.MemberExpr(expression(m.receiver()), m.memberName(), m.span());
|
||||
case PbsAst.IndexExpr i -> new PbsAst.IndexExpr(expression(i.receiver()), expression(i.index()), i.span());
|
||||
case PbsAst.ArrayLiteralExpr a -> new PbsAst.ArrayLiteralExpr(map(a.elements(), this::expression), a.span());
|
||||
case PbsAst.GroupExpr g -> new PbsAst.GroupExpr(expression(g.expression(), expected), g.span());
|
||||
case PbsAst.ElseExpr x -> new PbsAst.ElseExpr(expression(x.optionalExpression()), expression(x.fallbackExpression(), expected), x.span());
|
||||
case PbsAst.IfExpr i -> new PbsAst.IfExpr(expression(i.condition()), block(i.thenBlock()), expression(i.elseExpression(), expected), i.span());
|
||||
case PbsAst.SwitchExpr s -> new PbsAst.SwitchExpr(expression(s.selector()), map(s.arms(), a -> new PbsAst.SwitchArm(
|
||||
a.pattern() instanceof PbsAst.LiteralSwitchPattern l ? new PbsAst.LiteralSwitchPattern(expression(l.literal()), l.span()) : a.pattern(),
|
||||
block(a.block()), a.span())), s.span());
|
||||
case PbsAst.HandleExpr h -> new PbsAst.HandleExpr(expression(h.value()), map(h.arms(), a ->
|
||||
new PbsAst.HandleArm(a.pattern(), a.remapTarget(), block(a.block()), a.span())), h.span());
|
||||
case PbsAst.AsExpr a -> new PbsAst.AsExpr(expression(a.expression()), type(a.contractType()), a.span());
|
||||
case PbsAst.PropagateExpr p -> new PbsAst.PropagateExpr(expression(p.expression()), p.span());
|
||||
case PbsAst.SomeExpr s -> new PbsAst.SomeExpr(expression(s.value()), s.span());
|
||||
case PbsAst.OkExpr o -> new PbsAst.OkExpr(expression(o.value()), o.span());
|
||||
case PbsAst.TupleExpr t -> new PbsAst.TupleExpr(map(t.items(), i -> new PbsAst.TupleItem(i.label(), expression(i.expression()), i.span())), t.span());
|
||||
case PbsAst.BlockExpr b -> new PbsAst.BlockExpr(block(b.block()), b.span());
|
||||
case PbsAst.IntLiteralExpr i -> i;
|
||||
case PbsAst.FloatLiteralExpr f -> f;
|
||||
case PbsAst.BoundedLiteralExpr b -> b;
|
||||
case PbsAst.StringLiteralExpr s -> s;
|
||||
case PbsAst.BoolLiteralExpr b -> b;
|
||||
case PbsAst.ThisExpr t -> t;
|
||||
case PbsAst.NoneExpr n -> n;
|
||||
case PbsAst.ErrExpr x -> x;
|
||||
case PbsAst.UnitExpr u -> u;
|
||||
};
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -24,7 +24,7 @@ public final class PbsTypeTraversal {
|
||||
b.fields().forEach(f -> type(f.typeRef(), visitor));
|
||||
b.signatures().forEach(s -> signature(s, visitor));
|
||||
}
|
||||
case PbsAst.ImplementsDecl i -> { type(i.contractType(), visitor); i.methods().forEach(f -> function(f, visitor)); }
|
||||
case PbsAst.ImplementsDecl i -> { type(i.contractType(), visitor); type(i.ownerType(), visitor); i.methods().forEach(f -> function(f, visitor)); }
|
||||
case PbsAst.GlobalDecl g -> { type(g.explicitType(), visitor); expression(g.initializer(), visitor); }
|
||||
case PbsAst.ConstDecl c -> { type(c.explicitType(), visitor); expression(c.initializer(), visitor); }
|
||||
default -> { }
|
||||
@@ -67,6 +67,7 @@ public final class PbsTypeTraversal {
|
||||
private static void expression(PbsAst.Expression e, Consumer<PbsAst.TypeRef> visitor) {
|
||||
if (e == null) return;
|
||||
switch (e) {
|
||||
case PbsAst.IdentifierExpr i -> i.typeArguments().forEach(t -> type(t, visitor));
|
||||
case PbsAst.AsExpr a -> { type(a.contractType(), visitor); expression(a.expression(), visitor); }
|
||||
case PbsAst.NewExpr n -> { type(n.explicitType(), visitor); n.arguments().forEach(a -> expression(a, visitor)); }
|
||||
case PbsAst.LambdaExpr l -> { l.parameters().forEach(p -> type(p.typeRef(), visitor)); type(l.returnType(), visitor); block(l.body(), visitor); }
|
||||
|
||||
+57
-5
@@ -99,11 +99,12 @@ public final class PbsModuleVisibilityValidator {
|
||||
|
||||
for (final var item : barrel.ast().items()) {
|
||||
if (item instanceof PbsAst.BarrelFunctionItem(
|
||||
PbsAst.Visibility visibility, String name, ReadOnlyList<PbsAst.TypeRef> parameterTypes,
|
||||
PbsAst.Visibility visibility, String name, ReadOnlyList<PbsAst.TypeParameter> typeParameters, ReadOnlyList<PbsAst.TypeRef> parameterTypes,
|
||||
PbsAst.ReturnKind returnKind, PbsAst.TypeRef returnType, PbsAst.TypeRef resultErrorType, Span span
|
||||
)) {
|
||||
final var functionKey = functionKey(
|
||||
name,
|
||||
typeParameters.size(),
|
||||
parameterTypes.asList(),
|
||||
returnKind,
|
||||
returnType,
|
||||
@@ -122,7 +123,12 @@ public final class PbsModuleVisibilityValidator {
|
||||
continue;
|
||||
}
|
||||
|
||||
final var matches = declarations.functionsBySignature.getOrDefault(functionKey, List.of());
|
||||
var matches = declarations.functionsBySignature.getOrDefault(functionKey, List.of());
|
||||
if (matches.isEmpty() || !typeParameters.isEmpty()) matches = resolveFunctionExport(module, name, unitsByModule, new HashSet<>()).stream()
|
||||
.filter(f -> f.typeParameters().stream().map(PbsAst.TypeParameter::name).toList().equals(typeParameters.stream().map(PbsAst.TypeParameter::name).toList()))
|
||||
.filter(f -> functionKey.equals(functionKey(name, f.typeParameters().size(), f.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),
|
||||
f.returnKind(), f.returnType(), f.resultErrorType(), nameTable, signatureInterning)))
|
||||
.map(PbsAst.FunctionDecl::span).distinct().toList();
|
||||
if (matches.isEmpty()) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
PbsLinkErrors.E_LINK_UNRESOLVED_BARREL_ENTRY.name(),
|
||||
@@ -170,7 +176,10 @@ public final class PbsModuleVisibilityValidator {
|
||||
var matches = declarations.nonFunctionsByKindAndName.getOrDefault(symbolKey, List.of());
|
||||
var resolvedContract = item instanceof PbsAst.BarrelContractItem contractItem
|
||||
? resolveContractExport(module, contractItem.name(), unitsByModule, new HashSet<>()) : null;
|
||||
var resolvedStruct = item instanceof PbsAst.BarrelStructItem structItem
|
||||
? resolveStructExport(module, structItem.name(), unitsByModule, new HashSet<>()) : null;
|
||||
if (matches.isEmpty() && resolvedContract != null) matches = List.of(resolvedContract.span());
|
||||
if (matches.isEmpty() && resolvedStruct != null) matches = List.of(resolvedStruct.span());
|
||||
if (matches.isEmpty()) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
PbsLinkErrors.E_LINK_UNRESOLVED_BARREL_ENTRY.name(),
|
||||
@@ -200,6 +209,13 @@ public final class PbsModuleVisibilityValidator {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (item instanceof PbsAst.BarrelStructItem structItem && resolvedStruct != null &&
|
||||
!resolvedStruct.typeParameters().stream().map(PbsAst.TypeParameter::name).toList().equals(
|
||||
structItem.typeParameters().stream().map(PbsAst.TypeParameter::name).toList())) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_LINK_STRUCT_PARAMETERS",
|
||||
"Barrel struct parameters must preserve the declaration's ordered parameters", structItem.span());
|
||||
continue;
|
||||
}
|
||||
if (nonFunctionVisibility(item) == PbsAst.Visibility.PUB) {
|
||||
exports.publicNameIds.add(symbolKey.nameId());
|
||||
}
|
||||
@@ -208,6 +224,39 @@ public final class PbsModuleVisibilityValidator {
|
||||
return exports;
|
||||
}
|
||||
|
||||
private PbsAst.StructDecl resolveStructExport(ModuleUnit module, String name,
|
||||
Map<ModuleRefKey, ModuleUnit> units, Set<String> visited) {
|
||||
if (!visited.add(module.coordinates()+":"+name)) return null;
|
||||
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls())
|
||||
if (declaration instanceof PbsAst.StructDecl struct && struct.name().equals(name)) return struct;
|
||||
for (var source : module.sourceFiles()) for (var imported : source.ast().imports()) for (var item : imported.items()) {
|
||||
if (!(item.alias() == null ? item.name() : item.alias()).equals(name)) continue;
|
||||
var target = units.get(new ModuleRefKey(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
|
||||
if (target != null && target.barrelFiles().stream().anyMatch(b -> b.ast().items().stream().anyMatch(i ->
|
||||
i instanceof PbsAst.BarrelStructItem s && s.visibility() == PbsAst.Visibility.PUB && s.name().equals(item.name())))) {
|
||||
var resolved = resolveStructExport(target, item.name(), units, visited); if (resolved != null) return resolved;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<PbsAst.FunctionDecl> resolveFunctionExport(ModuleUnit module, String name,
|
||||
Map<ModuleRefKey, ModuleUnit> units, Set<String> visited) {
|
||||
if (!visited.add(module.coordinates()+":"+name)) return List.of();
|
||||
var result = new ArrayList<PbsAst.FunctionDecl>();
|
||||
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls())
|
||||
if (declaration instanceof PbsAst.FunctionDecl function && function.name().equals(name)) result.add(function);
|
||||
if (!result.isEmpty()) return result;
|
||||
for (var source : module.sourceFiles()) for (var imported : source.ast().imports()) for (var item : imported.items()) {
|
||||
if (!(item.alias() == null ? item.name() : item.alias()).equals(name)) continue;
|
||||
var target = units.get(new ModuleRefKey(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
|
||||
if (target != null && target.barrelFiles().stream().anyMatch(b -> b.ast().items().stream().anyMatch(i ->
|
||||
i instanceof PbsAst.BarrelFunctionItem f && f.visibility() == PbsAst.Visibility.PUB && f.name().equals(item.name()))))
|
||||
result.addAll(resolveFunctionExport(target, item.name(), units, visited));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void validateImplementationOwners(ModuleUnit module, DiagnosticSink diagnostics) {
|
||||
var localOwners = new HashSet<String>();
|
||||
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) {
|
||||
@@ -215,7 +264,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
if (declaration instanceof PbsAst.ServiceDecl s) localOwners.add(s.name());
|
||||
}
|
||||
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls())
|
||||
if (declaration instanceof PbsAst.ImplementsDecl i && !localOwners.contains(i.ownerName()))
|
||||
if (declaration instanceof PbsAst.ImplementsDecl i && !localOwners.contains(i.ownerType().name()))
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_SEM_CONTRACT_OWNER_MODULE",
|
||||
"Contract implementations must be declared in the owner's module", i.span());
|
||||
}
|
||||
@@ -300,6 +349,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
final var key = functionKey(
|
||||
functionDecl.name(),
|
||||
functionDecl.typeParameters().size(),
|
||||
functionDecl.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),
|
||||
functionDecl.returnKind(),
|
||||
functionDecl.returnType(),
|
||||
@@ -353,6 +403,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
|
||||
private FunctionSymbolKey functionKey(
|
||||
final String name,
|
||||
final int typeArity,
|
||||
final List<PbsAst.TypeRef> parameterTypes,
|
||||
final PbsAst.ReturnKind returnKind,
|
||||
final PbsAst.TypeRef returnType,
|
||||
@@ -361,7 +412,7 @@ public final class PbsModuleVisibilityValidator {
|
||||
final SignatureInterning signatureInterning) {
|
||||
return new FunctionSymbolKey(
|
||||
nameTable.register(name),
|
||||
callableShapeId(parameterTypes, returnKind, returnType, resultErrorType, signatureInterning));
|
||||
callableShapeId(parameterTypes, returnKind, returnType, resultErrorType, signatureInterning), typeArity);
|
||||
}
|
||||
|
||||
private CallableShapeId callableShapeId(
|
||||
@@ -536,7 +587,8 @@ public final class PbsModuleVisibilityValidator {
|
||||
|
||||
private record FunctionSymbolKey(
|
||||
NameId nameId,
|
||||
CallableShapeId callableShapeId) {
|
||||
CallableShapeId callableShapeId,
|
||||
int typeArity) {
|
||||
}
|
||||
|
||||
private record SignatureInterning(
|
||||
|
||||
+8
-4
@@ -66,7 +66,8 @@ final class PbsRuntimeTypes {
|
||||
if (services.containsKey(item.name())) services.put(item.alias(), services.get(item.name()));
|
||||
if (contracts.containsKey(item.name())) contracts.put(item.alias(), contracts.get(item.name()));
|
||||
}
|
||||
for (var declaration : supplemental) if (declaration instanceof PbsAst.TypeBindingDecl binding) {
|
||||
for (var declaration : declarations) if (declaration instanceof PbsAst.TypeBindingDecl binding) {
|
||||
aliases.put(binding.name(), p.studio.compiler.pbs.PbsGenericInstantiation.name(binding.declaration()));
|
||||
if (binding.declaration() instanceof PbsAst.StructDecl s) structs.put(binding.name(), s);
|
||||
if (binding.declaration() instanceof PbsAst.ServiceDecl s) services.put(binding.name(), s);
|
||||
if (binding.declaration() instanceof PbsAst.ContractDecl c) contracts.put(binding.name(), c);
|
||||
@@ -108,10 +109,13 @@ final class PbsRuntimeTypes {
|
||||
if (t.kind() == PbsAst.TypeRefKind.ARRAY) return "array("+key(t.inner())+")";
|
||||
if (t.kind() == PbsAst.TypeRefKind.OPTIONAL) return "optional("+key(t.inner())+")";
|
||||
if (t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) return "tuple("+t.fields().stream().map(f->key(f.typeRef())).reduce((a,b)->a+","+b).orElse("")+")";
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) return nominalKey("struct", s.span());
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) return nominalKey("struct", s.span())
|
||||
+ (s.applicationOrigin() == null ? "" : ":" + s.applicationOrigin().key());
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.ServiceDecl s) return nominalKey("struct", s.span());
|
||||
if (isContract(t)) {
|
||||
var nominal = nominalKey("contract", contractTypes.template(t).span());
|
||||
var origin = contractTypes.template(t).applicationOrigin();
|
||||
if (origin != null) return nominal + ":" + origin.key();
|
||||
return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t);
|
||||
}
|
||||
return canonical(t);
|
||||
@@ -170,11 +174,11 @@ final class PbsRuntimeTypes {
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.StructDecl || contractTypes.declaration(t) instanceof PbsAst.ServiceDecl) {
|
||||
var ref = new IRRegistry.TypeRef(key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Struct(null)));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Struct(null)));
|
||||
var fields = new ArrayList<IRRegistry.NamedType>();
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) for(var field : s.fields())
|
||||
fields.add(new IRRegistry.NamedType(registryType(field.typeRef()),field.name()));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Struct(ReadOnlyList.wrap(fields))));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Struct(ReadOnlyList.wrap(fields))));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
+5
-2
@@ -115,7 +115,7 @@ public final class PbsBarrelParser {
|
||||
final PbsToken visibilityToken,
|
||||
final PbsTokenKind kind) {
|
||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected declaration name in barrel item");
|
||||
final var typeParameters = kind == PbsTokenKind.CONTRACT
|
||||
final var typeParameters = kind == PbsTokenKind.CONTRACT || kind == PbsTokenKind.STRUCT
|
||||
? new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
|
||||
PbsParser.ParseMode.ORDINARY)).parseTypeParameters()
|
||||
: ReadOnlyList.<PbsAst.TypeParameter>empty();
|
||||
@@ -123,7 +123,7 @@ public final class PbsBarrelParser {
|
||||
final var itemSpan = span(visibilityToken.start(), semicolon.end());
|
||||
|
||||
return switch (kind) {
|
||||
case STRUCT -> new PbsAst.BarrelStructItem(visibility, name.lexeme(), itemSpan);
|
||||
case STRUCT -> new PbsAst.BarrelStructItem(visibility, name.lexeme(), typeParameters, itemSpan);
|
||||
case CONTRACT -> new PbsAst.BarrelContractItem(visibility, name.lexeme(), typeParameters, itemSpan);
|
||||
case HOST -> new PbsAst.BarrelHostItem(visibility, name.lexeme(), itemSpan);
|
||||
case ERROR -> new PbsAst.BarrelErrorItem(visibility, name.lexeme(), itemSpan);
|
||||
@@ -140,6 +140,8 @@ public final class PbsBarrelParser {
|
||||
final PbsAst.Visibility visibility,
|
||||
final PbsToken visibilityToken) {
|
||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected function name in barrel item");
|
||||
final var typeParameters = new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
|
||||
PbsParser.ParseMode.ORDINARY)).parseTypeParameters();
|
||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after function name");
|
||||
|
||||
final var parameterTypes = new ArrayList<PbsAst.TypeRef>();
|
||||
@@ -157,6 +159,7 @@ public final class PbsBarrelParser {
|
||||
return new PbsAst.BarrelFunctionItem(
|
||||
visibility,
|
||||
name.lexeme(),
|
||||
typeParameters,
|
||||
ReadOnlyList.wrap(parameterTypes),
|
||||
returnSpec.kind(),
|
||||
returnSpec.returnType(),
|
||||
|
||||
+8
-2
@@ -174,9 +174,10 @@ final class PbsDeclarationParser {
|
||||
}
|
||||
|
||||
PbsAst.ImplementsDecl parseImplementsDeclaration(final PbsToken implementsToken) {
|
||||
final var typeParameters = typeParser.parseTypeParameters();
|
||||
final var contractType = typeParser.parseTypeRef();
|
||||
consume(PbsTokenKind.FOR, "Expected 'for' in 'implements' declaration");
|
||||
final var ownerName = consume(PbsTokenKind.IDENTIFIER, "Expected owner name after 'for'");
|
||||
final var ownerType = typeParser.parseTypeRef();
|
||||
consume(PbsTokenKind.USING, "Expected 'using' in 'implements' declaration");
|
||||
final var binderName = consume(PbsTokenKind.IDENTIFIER, "Expected binder name after 'using'");
|
||||
|
||||
@@ -201,8 +202,9 @@ final class PbsDeclarationParser {
|
||||
}
|
||||
|
||||
return new PbsAst.ImplementsDecl(
|
||||
typeParameters,
|
||||
contractType,
|
||||
ownerName.lexeme(),
|
||||
ownerType,
|
||||
binderName.lexeme(),
|
||||
ReadOnlyList.wrap(methods),
|
||||
span(implementsToken.start(), end));
|
||||
@@ -312,6 +314,7 @@ final class PbsDeclarationParser {
|
||||
final PbsToken declareToken,
|
||||
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected struct name");
|
||||
final var typeParameters = typeParser.parseTypeParameters();
|
||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' in struct declaration");
|
||||
final var fields = parseStructFields();
|
||||
consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after struct fields");
|
||||
@@ -338,6 +341,7 @@ final class PbsDeclarationParser {
|
||||
|
||||
return new PbsAst.StructDecl(
|
||||
name.lexeme(),
|
||||
typeParameters,
|
||||
ReadOnlyList.wrap(fields),
|
||||
ReadOnlyList.wrap(methods),
|
||||
ReadOnlyList.wrap(ctors),
|
||||
@@ -568,6 +572,7 @@ final class PbsDeclarationParser {
|
||||
final ReadOnlyList<PbsAst.Attribute> pendingAttributes) {
|
||||
final var lifecycleMarker = validateAndResolveLifecycleMarker(pendingAttributes);
|
||||
final var name = consumeCallableName();
|
||||
final var typeParameters = typeParser.parseTypeParameters();
|
||||
consume(PbsTokenKind.LEFT_PAREN, "Expected '(' after function name");
|
||||
final var parameters = typeParser.parseParametersUntilRightParen();
|
||||
final var rightParen = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after parameter list");
|
||||
@@ -577,6 +582,7 @@ final class PbsDeclarationParser {
|
||||
final var body = parseBlock();
|
||||
return new PbsAst.FunctionDecl(
|
||||
name.lexeme(),
|
||||
typeParameters,
|
||||
ReadOnlyList.wrap(parameters),
|
||||
returnSpec.kind(),
|
||||
returnSpec.returnType(),
|
||||
|
||||
+37
-6
@@ -41,6 +41,11 @@ final class PbsExprPrimaryParser {
|
||||
var expression = parsePrimary();
|
||||
|
||||
while (true) {
|
||||
if (expression instanceof PbsAst.IdentifierExpr identifier && !identifier.applied()
|
||||
&& cursor.check(PbsTokenKind.LESS)) {
|
||||
var applied = parseFunctionApplication(identifier);
|
||||
if (applied != null) { expression = applied; continue; }
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.LEFT_PAREN)) {
|
||||
final var arguments = new ArrayList<PbsAst.Expression>();
|
||||
if (!cursor.check(PbsTokenKind.RIGHT_PAREN)) {
|
||||
@@ -234,18 +239,21 @@ final class PbsExprPrimaryParser {
|
||||
PbsAst.TypeRef explicitType = null;
|
||||
boolean diamond = false;
|
||||
if (cursor.match(PbsTokenKind.LESS)) {
|
||||
if (!typeName.lexeme().equals("array")) {
|
||||
context.report(typeName, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
|
||||
"Type arguments in construction are currently supported only for array");
|
||||
}
|
||||
var types = context.typeParser();
|
||||
if (cursor.check(PbsTokenKind.GREATER)) {
|
||||
diamond = true;
|
||||
types.consumeTypeClose();
|
||||
} else {
|
||||
var element = types.parseArrayElementType();
|
||||
var arguments = new ArrayList<PbsAst.TypeRef>();
|
||||
do { arguments.add(typeName.lexeme().equals("array") ? types.parseArrayElementType() : types.parseTypeRef()); }
|
||||
while (cursor.match(PbsTokenKind.COMMA));
|
||||
var closeType = types.consumeTypeClose();
|
||||
explicitType = PbsAst.TypeRef.array(element, context.span(typeName.start(), closeType.end()));
|
||||
var typeSpan = context.span(typeName.start(), closeType.end());
|
||||
if (typeName.lexeme().equals("array")) {
|
||||
if (arguments.size() != 1) context.report(typeName, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
|
||||
"Array construction requires exactly one type argument");
|
||||
explicitType = PbsAst.TypeRef.array(arguments.getFirst(), typeSpan);
|
||||
} else explicitType = PbsAst.TypeRef.applied(typeName.lexeme(), ReadOnlyList.wrap(arguments), typeSpan);
|
||||
}
|
||||
}
|
||||
String ctorName = null;
|
||||
@@ -270,6 +278,29 @@ final class PbsExprPrimaryParser {
|
||||
context.span(newToken.start(), close.end()));
|
||||
}
|
||||
|
||||
/** A complete type-argument expression is recognized without consuming comparison tokens on failure. */
|
||||
private PbsAst.IdentifierExpr parseFunctionApplication(PbsAst.IdentifierExpr identifier) {
|
||||
var trial = cursor.fork();
|
||||
var diagnostics = p.studio.compiler.source.diagnostics.DiagnosticSink.empty();
|
||||
var types = new PbsTypeParser(new PbsParserContext(trial, identifier.span().getFileId(), diagnostics,
|
||||
PbsParser.ParseMode.ORDINARY));
|
||||
trial.advance();
|
||||
var arguments = new ArrayList<PbsAst.TypeRef>();
|
||||
if (!trial.check(PbsTokenKind.GREATER)) {
|
||||
do { arguments.add(types.parseTypeRef()); } while (trial.match(PbsTokenKind.COMMA));
|
||||
}
|
||||
var close = types.consumeTypeClose();
|
||||
if (diagnostics.hasErrors() || close.lexeme().isEmpty()) return null;
|
||||
// A following primary continues an ordinary comparison, rather than a type application.
|
||||
if (switch (trial.peek().kind()) {
|
||||
case IDENTIFIER, INT_LITERAL, FLOAT_LITERAL, STRING_LITERAL, TRUE, FALSE -> true;
|
||||
default -> false;
|
||||
}) return null;
|
||||
cursor.commit(trial);
|
||||
return new PbsAst.IdentifierExpr(identifier.name(), ReadOnlyList.wrap(arguments), true,
|
||||
context.span(identifier.span().getStart(), close.end()));
|
||||
}
|
||||
|
||||
private PbsAst.Expression parseLambda(PbsToken start) {
|
||||
context.consume(PbsTokenKind.LEFT_BRACKET, "Lambda requires explicit capture list, including []");
|
||||
var captures = new ArrayList<PbsAst.IdentifierExpr>();
|
||||
|
||||
+12
@@ -25,6 +25,18 @@ final class PbsTokenCursor {
|
||||
}
|
||||
}
|
||||
|
||||
PbsTokenCursor fork() {
|
||||
var copy = new PbsTokenCursor(ReadOnlyList.wrap(tokens));
|
||||
copy.current = current;
|
||||
return copy;
|
||||
}
|
||||
|
||||
void commit(PbsTokenCursor copy) {
|
||||
tokens.clear();
|
||||
tokens.addAll(copy.tokens);
|
||||
current = copy.current;
|
||||
}
|
||||
|
||||
/** Peel one type closer without changing expression tokenization. */
|
||||
PbsToken consumeTypeClose() {
|
||||
var token = peek();
|
||||
|
||||
+8
-1
@@ -25,6 +25,9 @@ final class PbsAstDocumentSymbols {
|
||||
|
||||
private static Optional<PbsEditorialDocumentSymbol> symbolFor(final PbsAst.TopDecl topDecl) {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
if (!functionDecl.typeParameters().isEmpty()) return namedSymbol(functionDecl.name(), PbsEditorialSymbolKind.FUNCTION,
|
||||
parameterDetail(functionDecl.typeParameters())+callableDetail(functionDecl.parameters(), functionDecl.returnKind(),
|
||||
functionDecl.returnType(), functionDecl.resultErrorType()), functionDecl.span(), List.of());
|
||||
return callableSymbol(
|
||||
functionDecl.name(),
|
||||
PbsEditorialSymbolKind.FUNCTION,
|
||||
@@ -122,11 +125,15 @@ final class PbsAstDocumentSymbols {
|
||||
return namedSymbol(
|
||||
structDecl.name(),
|
||||
PbsEditorialSymbolKind.STRUCT,
|
||||
"",
|
||||
parameterDetail(structDecl.typeParameters()),
|
||||
structDecl.span(),
|
||||
children);
|
||||
}
|
||||
|
||||
private static String parameterDetail(ReadOnlyList<PbsAst.TypeParameter> parameters) {
|
||||
return parameters.isEmpty() ? "" : "<"+parameters.stream().map(PbsAst.TypeParameter::name).collect(java.util.stream.Collectors.joining(", "))+">";
|
||||
}
|
||||
|
||||
private static Optional<PbsEditorialDocumentSymbol> builtinTypeSymbol(final PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||
final ArrayList<PbsEditorialDocumentSymbol> children = new ArrayList<>();
|
||||
for (final PbsAst.BuiltinFieldDecl field : builtinTypeDecl.fields()) {
|
||||
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package p.studio.compiler.pbs.semantics;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.diagnostics.Diagnostics;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/** Definite field assignment on completing paths; null denotes an unreachable exit. */
|
||||
final class PbsCtorInitializationAnalyzer {
|
||||
private final PbsFlowSemanticSupport.Model model;
|
||||
|
||||
PbsCtorInitializationAnalyzer(PbsFlowSemanticSupport.Model model) { this.model = model; }
|
||||
|
||||
void validate(PbsAst.StructDecl owner, PbsAst.CtorDecl ctor, DiagnosticSink diagnostics) {
|
||||
var assigned = block(ctor.body(), Set.of()).normal();
|
||||
if (assigned == null) return;
|
||||
var missing = owner.fields().stream().map(PbsAst.StructField::name).filter(n -> !assigned.contains(n)).toList();
|
||||
if (!missing.isEmpty()) Diagnostics.error(diagnostics, "E_SEM_CTOR_FIELD_UNINITIALIZED",
|
||||
"Every completing constructor path must assign fields: " + String.join(", ", missing), ctor.span());
|
||||
}
|
||||
|
||||
private record Paths(Set<String> normal, Set<String> breaks, Set<String> continues) {
|
||||
static Paths normal(Set<String> fields) { return new Paths(fields, null, null); }
|
||||
Paths merge(Paths other) {
|
||||
return new Paths(meet(normal, other.normal), meet(breaks, other.breaks), meet(continues, other.continues));
|
||||
}
|
||||
Paths then(java.util.function.Function<Set<String>, Paths> next) {
|
||||
if (normal == null) return this;
|
||||
var result = next.apply(normal);
|
||||
return new Paths(result.normal, meet(breaks, result.breaks), meet(continues, result.continues));
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> meet(Set<String> left, Set<String> right) {
|
||||
if (left == null) return right;
|
||||
if (right == null) return left;
|
||||
var result = new HashSet<>(left); result.retainAll(right); return Set.copyOf(result);
|
||||
}
|
||||
|
||||
private Paths block(PbsAst.Block block, Set<String> fields) {
|
||||
var result = Paths.normal(fields);
|
||||
if (block == null) return result;
|
||||
for (var statement : block.statements()) result = result.then(f -> statement(statement, f));
|
||||
return result.then(f -> expression(block.tailExpression(), f));
|
||||
}
|
||||
|
||||
private Paths statement(PbsAst.Statement statement, Set<String> fields) {
|
||||
return switch (statement) {
|
||||
case PbsAst.LetStatement l -> expression(l.initializer(), fields);
|
||||
case PbsAst.ExpressionStatement e -> expression(e.expression(), fields);
|
||||
case PbsAst.ReturnStatement r -> new Paths(null, null, null); // rejected separately in constructors
|
||||
case PbsAst.BreakStatement b -> new Paths(null, fields, null);
|
||||
case PbsAst.ContinueStatement c -> new Paths(null, null, fields);
|
||||
case PbsAst.AssignStatement a -> expression(a.target().expression(), fields).then(f -> expression(a.value(), f)).then(f -> {
|
||||
var assigned = new HashSet<>(f);
|
||||
if (a.operator() == PbsAst.AssignOperator.ASSIGN && a.target().rootName().equals("this")
|
||||
&& a.target().pathSegments().size() == 1) assigned.add(a.target().pathSegments().getFirst());
|
||||
return Paths.normal(Set.copyOf(assigned));
|
||||
});
|
||||
case PbsAst.IfStatement i -> expression(i.condition(), fields).then(f -> {
|
||||
var yes = block(i.thenBlock(), f);
|
||||
var no = i.elseIf() == null ? block(i.elseBlock(), f) : statement(i.elseIf(), f);
|
||||
return yes.merge(no);
|
||||
});
|
||||
case PbsAst.ForStatement loop -> expression(loop.fromExpression(), fields)
|
||||
.then(f -> expression(loop.untilExpression(), f)).then(f -> expression(loop.stepExpression(), f))
|
||||
.then(f -> Paths.normal(meet(f, block(loop.body(), f).breaks())));
|
||||
case PbsAst.WhileStatement loop -> expression(loop.condition(), fields).then(f -> {
|
||||
var body = block(loop.body(), f);
|
||||
boolean always = unwrap(loop.condition()) instanceof PbsAst.BoolLiteralExpr b && b.value();
|
||||
return Paths.normal(always ? body.breaks() : meet(f, body.breaks()));
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
private Paths expression(PbsAst.Expression expression, Set<String> fields) {
|
||||
return switch (expression) {
|
||||
case null -> Paths.normal(fields);
|
||||
case PbsAst.GroupExpr g -> expression(g.expression(), fields);
|
||||
case PbsAst.BlockExpr b -> block(b.block(), fields);
|
||||
case PbsAst.IfExpr i -> expression(i.condition(), fields).then(f ->
|
||||
block(i.thenBlock(), f).merge(expression(i.elseExpression(), f)));
|
||||
case PbsAst.SwitchExpr s -> expression(s.selector(), fields).then(f -> {
|
||||
var result = new Paths(null, null, null);
|
||||
for (var arm : s.arms()) result = result.merge(block(arm.block(), f));
|
||||
if (!exhaustive(s)) result = result.merge(Paths.normal(f));
|
||||
return result;
|
||||
});
|
||||
case PbsAst.HandleExpr h -> expression(h.value(), fields).then(f -> {
|
||||
// The successful value bypasses every handler arm.
|
||||
var result = Paths.normal(f);
|
||||
for (var arm : h.arms()) if (arm.remapTarget() == null) result = result.merge(block(arm.block(), f));
|
||||
return result;
|
||||
});
|
||||
case PbsAst.ElseExpr e -> expression(e.optionalExpression(), fields).then(f ->
|
||||
Paths.normal(f).merge(expression(e.fallbackExpression(), f)));
|
||||
case PbsAst.BinaryExpr b -> expression(b.left(), fields).then(f -> {
|
||||
var right = expression(b.right(), f);
|
||||
return Set.of("&&", "||", "and", "or").contains(b.operator()) ? Paths.normal(f).merge(right) : right;
|
||||
});
|
||||
case PbsAst.UnaryExpr u -> expression(u.expression(), fields);
|
||||
case PbsAst.AsExpr a -> expression(a.expression(), fields);
|
||||
case PbsAst.PropagateExpr p -> expression(p.expression(), fields);
|
||||
case PbsAst.SomeExpr s -> expression(s.value(), fields);
|
||||
case PbsAst.OkExpr o -> expression(o.value(), fields);
|
||||
case PbsAst.MemberExpr m -> expression(m.receiver(), fields);
|
||||
case PbsAst.IndexExpr i -> expression(i.receiver(), fields).then(f -> expression(i.index(), f));
|
||||
case PbsAst.ApplyExpr a -> expression(a.callee(), fields).then(f -> expression(a.argument(), f));
|
||||
case PbsAst.CallExpr c -> expressions(c.arguments(), expression(c.callee(), fields));
|
||||
case PbsAst.NewExpr n -> expressions(n.arguments(), Paths.normal(fields));
|
||||
case PbsAst.ArrayLiteralExpr a -> expressions(a.elements(), Paths.normal(fields));
|
||||
case PbsAst.TupleExpr t -> {
|
||||
var result = Paths.normal(fields);
|
||||
for (var item : t.items()) result = result.then(f -> expression(item.expression(), f));
|
||||
yield result;
|
||||
}
|
||||
default -> Paths.normal(fields); // literals, identifiers and deferred lambda bodies do not assign fields
|
||||
};
|
||||
}
|
||||
|
||||
private Paths expressions(Iterable<PbsAst.Expression> expressions, Paths result) {
|
||||
for (var expression : expressions) result = result.then(f -> expression(expression, f));
|
||||
return result;
|
||||
}
|
||||
|
||||
private boolean exhaustive(PbsAst.SwitchExpr expression) {
|
||||
String enumName = null;
|
||||
var cases = new HashSet<String>();
|
||||
for (var arm : expression.arms()) {
|
||||
if (arm.pattern() instanceof PbsAst.WildcardSwitchPattern) return true;
|
||||
if (!(arm.pattern() instanceof PbsAst.EnumCaseSwitchPattern e) || e.path().segments().size() != 2) return false;
|
||||
var name = e.path().segments().getFirst();
|
||||
if (enumName != null && !enumName.equals(name)) return false;
|
||||
enumName = name; cases.add(e.path().segments().get(1));
|
||||
}
|
||||
return enumName != null && model.enums.containsKey(enumName) && cases.containsAll(model.enums.get(enumName));
|
||||
}
|
||||
|
||||
private PbsAst.Expression unwrap(PbsAst.Expression expression) {
|
||||
return expression instanceof PbsAst.GroupExpr g ? unwrap(g.expression()) : expression;
|
||||
}
|
||||
}
|
||||
+19
-18
@@ -58,17 +58,18 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
final ReadOnlyList<PbsFrontendCompiler.ImportedGlobalSurface> importedGlobals,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final var binder = new PbsNamespaceBinder(nameTable, diagnostics);
|
||||
final var rules = new PbsDeclarationRuleValidator(nameTable, diagnostics);
|
||||
final var interfaceModule = sourceKind == SourceKind.SDK_INTERFACE;
|
||||
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
final var declarationDiagnostics = p.studio.compiler.pbs.PbsGenericDiagnostics.forDeclaration(topDecl, diagnostics);
|
||||
final var rules = new PbsDeclarationRuleValidator(nameTable, declarationDiagnostics);
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
validateDocAttributes(functionDecl.attributes(), "function declarations", diagnostics);
|
||||
validateDocAttributes(functionDecl.attributes(), "function declarations", declarationDiagnostics);
|
||||
if (interfaceModule) {
|
||||
reportInterfaceNonDeclarativeDecl(
|
||||
functionDecl.span(),
|
||||
"Top-level functions are not allowed in interface modules",
|
||||
diagnostics);
|
||||
declarationDiagnostics);
|
||||
}
|
||||
validateCallable(
|
||||
PbsCallableScope.topLevelFunctions(),
|
||||
@@ -86,34 +87,34 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
validateDocAttributes(structDecl.attributes(), "struct declarations", diagnostics);
|
||||
validateDocAttributes(structDecl.attributes(), "struct declarations", declarationDiagnostics);
|
||||
binder.registerType(structDecl.name(), structDecl.span(), "struct");
|
||||
if (interfaceModule && (structDecl.hasBody() || !structDecl.methods().isEmpty() || !structDecl.ctors().isEmpty())) {
|
||||
reportInterfaceNonDeclarativeDecl(
|
||||
structDecl.span(),
|
||||
"Interface modules must not declare executable struct bodies",
|
||||
diagnostics);
|
||||
declarationDiagnostics);
|
||||
}
|
||||
validateStructDeclaration(structDecl, binder, rules, diagnostics);
|
||||
validateStructDeclaration(structDecl, binder, rules, declarationDiagnostics);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
validateDocAttributes(serviceDecl.attributes(), "service declarations", diagnostics);
|
||||
validateDocAttributes(serviceDecl.attributes(), "service declarations", declarationDiagnostics);
|
||||
binder.registerType(serviceDecl.name(), serviceDecl.span(), "service");
|
||||
binder.registerValue(serviceDecl.name(), serviceDecl.span(), "service singleton");
|
||||
binder.registerVisibleTopLevelSurface(serviceDecl.name(), serviceDecl.span(), "service");
|
||||
validateServiceDeclaration(serviceDecl, binder, rules, interfaceModule, diagnostics);
|
||||
validateServiceDeclaration(serviceDecl, binder, rules, interfaceModule, declarationDiagnostics);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
validateDocAttributes(contractDecl.attributes(), "contract declarations", diagnostics);
|
||||
validateDocAttributes(contractDecl.attributes(), "contract declarations", declarationDiagnostics);
|
||||
binder.registerType(contractDecl.name(), contractDecl.span(), "contract");
|
||||
if (interfaceModule) {
|
||||
for (final var signature : contractDecl.signatures()) {
|
||||
validateDocAttributes(signature.attributes(), "contract signatures", diagnostics);
|
||||
validateReservedAttributeTargetExceptDoc(signature.attributes(), "contract signature", diagnostics);
|
||||
validateDocAttributes(signature.attributes(), "contract signatures", declarationDiagnostics);
|
||||
validateReservedAttributeTargetExceptDoc(signature.attributes(), "contract signature", declarationDiagnostics);
|
||||
}
|
||||
}
|
||||
validateContractDeclaration(contractDecl, binder, rules);
|
||||
@@ -121,27 +122,27 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
||||
validateDocAttributes(hostDecl.attributes(), "host declarations", diagnostics);
|
||||
validateDocAttributes(hostDecl.attributes(), "host declarations", declarationDiagnostics);
|
||||
binder.registerHostOwner(hostDecl.name(), hostDecl.span(), "host owner");
|
||||
validateHostDeclaration(hostDecl, binder, rules, interfaceModule, diagnostics);
|
||||
validateHostDeclaration(hostDecl, binder, rules, interfaceModule, declarationDiagnostics);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||
binder.registerType(builtinTypeDecl.name(), builtinTypeDecl.span(), "builtin type");
|
||||
validateBuiltinTypeDeclaration(builtinTypeDecl, binder, rules, interfaceModule, diagnostics);
|
||||
validateBuiltinTypeDeclaration(builtinTypeDecl, binder, rules, interfaceModule, declarationDiagnostics);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.ErrorDecl errorDecl) {
|
||||
validateDocAttributes(errorDecl.attributes(), "error declarations", diagnostics);
|
||||
validateDocAttributes(errorDecl.attributes(), "error declarations", declarationDiagnostics);
|
||||
binder.registerType(errorDecl.name(), errorDecl.span(), "error");
|
||||
rules.validateErrorDeclaration(errorDecl);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
validateDocAttributes(enumDecl.attributes(), "enum declarations", diagnostics);
|
||||
validateDocAttributes(enumDecl.attributes(), "enum declarations", declarationDiagnostics);
|
||||
binder.registerType(enumDecl.name(), enumDecl.span(), "enum");
|
||||
rules.validateEnumDeclaration(enumDecl);
|
||||
continue;
|
||||
@@ -159,7 +160,7 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||
binder.registerValue(constDecl.name(), constDecl.span(), "const");
|
||||
binder.registerVisibleTopLevelSurface(constDecl.name(), constDecl.span(), "const");
|
||||
final var allowMissingInitializer = validateConstDeclarationAttributes(constDecl, interfaceModule, diagnostics);
|
||||
final var allowMissingInitializer = validateConstDeclarationAttributes(constDecl, interfaceModule, declarationDiagnostics);
|
||||
rules.validateConstDeclaration(constDecl, !allowMissingInitializer);
|
||||
continue;
|
||||
}
|
||||
@@ -169,7 +170,7 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
reportInterfaceNonDeclarativeDecl(
|
||||
implementsDecl.span(),
|
||||
"Interface modules must not declare executable 'implements' blocks",
|
||||
diagnostics);
|
||||
declarationDiagnostics);
|
||||
}
|
||||
validateImplementsDeclaration(implementsDecl, binder, rules);
|
||||
}
|
||||
|
||||
+108
-10
@@ -362,12 +362,15 @@ public final class PbsEditorialSupportService {
|
||||
private static final class DocumentContext {
|
||||
private final String sourceText;
|
||||
private final PbsAst.File ast;
|
||||
private final PbsAst.File semanticAst;
|
||||
private final Map<Span, String> genericResolutions;
|
||||
private final Map<String, PbsAst.TopDecl> concreteSymbols;
|
||||
private final ReadOnlyList<PbsAst.TopDecl> editorialSupplementalTopDecls;
|
||||
private final ReadOnlyList<PbsToken> tokens;
|
||||
private final Model model;
|
||||
private final PbsFlowTypeOps typeOps = new PbsFlowTypeOps();
|
||||
private final PbsFlowExpressionAnalyzer expressionAnalyzer = new PbsFlowExpressionAnalyzer(typeOps);
|
||||
private final PbsInlineHintSurfaceFormatter typeFormatter = new PbsInlineHintSurfaceFormatter();
|
||||
private final PbsInlineHintSurfaceFormatter typeFormatter;
|
||||
private final Map<String, TopDeclSymbol> topLevelSymbols;
|
||||
private final Map<String, TopDeclSymbol> importedSymbols;
|
||||
private final Map<String, TopDeclSymbol> supplementalSymbols;
|
||||
@@ -386,11 +389,28 @@ public final class PbsEditorialSupportService {
|
||||
this.importedSymbols = buildImportedSymbols(expandedSupplementals);
|
||||
this.editorialSupplementalTopDecls = ReadOnlyList.wrap(expandedSupplementals);
|
||||
this.tokens = PbsLexer.lex(this.sourceText, FileId.none(), DiagnosticSink.empty());
|
||||
var projection = p.studio.compiler.pbs.PbsGenericInstantiation.needed(ast)
|
||||
|| expandedSupplementals.stream().anyMatch(d -> !p.studio.compiler.pbs.PbsGenericInstantiation.parameters(
|
||||
d instanceof PbsAst.TypeBindingDecl b ? b.declaration() : d).isEmpty()
|
||||
&& !(d instanceof PbsAst.ContractDecl));
|
||||
var concrete = new LinkedHashMap<String, PbsAst.TopDecl>();
|
||||
if (projection) {
|
||||
var prepared = new p.studio.compiler.pbs.PbsGenericInstantiation(List.of(
|
||||
new p.studio.compiler.pbs.PbsGenericInstantiation.Source(ast, editorialSupplementalTopDecls)), DiagnosticSink.empty(), feSurfaceContext).prepare();
|
||||
semanticAst = prepared.files().get(ast.span().getFileId());
|
||||
genericResolutions = prepared.resolutions();
|
||||
for (var d : semanticAst.topDecls()) if (p.studio.compiler.pbs.PbsContractTypes.applicationOrigin(d) != null)
|
||||
concrete.put(p.studio.compiler.pbs.PbsGenericInstantiation.name(d), d);
|
||||
} else { semanticAst = ast; genericResolutions = Map.of(); }
|
||||
concreteSymbols = Map.copyOf(concrete);
|
||||
var modelSupplemental = ReadOnlyList.wrap(editorialSupplementalTopDecls.stream().filter(d ->
|
||||
!projection || p.studio.compiler.pbs.PbsGenericInstantiation.parameters(d instanceof PbsAst.TypeBindingDecl b ? b.declaration() : d).isEmpty()).toList());
|
||||
this.model = Model.from(
|
||||
ast,
|
||||
editorialSupplementalTopDecls,
|
||||
semanticAst,
|
||||
modelSupplemental,
|
||||
feSurfaceContext == null ? FESurfaceContext.empty() : feSurfaceContext,
|
||||
DiagnosticSink.empty());
|
||||
this.typeFormatter = new PbsInlineHintSurfaceFormatter(model.contractTypes);
|
||||
this.topLevelSymbols = buildTopLevelSymbols();
|
||||
this.supplementalSymbols = buildSupplementalSymbols();
|
||||
this.aliasedTypeRefs = buildAliasedTypeRefs();
|
||||
@@ -633,7 +653,10 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
|
||||
private CallableFrame callableFrameAt(final int offset) {
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
var declarations = new ArrayList<PbsAst.TopDecl>();
|
||||
for (var d : ast.topDecls()) if (!p.studio.compiler.pbs.PbsGenericInstantiation.parameters(d).isEmpty()) declarations.add(d);
|
||||
declarations.addAll(semanticAst.topDecls().asList());
|
||||
for (final var topDecl : declarations) {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl && functionDecl.span().contains(offset)) {
|
||||
return new CallableFrame(
|
||||
functionDecl.parameters(),
|
||||
@@ -734,6 +757,15 @@ public final class PbsEditorialSupportService {
|
||||
return List.of();
|
||||
}
|
||||
final Map<String, PbsEditorialCompletionCandidate> completions = new LinkedHashMap<>();
|
||||
var symbolic = symbolicStruct(receiverType);
|
||||
if (symbolic != null) {
|
||||
for (var field : symbolic.fields()) completions.put(field.name(), new PbsEditorialCompletionCandidate(
|
||||
field.name(), PbsEditorialSymbolKind.FIELD, field.typeRef().surface(), symbolic.name()));
|
||||
for (var method : symbolic.methods()) completions.put(method.name(), new PbsEditorialCompletionCandidate(
|
||||
method.name(), PbsEditorialSymbolKind.METHOD, signatureFromFunction(method.name(), method.parameters(),
|
||||
method.returnKind(), method.returnType(), method.resultErrorType()).label(), symbolic.name()));
|
||||
return List.copyOf(completions.values());
|
||||
}
|
||||
if (receiverType.kind() == Kind.ARRAY) {
|
||||
return List.of(new PbsEditorialCompletionCandidate("length", PbsEditorialSymbolKind.FIELD, "long", "array"),
|
||||
new PbsEditorialCompletionCandidate("clear", PbsEditorialSymbolKind.METHOD, "clear(index: int | long) -> unit", "array"));
|
||||
@@ -783,6 +815,13 @@ public final class PbsEditorialSupportService {
|
||||
return List.copyOf(completions.values());
|
||||
}
|
||||
|
||||
private PbsAst.StructDecl symbolicStruct(TypeView receiver) {
|
||||
if (receiver == null || receiver.kind() != Kind.STRUCT) return null;
|
||||
return ast.topDecls().stream().filter(d -> d instanceof PbsAst.StructDecl s
|
||||
&& !s.typeParameters().isEmpty() && s.name().equals(receiver.name()))
|
||||
.map(d -> (PbsAst.StructDecl) d).findFirst().orElse(null);
|
||||
}
|
||||
|
||||
private Optional<PbsEditorialResolvedSymbol> resolveSymbolHover(
|
||||
final String symbolName,
|
||||
final int tokenIndex,
|
||||
@@ -844,6 +883,15 @@ public final class PbsEditorialSupportService {
|
||||
if (receiverType == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
var symbolic = symbolicStruct(receiverType);
|
||||
if (symbolic != null) {
|
||||
var field = symbolic.fields().stream().filter(f -> f.name().equals(memberName)).findFirst();
|
||||
if (field.isPresent()) return Optional.of(new PbsEditorialResolvedSymbol(memberName,
|
||||
PbsEditorialSymbolKind.FIELD, field.get().typeRef().surface(), symbolic.name(), List.of(), ""));
|
||||
var methods = signaturesForTopDecl(symbolic).stream().filter(s -> s.label().startsWith(memberName + "(")).toList();
|
||||
if (!methods.isEmpty()) return Optional.of(new PbsEditorialResolvedSymbol(memberName,
|
||||
PbsEditorialSymbolKind.METHOD, methods.getFirst().label(), symbolic.name(), methods, ""));
|
||||
}
|
||||
if (receiverType.kind() == Kind.ARRAY || receiverType.kind() == Kind.OPTIONAL) {
|
||||
return memberCompletions(receiverType).stream().filter(item -> item.label().equals(memberName))
|
||||
.findFirst().map(item -> new PbsEditorialResolvedSymbol(item.label(), item.kind(), item.detail(), item.origin(), List.of(), ""));
|
||||
@@ -915,11 +963,11 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
|
||||
private PbsAst.TypeParameter typeParameterAt(String name, long offset) {
|
||||
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ContractDecl contract && contract.span().contains(offset)) {
|
||||
for (var parameter : contract.typeParameters()) if (parameter.name().equals(name)) {
|
||||
for (var declaration : ast.topDecls()) if (declaration.span().contains(offset)) {
|
||||
for (var parameter : p.studio.compiler.pbs.PbsGenericInstantiation.parameters(declaration)) if (parameter.name().equals(name)) {
|
||||
if (parameter.span().contains(offset)) return parameter;
|
||||
var found = new boolean[1];
|
||||
p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(contract, t -> findTypeAt(t, name, offset, found));
|
||||
p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(declaration, t -> findTypeAt(t, name, offset, found));
|
||||
if (found[0]) return parameter;
|
||||
}
|
||||
}
|
||||
@@ -938,7 +986,20 @@ public final class PbsEditorialSupportService {
|
||||
private Optional<PbsEditorialResolvedSymbol> genericHover(String name, long offset) {
|
||||
var parameter = typeParameterAt(name, offset);
|
||||
if (parameter != null) return Optional.of(new PbsEditorialResolvedSymbol(name, PbsEditorialSymbolKind.PARAMETER,
|
||||
"type parameter " + name, "contract", List.of(), ""));
|
||||
"type parameter " + name, "generic declaration", List.of(), ""));
|
||||
boolean symbolicScope = ast.topDecls().stream().anyMatch(d -> !p.studio.compiler.pbs.PbsGenericInstantiation.parameters(d).isEmpty() && d.span().contains(offset));
|
||||
for (var resolution : genericResolutions.entrySet()) {
|
||||
if (symbolicScope) break;
|
||||
if (!resolution.getKey().contains(offset) || resolution.getKey().getFileId() == null
|
||||
|| !resolution.getKey().getFileId().equals(ast.span().getFileId())
|
||||
|| offset >= resolution.getKey().getStart()+name.length()) continue;
|
||||
var declaration = concreteSymbols.get(resolution.getValue());
|
||||
if (declaration == null) continue;
|
||||
var origin = p.studio.compiler.pbs.PbsContractTypes.applicationOrigin(declaration);
|
||||
return Optional.of(new PbsEditorialResolvedSymbol(origin.display(), symbolKind(declaration),
|
||||
symbolKind(declaration).name().toLowerCase(Locale.ROOT)+" "+origin.display(), "generic application",
|
||||
signaturesForTopDecl(declaration), documentationFromTopDecl(declaration)));
|
||||
}
|
||||
var references = new ArrayList<PbsAst.TypeRef>();
|
||||
for (var declaration : ast.topDecls()) p.studio.compiler.pbs.ast.PbsTypeTraversal.visit(declaration, references::add);
|
||||
var pending = new ArrayDeque<>(references);
|
||||
@@ -1222,6 +1283,8 @@ public final class PbsEditorialSupportService {
|
||||
private List<PbsEditorialSignature> resolveCallableSignatures(
|
||||
final String callableName,
|
||||
final ScopeState scopeState) {
|
||||
var applied = concreteSymbols.get(callableName);
|
||||
if (applied != null) return signaturesForTopDecl(applied);
|
||||
final TopDeclSymbol importedSymbol = importedSymbols.get(callableName);
|
||||
if (importedSymbol != null) {
|
||||
return signaturesForTopDecl(importedSymbol.decl());
|
||||
@@ -1246,6 +1309,8 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
|
||||
private List<PbsEditorialSignature> resolveConstructorSignatures(final String typeName) {
|
||||
var applied = concreteSymbols.get(typeName);
|
||||
if (applied != null) return constructorSignaturesForTopDecl(applied);
|
||||
final TopDeclSymbol importedSymbol = importedSymbols.get(typeName);
|
||||
if (importedSymbol != null) {
|
||||
return constructorSignaturesForTopDecl(importedSymbol.decl());
|
||||
@@ -1366,8 +1431,11 @@ public final class PbsEditorialSupportService {
|
||||
|
||||
private List<PbsEditorialSignature> signaturesForTopDecl(final PbsAst.TopDecl topDecl) {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
return List.of(signatureFromFunction(functionDecl.name(), functionDecl.parameters(), functionDecl.returnKind(), functionDecl.returnType(), functionDecl.resultErrorType()));
|
||||
var name = functionDecl.applicationOrigin() == null ? functionDecl.name() : functionDecl.applicationOrigin().display();
|
||||
return List.of(signatureFromFunction(name, functionDecl.parameters(), functionDecl.returnKind(), functionDecl.returnType(), functionDecl.resultErrorType()));
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) return structDecl.methods().stream()
|
||||
.map(method -> signatureFromFunction(method.name(), method.parameters(), method.returnKind(), method.returnType(), method.resultErrorType())).toList();
|
||||
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
return serviceDecl.methods().stream()
|
||||
@@ -1475,7 +1543,7 @@ public final class PbsEditorialSupportService {
|
||||
return switch (typeRef.kind()) {
|
||||
case UNIT -> "unit";
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.surface();
|
||||
case SIMPLE -> typeRef.name().startsWith("$generic$") ? model.contractTypes.display(typeRef) : typeRef.surface();
|
||||
case FN -> "Fn(" + typeRef.fields().stream().map(f -> formatTypeRef(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + formatTypeRef(typeRef.inner());
|
||||
case ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">";
|
||||
case OPTIONAL -> formatTypeRef(typeRef.inner()) + "?";
|
||||
@@ -1522,6 +1590,19 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
|
||||
private PbsAst.Expression receiverExpressionBefore(final int dotTokenIndex) {
|
||||
var receivers = new ArrayList<PbsAst.Expression>();
|
||||
var before = previousSignificantTokenIndex(dotTokenIndex);
|
||||
if (before != null) {
|
||||
var endingAt = token(before).end();
|
||||
var visitor = new p.studio.compiler.pbs.ast.PbsAstRewriter() {
|
||||
@Override public PbsAst.Expression expression(PbsAst.Expression e, PbsAst.TypeRef expected) {
|
||||
if (e instanceof PbsAst.MemberExpr m && m.receiver().span().getEnd() == endingAt) receivers.add(m.receiver());
|
||||
return super.expression(e, expected);
|
||||
}
|
||||
};
|
||||
visitor.file(semanticAst);
|
||||
if (!receivers.isEmpty()) return receivers.getFirst();
|
||||
}
|
||||
// Locate only the fragment boundary here; grammar and overload selection
|
||||
// remain in the existing PBS parser and flow expression analyzer.
|
||||
int start = dotTokenIndex;
|
||||
@@ -1645,11 +1726,22 @@ public final class PbsEditorialSupportService {
|
||||
return null;
|
||||
}
|
||||
final PbsToken calleeToken = token(calleeIndex);
|
||||
if (calleeToken.kind() == PbsTokenKind.GREATER || calleeToken.kind() == PbsTokenKind.GREATER_EQUAL) {
|
||||
for (var resolution : genericResolutions.entrySet()) if (resolution.getKey().getEnd() == calleeToken.end()) {
|
||||
var declaration = concreteSymbols.get(resolution.getValue());
|
||||
if (declaration != null) return new CallSite(declaration instanceof PbsAst.StructDecl ? CallSiteKind.CONSTRUCTOR : CallSiteKind.FUNCTION,
|
||||
resolution.getValue(), activeParameter, -1);
|
||||
}
|
||||
}
|
||||
if (calleeToken.kind() != PbsTokenKind.IDENTIFIER) {
|
||||
return null;
|
||||
}
|
||||
final Integer maybeDotIndex = previousSignificantTokenIndex(calleeIndex);
|
||||
if (maybeDotIndex != null && token(maybeDotIndex).kind() == PbsTokenKind.DOT) {
|
||||
var ownerIndex = previousSignificantTokenIndex(maybeDotIndex);
|
||||
if (ownerIndex != null) for (var resolution : genericResolutions.entrySet())
|
||||
if (resolution.getKey().getEnd() == token(ownerIndex).end() && concreteSymbols.get(resolution.getValue()) instanceof PbsAst.StructDecl)
|
||||
return new CallSite(CallSiteKind.CONSTRUCTOR, resolution.getValue(), activeParameter, -1);
|
||||
return new CallSite(CallSiteKind.MEMBER, calleeToken.lexeme(), activeParameter, maybeDotIndex);
|
||||
}
|
||||
if (maybeDotIndex != null && token(maybeDotIndex).kind() == PbsTokenKind.NEW) {
|
||||
@@ -2191,6 +2283,7 @@ public final class PbsEditorialSupportService {
|
||||
if (topDecl instanceof PbsAst.FunctionDecl functionDecl) {
|
||||
return new PbsAst.FunctionDecl(
|
||||
newName,
|
||||
functionDecl.typeParameters(),
|
||||
functionDecl.parameters(),
|
||||
functionDecl.returnKind(),
|
||||
functionDecl.returnType(),
|
||||
@@ -2198,16 +2291,19 @@ public final class PbsEditorialSupportService {
|
||||
functionDecl.attributes(),
|
||||
functionDecl.lifecycleMarker(),
|
||||
functionDecl.body(),
|
||||
functionDecl.applicationOrigin(),
|
||||
functionDecl.span());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
return new PbsAst.StructDecl(
|
||||
newName,
|
||||
structDecl.typeParameters(),
|
||||
structDecl.fields(),
|
||||
structDecl.methods(),
|
||||
structDecl.ctors(),
|
||||
structDecl.hasBody(),
|
||||
structDecl.attributes(),
|
||||
structDecl.applicationOrigin(),
|
||||
structDecl.span());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.BuiltinTypeDecl builtinTypeDecl) {
|
||||
@@ -2244,6 +2340,8 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
|
||||
private TopDeclSymbol resolveTopDeclSymbol(final String symbolName) {
|
||||
var concrete = concreteSymbols.get(symbolName);
|
||||
if (concrete != null) return new TopDeclSymbol(symbolName, concrete, "generic application");
|
||||
final TopDeclSymbol importedSymbol = importedSymbols.get(symbolName);
|
||||
if (importedSymbol != null) {
|
||||
return importedSymbol;
|
||||
|
||||
+4
-3
@@ -36,7 +36,7 @@ final class PbsFlowBodyAnalyzer {
|
||||
final var model = Model.from(ast, supplementalTopDecls, feSurfaceContext, diagnostics);
|
||||
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
validateTopDecl(topDecl, model, diagnostics);
|
||||
validateTopDecl(topDecl, model, p.studio.compiler.pbs.PbsGenericDiagnostics.forDeclaration(topDecl, diagnostics));
|
||||
}
|
||||
} finally {
|
||||
inlineHintCollector = previousCollector;
|
||||
@@ -53,7 +53,7 @@ final class PbsFlowBodyAnalyzer {
|
||||
inlineHintCollector = collector;
|
||||
try {
|
||||
final var model = Model.from(ast, supplementalTopDecls, feSurfaceContext, diagnostics);
|
||||
|
||||
collector.formatter = new PbsInlineHintSurfaceFormatter(model.contractTypes);
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
validateTopDecl(topDecl, model, diagnostics);
|
||||
}
|
||||
@@ -75,7 +75,7 @@ final class PbsFlowBodyAnalyzer {
|
||||
private static final String TYPE_HINT_CATEGORY = "type";
|
||||
|
||||
private final ArrayList<PbsInlineHintSurface> hints = new ArrayList<>();
|
||||
private final PbsInlineHintSurfaceFormatter formatter = new PbsInlineHintSurfaceFormatter();
|
||||
private PbsInlineHintSurfaceFormatter formatter = new PbsInlineHintSurfaceFormatter();
|
||||
|
||||
@Override
|
||||
public void collect(final PbsAst.LetStatement letStatement, final TypeView inferredType) {
|
||||
@@ -167,6 +167,7 @@ final class PbsFlowBodyAnalyzer {
|
||||
diagnostics);
|
||||
}
|
||||
for (final var ctor : structDecl.ctors()) {
|
||||
new PbsCtorInitializationAnalyzer(model).validate(structDecl, ctor, diagnostics);
|
||||
validateCallableBody(
|
||||
ctor.parameters(),
|
||||
ctor.body(),
|
||||
|
||||
+6
-2
@@ -318,7 +318,7 @@ final class PbsFlowStatementAnalyzer {
|
||||
analyzeReturnErr(errExpr, context);
|
||||
return;
|
||||
}
|
||||
expressionAnalyzer.analyzeExpression(
|
||||
final var actual = expressionAnalyzer.analyzeExpression(
|
||||
value,
|
||||
context.scope(),
|
||||
context.returnType(),
|
||||
@@ -329,7 +329,11 @@ final class PbsFlowStatementAnalyzer {
|
||||
context.diagnostics(),
|
||||
ExprUse.VALUE,
|
||||
true,
|
||||
this::analyzeNestedBlock);
|
||||
this::analyzeNestedBlock).type();
|
||||
if (!typeOps.compatible(actual, context.returnType())) {
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_RETURN_TYPE_MISMATCH",
|
||||
"Returned value does not match the declared result type", value.span());
|
||||
}
|
||||
}
|
||||
|
||||
private void analyzeReturnOk(
|
||||
|
||||
+5
-1
@@ -4,6 +4,9 @@ import p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.TupleField;
|
||||
import p.studio.compiler.pbs.semantics.PbsFlowSemanticSupport.TypeView;
|
||||
|
||||
final class PbsInlineHintSurfaceFormatter {
|
||||
private final p.studio.compiler.pbs.PbsContractTypes types;
|
||||
PbsInlineHintSurfaceFormatter() { this(null); }
|
||||
PbsInlineHintSurfaceFormatter(p.studio.compiler.pbs.PbsContractTypes types) { this.types = types; }
|
||||
String format(final TypeView type) {
|
||||
if (type == null) {
|
||||
return null;
|
||||
@@ -18,7 +21,8 @@ final class PbsInlineHintSurfaceFormatter {
|
||||
ENUM,
|
||||
ERROR,
|
||||
TYPE_REF,
|
||||
ADDRESSABLE -> type.name();
|
||||
ADDRESSABLE -> types == null || type.name() == null || !type.name().startsWith("$generic$") ? type.name()
|
||||
: types.display(p.studio.compiler.pbs.ast.PbsAst.TypeRef.simple(type.name(), p.studio.compiler.source.Span.none()));
|
||||
case FN -> "Fn(" + type.functionInputs().stream().map(this::format)
|
||||
.collect(java.util.stream.Collectors.joining(", ")) + ") -> " + format(type.functionOutput());
|
||||
case ARRAY -> {
|
||||
|
||||
+10
-3
@@ -58,7 +58,9 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
final var nameTable = ctx.nameTable();
|
||||
final var feSurfaceContext = ctx.feSurfaceContext();
|
||||
final var assembly = moduleAssemblyService.assemble(ctx, nameTable, diagnostics, issues);
|
||||
final var parsedSourceFiles = assembly.parsedSourceFiles();
|
||||
final var sourceContexts = importedSemanticContextService.build(assembly.parsedSourceFiles(), assembly.moduleTable());
|
||||
final var parsedSourceFiles = new PbsGenericProgramService().prepare(assembly.parsedSourceFiles(), sourceContexts,
|
||||
assembly.moduleTable(), diagnostics, feSurfaceContext);
|
||||
final var importedSemanticContexts = importedSemanticContextService.build(parsedSourceFiles, assembly.moduleTable());
|
||||
projectLifecycleSemanticsValidator.validate(parsedSourceFiles.asList(), diagnostics);
|
||||
final var failedModuleIds = assembly.mutableFailedModuleIds();
|
||||
@@ -127,6 +129,11 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
final var importedSemanticContexts = service.importedSemanticContextService.build(
|
||||
assembly.parsedSourceFiles(),
|
||||
assembly.moduleTable());
|
||||
final var semanticFiles = new PbsGenericProgramService().prepare(assembly.parsedSourceFiles(), importedSemanticContexts,
|
||||
assembly.moduleTable(), diagnostics, ctx.feSurfaceContext());
|
||||
final var semanticContexts = service.importedSemanticContextService.build(semanticFiles, assembly.moduleTable());
|
||||
final var semanticAstByFile = new HashMap<FileId, p.studio.compiler.pbs.ast.PbsAst.File>();
|
||||
semanticFiles.forEach(f -> semanticAstByFile.put(f.fileId(), f.ast()));
|
||||
final var flowSemanticsValidator = new PbsFlowSemanticsValidator();
|
||||
final Map<FileId, p.studio.compiler.pbs.ast.PbsAst.File> astByFile = new LinkedHashMap<>();
|
||||
final Map<FileId, ReadOnlyList<p.studio.compiler.pbs.ast.PbsAst.TopDecl>> supplementalTopDeclsByFile = new LinkedHashMap<>();
|
||||
@@ -149,8 +156,8 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
parsedSourceFile.fileId(),
|
||||
PbsImportedSemanticContext.empty());
|
||||
final var inlineHints = flowSemanticsValidator.collectInlineHints(
|
||||
parsedSourceFile.ast(),
|
||||
importedSemanticContext.supplementalTopDecls(),
|
||||
semanticAstByFile.get(parsedSourceFile.fileId()),
|
||||
semanticContexts.getOrDefault(parsedSourceFile.fileId(), PbsImportedSemanticContext.empty()).supplementalTopDecls(),
|
||||
ctx.feSurfaceContext(),
|
||||
diagnostics);
|
||||
if (!inlineHints.isEmpty()) {
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package p.studio.compiler.services;
|
||||
|
||||
import p.studio.compiler.pbs.PbsContractTypes;
|
||||
import p.studio.compiler.pbs.PbsGenericInstantiation;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.tables.ModuleTable;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
/** Instantiates once per program and emits bodies in their definition modules. */
|
||||
final class PbsGenericProgramService {
|
||||
ReadOnlyList<PbsParsedSourceFile> prepare(ReadOnlyList<PbsParsedSourceFile> files,
|
||||
Map<FileId, PbsImportedSemanticContext> contexts, ModuleTable modules, DiagnosticSink diagnostics,
|
||||
p.studio.compiler.messages.FESurfaceContext surface) {
|
||||
if (files.stream().noneMatch(f -> PbsGenericInstantiation.needed(f.ast()))) return files;
|
||||
var sources = files.stream().map(f -> new PbsGenericInstantiation.Source(f.ast(),
|
||||
contexts.getOrDefault(f.fileId(), PbsImportedSemanticContext.empty()).supplementalTopDecls(), f.moduleId())).toList();
|
||||
var prepared = new PbsGenericInstantiation(sources, diagnostics, surface).prepare();
|
||||
var sourceByFile = new HashMap<FileId, PbsParsedSourceFile>();
|
||||
files.forEach(f -> sourceByFile.put(f.fileId(), f));
|
||||
var output = new ArrayList<PbsParsedSourceFile>();
|
||||
for (var file : files) {
|
||||
var ast = prepared.files().get(file.fileId());
|
||||
var imports = new ArrayList<>(ast.imports().asList());
|
||||
var requested = prepared.dependencies().getOrDefault(file.fileId(), Set.of());
|
||||
var generatedImports = new HashMap<FileId, LinkedHashMap<String, String>>();
|
||||
for (var provider : prepared.files().entrySet()) {
|
||||
if (file.moduleId().equals(sourceByFile.get(provider.getKey()).moduleId())) continue;
|
||||
for (var declaration : provider.getValue().topDecls()) {
|
||||
var origin = PbsContractTypes.applicationOrigin(declaration);
|
||||
if (origin != null && requested.contains(origin.declaration()))
|
||||
generatedImports.computeIfAbsent(provider.getKey(), ignored -> new LinkedHashMap<>()).put(PbsGenericInstantiation.name(declaration), null);
|
||||
else if (origin == null && requested.stream().anyMatch(d -> d.getClass() == declaration.getClass()
|
||||
&& d.span().equals(declaration.span())) && PbsGenericInstantiation.name(declaration) != null)
|
||||
generatedImports.computeIfAbsent(provider.getKey(), ignored -> new LinkedHashMap<>()).put(
|
||||
PbsGenericInstantiation.name(declaration), PbsGenericInstantiation.nominalBinding(declaration));
|
||||
}
|
||||
}
|
||||
for (var imported : generatedImports.entrySet()) {
|
||||
var provider = sourceByFile.get(imported.getKey());
|
||||
var module = modules.get(provider.moduleId());
|
||||
imports.add(new PbsAst.ImportDecl(ReadOnlyList.wrap(imported.getValue().entrySet().stream().map(entry ->
|
||||
new PbsAst.ImportItem(entry.getKey(), entry.getValue(), ast.span())).toList()),
|
||||
new PbsAst.ModuleRef(module.project(), module.pathSegments(), ast.span()), ast.span()));
|
||||
}
|
||||
output.add(new PbsParsedSourceFile(file.fileId(), new PbsAst.File(ReadOnlyList.wrap(imports), ast.topDecls(), ast.span()), file.moduleId(), file.sourceKind()));
|
||||
}
|
||||
return ReadOnlyList.wrap(output);
|
||||
}
|
||||
}
|
||||
+9
-4
@@ -58,7 +58,8 @@ final class PbsImportedSemanticContextService {
|
||||
var importedIndex = topDeclsByNameByModule.getOrDefault(target, Map.of());
|
||||
var localIndex = topDeclsByNameByModule.get(source.moduleId());
|
||||
for (var item : imported.items()) for (var declaration : new ArrayList<>(importedIndex.getOrDefault(item.name(), new ArrayList<>())))
|
||||
if (declaration instanceof PbsAst.ContractDecl) {
|
||||
if (declaration instanceof PbsAst.ContractDecl || declaration instanceof PbsAst.StructDecl
|
||||
|| declaration instanceof PbsAst.FunctionDecl) {
|
||||
var candidates = localIndex.computeIfAbsent(importItemLocalName(item), ignored -> new ArrayList<>());
|
||||
if (candidates.stream().noneMatch(d -> d.span().equals(declaration.span()))) {
|
||||
candidates.add(declaration); exportedContractsChanged = true;
|
||||
@@ -82,7 +83,7 @@ final class PbsImportedSemanticContextService {
|
||||
for (var sibling : sourcesByModule.getOrDefault(parsedSource.moduleId(), new ArrayList<>())) {
|
||||
if (sibling.fileId().equals(parsedSource.fileId())) continue;
|
||||
for (var declaration : sibling.ast().topDecls()) {
|
||||
if (isTypeDecl(declaration)) appendSupplementalTopDecl(
|
||||
if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl(
|
||||
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys);
|
||||
if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
|
||||
}
|
||||
@@ -110,12 +111,12 @@ final class PbsImportedSemanticContextService {
|
||||
final var directDecls = importedTopDeclsByName.getOrDefault(importName, new ArrayList<>());
|
||||
for (final var topDecl : directDecls) {
|
||||
appendSupplementalTopDecl(topDecl, supplementalTopDecls, supplementalKeys);
|
||||
if (isTypeDecl(topDecl)) appendSupplementalTopDecl(new PbsAst.TypeBindingDecl(localName, topDecl, importItem.span()), supplementalTopDecls, supplementalKeys);
|
||||
if (isTypeDecl(topDecl) || topDecl instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl(new PbsAst.TypeBindingDecl(localName, topDecl, importItem.span()), supplementalTopDecls, supplementalKeys);
|
||||
var definingModule = moduleBySource.getOrDefault(topDecl.span().getFileId(), importedModuleId);
|
||||
appendTypeDependencyDecls(topDecl, topDeclsByNameByModule.getOrDefault(definingModule, importedTopDeclsByName), supplementalTopDecls, supplementalKeys);
|
||||
if (topDecl instanceof PbsAst.StructDecl || topDecl instanceof PbsAst.ServiceDecl) {
|
||||
for (var ownerSource : importedSources) for (var declaration : ownerSource.ast().topDecls())
|
||||
if (declaration instanceof PbsAst.ImplementsDecl implementation && implementation.ownerName().equals(importName)) {
|
||||
if (declaration instanceof PbsAst.ImplementsDecl implementation && implementation.ownerType().name().equals(importName)) {
|
||||
appendSupplementalTopDecl(implementation, supplementalTopDecls, supplementalKeys);
|
||||
appendTypeDependencyDecls(implementation, importedTopDeclsByName, supplementalTopDecls, supplementalKeys);
|
||||
}
|
||||
@@ -235,6 +236,10 @@ final class PbsImportedSemanticContextService {
|
||||
final Map<String, ArrayList<PbsAst.TopDecl>> index = new HashMap<>();
|
||||
for (final var source : moduleSources) {
|
||||
for (final var topDecl : source.ast().topDecls()) {
|
||||
if (topDecl instanceof PbsAst.TypeBindingDecl binding) {
|
||||
index.computeIfAbsent(binding.name(), ignored -> new ArrayList<>()).add(binding.declaration());
|
||||
continue;
|
||||
}
|
||||
final var declName = topDeclName(topDecl);
|
||||
if (declName == null || declName.isBlank()) {
|
||||
continue;
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
declare struct Box<T>(value: T) {
|
||||
fn get() -> T { return this.value; }
|
||||
fn set(value: T) { this.value = value; }
|
||||
}
|
||||
|
||||
declare contract Reader<T> { fn read() -> T; }
|
||||
|
||||
implements<T> Reader<T> for Box<T> using box {
|
||||
fn read() -> T { return box.get(); }
|
||||
}
|
||||
|
||||
fn read<T>(reader: Reader<T>) -> T { return reader.read(); }
|
||||
|
||||
fn genericsExample() -> int {
|
||||
let box: Box<int> = new Box<>(40);
|
||||
let alias = box;
|
||||
alias.set(42);
|
||||
let reader: Reader<int> = box;
|
||||
let invoke: Fn(Reader<int>) -> int = read<int>;
|
||||
return invoke(reader);
|
||||
}
|
||||
+1
@@ -1,3 +1,4 @@
|
||||
pub fn init() -> void;
|
||||
pub fn frame() -> void;
|
||||
pub fn contractExample() -> int;
|
||||
pub fn genericsExample() -> int;
|
||||
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsGenericStructsTest {
|
||||
private static final String BOX = """
|
||||
declare struct Box<T>(value: T) {
|
||||
fn get() -> T { return this.value; }
|
||||
fn set(value: T) { this.value = value; }
|
||||
}
|
||||
""";
|
||||
private DiagnosticSink compile(String source) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
return diagnostics;
|
||||
}
|
||||
private void accepts(String source) {
|
||||
var diagnostics = compile(source);
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString());
|
||||
}
|
||||
private void rejects(String source, String code) {
|
||||
var diagnostics = compile(source);
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals(code)), () -> diagnostics.stream().map(d -> d.getCode()+": "+d.getMessage()).toList().toString());
|
||||
}
|
||||
@Test void specializesStateMethodsAndContextualConstructions() {
|
||||
accepts(BOX+"""
|
||||
fn main() -> int {
|
||||
let a = new Box<int>(40);
|
||||
let b: Box<int> = new Box<>(41);
|
||||
let c: Box<int> = new Box(42);
|
||||
a.set(c.get()); return a.get();
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void explicitFreeFunctionsBecomeFnValuesAndComposeWithGenericDispatch() {
|
||||
accepts(BOX+"""
|
||||
declare contract Reader<T> { fn read() -> T; }
|
||||
implements<T> Reader<T> for Box<T> using box { fn read() -> T { return box.get(); } }
|
||||
fn read<T>(reader: Reader<T>) -> T { return reader.read(); }
|
||||
fn main() -> int {
|
||||
let box = new Box<int>(42);
|
||||
let reader: Reader<int> = box;
|
||||
let invoke: Fn(Reader<int>) -> int = read<int>;
|
||||
return invoke(reader);
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void rejectsUnjustifiedCapabilitiesEvenWhenTemplateIsUnused() {
|
||||
rejects("fn double<T>(value: T) -> T { return value + value; }", "E_SEM_GENERIC_CAPABILITY");
|
||||
rejects(BOX+"fn main() { let x = new Box(42); }", "E_SEM_GENERIC_CONTEXT");
|
||||
rejects("fn identity<T>(value: T) -> T { return value; } fn main() { let x = identity(42); }", "E_SEM_GENERIC_FUNCTION_ARGUMENTS");
|
||||
}
|
||||
@Test void rejectsOverlappingRulesWithoutRequestingTheConflictingApplication() {
|
||||
rejects(BOX+"""
|
||||
declare contract Reader<T> { fn read() -> T; }
|
||||
implements<T> Reader<T> for Box<T> using box { fn read() -> T { return box.get(); } }
|
||||
implements Reader<int> for Box<int> using box { fn read() -> int { return box.get(); } }
|
||||
""", "E_SEM_GENERIC_OVERLAP");
|
||||
}
|
||||
|
||||
@Test void substitutesNestedBodiesAndSnapshotCaptures() {
|
||||
accepts(BOX+"""
|
||||
fn box<U>(value: U) -> Box<U> { return new Box<U>(value); }
|
||||
fn wrap<T>(value: T) -> Fn() -> T {
|
||||
let owner: Box<T> = box<T>(value);
|
||||
return fn [owner]() -> T { return owner.get(); };
|
||||
}
|
||||
fn main() -> int { let read = wrap<int>(42); return read(); }
|
||||
""");
|
||||
}
|
||||
@Test void composesOptionalTupleArrayAndFunctionFields() {
|
||||
accepts(BOX+"""
|
||||
fn add(value: int) -> int { return value + 2; }
|
||||
fn main() -> int {
|
||||
let option = new Box<optional int>(some(40));
|
||||
let pair = new Box<(left: int, right: int)>((left: 20, right: 22));
|
||||
let array = new Box<array<int>>([40]);
|
||||
let function = new Box<Fn(int) -> int>(add);
|
||||
let values = pair.get();
|
||||
let call = function.get();
|
||||
return call(array.get()[0] else 0);
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void checksUnusedMethodsAndRejectsCollapsingOverloads() {
|
||||
rejects("""
|
||||
declare struct Container<T>(value: T) {
|
||||
fn unused() { let values: array<T> = new array(1); }
|
||||
}
|
||||
fn main() { let c = new Container<optional int>(none); }
|
||||
""", "E_SEM_ARRAY_ELEMENT_TYPE");
|
||||
rejects("""
|
||||
declare struct Overload<T>(value: T) {
|
||||
fn set(value: T) { this.value = value; }
|
||||
fn set(value: int) { }
|
||||
}
|
||||
fn main() { let c = new Overload<int>(42); }
|
||||
""", "E_SEM_GENERIC_COLLISION");
|
||||
}
|
||||
@Test void supportsNominalRecursionAndBoundsExpansionThroughUnusedBodies() {
|
||||
accepts("""
|
||||
declare struct Node<T>(value: T, next: optional Node<T>) {
|
||||
fn get() -> T { return this.value; }
|
||||
}
|
||||
fn main() -> int { let node = new Node<int>(42, none); return node.get(); }
|
||||
""");
|
||||
rejects("""
|
||||
declare struct Growing<T>(value: T) {
|
||||
fn unused() { let larger = new Growing<array<T>>([this.value]); }
|
||||
}
|
||||
fn main() { let c = new Growing<int>(42); }
|
||||
""", "E_SEM_GENERIC_EXPANSION");
|
||||
}
|
||||
@Test void acceptsNamedConstructorsAppliedSelfAndDifferentContractTargets() {
|
||||
accepts("""
|
||||
declare struct Box<T>(value: T) {
|
||||
ctor make(value: T) { this.value = value; }
|
||||
fn same() -> Self { return this; }
|
||||
fn get() -> T { return this.value; }
|
||||
}
|
||||
fn main() -> int { let b = new Box<int>.make(42); return b.same().get(); }
|
||||
""");
|
||||
}
|
||||
@Test void preservesNominalArgumentsAndResolvesEveryExpectedConstructionPosition() {
|
||||
accepts(BOX+"""
|
||||
declare struct Enemy(pub hp: int);
|
||||
fn take(value: Box<Enemy>) -> Box<Enemy> { return value; }
|
||||
fn make() -> Box<Enemy> { return new Box(new Enemy(42)); }
|
||||
fn main() -> int {
|
||||
let box = make();
|
||||
box = new Box<>(new Enemy(42));
|
||||
let selected = take(new Box(new Enemy(42)));
|
||||
return selected.get().hp;
|
||||
}
|
||||
""");
|
||||
}
|
||||
@Test void unusedTemplatesStillObeyOrdinaryFlowAndConstructorRules() {
|
||||
rejects("fn unfinished<T>(value: T) -> T {}", "E_SEM_POSSIBLE_FALLTHROUGH_NON_UNIT");
|
||||
rejects("fn wrong<T>(value: T) -> int { return true; }", "E_SEM_RETURN_TYPE_MISMATCH");
|
||||
var diagnostics = compile("declare struct Uninitialized<T>(value: T) { ctor make() {} }");
|
||||
assertTrue(diagnostics.hasErrors(), "An unused generic constructor must initialize its fields");
|
||||
}
|
||||
@Test void constructorsRequireInitializationAcrossBranchesAndLoopExits() {
|
||||
accepts("""
|
||||
declare struct Box<T>(value: T) {
|
||||
ctor choose(flag: bool, a: T, b: T) {
|
||||
if flag { this.value = a; } else { this.value = b; }
|
||||
}
|
||||
ctor once(value: T) { while true { this.value = value; break; } }
|
||||
}
|
||||
fn main() { let value = new Box<int>.choose(true, 40, 42); }
|
||||
""");
|
||||
rejects("declare struct Box(value: int) { ctor choose(flag: bool) { if flag { this.value = 42; } } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
rejects("declare struct Box<T>(value: T) { ctor loop(value: T) { for i: int from 0 until 1 { this.value = value; } } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
rejects("declare struct Box(value: int) { ctor loop(flag: bool) { while true { if flag { break; } this.value = 42; break; } } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
rejects("declare struct Box(value: int) { ctor choose(flag: bool) { let ignored = flag and { this.value = 42; true }; } }",
|
||||
"E_SEM_CTOR_FIELD_UNINITIALIZED");
|
||||
}
|
||||
@Test void preservesCallableFieldsAndLexicalApplicationScope() {
|
||||
accepts("""
|
||||
declare struct Callback<T>(transform: Fn(T) -> T) {
|
||||
fn invoke(value: T) -> T { return this.transform(value); }
|
||||
}
|
||||
fn identity<T>(value: T) -> T { return value; }
|
||||
fn main() -> int { let transform = new Callback<int>(identity<int>); return transform.invoke(42); }
|
||||
""");
|
||||
rejects("fn id<T>(value: T) -> T { return value; } fn main() { let id = id<int>; id<int>(42); }",
|
||||
"E_SEM_GENERIC_FUNCTION_ARGUMENTS");
|
||||
rejects("declare struct Marker<T>(); fn main() { let marker = new Marker<Self>(); }", "E_SEM_INVALID_SELF_CONTEXT");
|
||||
}
|
||||
@Test void filtersExplicitOverloadsAndPreservesComparisonsAndNestedClosers() {
|
||||
accepts("""
|
||||
declare struct Box<T>(value: T);
|
||||
fn identity(value: bool) -> bool { return value; }
|
||||
fn identity<T>(value: T) -> T { return value; }
|
||||
fn main() -> int {
|
||||
let nested = identity<Box<array<int>>>(new Box<array<int>>([42]));
|
||||
let a = 1; let b = 2; let c = 3;
|
||||
if a < b && c >= b && identity(true) { return 42; }
|
||||
return identity<int>(0);
|
||||
}
|
||||
""");
|
||||
rejects("fn duplicate<T>(value: T) -> T { return value; } fn duplicate<U>(value: U) -> U { return value; }",
|
||||
"E_SEM_GENERIC_DUPLICATE");
|
||||
accepts("fn recurse<T>(value: T, stop: bool) -> T { if stop { return value; } return recurse<T>(value, true); } fn main() -> int { return recurse<int>(42, false); }");
|
||||
rejects("fn grow<T>(value: T) { grow<array<T>>([value]); } fn main() { grow<int>(42); }", "E_SEM_GENERIC_EXPANSION");
|
||||
}
|
||||
@Test void concreteErrorsRetainDefinitionAndRequestingUse() {
|
||||
String source = "declare struct Storage<T>(values: array<T>); fn main() { let value = new Storage<optional int>([]); }";
|
||||
var diagnostics = compile(source);
|
||||
var error = diagnostics.stream().filter(d -> d.getCode().equals("E_SEM_ARRAY_ELEMENT_TYPE")).findFirst().orElseThrow();
|
||||
assertTrue(error.getMessage().contains("Storage<optional int>"), error.getMessage());
|
||||
assertFalse(error.getMessage().contains("$generic$"), error.getMessage());
|
||||
assertTrue(error.getRelated().stream().anyMatch(r -> r.getSpan().getStart() == 0));
|
||||
assertTrue(error.getRelated().stream().anyMatch(r -> r.getSpan().getStart() >= source.indexOf("new Storage")));
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package p.studio.compiler.pbs.semantics;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||
import p.studio.compiler.pbs.parser.PbsParser;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsGenericStructsEditorialTest {
|
||||
private PbsAst.File parse(String source, int id) {
|
||||
var diagnostics = DiagnosticSink.empty(); var file = new FileId(id);
|
||||
var ast = PbsParser.parse(PbsLexer.lex(source, file, diagnostics), file, diagnostics, PbsParser.ParseMode.ORDINARY);
|
||||
assertFalse(diagnostics.hasErrors(), diagnostics.toString()); return ast;
|
||||
}
|
||||
@Test void symbolicNavigationAndConcreteSignaturesShareSourceOrigins() {
|
||||
var source = """
|
||||
declare struct Box<T>(value: T) { fn get() -> T { return this.value; } }
|
||||
fn identity<U>(value: U) -> U { return value; }
|
||||
fn demo() -> int {
|
||||
let box: Box<int> = new Box<int>(42);
|
||||
let copy = identity<int>(42);
|
||||
return box.get();
|
||||
}
|
||||
""";
|
||||
var ast = parse(source, 0); var service = new PbsEditorialSupportService();
|
||||
var empty = ReadOnlyList.<PbsAst.TopDecl>empty();
|
||||
var parameter = service.definition(source, ast, empty, source.indexOf("value: T")+7);
|
||||
assertEquals(source.indexOf("<T>")+1, parameter.getFirst().span().getStart());
|
||||
assertTrue(service.hover(source, ast, empty, source.indexOf("value: T")+7).orElseThrow().detail().contains("type parameter"));
|
||||
var hover = service.hover(source, ast, empty, source.indexOf("Box<int>"));
|
||||
assertEquals("Box<int>", hover.orElseThrow().displayName());
|
||||
assertEquals("get() -> int", hover.orElseThrow().signatures().getFirst().label());
|
||||
int member = source.indexOf("box.get")+4;
|
||||
assertTrue(service.completion(source, ast, empty, member).stream().anyMatch(c -> c.label().equals("get") && c.detail().contains("int")));
|
||||
assertFalse(service.definition(source, ast, empty, member).isEmpty());
|
||||
assertEquals("identity<int>(value: int) -> int", service.signatureHelp(source, ast, empty,
|
||||
source.indexOf("identity<int>(42")+14).orElseThrow().signatures().getFirst().label());
|
||||
var usages = service.references(source, ast, empty, source.indexOf("<T>")+1);
|
||||
assertTrue(usages.size() >= 3);
|
||||
int symbolicMember = source.indexOf("this.value") + 5;
|
||||
assertTrue(service.completion(source, ast, empty, symbolicMember).stream()
|
||||
.anyMatch(c -> c.label().equals("value") && c.detail().equals("T")));
|
||||
assertEquals("T", service.hover(source, ast, empty, symbolicMember).orElseThrow().detail());
|
||||
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
|
||||
parse(formatted, 0);
|
||||
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
|
||||
}
|
||||
@Test void importedGenericAliasesKeepCanonicalPresentationAndDefinitionSpans() {
|
||||
var remote = parse("declare struct Box<T>(value: T) { fn get() -> T { return this.value; } }", 1);
|
||||
var source = "import { Box as Package } from @sdk:boxes; fn demo(box: Package<int>) -> int { return box.get(); }";
|
||||
var ast = parse(source, 2);
|
||||
var supplemental = ReadOnlyList.wrap(java.util.List.<PbsAst.TopDecl>of(new PbsAst.TypeBindingDecl("Package", remote.topDecls().getFirst(), ast.span())));
|
||||
var service = new PbsEditorialSupportService();
|
||||
assertEquals(remote.topDecls().getFirst().span(), service.definition(source, ast, supplemental, source.indexOf("Package<int>")).getFirst().span());
|
||||
assertEquals("Box<int>", service.hover(source, ast, supplemental, source.indexOf("Package<int>")).orElseThrow().displayName());
|
||||
assertEquals("get() -> int", service.hover(source, ast, supplemental, source.indexOf("box.get")+4).orElseThrow().signatures().getFirst().label());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user