feat(pbs): add parametric arrays and concrete generic contracts
Support explicit contract type parameters, canonical nominal applications, recursive substitution, concrete implementations and instantiated editor views. Complete parametric Array syntax and contextual construction integration. Preserve type origins across imports and reexports, fix trait argument stack order, and relocate global slots before lifecycle assembly. Publish specs, installed examples and consolidated discussion lessons. Validate frontend, common pipeline, architecture, LSP and installed knowledge gates, plus the full production VM conformance corpus with 14 generic fixtures.
This commit is contained in:
+325
@@ -0,0 +1,325 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.pbs.ast.PbsTypeTraversal;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.diagnostics.Diagnostics;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** PBS-owned nominal applications and recursive signature substitution, shared by all consumers. */
|
||||
public final class PbsContractTypes {
|
||||
// Match existing type-depth and Registry graph/storage ceilings; never relax provider limits.
|
||||
private static final int MAX_DEPTH = 256;
|
||||
private static final int MAX_INSTANCES = 65_536;
|
||||
private static final int MAX_WORK = 1_048_576;
|
||||
private static final long MAX_KEY_CHARS = 64L * 1024 * 1024;
|
||||
private static final Set<String> BUILTINS = Set.of("int", "long", "float", "bool", "str", "Addressable");
|
||||
|
||||
public record Instance(String key, PbsAst.TypeRef type, PbsAst.ContractDecl declaration) {}
|
||||
|
||||
private final Map<String, PbsAst.TopDecl> declarations = new LinkedHashMap<>();
|
||||
private final Map<p.studio.compiler.source.identifiers.FileId, Map<String, PbsAst.TopDecl>> scopes = new HashMap<>();
|
||||
private final Map<String, Instance> instances = new LinkedHashMap<>();
|
||||
private final IdentityHashMap<PbsAst.TypeRef, String> keys = new IdentityHashMap<>();
|
||||
private final ArrayDeque<PbsAst.TypeRef> pending = new ArrayDeque<>();
|
||||
private final List<PbsAst.ImplementsDecl> implementations = new ArrayList<>();
|
||||
private final Set<String> reported = new HashSet<>();
|
||||
private final DiagnosticSink diagnostics;
|
||||
private long keyChars;
|
||||
private int work;
|
||||
private boolean failed;
|
||||
|
||||
public PbsContractTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, DiagnosticSink diagnostics) {
|
||||
this.diagnostics = diagnostics;
|
||||
supplemental.forEach(this::index);
|
||||
ast.topDecls().forEach(this::index);
|
||||
for (var imported : ast.imports()) for (var item : imported.items()) {
|
||||
if (item.alias() != null && !item.alias().isBlank() && !declarations.containsKey(item.alias())) {
|
||||
var declaration = declarations.get(item.name());
|
||||
if (declaration != null) declarations.put(item.alias(), declaration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void index(PbsAst.TopDecl declaration) {
|
||||
if (declaration instanceof PbsAst.TypeBindingDecl binding) {
|
||||
index(binding.declaration());
|
||||
declarations.put(binding.name(), binding.declaration());
|
||||
scopes.computeIfAbsent(binding.span().getFileId(), ignored -> new HashMap<>()).put(binding.name(), binding.declaration());
|
||||
return;
|
||||
}
|
||||
String name = switch (declaration) {
|
||||
case PbsAst.ContractDecl d -> d.name();
|
||||
case PbsAst.StructDecl d -> d.name();
|
||||
case PbsAst.ServiceDecl d -> d.name();
|
||||
case PbsAst.BuiltinTypeDecl d -> d.name();
|
||||
case PbsAst.EnumDecl d -> d.name();
|
||||
case PbsAst.ErrorDecl d -> d.name();
|
||||
default -> null;
|
||||
};
|
||||
if (name != null) {
|
||||
declarations.put(name, declaration);
|
||||
scopes.computeIfAbsent(declaration.span().getFileId(), ignored -> new HashMap<>()).put(name, declaration);
|
||||
}
|
||||
if (declaration instanceof PbsAst.ImplementsDecl implementation && implementations.stream().noneMatch(i -> i.span().equals(implementation.span()))) implementations.add(implementation);
|
||||
}
|
||||
|
||||
public PbsAst.TopDecl declaration(PbsAst.TypeRef type) {
|
||||
if (type == null) return null;
|
||||
return scopes.getOrDefault(type.span().getFileId(), Map.of()).getOrDefault(type.name(), declarations.get(type.name()));
|
||||
}
|
||||
|
||||
public String display(PbsAst.TypeRef type) {
|
||||
if (type == null) return "void";
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE) {
|
||||
var declaration = declaration(type);
|
||||
var name = switch (declaration) {
|
||||
case PbsAst.ContractDecl c -> c.name();
|
||||
case PbsAst.StructDecl s -> s.name();
|
||||
case PbsAst.ServiceDecl s -> s.name();
|
||||
case PbsAst.BuiltinTypeDecl b -> b.name();
|
||||
case PbsAst.EnumDecl e -> e.name();
|
||||
case PbsAst.ErrorDecl e -> e.name();
|
||||
case null, default -> type.name();
|
||||
};
|
||||
return name + (type.arguments().isEmpty() ? "" : "<" + type.arguments().stream().map(this::display).collect(Collectors.joining(", ")) + ">");
|
||||
}
|
||||
return switch (type.kind()) {
|
||||
case ARRAY -> "array<" + display(type.inner()) + ">";
|
||||
case OPTIONAL -> "optional " + display(type.inner());
|
||||
case GROUP -> "(" + display(type.inner()) + ")";
|
||||
case FN -> "Fn(" + type.fields().stream().map(f -> display(f.typeRef())).collect(Collectors.joining(", ")) + ") -> " + display(type.inner());
|
||||
case NAMED_TUPLE -> "(" + type.fields().stream().map(f -> f.label() + ": " + display(f.typeRef())).collect(Collectors.joining(", ")) + ")";
|
||||
default -> type.surface();
|
||||
};
|
||||
}
|
||||
|
||||
public String implementationCallableName(PbsAst.ImplementsDecl implementation, String method) {
|
||||
var template = template(implementation.contractType());
|
||||
var contractKey = "pbs:contract:file" + template.span().getFileId().getId() + ":" + template.span().getStart()
|
||||
+ (implementation.contractType().arguments().isEmpty() ? "" : ":" + key(implementation.contractType()));
|
||||
return implementation.ownerName() + ".$impl." + contractKey + "." + method;
|
||||
}
|
||||
|
||||
public boolean isContract(PbsAst.TypeRef type) {
|
||||
return type != null && type.kind() == PbsAst.TypeRefKind.SIMPLE
|
||||
&& declaration(type) instanceof PbsAst.ContractDecl;
|
||||
}
|
||||
|
||||
public PbsAst.ContractDecl template(PbsAst.TypeRef type) {
|
||||
return isContract(type) ? (PbsAst.ContractDecl) declaration(type) : null;
|
||||
}
|
||||
|
||||
public String key(PbsAst.TypeRef type) { return key(type, 0); }
|
||||
|
||||
private String key(PbsAst.TypeRef type, int depth) {
|
||||
if (type == null) return "void";
|
||||
var cached = keys.get(type);
|
||||
if (cached != null) return cached;
|
||||
budget(type.span(), depth);
|
||||
String head;
|
||||
var children = new ArrayList<String>();
|
||||
switch (type.kind()) {
|
||||
case GROUP -> { return key(type.inner(), depth + 1); }
|
||||
case SIMPLE -> {
|
||||
var declaration = declaration(type);
|
||||
head = declaration == null ? type.name() : nominal(declaration);
|
||||
for (var argument : type.arguments()) children.add(key(argument, depth + 1));
|
||||
}
|
||||
case FN -> {
|
||||
head = "Fn";
|
||||
for (var input : type.fields()) children.add(key(input.typeRef(), depth + 1));
|
||||
children.add("->" + returnKey(type.inner(), depth + 1));
|
||||
}
|
||||
case NAMED_TUPLE -> {
|
||||
head = "tuple";
|
||||
for (var field : type.fields()) children.add(key(field.typeRef(), depth + 1));
|
||||
}
|
||||
default -> {
|
||||
head = type.kind().name();
|
||||
if (type.inner() != null) children.add(key(type.inner(), depth + 1));
|
||||
}
|
||||
}
|
||||
long length = head.length() + 2L;
|
||||
for (var child : children) length += child.length() + 16L;
|
||||
if (keyChars + length > MAX_KEY_CHARS) throw expansion(type.span(), "Contract type identity storage budget exceeded");
|
||||
// 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);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String nominal(PbsAst.TopDecl declaration) {
|
||||
return "pbs:" + declaration.getClass().getSimpleName() + ":" + declaration.span().getFileId().getId() + ":" + declaration.span().getStart();
|
||||
}
|
||||
|
||||
public Instance resolve(PbsAst.TypeRef type) {
|
||||
if (failed) return null;
|
||||
var template = template(type);
|
||||
if (template == null) return null;
|
||||
if (template.typeParameters().size() != type.arguments().size()) {
|
||||
error("E_SEM_CONTRACT_ARITY", "Contract " + template.name() + " requires " + template.typeParameters().size() + " explicit type argument(s)", type.span());
|
||||
return null;
|
||||
}
|
||||
String key = key(type);
|
||||
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");
|
||||
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());
|
||||
var concrete = new PbsAst.ContractDecl(display(type), signatures, template.attributes(), template.span());
|
||||
var instance = new Instance(key, type, concrete);
|
||||
instances.put(key, instance); // Anchor before discovering recursively referenced applications.
|
||||
for (var signature : signatures) PbsTypeTraversal.signature(signature, t -> validateType(t, Set.of(), false, 0));
|
||||
return instance;
|
||||
}
|
||||
|
||||
public void expand() {
|
||||
while (!pending.isEmpty() && !failed) resolve(pending.removeFirst());
|
||||
}
|
||||
|
||||
public void validate(PbsAst.File ast) {
|
||||
try {
|
||||
for (var declaration : ast.topDecls()) {
|
||||
if (declaration instanceof PbsAst.ContractDecl contract) {
|
||||
var parameters = new HashSet<String>();
|
||||
for (var parameter : contract.typeParameters()) if (!parameters.add(parameter.name()))
|
||||
error("E_SEM_CONTRACT_PARAMETER", "Duplicate contract type parameter " + parameter.name(), parameter.span());
|
||||
PbsTypeTraversal.visit(declaration, t -> validateType(t, parameters, !parameters.isEmpty(), 0));
|
||||
} else {
|
||||
var owner = declaration instanceof PbsAst.StructDecl s ? s.name()
|
||||
: declaration instanceof PbsAst.ServiceDecl s ? s.name() : null;
|
||||
PbsTypeTraversal.visit(declaration, t -> validateType(owner == null ? t : PbsTypeSubstitution.replaceSelf(t, owner), Set.of(), false, 0));
|
||||
}
|
||||
}
|
||||
expand();
|
||||
validateImplementations(ast);
|
||||
} catch (ExpansionFailure failure) {
|
||||
failed = true;
|
||||
pending.clear();
|
||||
}
|
||||
}
|
||||
|
||||
private void validateType(PbsAst.TypeRef type, Set<String> parameters, boolean templateScope, int depth) {
|
||||
if (type == null || failed) return;
|
||||
budget(type.span(), depth);
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE) {
|
||||
var declaration = declaration(type);
|
||||
if (parameters.contains(type.name())) {
|
||||
if (!type.arguments().isEmpty()) error("E_SEM_CONTRACT_PARAMETER", "Type parameter cannot be applied", type.span());
|
||||
} else if (declaration instanceof PbsAst.ContractDecl contract) {
|
||||
if (contract.typeParameters().size() != type.arguments().size())
|
||||
error("E_SEM_CONTRACT_ARITY", "Contract " + type.name() + " requires " + contract.typeParameters().size() + " explicit type argument(s)", type.span());
|
||||
else if (!containsParameter(type, parameters)) pending.add(type);
|
||||
} else if (!type.arguments().isEmpty()) {
|
||||
error("E_SEM_CONTRACT_ARGUMENT", "Only a parameterized contract accepts type arguments", type.span());
|
||||
} else if (templateScope && declaration == null && !BUILTINS.contains(type.name())) {
|
||||
error("E_SEM_CONTRACT_PARAMETER", "Unresolved type or undeclared type parameter " + type.name(), type.span());
|
||||
}
|
||||
}
|
||||
if (type.kind() == PbsAst.TypeRefKind.ARRAY && type.inner() != null) {
|
||||
var element = unwrap(type.inner());
|
||||
if (element.kind() == PbsAst.TypeRefKind.OPTIONAL || element.kind() == PbsAst.TypeRefKind.UNIT)
|
||||
error("E_SEM_ARRAY_ELEMENT_TYPE", "Array elements must be non-optional values after substitution", type.span());
|
||||
}
|
||||
if (type.kind() == PbsAst.TypeRefKind.OPTIONAL && unwrap(type.inner()).kind() == PbsAst.TypeRefKind.UNIT)
|
||||
error("E_SEM_INVALID_OPTIONAL_VOID_TYPE_SURFACE", "optional void is not a valid substituted type", type.span());
|
||||
if (type.kind() == PbsAst.TypeRefKind.FN) for (var input : type.fields())
|
||||
if (unwrap(input.typeRef()).kind() == PbsAst.TypeRefKind.UNIT)
|
||||
error("E_SEM_FN_PARAMETER", "Fn parameter must remain a value type after substitution", input.span());
|
||||
for (var argument : type.arguments()) validateType(argument, parameters, true, depth + 1);
|
||||
for (var field : type.fields()) validateType(field.typeRef(), parameters, templateScope, depth + 1);
|
||||
validateType(type.inner(), parameters, templateScope, depth + 1);
|
||||
}
|
||||
|
||||
private boolean containsParameter(PbsAst.TypeRef type, Set<String> parameters) {
|
||||
if (type == null || parameters.isEmpty()) return false;
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE && parameters.contains(type.name())) return true;
|
||||
if (containsParameter(type.inner(), parameters)) return true;
|
||||
return type.arguments().stream().anyMatch(t -> containsParameter(t, parameters))
|
||||
|| type.fields().stream().anyMatch(f -> containsParameter(f.typeRef(), parameters));
|
||||
}
|
||||
|
||||
private void validateImplementations(PbsAst.File ast) {
|
||||
var seen = new HashSet<String>();
|
||||
for (var implementation : implementations) {
|
||||
var instance = resolve(implementation.contractType());
|
||||
if (instance == null) {
|
||||
error("E_SEM_CONTRACT_IMPLEMENTATION", "Implementation target must be a concrete contract", implementation.contractType().span());
|
||||
continue;
|
||||
}
|
||||
var owner = declaration(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()));
|
||||
if (!(owner instanceof PbsAst.StructDecl) && !(owner instanceof PbsAst.ServiceDecl)) {
|
||||
error("E_SEM_CONTRACT_OWNER", "Contract owner must be a declared struct or service", implementation.span());
|
||||
continue;
|
||||
}
|
||||
var pair = nominal(owner) + ":" + instance.key();
|
||||
if (!seen.add(pair)) error("E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION", "Duplicate implementation of " + implementation.contractName() + " for " + implementation.ownerName(), implementation.span());
|
||||
var expected = instance.declaration().signatures();
|
||||
var matched = new HashSet<PbsAst.FunctionDecl>();
|
||||
for (var signature : expected) {
|
||||
var methods = implementation.methods().stream().filter(m -> matches(m, signature)).toList();
|
||||
if (methods.size() != 1) error("E_SEM_CONTRACT_SIGNATURE", "Implementation must supply exactly one matching " + signature.name() + " for " + implementation.contractName(), implementation.span());
|
||||
else matched.add(methods.getFirst());
|
||||
}
|
||||
if (matched.size() != implementation.methods().size()) error("E_SEM_CONTRACT_SIGNATURE", "Implementation contains extra or incompatible contract methods", implementation.span());
|
||||
}
|
||||
}
|
||||
|
||||
private boolean matches(PbsAst.FunctionDecl method, PbsAst.FunctionSignature signature) {
|
||||
if (!method.name().equals(signature.name()) || method.parameters().size() != signature.parameters().size()) return false;
|
||||
if ((method.returnKind() == PbsAst.ReturnKind.RESULT) != (signature.returnKind() == PbsAst.ReturnKind.RESULT)
|
||||
|| !returnKey(method.returnType()).equals(returnKey(signature.returnType()))) return false;
|
||||
if (!key(method.resultErrorType()).equals(key(signature.resultErrorType()))) return false;
|
||||
for (int i = 0; i < method.parameters().size(); i++) if (!key(method.parameters().get(i).typeRef()).equals(key(signature.parameters().get(i).typeRef()))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private String returnKey(PbsAst.TypeRef type) {
|
||||
return returnKey(type, 0);
|
||||
}
|
||||
|
||||
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();
|
||||
return key(type, depth);
|
||||
}
|
||||
|
||||
public Set<String> implementers(PbsAst.TypeRef target) {
|
||||
var result = new HashSet<String>();
|
||||
var targetKey = key(target);
|
||||
for (var implementation : implementations) if (key(implementation.contractType()).equals(targetKey)) {
|
||||
var owner = declaration(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()));
|
||||
if (owner != null) result.add(key(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span())));
|
||||
declarations.forEach((name, d) -> { if (d == owner || (d != null && owner != null && nominal(d).equals(nominal(owner)))) result.add(name); });
|
||||
}
|
||||
return Set.copyOf(result);
|
||||
}
|
||||
|
||||
public List<Instance> instances() { return List.copyOf(instances.values()); }
|
||||
|
||||
private void budget(Span span, int depth) {
|
||||
if (depth > MAX_DEPTH || ++work > MAX_WORK) throw expansion(span, "Contract expansion exceeds bounded type analysis; recursive applications may expand indefinitely");
|
||||
}
|
||||
|
||||
private ExpansionFailure expansion(Span span, String message) {
|
||||
error("E_SEM_CONTRACT_EXPANSION", message, span);
|
||||
return new ExpansionFailure();
|
||||
}
|
||||
|
||||
private void error(String code, String message, Span span) {
|
||||
if (reported.add(code + ":" + span + ":" + message)) Diagnostics.error(diagnostics, code, message, span);
|
||||
}
|
||||
|
||||
private static PbsAst.TypeRef unwrap(PbsAst.TypeRef type) {
|
||||
while (type != null && type.kind() == PbsAst.TypeRefKind.GROUP) type = type.inner();
|
||||
return type;
|
||||
}
|
||||
|
||||
private static final class ExpansionFailure extends RuntimeException {}
|
||||
}
|
||||
+6
-1
@@ -565,7 +565,12 @@ public final class PbsFrontendCompiler {
|
||||
int returnSlots,
|
||||
PbsAst.ReturnKind returnKind,
|
||||
PbsAst.TypeRef returnType,
|
||||
String shapeSurface) {
|
||||
String shapeSurface,
|
||||
String targetName) {
|
||||
public ImportedCallableSurface(ModuleId moduleId, String callableName, int arity, int returnSlots,
|
||||
PbsAst.ReturnKind returnKind, PbsAst.TypeRef returnType, String shapeSurface) {
|
||||
this(moduleId, callableName, arity, returnSlots, returnKind, returnType, shapeSurface, callableName);
|
||||
}
|
||||
public ImportedCallableSurface {
|
||||
moduleId = moduleId == null ? ModuleId.none() : moduleId;
|
||||
}
|
||||
|
||||
+1
-1
@@ -241,7 +241,7 @@ public final class PbsReservedMetadataExtractor {
|
||||
return "unit";
|
||||
}
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> "simple:" + typeRef.name();
|
||||
case SIMPLE -> "simple:" + typeRef.surface();
|
||||
case SELF -> "self";
|
||||
case FN -> "Fn(" + typeRef.fields().stream().map(f -> typeSurfaceKey(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + typeSurfaceKey(typeRef.inner());
|
||||
case ARRAY -> "array(" + typeSurfaceKey(typeRef.inner()) + ")";
|
||||
|
||||
+20
-1
@@ -2,6 +2,7 @@ package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.Map;
|
||||
|
||||
/** Resolves Self consistently in source signatures and executable metadata. */
|
||||
public final class PbsTypeSubstitution {
|
||||
@@ -17,11 +18,29 @@ public final class PbsTypeSubstitution {
|
||||
new PbsAst.NamedTypeField(field.label(), replaceSelf(field.typeRef(), owner), field.span())).toList()), type.span());
|
||||
}
|
||||
if (type.inner() != null) {
|
||||
return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), replaceSelf(type.inner(), owner), type.span());
|
||||
return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), replaceSelf(type.inner(), owner),
|
||||
ReadOnlyList.wrap(type.arguments().stream().map(t -> replaceSelf(t, owner)).toList()), type.span());
|
||||
}
|
||||
if (!type.arguments().isEmpty()) return new PbsAst.TypeRef(type.kind(), type.name(), type.fields(), null,
|
||||
ReadOnlyList.wrap(type.arguments().stream().map(t -> replaceSelf(t, owner)).toList()), type.span());
|
||||
return type;
|
||||
}
|
||||
|
||||
public static PbsAst.TypeRef substitute(PbsAst.TypeRef type, Map<String, PbsAst.TypeRef> bindings) {
|
||||
if (type == null) return null;
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE && type.arguments().isEmpty() && bindings.containsKey(type.name()))
|
||||
return bindings.get(type.name());
|
||||
return new PbsAst.TypeRef(type.kind(), type.name(), ReadOnlyList.wrap(type.fields().stream().map(f ->
|
||||
new PbsAst.NamedTypeField(f.label(), substitute(f.typeRef(), bindings), f.span())).toList()),
|
||||
substitute(type.inner(), bindings), ReadOnlyList.wrap(type.arguments().stream().map(t -> substitute(t, bindings)).toList()), type.span());
|
||||
}
|
||||
|
||||
public static PbsAst.FunctionSignature substitute(PbsAst.FunctionSignature signature, Map<String, PbsAst.TypeRef> bindings) {
|
||||
return new PbsAst.FunctionSignature(signature.name(), ReadOnlyList.wrap(signature.parameters().stream().map(p ->
|
||||
new PbsAst.Parameter(p.name(), substitute(p.typeRef(), bindings), p.span())).toList()), signature.returnKind(),
|
||||
substitute(signature.returnType(), bindings), substitute(signature.resultErrorType(), bindings), signature.attributes(), signature.span());
|
||||
}
|
||||
|
||||
public static PbsAst.FunctionDecl forOwner(PbsAst.FunctionDecl function, String owner) {
|
||||
var parameters = ReadOnlyList.wrap(function.parameters().stream().map(parameter ->
|
||||
new PbsAst.Parameter(parameter.name(), replaceSelf(parameter.typeRef(), owner), parameter.span())).toList());
|
||||
|
||||
+51
-2
@@ -122,6 +122,7 @@ public final class PbsAst {
|
||||
EnumDecl,
|
||||
GlobalDecl,
|
||||
ConstDecl,
|
||||
TypeBindingDecl,
|
||||
ImplementsDecl,
|
||||
InvalidDecl {
|
||||
Span span();
|
||||
@@ -157,11 +158,21 @@ public final class PbsAst {
|
||||
|
||||
public record ContractDecl(
|
||||
String name,
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
ReadOnlyList<FunctionSignature> signatures,
|
||||
ReadOnlyList<Attribute> attributes,
|
||||
Span span) implements TopDecl {
|
||||
public ContractDecl(String name, ReadOnlyList<FunctionSignature> signatures,
|
||||
ReadOnlyList<Attribute> attributes, Span span) {
|
||||
this(name, ReadOnlyList.empty(), signatures, attributes, span);
|
||||
}
|
||||
}
|
||||
|
||||
public record TypeParameter(String name, Span span) {}
|
||||
|
||||
/** Imported lexical binding; retains the original declaration and the importing source scope. */
|
||||
public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {}
|
||||
|
||||
public record HostDecl(
|
||||
String name,
|
||||
ReadOnlyList<FunctionSignature> signatures,
|
||||
@@ -221,11 +232,16 @@ public final class PbsAst {
|
||||
}
|
||||
|
||||
public record ImplementsDecl(
|
||||
String contractName,
|
||||
TypeRef contractType,
|
||||
String ownerName,
|
||||
String binderName,
|
||||
ReadOnlyList<FunctionDecl> methods,
|
||||
Span span) implements TopDecl {
|
||||
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 record InvalidDecl(
|
||||
@@ -251,7 +267,27 @@ public final class PbsAst {
|
||||
String name,
|
||||
ReadOnlyList<NamedTypeField> fields,
|
||||
TypeRef inner,
|
||||
ReadOnlyList<TypeRef> arguments,
|
||||
Span span) {
|
||||
public TypeRef(TypeRefKind kind, String name, ReadOnlyList<NamedTypeField> fields, TypeRef inner, Span span) {
|
||||
this(kind, name, fields, inner, ReadOnlyList.empty(), span);
|
||||
}
|
||||
public static TypeRef applied(String name, ReadOnlyList<TypeRef> arguments, Span span) {
|
||||
return new TypeRef(TypeRefKind.SIMPLE, name, ReadOnlyList.empty(), null, arguments, span);
|
||||
}
|
||||
public String surface() {
|
||||
return switch (kind) {
|
||||
case SIMPLE -> name + (arguments.isEmpty() ? "" : "<" + arguments.stream().map(TypeRef::surface).collect(java.util.stream.Collectors.joining(", ")) + ">");
|
||||
case ARRAY -> "array<" + inner.surface() + ">";
|
||||
case OPTIONAL -> "optional " + inner.surface();
|
||||
case GROUP -> "(" + inner.surface() + ")";
|
||||
case FN -> "Fn(" + fields.stream().map(f -> f.typeRef().surface()).collect(java.util.stream.Collectors.joining(", ")) + ") -> " + inner.surface();
|
||||
case NAMED_TUPLE -> "(" + fields.stream().map(f -> f.label() + ": " + f.typeRef().surface()).collect(java.util.stream.Collectors.joining(", ")) + ")";
|
||||
case UNIT -> "void";
|
||||
case SELF -> "Self";
|
||||
case ERROR -> "?";
|
||||
};
|
||||
}
|
||||
public static TypeRef function(ReadOnlyList<NamedTypeField> inputs, TypeRef output, Span span) {
|
||||
return new TypeRef(TypeRefKind.FN, "Fn", inputs, output, span);
|
||||
}
|
||||
@@ -589,8 +625,12 @@ public final class PbsAst {
|
||||
|
||||
public record AsExpr(
|
||||
Expression expression,
|
||||
String contractName,
|
||||
TypeRef contractType,
|
||||
Span span) implements Expression {
|
||||
public AsExpr(Expression expression, String contractName, Span span) {
|
||||
this(expression, TypeRef.simple(contractName, span), span);
|
||||
}
|
||||
public String contractName() { return contractType.surface(); }
|
||||
}
|
||||
|
||||
public record CallExpr(
|
||||
@@ -627,7 +667,12 @@ public final class PbsAst {
|
||||
String typeName,
|
||||
String ctorName,
|
||||
ReadOnlyList<Expression> arguments,
|
||||
TypeRef explicitType,
|
||||
boolean diamond,
|
||||
Span span) implements Expression {
|
||||
public NewExpr(String typeName, String ctorName, ReadOnlyList<Expression> arguments, Span span) {
|
||||
this(typeName, ctorName, arguments, null, false, span);
|
||||
}
|
||||
}
|
||||
|
||||
public record LambdaExpr(
|
||||
@@ -725,7 +770,11 @@ public final class PbsAst {
|
||||
public record BarrelContractItem(
|
||||
Visibility visibility,
|
||||
String name,
|
||||
ReadOnlyList<TypeParameter> typeParameters,
|
||||
Span span) implements BarrelItem {
|
||||
public BarrelContractItem(Visibility visibility, String name, Span span) {
|
||||
this(visibility, name, ReadOnlyList.empty(), span);
|
||||
}
|
||||
}
|
||||
|
||||
public record BarrelHostItem(
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package p.studio.compiler.pbs.ast;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Visits source type roots, including annotations inside executable expressions. */
|
||||
public final class PbsTypeTraversal {
|
||||
private PbsTypeTraversal() {}
|
||||
|
||||
public static void visit(PbsAst.TopDecl declaration, Consumer<PbsAst.TypeRef> visitor) {
|
||||
switch (declaration) {
|
||||
case PbsAst.FunctionDecl f -> function(f, visitor);
|
||||
case PbsAst.ContractDecl c -> c.signatures().forEach(s -> signature(s, visitor));
|
||||
case PbsAst.HostDecl h -> h.signatures().forEach(s -> signature(s, visitor));
|
||||
case PbsAst.StructDecl s -> {
|
||||
s.fields().forEach(f -> type(f.typeRef(), visitor));
|
||||
s.methods().forEach(f -> function(f, visitor));
|
||||
s.ctors().forEach(c -> { c.parameters().forEach(p -> type(p.typeRef(), visitor)); block(c.body(), visitor); });
|
||||
}
|
||||
case PbsAst.ServiceDecl s -> {
|
||||
s.methods().forEach(f -> function(f, visitor));
|
||||
s.constants().forEach(c -> visit(c, visitor));
|
||||
}
|
||||
case PbsAst.BuiltinTypeDecl b -> {
|
||||
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.GlobalDecl g -> { type(g.explicitType(), visitor); expression(g.initializer(), visitor); }
|
||||
case PbsAst.ConstDecl c -> { type(c.explicitType(), visitor); expression(c.initializer(), visitor); }
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
|
||||
public static void signature(PbsAst.FunctionSignature s, Consumer<PbsAst.TypeRef> visitor) {
|
||||
s.parameters().forEach(p -> type(p.typeRef(), visitor)); type(s.returnType(), visitor); type(s.resultErrorType(), visitor);
|
||||
}
|
||||
|
||||
private static void function(PbsAst.FunctionDecl f, Consumer<PbsAst.TypeRef> visitor) {
|
||||
f.parameters().forEach(p -> type(p.typeRef(), visitor)); type(f.returnType(), visitor); type(f.resultErrorType(), visitor); block(f.body(), visitor);
|
||||
}
|
||||
|
||||
private static void type(PbsAst.TypeRef t, Consumer<PbsAst.TypeRef> visitor) { if (t != null) visitor.accept(t); }
|
||||
|
||||
public static void block(PbsAst.Block b, Consumer<PbsAst.TypeRef> visitor) {
|
||||
if (b == null) return;
|
||||
for (var statement : b.statements()) switch (statement) {
|
||||
case PbsAst.LetStatement s -> { type(s.explicitType(), visitor); expression(s.initializer(), visitor); }
|
||||
case PbsAst.AssignStatement s -> { expression(s.target().expression(), visitor); expression(s.value(), visitor); }
|
||||
case PbsAst.ReturnStatement s -> expression(s.value(), visitor);
|
||||
case PbsAst.ExpressionStatement s -> expression(s.expression(), visitor);
|
||||
case PbsAst.IfStatement s -> conditional(s, visitor);
|
||||
case PbsAst.WhileStatement s -> { expression(s.condition(), visitor); block(s.body(), visitor); }
|
||||
case PbsAst.ForStatement s -> {
|
||||
type(s.iteratorType(), visitor); expression(s.fromExpression(), visitor); expression(s.untilExpression(), visitor);
|
||||
expression(s.stepExpression(), visitor); block(s.body(), visitor);
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
expression(b.tailExpression(), visitor);
|
||||
}
|
||||
|
||||
private static void conditional(PbsAst.IfStatement s, Consumer<PbsAst.TypeRef> visitor) {
|
||||
if (s == null) return;
|
||||
expression(s.condition(), visitor); block(s.thenBlock(), visitor); block(s.elseBlock(), visitor); conditional(s.elseIf(), visitor);
|
||||
}
|
||||
|
||||
private static void expression(PbsAst.Expression e, Consumer<PbsAst.TypeRef> visitor) {
|
||||
if (e == null) return;
|
||||
switch (e) {
|
||||
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); }
|
||||
case PbsAst.CallExpr c -> { expression(c.callee(), visitor); c.arguments().forEach(a -> expression(a, visitor)); }
|
||||
case PbsAst.ApplyExpr a -> { expression(a.callee(), visitor); expression(a.argument(), visitor); }
|
||||
case PbsAst.BinaryExpr b -> { expression(b.left(), visitor); expression(b.right(), visitor); }
|
||||
case PbsAst.UnaryExpr u -> expression(u.expression(), visitor);
|
||||
case PbsAst.MemberExpr m -> expression(m.receiver(), visitor);
|
||||
case PbsAst.IndexExpr i -> { expression(i.receiver(), visitor); expression(i.index(), visitor); }
|
||||
case PbsAst.ArrayLiteralExpr a -> a.elements().forEach(v -> expression(v, visitor));
|
||||
case PbsAst.TupleExpr t -> t.items().forEach(i -> expression(i.expression(), visitor));
|
||||
case PbsAst.GroupExpr g -> expression(g.expression(), visitor);
|
||||
case PbsAst.SomeExpr s -> expression(s.value(), visitor);
|
||||
case PbsAst.OkExpr o -> expression(o.value(), visitor);
|
||||
case PbsAst.PropagateExpr p -> expression(p.expression(), visitor);
|
||||
case PbsAst.ElseExpr f -> { expression(f.optionalExpression(), visitor); expression(f.fallbackExpression(), visitor); }
|
||||
case PbsAst.BlockExpr b -> block(b.block(), visitor);
|
||||
case PbsAst.IfExpr i -> { expression(i.condition(), visitor); block(i.thenBlock(), visitor); expression(i.elseExpression(), visitor); }
|
||||
case PbsAst.SwitchExpr s -> { expression(s.selector(), visitor); s.arms().forEach(a -> block(a.block(), visitor)); }
|
||||
case PbsAst.HandleExpr h -> { expression(h.value(), visitor); h.arms().forEach(a -> block(a.block(), visitor)); }
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
}
|
||||
+50
-3
@@ -32,13 +32,16 @@ public final class PbsModuleVisibilityValidator {
|
||||
final DiagnosticSink diagnostics) {
|
||||
final var signatureInterning = new SignatureInterning(new TypeSurfaceTable(), new CallableShapeTable());
|
||||
final var exportsByModule = new HashMap<ModuleRefKey, ModuleExports>();
|
||||
final var unitsByModule = new HashMap<ModuleRefKey, ModuleUnit>();
|
||||
for (var module : modules) unitsByModule.put(toModuleRef(module.coordinates()), module);
|
||||
|
||||
for (final var module : modules) {
|
||||
final var exports = validateModule(module, nameTable, signatureInterning, diagnostics);
|
||||
final var exports = validateModule(module, nameTable, signatureInterning, diagnostics, unitsByModule);
|
||||
exportsByModule.put(toModuleRef(module.coordinates()), exports);
|
||||
}
|
||||
|
||||
for (final var module : modules) {
|
||||
validateImplementationOwners(module, diagnostics);
|
||||
validateImports(module, exportsByModule, nameTable, diagnostics);
|
||||
}
|
||||
}
|
||||
@@ -53,7 +56,8 @@ public final class PbsModuleVisibilityValidator {
|
||||
final ModuleUnit module,
|
||||
final NameTable nameTable,
|
||||
final SignatureInterning signatureInterning,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final DiagnosticSink diagnostics,
|
||||
final Map<ModuleRefKey, ModuleUnit> unitsByModule) {
|
||||
final var exports = new ModuleExports();
|
||||
|
||||
if (module.sourceFiles().isEmpty()) {
|
||||
@@ -163,7 +167,10 @@ public final class PbsModuleVisibilityValidator {
|
||||
continue;
|
||||
}
|
||||
|
||||
final var matches = declarations.nonFunctionsByKindAndName.getOrDefault(symbolKey, List.of());
|
||||
var matches = declarations.nonFunctionsByKindAndName.getOrDefault(symbolKey, List.of());
|
||||
var resolvedContract = item instanceof PbsAst.BarrelContractItem contractItem
|
||||
? resolveContractExport(module, contractItem.name(), unitsByModule, new HashSet<>()) : null;
|
||||
if (matches.isEmpty() && resolvedContract != null) matches = List.of(resolvedContract.span());
|
||||
if (matches.isEmpty()) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
PbsLinkErrors.E_LINK_UNRESOLVED_BARREL_ENTRY.name(),
|
||||
@@ -184,6 +191,15 @@ public final class PbsModuleVisibilityValidator {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (item instanceof PbsAst.BarrelContractItem contractItem) {
|
||||
var expected = resolvedContract;
|
||||
if (expected != null && !expected.typeParameters().stream().map(PbsAst.TypeParameter::name).toList().equals(
|
||||
contractItem.typeParameters().stream().map(PbsAst.TypeParameter::name).toList())) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics, "E_LINK_CONTRACT_PARAMETERS",
|
||||
"Barrel contract parameters must preserve the declaration's ordered parameters", contractItem.span());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (nonFunctionVisibility(item) == PbsAst.Visibility.PUB) {
|
||||
exports.publicNameIds.add(symbolKey.nameId());
|
||||
}
|
||||
@@ -192,6 +208,37 @@ public final class PbsModuleVisibilityValidator {
|
||||
return exports;
|
||||
}
|
||||
|
||||
private void validateImplementationOwners(ModuleUnit module, DiagnosticSink diagnostics) {
|
||||
var localOwners = new HashSet<String>();
|
||||
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls()) {
|
||||
if (declaration instanceof PbsAst.StructDecl s) localOwners.add(s.name());
|
||||
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()))
|
||||
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());
|
||||
}
|
||||
|
||||
private record ContractExportKey(ModuleRefKey module, String name) {}
|
||||
|
||||
private PbsAst.ContractDecl resolveContractExport(ModuleUnit module, String name,
|
||||
Map<ModuleRefKey, ModuleUnit> units, Set<ContractExportKey> visited) {
|
||||
if (!visited.add(new ContractExportKey(toModuleRef(module.coordinates()), name))) return null;
|
||||
for (var source : module.sourceFiles()) for (var declaration : source.ast().topDecls())
|
||||
if (declaration instanceof PbsAst.ContractDecl contract && contract.name().equals(name)) return contract;
|
||||
for (var source : module.sourceFiles()) for (var imported : source.ast().imports()) for (var item : imported.items()) {
|
||||
var local = item.alias() == null || item.alias().isBlank() ? item.name() : item.alias();
|
||||
if (!local.equals(name)) continue;
|
||||
var target = units.get(new ModuleRefKey(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
|
||||
if (target == null || target.barrelFiles().stream().noneMatch(b -> b.ast().items().stream().anyMatch(i ->
|
||||
i instanceof PbsAst.BarrelContractItem c && c.visibility() == PbsAst.Visibility.PUB && c.name().equals(item.name())))) continue;
|
||||
var contract = resolveContractExport(target, item.name(), units, visited);
|
||||
if (contract != null) return contract;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void validateImports(
|
||||
final ModuleUnit module,
|
||||
final Map<ModuleRefKey, ModuleExports> exportsByModule,
|
||||
|
||||
+1
-1
@@ -68,7 +68,7 @@ final class PbsCallableShapeSurfaceService {
|
||||
return "unit";
|
||||
}
|
||||
return switch (unwrapped.kind()) {
|
||||
case SIMPLE -> "simple:" + unwrapped.name();
|
||||
case SIMPLE -> "simple:" + unwrapped.surface();
|
||||
case SELF -> "self";
|
||||
case FN -> "Fn(" + unwrapped.fields().stream().map(f -> typeSurfaceKey(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + typeSurfaceKey(unwrapped.inner());
|
||||
case ARRAY -> "array(" + typeSurfaceKey(unwrapped.inner()) + ")";
|
||||
|
||||
+23
-15
@@ -1093,8 +1093,8 @@ final class PbsExecutableBodyLowerer {
|
||||
try {
|
||||
var target=PbsRuntimeTypes.unwrap(expected);
|
||||
var actual=PbsRuntimeTypes.unwrap(expressionType(expression,context));
|
||||
if(target!=null && actual!=null && context.types().contracts.containsKey(target.name()) && !target.name().equals(actual.name()))
|
||||
lowerConversion(new PbsAst.AsExpr(expression,target.name(),expression.span()),context);
|
||||
if(target!=null && actual!=null && context.types().isContract(target) && !context.types().key(target).equals(context.types().key(actual)))
|
||||
lowerConversion(new PbsAst.AsExpr(expression,target,expression.span()),context);
|
||||
else lowerExpression(expression, context);
|
||||
} finally { context.expectedType = previous; }
|
||||
}
|
||||
@@ -1141,13 +1141,13 @@ final class PbsExecutableBodyLowerer {
|
||||
return null;
|
||||
}
|
||||
if (e instanceof PbsAst.GroupExpr g) return expressionType(g.expression(), c);
|
||||
if (e instanceof PbsAst.AsExpr a) return PbsRuntimeTypes.type(a.contractName());
|
||||
if (e instanceof PbsAst.AsExpr a) return a.contractType();
|
||||
if (e instanceof PbsAst.UnaryExpr u) return java.util.Set.of("!", "not").contains(u.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(u.expression(), c);
|
||||
if (e instanceof PbsAst.BinaryExpr b) return java.util.Set.of("==", "!=", "<", "<=", ">", ">=", "&&", "||", "and", "or").contains(b.operator()) ? PbsRuntimeTypes.type("bool") : expressionType(b.left(), c);
|
||||
if (e instanceof PbsAst.IfExpr branch) return expressionType(branch.thenBlock().tailExpression(), c);
|
||||
if (e instanceof PbsAst.SwitchExpr branch && !branch.arms().isEmpty()) return expressionType(branch.arms().getFirst().block().tailExpression(), c);
|
||||
if (e instanceof PbsAst.ApplyExpr apply) return expressionType(applyCall(apply), c);
|
||||
if (e instanceof PbsAst.NewExpr value) return value.typeName().equals("array") ? c.expectedType : PbsRuntimeTypes.type(value.typeName());
|
||||
if (e instanceof PbsAst.NewExpr value) return value.typeName().equals("array") ? (value.explicitType() != null ? value.explicitType() : c.expectedType) : PbsRuntimeTypes.type(value.typeName());
|
||||
if (e instanceof PbsAst.CallExpr call) {
|
||||
var fn = isDirectFunction(call.callee(), c) ? null : PbsRuntimeTypes.unwrap(expressionType(call.callee(),c));
|
||||
if (fn != null && fn.kind() == PbsAst.TypeRefKind.FN) return fn.inner();
|
||||
@@ -1162,9 +1162,13 @@ final class PbsExecutableBodyLowerer {
|
||||
if(owner!=null) {
|
||||
if (owner.kind() == PbsAst.TypeRefKind.OPTIONAL
|
||||
&& (member.memberName().equals("hasSome") || member.memberName().equals("hasNone"))) return PbsRuntimeTypes.type("bool");
|
||||
var contract=c.types().contracts.get(owner.name());
|
||||
if(contract!=null) for(var method:contract.signatures()) if(method.name().equals(member.memberName()) && parametersMatch(method.parameters(),call.arguments(),c)
|
||||
&& returnMatches(method.returnType(),owner.name(),c)) return method.returnType();
|
||||
var contract=c.types().contract(owner);
|
||||
if(contract!=null) {
|
||||
var candidates = contract.signatures().stream().filter(method -> method.name().equals(member.memberName())
|
||||
&& parametersMatch(method.parameters(),call.arguments(),c)).toList();
|
||||
if (candidates.size() == 1) return candidates.getFirst().returnType();
|
||||
for (var method : candidates) if (returnMatches(method.returnType(),owner.name(),c)) return method.returnType();
|
||||
}
|
||||
var struct = c.types().structs.get(owner.name());
|
||||
var service = c.types().services.get(owner.name());
|
||||
var methods = struct != null ? struct.methods() : service != null ? service.methods() : ReadOnlyList.<PbsAst.FunctionDecl>empty();
|
||||
@@ -1200,11 +1204,11 @@ final class PbsExecutableBodyLowerer {
|
||||
var sourceType = expressionType(expr.expression(),c);
|
||||
var source = c.types().canonical(sourceType);
|
||||
var target = expr.contractName();
|
||||
if(c.types().contracts.containsKey(target)) {
|
||||
if(c.types().isContract(expr.contractType())) {
|
||||
lowerExpected(expr.expression(),null,c);
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
|
||||
null,"",null,null,null,"","",c.types().slots(sourceType),2,expr.span(),
|
||||
new IRRegistryInstruction(REF_TO_TRAIT,c.types().registryType(sourceType),c.types().registryType(PbsRuntimeTypes.type(target)),null,0)));
|
||||
new IRRegistryInstruction(REF_TO_TRAIT,c.types().registryType(sourceType),c.types().registryType(expr.contractType()),null,0)));
|
||||
return;
|
||||
}
|
||||
lowerExpected(expr.expression(), null, c);
|
||||
@@ -1746,7 +1750,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
if(!(call.callee() instanceof PbsAst.MemberExpr member))return false;
|
||||
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));if(owner==null)return false;
|
||||
var contract=c.types().contracts.get(owner.name());
|
||||
var contract=c.types().contract(owner);
|
||||
if(contract!=null) {
|
||||
int ordinal=-1;
|
||||
for(int i=0;i<contract.signatures().size();i++) {
|
||||
@@ -1755,8 +1759,11 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
if(ordinal<0)return false;
|
||||
var method=contract.signatures().get(ordinal);lowerExpected(member.receiver(),owner,c);
|
||||
// Evaluate/root the receiver first, then place its complete view after explicit arguments.
|
||||
int receiverView = save(2, member.receiver().span(), c);
|
||||
int pops=2;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
emitLoadLocalSlots(receiverView, 2, member.receiver().span(), c);
|
||||
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var service=c.types().services.get(owner.name());
|
||||
@@ -1769,7 +1776,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
int pops=0;
|
||||
for(int i=0;i<call.arguments().size();i++){var type=PbsTypeSubstitution.replaceSelf(method.parameters().get(i).typeRef(),owner.name());lowerExpected(call.arguments().get(i),type,c);pops+=c.types().slots(type);}
|
||||
emitStructuredFunction(service.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),pops,c.types().slots(method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
|
||||
var method=struct.methods().stream().filter(m->m.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
|
||||
@@ -1807,11 +1814,12 @@ final class PbsExecutableBodyLowerer {
|
||||
if (expected.kind() == PbsAst.TypeRefKind.SELF) continue;
|
||||
// Contextual expressions have already been disambiguated by static semantics.
|
||||
if (actual == null || arguments.get(i) instanceof PbsAst.ArrayLiteralExpr
|
||||
|| arguments.get(i) instanceof PbsAst.NoneExpr) continue;
|
||||
|| arguments.get(i) instanceof PbsAst.NoneExpr
|
||||
|| arguments.get(i) instanceof PbsAst.NewExpr allocation
|
||||
&& allocation.typeName().equals("array") && allocation.explicitType() == null) continue;
|
||||
if (c.types().shapeKey(actual).equals(c.types().shapeKey(expected))) continue;
|
||||
if (arguments.get(i) instanceof PbsAst.IntLiteralExpr && "long".equals(c.types().canonical(expected))) continue;
|
||||
if (c.types().contracts.containsKey(expected.name()) && c.types().implementations.stream().anyMatch(
|
||||
impl -> impl.ownerName().equals(actual.name()) && impl.contractName().equals(expected.name()))) continue;
|
||||
if (c.types().isContract(expected) && c.types().contractTypes.implementers(expected).contains(actual.name())) continue;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -1826,7 +1834,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
c.callableSignatureByCallableId().get(callableId).moduleId(),
|
||||
name, callableId, null, null, pops, pushes, span));
|
||||
c.callableSignatureByCallableId().get(callableId).callableName(), callableId, null, null, pops, pushes, span));
|
||||
}
|
||||
|
||||
private void lowerServiceValue(String name,Span span,PbsExecutableLoweringContext c) {
|
||||
|
||||
+6
-5
@@ -24,7 +24,8 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
final ModuleId moduleId,
|
||||
final NameTable nameTable,
|
||||
final Map<String, String> builtinCanonicalBySourceType,
|
||||
final ReadOnlyList<PbsFrontendCompiler.ImportedCallableSurface> importedCallables) {
|
||||
final ReadOnlyList<PbsFrontendCompiler.ImportedCallableSurface> importedCallables,
|
||||
final PbsRuntimeTypes types) {
|
||||
final var callableIdTable = new CallableTable();
|
||||
final var callableIdsByNameAndArity = new HashMap<PbsCallableResolutionKey, List<CallableId>>();
|
||||
final var callableIdByDeclaration = new HashMap<PbsLowerableCallable, CallableId>();
|
||||
@@ -33,7 +34,7 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
final var tupleProjectionByCallableId = new HashMap<CallableId, PbsTupleProjection>();
|
||||
final var typeSurfaceTable = new TypeSurfaceTable();
|
||||
final var callableShapeTable = new CallableShapeTable();
|
||||
final var localCallables = collectLocalLowerableCallables(ast);
|
||||
final var localCallables = collectLocalLowerableCallables(ast, types);
|
||||
|
||||
registerLocalCallables(
|
||||
moduleId,
|
||||
@@ -76,7 +77,7 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
ReadOnlyList.wrap(callableSignatures));
|
||||
}
|
||||
|
||||
private ReadOnlyList<PbsLowerableCallable> collectLocalLowerableCallables(final PbsAst.File ast) {
|
||||
private ReadOnlyList<PbsLowerableCallable> collectLocalLowerableCallables(final PbsAst.File ast, PbsRuntimeTypes types) {
|
||||
final var callables = new ArrayList<PbsLowerableCallable>();
|
||||
var globals = new java.util.LinkedHashMap<String, PbsAst.GlobalDecl>();
|
||||
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.GlobalDecl global) globals.put(global.name(),global);
|
||||
@@ -104,7 +105,7 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
|
||||
for (var method : implementation.methods()) callables.add(new PbsLowerableCallable(
|
||||
implementation.ownerName()+".$impl."+implementation.contractName()+"."+method.name(),
|
||||
types.implementationCallableName(implementation, method.name()),
|
||||
withReceiver(method,implementation.ownerName(),implementation.binderName())));
|
||||
}
|
||||
if (!(topDecl instanceof PbsAst.ServiceDecl serviceDecl)) {
|
||||
@@ -200,7 +201,7 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
for (final var importedCallable : importedCallables) {
|
||||
final var callableId = callableIdTable.register(
|
||||
importedCallable.moduleId(),
|
||||
importedCallable.callableName(),
|
||||
importedCallable.targetName(),
|
||||
importedCallable.arity(),
|
||||
importedCallable.shapeSurface());
|
||||
callableIdsByNameAndArity
|
||||
|
||||
+3
-2
@@ -111,8 +111,9 @@ final class PbsExecutableLoweringContext {
|
||||
.collect(java.util.stream.Collectors.joining(",")) + ")->";
|
||||
var output = returnType == null || returnType.kind() == p.studio.compiler.pbs.ast.PbsAst.TypeRefKind.UNIT
|
||||
? "unit" : formatter.typeSurfaceKey(returnType);
|
||||
var importedIds = callableIdsByNameAndArity().getOrDefault(new PbsCallableResolutionKey(nameTable().register(name), parameterTypes.size()), java.util.List.of());
|
||||
var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry ->
|
||||
entry.getValue().callableName().equals(name) && entry.getValue().arity() == parameterTypes.size()
|
||||
importedIds.contains(entry.getKey()) && entry.getValue().arity() == parameterTypes.size()
|
||||
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + output))).toList();
|
||||
if (candidates.size() == 1) return candidates.getFirst().getKey();
|
||||
return null;
|
||||
@@ -121,7 +122,7 @@ final class PbsExecutableLoweringContext {
|
||||
private String normalizeShape(String shape) {
|
||||
var normalized = shape.replace(" ", "");
|
||||
for (var alias : types().aliases.entrySet()) normalized = normalized.replaceAll(
|
||||
"simple:" + java.util.regex.Pattern.quote(alias.getKey()) + "(?=[,()])",
|
||||
"simple:" + java.util.regex.Pattern.quote(alias.getKey()) + "(?=[<>,()]|$)",
|
||||
java.util.regex.Matcher.quoteReplacement("simple:" + alias.getValue()));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
+5
-5
@@ -46,7 +46,7 @@ public final class PbsExecutableLoweringService {
|
||||
normalizedModuleId,
|
||||
nameTable,
|
||||
metadataIndex.builtinCanonicalBySourceType(),
|
||||
importedCallables);
|
||||
importedCallables, metadataIndex.types());
|
||||
for (var entry : callableRegistry.callableSignatureByCallableId().entrySet()) {
|
||||
var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity());
|
||||
if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0);
|
||||
@@ -60,10 +60,10 @@ public final class PbsExecutableLoweringService {
|
||||
}
|
||||
for (var implementation : metadataIndex.types().implementations) {
|
||||
var methods = new ArrayList<p.studio.compiler.source.identifiers.CallableId>();
|
||||
var contract = metadataIndex.types().contracts.get(implementation.contractName());
|
||||
var contract = metadataIndex.types().contract(implementation.contractType());
|
||||
for (var signature : contract.signatures()) {
|
||||
var candidates = callableRegistry.localCallables().stream().filter(callable ->
|
||||
callable.callableName().equals(implementation.ownerName()+".$impl."+implementation.contractName()+"."+signature.name())
|
||||
callable.callableName().equals(metadataIndex.types().implementationCallableName(implementation, signature.name()))
|
||||
&& callable.functionDecl().parameters().size()==signature.parameters().size()+1
|
||||
&& metadataIndex.types().shapeKey(callable.functionDecl().returnType()).equals(metadataIndex.types().shapeKey(signature.returnType()))
|
||||
&& java.util.stream.IntStream.range(0, signature.parameters().size()).allMatch(i ->
|
||||
@@ -73,9 +73,9 @@ public final class PbsExecutableLoweringService {
|
||||
methods.add(callableRegistry.callableIdByDeclaration().get(candidates.getFirst()));
|
||||
}
|
||||
metadataIndex.types().runtimeImplementations.add(new p.studio.compiler.models.registry.IRRegistry.Implementation(
|
||||
"pbs:impl:"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.ownerName()))+":"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.contractName())),
|
||||
"pbs:impl:"+metadataIndex.types().key(PbsRuntimeTypes.type(implementation.ownerName()))+":"+metadataIndex.types().key(implementation.contractType()),
|
||||
metadataIndex.types().registryType(PbsRuntimeTypes.type(implementation.ownerName())),
|
||||
metadataIndex.types().registryType(PbsRuntimeTypes.type(implementation.contractName())),ReadOnlyList.wrap(methods)));
|
||||
metadataIndex.types().registryType(implementation.contractType()),ReadOnlyList.wrap(methods)));
|
||||
}
|
||||
final var intrinsicIdTable = new IntrinsicTable();
|
||||
final var executableFunctions = new ArrayList<IRBackendExecutableFunction>(callableRegistry.localCallables().size());
|
||||
|
||||
+29
-10
@@ -22,17 +22,20 @@ final class PbsRuntimeTypes {
|
||||
private final Map<String, IRRegistry.TypeDeclaration> used = new TreeMap<>();
|
||||
final Map<String, PbsAst.StructDecl> structs = new LinkedHashMap<>();
|
||||
final Map<String, PbsAst.ContractDecl> contracts = new LinkedHashMap<>();
|
||||
final p.studio.compiler.pbs.PbsContractTypes contractTypes;
|
||||
final Map<String, PbsAst.ServiceDecl> services = new LinkedHashMap<>();
|
||||
final List<PbsAst.ImplementsDecl> implementations = new ArrayList<>();
|
||||
final List<IRRegistry.Implementation> runtimeImplementations = new ArrayList<>();
|
||||
|
||||
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
|
||||
builtinNames = builtins;
|
||||
contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplemental, p.studio.compiler.source.diagnostics.DiagnosticSink.empty());
|
||||
for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ImplementsDecl implementation)
|
||||
implementations.add(implementation);
|
||||
var declarations = new ArrayList<>(ast.topDecls().asList());
|
||||
declarations.addAll(supplemental.asList());
|
||||
for (var decl : declarations) {
|
||||
if (decl instanceof PbsAst.TypeBindingDecl binding) decl = binding.declaration();
|
||||
if (decl instanceof PbsAst.StructDecl s) {
|
||||
structs.put(s.name(), s);
|
||||
for (var f : s.methods()) addSignature(s.name()+"."+f.name(), f);
|
||||
@@ -63,10 +66,23 @@ 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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
private void addSignature(String name, PbsAst.FunctionDecl f) {
|
||||
signatures.put(name+"#"+f.parameters().size(), new PbsAst.FunctionSignature(f.name(), f.parameters(), f.returnKind(), f.returnType(), f.resultErrorType(), f.attributes(), f.span()));
|
||||
}
|
||||
boolean isContract(PbsAst.TypeRef type) { return contractTypes.isContract(unwrap(type)); }
|
||||
PbsAst.ContractDecl contract(PbsAst.TypeRef type) {
|
||||
var instance = contractTypes.resolve(unwrap(type));
|
||||
return instance == null ? null : instance.declaration();
|
||||
}
|
||||
String implementationCallableName(PbsAst.ImplementsDecl implementation, String method) {
|
||||
return contractTypes.implementationCallableName(implementation, method);
|
||||
}
|
||||
static PbsAst.TypeRef type(String name) { return PbsAst.TypeRef.simple(name, Span.none()); }
|
||||
String canonical(PbsAst.TypeRef t) {
|
||||
if(t==null) return "void";
|
||||
@@ -78,7 +94,7 @@ final class PbsRuntimeTypes {
|
||||
if(t==null || t.kind()==PbsAst.TypeRefKind.UNIT) return 0;
|
||||
if(t.kind()==PbsAst.TypeRefKind.GROUP) return slots(t.inner());
|
||||
if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().mapToInt(f->slots(f.typeRef())).sum();
|
||||
if (contracts.containsKey(canonical(t))) return 2;
|
||||
if (isContract(t)) return 2;
|
||||
return switch(canonical(t)) { case "vec2" -> 2; case "pixel" -> 3; default -> 1; };
|
||||
}
|
||||
static PbsAst.TypeRef unwrap(PbsAst.TypeRef t) {
|
||||
@@ -92,9 +108,12 @@ 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 (structs.containsKey(t.name())) return nominalKey("struct", structs.get(t.name()).span());
|
||||
if (services.containsKey(t.name())) return nominalKey("struct", services.get(t.name()).span());
|
||||
if (contracts.containsKey(t.name())) return nominalKey("contract", contracts.get(t.name()).span());
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.StructDecl s) return nominalKey("struct", s.span());
|
||||
if (contractTypes.declaration(t) instanceof PbsAst.ServiceDecl s) return nominalKey("struct", s.span());
|
||||
if (isContract(t)) {
|
||||
var nominal = nominalKey("contract", contractTypes.template(t).span());
|
||||
return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t);
|
||||
}
|
||||
return canonical(t);
|
||||
}
|
||||
String shapeKey(PbsAst.TypeRef type) {
|
||||
@@ -148,28 +167,28 @@ final class PbsRuntimeTypes {
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
if (structs.containsKey(t.name()) || services.containsKey(t.name())) {
|
||||
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)));
|
||||
var fields = new ArrayList<IRRegistry.NamedType>();
|
||||
if (structs.containsKey(t.name())) for(var field : structs.get(t.name()).fields())
|
||||
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))));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
if (contracts.containsKey(t.name())) {
|
||||
if (isContract(t)) {
|
||||
var ref = new IRRegistry.TypeRef(key(t));
|
||||
if (!used.containsKey(ref.declarationKey())) {
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Trait(null)));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(null)));
|
||||
var methods = new ArrayList<IRRegistry.Method>();
|
||||
for (var method : contracts.get(t.name()).signatures()) {
|
||||
for (var method : contract(t).signatures()) {
|
||||
var args = new ArrayList<IRRegistry.NamedType>();
|
||||
for(var arg : method.parameters()) for(var part : results(arg.typeRef())) args.add(new IRRegistry.NamedType(part,arg.name()));
|
||||
methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(results(method.returnType())))));
|
||||
}
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,canonical(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
|
||||
used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods))));
|
||||
}
|
||||
return ref;
|
||||
}
|
||||
|
||||
+9
-63
@@ -14,8 +14,6 @@ import java.util.ArrayList;
|
||||
* Parser for `mod.barrel` files.
|
||||
*/
|
||||
public final class PbsBarrelParser {
|
||||
private static final int MAX_NAMED_TUPLE_ARITY = 6;
|
||||
|
||||
private final PbsTokenCursor cursor;
|
||||
private final FileId fileId;
|
||||
private final DiagnosticSink diagnostics;
|
||||
@@ -117,12 +115,16 @@ 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
|
||||
? new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
|
||||
PbsParser.ParseMode.ORDINARY)).parseTypeParameters()
|
||||
: ReadOnlyList.<PbsAst.TypeParameter>empty();
|
||||
final var semicolon = consume(PbsTokenKind.SEMICOLON, "Expected ';' after barrel item");
|
||||
final var itemSpan = span(visibilityToken.start(), semicolon.end());
|
||||
|
||||
return switch (kind) {
|
||||
case STRUCT -> new PbsAst.BarrelStructItem(visibility, name.lexeme(), itemSpan);
|
||||
case CONTRACT -> new PbsAst.BarrelContractItem(visibility, name.lexeme(), 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);
|
||||
case ENUM -> new PbsAst.BarrelEnumItem(visibility, name.lexeme(), itemSpan);
|
||||
@@ -185,7 +187,8 @@ public final class PbsBarrelParser {
|
||||
final var resultToken = cursor.previous();
|
||||
consume(PbsTokenKind.LESS, "Expected '<' after 'result'");
|
||||
final var errorType = parseTypeRef();
|
||||
consume(PbsTokenKind.GREATER, "Expected '>' after result error type");
|
||||
new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
|
||||
PbsParser.ParseMode.INTERFACE_MODULE)).consumeTypeClose();
|
||||
|
||||
final PbsAst.TypeRef payloadType;
|
||||
if (isTypeStart(cursor.peek().kind())) {
|
||||
@@ -208,65 +211,8 @@ public final class PbsBarrelParser {
|
||||
}
|
||||
|
||||
private PbsAst.TypeRef parseTypeRef() {
|
||||
if (cursor.match(PbsTokenKind.OPTIONAL)) {
|
||||
final var optionalToken = cursor.previous();
|
||||
final var inner = parseTypeRef();
|
||||
if (inner.kind() == PbsAst.TypeRefKind.UNIT) {
|
||||
report(optionalToken, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
|
||||
"'optional void' is not a valid type surface");
|
||||
}
|
||||
return PbsAst.TypeRef.optional(inner, span(optionalToken.start(), inner.span().getEnd()));
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.VOID)) {
|
||||
final var token = cursor.previous();
|
||||
return PbsAst.TypeRef.unit(span(token.start(), token.end()));
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.SELF)) {
|
||||
final var token = cursor.previous();
|
||||
return PbsAst.TypeRef.self(span(token.start(), token.end()));
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.IDENTIFIER)) {
|
||||
final var token = cursor.previous();
|
||||
return PbsAst.TypeRef.simple(token.lexeme(), span(token.start(), token.end()));
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.LEFT_PAREN)) {
|
||||
final var open = cursor.previous();
|
||||
if (cursor.match(PbsTokenKind.RIGHT_PAREN)) {
|
||||
return PbsAst.TypeRef.unit(span(open.start(), cursor.previous().end()));
|
||||
}
|
||||
|
||||
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.checkNext(PbsTokenKind.COLON)) {
|
||||
final var fields = new ArrayList<PbsAst.NamedTypeField>();
|
||||
do {
|
||||
final var label = consume(PbsTokenKind.IDENTIFIER, "Expected tuple field label");
|
||||
consume(PbsTokenKind.COLON, "Expected ':' after tuple field label");
|
||||
final var type = parseTypeRef();
|
||||
fields.add(new PbsAst.NamedTypeField(label.lexeme(), type, span(label.start(), type.span().getEnd())));
|
||||
if (fields.size() == MAX_NAMED_TUPLE_ARITY + 1) {
|
||||
report(label, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
|
||||
"Named tuple type arity must be between 1 and 6 fields");
|
||||
}
|
||||
} while (cursor.match(PbsTokenKind.COMMA) && !cursor.check(PbsTokenKind.RIGHT_PAREN));
|
||||
|
||||
final var close = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after named tuple type");
|
||||
return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(fields), span(open.start(), close.end()));
|
||||
}
|
||||
|
||||
final var inner = parseTypeRef();
|
||||
final var close = consume(PbsTokenKind.RIGHT_PAREN, "Expected ')' after grouped type");
|
||||
return PbsAst.TypeRef.group(inner, span(open.start(), close.end()));
|
||||
}
|
||||
|
||||
final var token = cursor.peek();
|
||||
report(token, ParseErrors.E_PARSE_EXPECTED_TOKEN, "Expected type surface");
|
||||
if (!cursor.isAtEnd()) {
|
||||
cursor.advance();
|
||||
}
|
||||
return PbsAst.TypeRef.error(span(token.start(), token.end()));
|
||||
return new PbsTypeParser(new PbsParserContext(cursor, fileId, diagnostics,
|
||||
PbsParser.ParseMode.INTERFACE_MODULE)).parseTypeRef();
|
||||
}
|
||||
|
||||
private boolean isTypeStart(final PbsTokenKind kind) {
|
||||
|
||||
+4
-3
@@ -174,7 +174,7 @@ final class PbsDeclarationParser {
|
||||
}
|
||||
|
||||
PbsAst.ImplementsDecl parseImplementsDeclaration(final PbsToken implementsToken) {
|
||||
final var contractName = consume(PbsTokenKind.IDENTIFIER, "Expected contract name in 'implements'");
|
||||
final var contractType = typeParser.parseTypeRef();
|
||||
consume(PbsTokenKind.FOR, "Expected 'for' in 'implements' declaration");
|
||||
final var ownerName = consume(PbsTokenKind.IDENTIFIER, "Expected owner name after 'for'");
|
||||
consume(PbsTokenKind.USING, "Expected 'using' in 'implements' declaration");
|
||||
@@ -201,7 +201,7 @@ final class PbsDeclarationParser {
|
||||
}
|
||||
|
||||
return new PbsAst.ImplementsDecl(
|
||||
contractName.lexeme(),
|
||||
contractType,
|
||||
ownerName.lexeme(),
|
||||
binderName.lexeme(),
|
||||
ReadOnlyList.wrap(methods),
|
||||
@@ -425,6 +425,7 @@ final class PbsDeclarationParser {
|
||||
final PbsToken declareToken,
|
||||
final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected contract name");
|
||||
final var typeParameters = typeParser.parseTypeParameters();
|
||||
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start contract body");
|
||||
final var signatures = new ArrayList<PbsAst.FunctionSignature>();
|
||||
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
||||
@@ -445,7 +446,7 @@ final class PbsDeclarationParser {
|
||||
signatures.add(parseFunctionSignature(cursor.previous(), signatureAttributes));
|
||||
}
|
||||
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end contract body");
|
||||
return new PbsAst.ContractDecl(name.lexeme(), ReadOnlyList.wrap(signatures), attributes, span(declareToken.start(), rightBrace.end()));
|
||||
return new PbsAst.ContractDecl(name.lexeme(), typeParameters, ReadOnlyList.wrap(signatures), attributes, span(declareToken.start(), rightBrace.end()));
|
||||
}
|
||||
|
||||
private PbsAst.ServiceDecl parseServiceDeclaration(
|
||||
|
||||
+5
-3
@@ -17,11 +17,13 @@ final class PbsExprParser {
|
||||
private final PbsTokenCursor cursor;
|
||||
private final PbsExprControlFlowParser controlFlowParser;
|
||||
private final PbsExprPrimaryParser primaryParser;
|
||||
private final PbsTypeParser typeParser;
|
||||
|
||||
PbsExprParser(
|
||||
final PbsParserContext parserContext,
|
||||
final BlockParserDelegate blockParserDelegate) {
|
||||
this.context = new PbsExprParserContext(parserContext, blockParserDelegate);
|
||||
this.typeParser = new PbsTypeParser(parserContext);
|
||||
this.cursor = context.cursor();
|
||||
this.controlFlowParser = new PbsExprControlFlowParser(context, this::parseExpression, this::parsePrecedenceExpression);
|
||||
this.primaryParser = new PbsExprPrimaryParser(context, this::parseExpression, controlFlowParser::parseErrorPath);
|
||||
@@ -119,11 +121,11 @@ final class PbsExprParser {
|
||||
private PbsAst.Expression parseAs() {
|
||||
var expression = parseTerm();
|
||||
if (cursor.match(PbsTokenKind.AS)) {
|
||||
final var contract = context.consume(PbsTokenKind.IDENTIFIER, "Expected contract identifier after 'as'");
|
||||
final var contract = typeParser.parseTypeRef();
|
||||
expression = new PbsAst.AsExpr(
|
||||
expression,
|
||||
contract.lexeme(),
|
||||
span(expression.span().getStart(), contract.end()));
|
||||
contract,
|
||||
span(expression.span().getStart(), contract.span().getEnd()));
|
||||
}
|
||||
return expression;
|
||||
}
|
||||
|
||||
+19
@@ -231,6 +231,23 @@ final class PbsExprPrimaryParser {
|
||||
|
||||
private PbsAst.Expression parseNewExpression(final PbsToken newToken) {
|
||||
final var typeName = context.consume(PbsTokenKind.IDENTIFIER, "Expected type name after 'new'");
|
||||
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 closeType = types.consumeTypeClose();
|
||||
explicitType = PbsAst.TypeRef.array(element, context.span(typeName.start(), closeType.end()));
|
||||
}
|
||||
}
|
||||
String ctorName = null;
|
||||
if (cursor.match(PbsTokenKind.DOT)) {
|
||||
ctorName = context.consume(PbsTokenKind.IDENTIFIER, "Expected constructor name after '.' in new target").lexeme();
|
||||
@@ -248,6 +265,8 @@ final class PbsExprPrimaryParser {
|
||||
typeName.lexeme(),
|
||||
ctorName,
|
||||
ReadOnlyList.wrap(arguments),
|
||||
explicitType,
|
||||
diamond,
|
||||
context.span(newToken.start(), close.end()));
|
||||
}
|
||||
|
||||
|
||||
+19
@@ -25,6 +25,25 @@ final class PbsTokenCursor {
|
||||
}
|
||||
}
|
||||
|
||||
/** Peel one type closer without changing expression tokenization. */
|
||||
PbsToken consumeTypeClose() {
|
||||
var token = peek();
|
||||
if (!token.lexeme().startsWith(">")) return null;
|
||||
if (token.lexeme().equals(">")) return advance();
|
||||
var rest = token.lexeme().substring(1);
|
||||
var kind = switch (rest) {
|
||||
case "=" -> PbsTokenKind.EQUAL;
|
||||
case ">" -> PbsTokenKind.GREATER;
|
||||
case ">=" -> PbsTokenKind.GREATER_EQUAL;
|
||||
default -> null;
|
||||
};
|
||||
if (kind == null) return null;
|
||||
var close = new PbsToken(PbsTokenKind.GREATER, ">", token.start(), token.start() + 1);
|
||||
tokens.set(current, close);
|
||||
tokens.add(current + 1, new PbsToken(kind, rest, token.start() + 1, token.end()));
|
||||
return advance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes the next token if it matches any provided kind.
|
||||
*/
|
||||
|
||||
+47
-22
@@ -86,30 +86,20 @@ final class PbsTypeParser {
|
||||
}
|
||||
if (cursor.check(PbsTokenKind.IDENTIFIER) && cursor.peek().lexeme().equals("array")) {
|
||||
final var start = cursor.advance();
|
||||
int depth = 1;
|
||||
if (cursor.match(PbsTokenKind.LEFT_BRACKET)) {
|
||||
final var number = consume(PbsTokenKind.INT_LITERAL, "Array depth must be a positive integer literal");
|
||||
try { depth = Integer.parseInt(number.lexeme()); }
|
||||
catch (NumberFormatException invalid) { depth = 0; }
|
||||
if (depth < 1) {
|
||||
context.report(number, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Array depth must be a positive integer literal");
|
||||
depth = 1;
|
||||
}
|
||||
consume(PbsTokenKind.RIGHT_BRACKET, "Expected ']' after array depth");
|
||||
if (!cursor.match(PbsTokenKind.LESS)) {
|
||||
context.report(cursor.peek(), ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
|
||||
"Array types use array<T>; legacy array T and array[N] T are not supported");
|
||||
return PbsAst.TypeRef.error(context.span(start.start(), start.end()));
|
||||
}
|
||||
if (depth > MAX_TYPE_DEPTH - typeDepth) {
|
||||
context.report(start, ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Array depth exceeds compiler type nesting limit of " + MAX_TYPE_DEPTH);
|
||||
depth = 1;
|
||||
var inner = parseTypeRef();
|
||||
var close = consumeTypeClose();
|
||||
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
||||
context.report(cursor.peek(), ParseErrors.E_PARSE_INVALID_TYPE_SURFACE,
|
||||
"Nested arrays use array<array<T>>, not array<T>[N]");
|
||||
}
|
||||
typeDepth += depth - 1;
|
||||
PbsAst.TypeRef inner;
|
||||
try { inner = parseTypeRef(); }
|
||||
finally { typeDepth -= depth - 1; }
|
||||
for (int level = 0; level < depth; level++) {
|
||||
inner = PbsAst.TypeRef.array(inner, context.span(start.start(), inner.span().getEnd()));
|
||||
}
|
||||
return inner;
|
||||
return PbsAst.TypeRef.array(inner, context.span(start.start(), close.end()));
|
||||
}
|
||||
|
||||
if (cursor.match(PbsTokenKind.OPTIONAL)) {
|
||||
final var optionalToken = cursor.previous();
|
||||
final var inner = parseTypeRef();
|
||||
@@ -132,6 +122,15 @@ final class PbsTypeParser {
|
||||
|
||||
if (cursor.match(PbsTokenKind.IDENTIFIER)) {
|
||||
final var token = cursor.previous();
|
||||
if (cursor.match(PbsTokenKind.LESS)) {
|
||||
var arguments = new ArrayList<PbsAst.TypeRef>();
|
||||
if (!cursor.check(PbsTokenKind.GREATER) && !cursor.check(PbsTokenKind.GREATER_EQUAL)) {
|
||||
do { arguments.add(parseTypeRef()); } while (cursor.match(PbsTokenKind.COMMA));
|
||||
} else context.report(cursor.peek(), ParseErrors.E_PARSE_INVALID_TYPE_SURFACE, "Contract type arguments must be explicit and nonempty");
|
||||
var close = consumeTypeClose();
|
||||
return PbsAst.TypeRef.applied(token.lexeme(), p.studio.utilities.structures.ReadOnlyList.wrap(arguments),
|
||||
context.span(token.start(), close.end()));
|
||||
}
|
||||
return PbsAst.TypeRef.simple(token.lexeme(), context.span(token.start(), token.end()));
|
||||
}
|
||||
|
||||
@@ -167,7 +166,7 @@ final class PbsTypeParser {
|
||||
final var resultToken = cursor.previous();
|
||||
consume(PbsTokenKind.LESS, "Expected '<' after 'result'");
|
||||
final var errorType = parseTypeRef();
|
||||
consume(PbsTokenKind.GREATER, "Expected '>' after result error type");
|
||||
consumeTypeClose();
|
||||
|
||||
final PbsAst.TypeRef payloadType;
|
||||
if (isTypeStart(cursor.peek().kind())) {
|
||||
@@ -215,6 +214,32 @@ final class PbsTypeParser {
|
||||
|| kind == PbsTokenKind.LEFT_PAREN;
|
||||
}
|
||||
|
||||
PbsAst.TypeRef parseArrayElementType() {
|
||||
// Count the constructor's outer array just as an annotated array type.
|
||||
typeDepth++;
|
||||
try { return parseTypeRef(); }
|
||||
finally { typeDepth--; }
|
||||
}
|
||||
|
||||
PbsToken consumeTypeClose() {
|
||||
var close = cursor.consumeTypeClose();
|
||||
if (close != null) return close;
|
||||
var token = cursor.peek();
|
||||
context.report(token, ParseErrors.E_PARSE_EXPECTED_TOKEN, "Expected '>' after type argument");
|
||||
return new PbsToken(PbsTokenKind.GREATER, "", token.start(), token.start());
|
||||
}
|
||||
|
||||
p.studio.utilities.structures.ReadOnlyList<PbsAst.TypeParameter> parseTypeParameters() {
|
||||
var parameters = new ArrayList<PbsAst.TypeParameter>();
|
||||
if (!cursor.match(PbsTokenKind.LESS)) return p.studio.utilities.structures.ReadOnlyList.empty();
|
||||
do {
|
||||
var token = consume(PbsTokenKind.IDENTIFIER, "Expected type parameter name");
|
||||
parameters.add(new PbsAst.TypeParameter(token.lexeme(), context.span(token.start(), token.end())));
|
||||
} while (cursor.match(PbsTokenKind.COMMA));
|
||||
consumeTypeClose();
|
||||
return p.studio.utilities.structures.ReadOnlyList.wrap(parameters);
|
||||
}
|
||||
|
||||
private PbsToken consume(final PbsTokenKind kind, final String message) {
|
||||
if (cursor.check(kind)) {
|
||||
return cursor.advance();
|
||||
|
||||
+2
-2
@@ -298,9 +298,9 @@ final class PbsAstDocumentSymbols {
|
||||
return switch (typeRef.kind()) {
|
||||
case UNIT -> typeRef.name() == null || typeRef.name().isBlank() ? "void" : typeRef.name();
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.name() == null ? "void" : typeRef.name();
|
||||
case SIMPLE -> typeRef.name() == null ? "void" : 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 ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">";
|
||||
case OPTIONAL -> "optional " + formatTypeRef(typeRef.inner());
|
||||
case GROUP -> "(" + formatTypeRef(typeRef.inner()) + ")";
|
||||
case NAMED_TUPLE -> {
|
||||
|
||||
+1
-1
@@ -218,7 +218,7 @@ public final class PbsBuiltinLayoutResolver {
|
||||
case SIMPLE -> typeRef.name();
|
||||
case SELF -> "Self";
|
||||
case FN -> "Fn(" + typeRef.fields().stream().map(f -> renderTypeSurface(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ") -> " + renderTypeSurface(typeRef.inner());
|
||||
case ARRAY -> "array %s".formatted(renderTypeSurface(typeRef.inner()));
|
||||
case ARRAY -> "array<%s>".formatted(renderTypeSurface(typeRef.inner()));
|
||||
case OPTIONAL -> "optional %s".formatted(renderTypeSurface(typeRef.inner()));
|
||||
case UNIT -> "void";
|
||||
case GROUP -> "(%s)".formatted(renderTypeSurface(typeRef.inner()));
|
||||
|
||||
+68
-8
@@ -67,6 +67,8 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
final var scopeState = context.scopeStateAt(offset);
|
||||
final var token = context.token(tokenIndex);
|
||||
var generic = context.genericHover(token.lexeme(), offset);
|
||||
if (generic.isPresent()) return generic;
|
||||
final Integer previousTokenIndex = context.previousSignificantTokenIndex(tokenIndex);
|
||||
if (previousTokenIndex != null && context.token(previousTokenIndex).kind() == PbsTokenKind.DOT) {
|
||||
final TypeView receiverType = context.resolveReceiverTypeBeforeDot(previousTokenIndex, scopeState);
|
||||
@@ -414,7 +416,10 @@ public final class PbsEditorialSupportService {
|
||||
final String localName = item.alias() == null || item.alias().isBlank()
|
||||
? item.name()
|
||||
: item.alias();
|
||||
final PbsAst.TopDecl target = findSupplementalTopDecl(item.name(), expandedSupplementals);
|
||||
final PbsAst.TopDecl target = expandedSupplementals.stream()
|
||||
.filter(d -> d instanceof PbsAst.TypeBindingDecl b && b.name().equals(localName) && b.span().getFileId().equals(ast.span().getFileId()))
|
||||
.map(d -> ((PbsAst.TypeBindingDecl) d).declaration()).findFirst()
|
||||
.orElseGet(() -> findSupplementalTopDecl(item.name(), expandedSupplementals));
|
||||
if (target == null) {
|
||||
continue;
|
||||
}
|
||||
@@ -765,7 +770,7 @@ public final class PbsEditorialSupportService {
|
||||
});
|
||||
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
|
||||
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
|
||||
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
|
||||
: Optional.ofNullable(model.contractInfo(receiverType)).map(ContractInfo::methods).orElse(Map.of());
|
||||
for (final var method : methods.entrySet()) {
|
||||
completions.put(method.getKey(), new PbsEditorialCompletionCandidate(
|
||||
method.getKey(),
|
||||
@@ -877,7 +882,7 @@ public final class PbsEditorialSupportService {
|
||||
List.of(), Model.documentationFromAttributes(constant.attributes())));
|
||||
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
|
||||
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
|
||||
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
|
||||
: Optional.ofNullable(model.contractInfo(receiverType)).map(ContractInfo::methods).orElse(Map.of());
|
||||
final List<CallableSymbol> signatures = methods.get(memberName);
|
||||
if (signatures != null && !signatures.isEmpty()) {
|
||||
return Optional.of(new PbsEditorialResolvedSymbol(
|
||||
@@ -899,6 +904,8 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
final var scopeState = scopeStateAt(offset);
|
||||
final var token = token(tokenIndex);
|
||||
var parameter = typeParameterAt(token.lexeme(), offset);
|
||||
if (parameter != null) return List.of(new PbsEditorialLocation(parameter.span()));
|
||||
final Integer previousTokenIndex = previousSignificantTokenIndex(tokenIndex);
|
||||
if (previousTokenIndex != null && token(previousTokenIndex).kind() == PbsTokenKind.DOT) {
|
||||
final TypeView receiverType = resolveReceiverTypeBeforeDot(previousTokenIndex, scopeState);
|
||||
@@ -907,6 +914,51 @@ public final class PbsEditorialSupportService {
|
||||
return resolveSymbolDefinition(token.lexeme(), tokenIndex, scopeState, offset);
|
||||
}
|
||||
|
||||
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)) {
|
||||
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));
|
||||
if (found[0]) return parameter;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void findTypeAt(PbsAst.TypeRef type, String name, long offset, boolean[] found) {
|
||||
if (type == null) return;
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE && type.name().equals(name)
|
||||
&& type.span().getStart() <= offset && offset < type.span().getStart() + name.length()) found[0] = true;
|
||||
findTypeAt(type.inner(), name, offset, found);
|
||||
type.arguments().forEach(t -> findTypeAt(t, name, offset, found));
|
||||
type.fields().forEach(f -> findTypeAt(f.typeRef(), name, offset, found));
|
||||
}
|
||||
|
||||
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(), ""));
|
||||
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);
|
||||
while (!pending.isEmpty()) {
|
||||
var reference = pending.removeFirst();
|
||||
if (reference.kind() == PbsAst.TypeRefKind.SIMPLE && reference.name().equals(name) && !reference.arguments().isEmpty()
|
||||
&& reference.span().getStart() <= offset && offset < reference.span().getStart() + name.length()
|
||||
&& model.contractTypes.isContract(reference)) {
|
||||
var instance = model.contractTypes.resolve(reference);
|
||||
if (instance != null) return Optional.of(new PbsEditorialResolvedSymbol(instance.declaration().name(), PbsEditorialSymbolKind.CONTRACT,
|
||||
"contract " + instance.declaration().name(), "contract", signaturesForTopDecl(instance.declaration()),
|
||||
Model.documentationFromAttributes(instance.declaration().attributes())));
|
||||
}
|
||||
if (reference.inner() != null) pending.add(reference.inner());
|
||||
pending.addAll(reference.arguments().asList());
|
||||
reference.fields().forEach(f -> pending.add(f.typeRef()));
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private List<PbsEditorialLocation> usagesMatching(final Set<String> identityKeys) {
|
||||
if (identityKeys == null || identityKeys.isEmpty()) {
|
||||
return List.of();
|
||||
@@ -996,7 +1048,7 @@ public final class PbsEditorialSupportService {
|
||||
if (constant != null) return locations(constant.span());
|
||||
final Map<String, List<CallableSymbol>> methods = receiverType.kind() == Kind.SERVICE
|
||||
? Optional.ofNullable(model.services.get(receiverType.name())).map(ServiceInfo::methods).orElse(Map.of())
|
||||
: Optional.ofNullable(model.contracts.get(receiverType.name())).map(ContractInfo::methods).orElse(Map.of());
|
||||
: Optional.ofNullable(model.contractInfo(receiverType)).map(ContractInfo::methods).orElse(Map.of());
|
||||
return callableLocations(methods.get(memberName));
|
||||
}
|
||||
return List.of();
|
||||
@@ -1423,9 +1475,9 @@ public final class PbsEditorialSupportService {
|
||||
return switch (typeRef.kind()) {
|
||||
case UNIT -> "unit";
|
||||
case SELF -> "Self";
|
||||
case SIMPLE -> typeRef.name();
|
||||
case SIMPLE -> 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 ARRAY -> "array<" + formatTypeRef(typeRef.inner()) + ">";
|
||||
case OPTIONAL -> formatTypeRef(typeRef.inner()) + "?";
|
||||
case GROUP -> formatTypeRef(typeRef.inner());
|
||||
case NAMED_TUPLE -> {
|
||||
@@ -2051,7 +2103,15 @@ public final class PbsEditorialSupportService {
|
||||
return null;
|
||||
}
|
||||
return switch (typeRef.kind()) {
|
||||
case SIMPLE -> aliasedTypeRefs.getOrDefault(typeRef.name(), typeRef);
|
||||
case SIMPLE -> {
|
||||
var base = aliasedTypeRefs.getOrDefault(typeRef.name(), typeRef);
|
||||
var origin = model.contractTypes.declaration(typeRef);
|
||||
if (origin != null && topDeclName(origin) != null) {
|
||||
base = PbsAst.TypeRef.simple(topDeclName(origin), origin.span());
|
||||
}
|
||||
yield typeRef.arguments().isEmpty() ? base : PbsAst.TypeRef.applied(base.name(),
|
||||
ReadOnlyList.wrap(typeRef.arguments().stream().map(this::aliasExpandedTypeRef).toList()), base.span());
|
||||
}
|
||||
case FN -> PbsAst.TypeRef.function(ReadOnlyList.wrap(typeRef.fields().stream().map(f ->
|
||||
new PbsAst.NamedTypeField(null, aliasExpandedTypeRef(f.typeRef()), f.span())).toList()),
|
||||
aliasExpandedTypeRef(typeRef.inner()), typeRef.span());
|
||||
@@ -2165,7 +2225,7 @@ public final class PbsEditorialSupportService {
|
||||
return new PbsAst.HostDecl(newName, hostDecl.signatures(), hostDecl.attributes(), hostDecl.span());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
return new PbsAst.ContractDecl(newName, contractDecl.signatures(), contractDecl.attributes(), contractDecl.span());
|
||||
return new PbsAst.ContractDecl(newName, contractDecl.typeParameters(), contractDecl.signatures(), contractDecl.attributes(), contractDecl.span());
|
||||
}
|
||||
|
||||
if (topDecl instanceof PbsAst.EnumDecl enumDecl) {
|
||||
|
||||
+12
@@ -108,6 +108,18 @@ final class PbsFlowBodyAnalyzer {
|
||||
validateFunction(functionDecl, model, diagnostics);
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
|
||||
var ownerType = typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()), model, null);
|
||||
for (var method : implementation.methods()) {
|
||||
var parameters = new ArrayList<PbsAst.Parameter>();
|
||||
parameters.add(new PbsAst.Parameter(implementation.binderName(), PbsAst.TypeRef.simple(implementation.ownerName(), implementation.span()), implementation.span()));
|
||||
parameters.addAll(method.parameters().asList());
|
||||
validateCallableBody(ReadOnlyList.wrap(parameters), method.body(), typeOps.callableReturnType(
|
||||
method.returnKind(), method.returnType(), method.resultErrorType(), model), errorName(method.resultErrorType()),
|
||||
ownerType, model, diagnostics);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
validateStruct(structDecl, model, diagnostics);
|
||||
return;
|
||||
|
||||
+1
-1
@@ -238,7 +238,7 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
}
|
||||
|
||||
if (receiver.kind() == Kind.CONTRACT) {
|
||||
final var contract = model.contracts.get(receiver.name());
|
||||
final var contract = model.contractInfo(receiver);
|
||||
if (contract == null) {
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
|
||||
+72
-8
@@ -68,7 +68,14 @@ final class PbsFlowSemanticSupport {
|
||||
TypeView inner,
|
||||
TypeView errorType,
|
||||
List<TypeView> functionInputs,
|
||||
TypeView functionOutput) {
|
||||
TypeView functionOutput,
|
||||
String nominalIdentity,
|
||||
PbsAst.TypeRef sourceType,
|
||||
Set<String> implementers) {
|
||||
TypeView(Kind kind, String name, List<TupleField> tupleFields, TypeView inner, TypeView errorType,
|
||||
List<TypeView> functionInputs, TypeView functionOutput) {
|
||||
this(kind, name, tupleFields, inner, errorType, functionInputs, functionOutput, null, null, Set.of());
|
||||
}
|
||||
static TypeView unknown() {
|
||||
return new TypeView(Kind.UNKNOWN, null, List.of(), null, null, List.of(), null);
|
||||
}
|
||||
@@ -190,6 +197,7 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
|
||||
static final class Model {
|
||||
p.studio.compiler.pbs.PbsContractTypes contractTypes;
|
||||
final Map<String, List<CallableSymbol>> topLevelCallables = new HashMap<>();
|
||||
final Map<String, StructInfo> structs = new HashMap<>();
|
||||
final Map<String, ServiceInfo> services = new HashMap<>();
|
||||
@@ -219,6 +227,8 @@ final class PbsFlowSemanticSupport {
|
||||
final FESurfaceContext feSurfaceContext,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final var model = new Model();
|
||||
model.contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplementalTopDecls, diagnostics);
|
||||
model.contractTypes.validate(ast);
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
model.registerKnownTopDecl(topDecl);
|
||||
}
|
||||
@@ -233,13 +243,37 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
for (var imported : ast.imports()) for (var item : imported.items()) {
|
||||
if (item.alias() == null || item.alias().isBlank() || !model.services.containsKey(item.name())) continue;
|
||||
model.services.put(item.alias(), model.services.get(item.name()));
|
||||
model.serviceSingletons.put(item.alias(), TypeView.service(item.name()));
|
||||
model.services.putIfAbsent(item.alias(), model.services.get(item.name()));
|
||||
model.serviceSingletons.put(item.alias(), model.withIdentity(TypeView.service(item.alias()), PbsAst.TypeRef.simple(item.alias(), item.span())));
|
||||
}
|
||||
model.ingestAssetSurface(feSurfaceContext, diagnostics);
|
||||
return model;
|
||||
}
|
||||
|
||||
ContractInfo contractInfo(TypeView type) {
|
||||
return contracts.get(type.nominalIdentity() == null ? type.name() : type.nominalIdentity());
|
||||
}
|
||||
|
||||
TypeView withIdentity(TypeView type, PbsAst.TypeRef reference) {
|
||||
if (contractTypes.declaration(reference) == null) return type;
|
||||
return new TypeView(type.kind(), type.name(), type.tupleFields(), type.inner(), type.errorType(),
|
||||
type.functionInputs(), type.functionOutput(), contractTypes.key(reference), reference, type.implementers());
|
||||
}
|
||||
|
||||
TypeView contractView(PbsAst.TypeRef reference) {
|
||||
var instance = contractTypes.resolve(reference);
|
||||
if (instance == null) return TypeView.unknown();
|
||||
if (!contracts.containsKey(instance.key())) {
|
||||
var methods = new HashMap<String, List<CallableSymbol>>();
|
||||
contracts.put(instance.key(), new ContractInfo(methods));
|
||||
for (var signature : instance.declaration().signatures()) methods.computeIfAbsent(signature.name(), ignored -> new ArrayList<>())
|
||||
.add(callableFrom(signature.name(), signature.parameters(), signature.returnKind(), signature.returnType(),
|
||||
signature.resultErrorType(), signature.span(), documentationFromAttributes(signature.attributes())));
|
||||
}
|
||||
return new TypeView(Kind.CONTRACT, contractTypes.display(reference), List.of(), null, null, List.of(), null,
|
||||
instance.key(), reference, contractTypes.implementers(reference));
|
||||
}
|
||||
|
||||
boolean isOpaqueBuiltin(TypeView type) {
|
||||
if (type == null || !knownBuiltinTypeNames.contains(type.name())) return false;
|
||||
var declaration = structs.get(type.name());
|
||||
@@ -247,6 +281,16 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
|
||||
private void registerKnownTopDecl(final PbsAst.TopDecl topDecl) {
|
||||
if (topDecl instanceof PbsAst.TypeBindingDecl binding) {
|
||||
registerKnownTopDecl(binding.declaration());
|
||||
if (binding.declaration() instanceof PbsAst.ContractDecl) knownContractNames.add(binding.name());
|
||||
if (binding.declaration() instanceof PbsAst.StructDecl || binding.declaration() instanceof PbsAst.BuiltinTypeDecl) knownStructNames.add(binding.name());
|
||||
if (binding.declaration() instanceof PbsAst.BuiltinTypeDecl) knownBuiltinTypeNames.add(binding.name());
|
||||
if (binding.declaration() instanceof PbsAst.ServiceDecl) knownServiceNames.add(binding.name());
|
||||
if (binding.declaration() instanceof PbsAst.EnumDecl) knownEnumNames.add(binding.name());
|
||||
if (binding.declaration() instanceof PbsAst.ErrorDecl) knownErrorNames.add(binding.name());
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
knownStructNames.add(structDecl.name());
|
||||
return;
|
||||
@@ -280,6 +324,24 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
|
||||
private void ingestTopDecl(final PbsAst.TopDecl topDecl) {
|
||||
if (topDecl instanceof PbsAst.TypeBindingDecl binding) {
|
||||
ingestTopDecl(binding.declaration());
|
||||
if (binding.declaration() instanceof PbsAst.StructDecl s) structs.put(binding.name(), structs.get(s.name()));
|
||||
if (binding.declaration() instanceof PbsAst.BuiltinTypeDecl b) structs.put(binding.name(), structs.get(b.name()));
|
||||
if (binding.declaration() instanceof PbsAst.EnumDecl e) enums.put(binding.name(), enums.get(e.name()));
|
||||
if (binding.declaration() instanceof PbsAst.ErrorDecl e) errors.put(binding.name(), errors.get(e.name()));
|
||||
if (binding.declaration() instanceof PbsAst.ServiceDecl s) {
|
||||
services.put(binding.name(), services.get(s.name()));
|
||||
serviceSingletons.put(binding.name(), withIdentity(TypeView.service(binding.name()), PbsAst.TypeRef.simple(binding.name(), binding.span())));
|
||||
for (var constant : s.constants()) {
|
||||
var original = s.name() + "." + constant.name();
|
||||
var alias = binding.name() + "." + constant.name();
|
||||
constTypes.put(alias, constTypes.get(original));
|
||||
serviceConstants.put(alias, constant);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
final var fields = new HashMap<String, StructFieldInfo>();
|
||||
for (final var field : structDecl.fields()) {
|
||||
@@ -351,7 +413,7 @@ final class PbsFlowSemanticSupport {
|
||||
serviceConstants.put(key, constant);
|
||||
}
|
||||
services.put(serviceDecl.name(), new ServiceInfo(methods));
|
||||
serviceSingletons.put(serviceDecl.name(), TypeView.service(serviceDecl.name()));
|
||||
serviceSingletons.put(serviceDecl.name(), withIdentity(TypeView.service(serviceDecl.name()), PbsAst.TypeRef.simple(serviceDecl.name(), serviceDecl.span())));
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
||||
@@ -373,6 +435,7 @@ final class PbsFlowSemanticSupport {
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
if (!contractDecl.typeParameters().isEmpty()) return;
|
||||
final var methods = new HashMap<String, List<CallableSymbol>>();
|
||||
for (final var signature : contractDecl.signatures()) {
|
||||
methods.computeIfAbsent(signature.name(), ignored -> new ArrayList<>())
|
||||
@@ -551,6 +614,7 @@ final class PbsFlowSemanticSupport {
|
||||
case UNIT -> TypeView.unit();
|
||||
case SELF, ERROR -> TypeView.unknown();
|
||||
case SIMPLE -> {
|
||||
if (contractTypes.isContract(typeRef)) yield contractView(typeRef);
|
||||
if ("long".equals(typeRef.name())) {
|
||||
yield TypeView.longType();
|
||||
}
|
||||
@@ -570,13 +634,13 @@ final class PbsFlowSemanticSupport {
|
||||
yield TypeView.addressable(typeRef.name());
|
||||
}
|
||||
if (structs.containsKey(typeRef.name()) || knownStructNames.contains(typeRef.name())) {
|
||||
yield TypeView.struct(typeRef.name());
|
||||
yield withIdentity(TypeView.struct(typeRef.name()), typeRef);
|
||||
}
|
||||
if (services.containsKey(typeRef.name()) || knownServiceNames.contains(typeRef.name())) {
|
||||
yield TypeView.service(typeRef.name());
|
||||
yield withIdentity(TypeView.service(typeRef.name()), typeRef);
|
||||
}
|
||||
if (contracts.containsKey(typeRef.name()) || knownContractNames.contains(typeRef.name())) {
|
||||
yield TypeView.contract(typeRef.name());
|
||||
yield contractView(typeRef);
|
||||
}
|
||||
if (enums.containsKey(typeRef.name()) || knownEnumNames.contains(typeRef.name())) {
|
||||
yield TypeView.enumType(typeRef.name());
|
||||
@@ -586,7 +650,7 @@ final class PbsFlowSemanticSupport {
|
||||
}
|
||||
yield TypeView.unknown();
|
||||
}
|
||||
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFrom(f.typeRef())).toList(), typeFrom(typeRef.inner()));
|
||||
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFrom(f.typeRef())).toList(), collapse(typeFrom(typeRef.inner())));
|
||||
case ARRAY -> TypeView.array(typeFrom(typeRef.inner()));
|
||||
case OPTIONAL -> TypeView.optional(typeFrom(typeRef.inner()));
|
||||
case GROUP -> typeFrom(typeRef.inner());
|
||||
|
||||
+3
-2
@@ -116,9 +116,10 @@ final class PbsFlowStatementAnalyzer {
|
||||
true,
|
||||
this::analyzeNestedBlock);
|
||||
if (expected != null && (expected.kind() == Kind.ARRAY || initializer.type().kind() == Kind.ARRAY
|
||||
|| expected.kind() == Kind.FN || initializer.type().kind() == Kind.FN)
|
||||
|| expected.kind() == Kind.FN || initializer.type().kind() == Kind.FN || expected.kind() == Kind.CONTRACT)
|
||||
&& !typeOps.compatible(initializer.type(),expected)) {
|
||||
Diagnostics.error(diagnostics,"E_SEM_ARRAY_TYPE_MISMATCH","Array assignment requires the exact element type",letStatement.span());
|
||||
Diagnostics.error(diagnostics, expected.kind() == Kind.CONTRACT ? "E_SEM_CONTRACT_COERCION" : "E_SEM_ARRAY_TYPE_MISMATCH",
|
||||
expected.kind() == Kind.CONTRACT ? "Initializer does not supply the selected contract application" : "Assignment requires the exact declared type",letStatement.span());
|
||||
}
|
||||
final var resolvedType = expected == null ? initializer.type() : expected;
|
||||
scope.bind(letStatement.name(), resolvedType, !letStatement.isConst());
|
||||
|
||||
+29
-5
@@ -60,9 +60,20 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(TypeView.optional(receiver.inner()));
|
||||
}
|
||||
if (expression instanceof PbsAst.NewExpr allocation && allocation.typeName().equals("array")) {
|
||||
final var array = requireArrayContext(expectedType, expression, context);
|
||||
if (allocation.explicitType() != null) {
|
||||
PbsTypeSurfaceSemanticsValidator.validateTypeSurfaceRecursive(
|
||||
java.util.List.of(allocation.explicitType()), "array constructor", receiverType != null, diagnostics);
|
||||
validateConstructionType(allocation.explicitType(), context);
|
||||
}
|
||||
final var array = allocation.explicitType() == null
|
||||
? requireArrayContext(expectedType, expression, context)
|
||||
: typeOps.typeFromTypeRef(allocation.explicitType(), model, receiverType);
|
||||
if (expectedType != null && !typeOps.compatible(array, expectedType)) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_ARRAY_TYPE_MISMATCH",
|
||||
"Array construction requires the exact expected element type", allocation.span());
|
||||
}
|
||||
if (allocation.ctorName() != null || allocation.arguments().size() != 1) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_ARRAY_CONSTRUCTION", "Use new array(length)", allocation.span());
|
||||
Diagnostics.error(diagnostics, "E_SEM_ARRAY_CONSTRUCTION", "Use new array<T>(length), new array<>(length), or contextual new array(length)", allocation.span());
|
||||
}
|
||||
for (var length : allocation.arguments()) checkArrayIndex(length, context);
|
||||
return ExprResult.type(array);
|
||||
@@ -216,7 +227,7 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
if (model.structs.containsKey(newExpr.typeName())) {
|
||||
return ExprResult.type(TypeView.struct(newExpr.typeName()));
|
||||
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span()), model, null));
|
||||
}
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
@@ -228,12 +239,15 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
}
|
||||
return ExprResult.type(typeOps.typeFromTypeRef(PbsAst.TypeRef.simple(asExpr.contractName(), asExpr.span()), model, null));
|
||||
}
|
||||
if (model.contracts.containsKey(asExpr.contractName())) {
|
||||
if (model.contractTypes.isContract(asExpr.contractType())) {
|
||||
if (model.isOpaqueBuiltin(source)) {
|
||||
Diagnostics.error(diagnostics, "E_SEM_OPAQUE_BUILTIN_TYPE_MISMATCH",
|
||||
"Opaque builtin references cannot adapt to contracts", asExpr.span());
|
||||
}
|
||||
return ExprResult.type(TypeView.contract(asExpr.contractName()));
|
||||
var target = model.contractView(asExpr.contractType());
|
||||
if (source.kind() != Kind.CONTRACT && !typeOps.compatible(source, target)) Diagnostics.error(diagnostics, "E_SEM_CONTRACT_COERCION",
|
||||
"Source does not supply the selected contract implementation", asExpr.span());
|
||||
return ExprResult.type(target);
|
||||
}
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
@@ -256,6 +270,16 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void validateConstructionType(PbsAst.TypeRef type, PbsFlowExpressionContext context) {
|
||||
if (type.kind() == PbsAst.TypeRefKind.SIMPLE
|
||||
&& typeOps.typeFromTypeRef(type, context.model(), context.receiverType()).kind() == Kind.UNKNOWN) {
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_ELEMENT_TYPE",
|
||||
"Unknown array element type: " + type.name(), type.span());
|
||||
}
|
||||
if (type.inner() != null) validateConstructionType(type.inner(), context);
|
||||
for (var field : type.fields()) validateConstructionType(field.typeRef(), context);
|
||||
}
|
||||
|
||||
private TypeView requireArrayContext(TypeView expected, PbsAst.Expression expression, PbsFlowExpressionContext context) {
|
||||
if (expected != null && expected.kind() == Kind.ARRAY) return expected;
|
||||
Diagnostics.error(context.diagnostics(), "E_SEM_ARRAY_CONTEXT_REQUIRED",
|
||||
|
||||
+9
-2
@@ -45,12 +45,18 @@ final class PbsFlowTypeOps {
|
||||
if (actual.kind() == Kind.UNKNOWN || expected.kind() == Kind.UNKNOWN) {
|
||||
return true;
|
||||
}
|
||||
if (expected.kind() == Kind.CONTRACT && (actual.kind() == Kind.STRUCT || actual.kind() == Kind.SERVICE))
|
||||
return expected.implementers().contains(actual.nominalIdentity() == null ? actual.name() : actual.nominalIdentity());
|
||||
if (actual.kind() != expected.kind()) {
|
||||
return false;
|
||||
}
|
||||
return switch (actual.kind()) {
|
||||
case UNIT, INT, LONG, FLOAT, BOOL, STR -> true;
|
||||
case STRUCT, SERVICE, CONTRACT, ENUM, ERROR, TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
|
||||
case CONTRACT -> actual.nominalIdentity() != null && expected.nominalIdentity() != null
|
||||
? actual.nominalIdentity().equals(expected.nominalIdentity()) : actual.name().equals(expected.name());
|
||||
case STRUCT, SERVICE, ENUM, ERROR -> actual.nominalIdentity() != null && expected.nominalIdentity() != null
|
||||
? actual.nominalIdentity().equals(expected.nominalIdentity()) : actual.name().equals(expected.name());
|
||||
case TYPE_REF, ASSET_NAMESPACE -> actual.name().equals(expected.name());
|
||||
case FN -> actual.functionInputs().size() == expected.functionInputs().size()
|
||||
&& java.util.stream.IntStream.range(0, actual.functionInputs().size()).allMatch(i ->
|
||||
compatible(actual.functionInputs().get(i), expected.functionInputs().get(i)))
|
||||
@@ -109,7 +115,8 @@ final class PbsFlowTypeOps {
|
||||
return switch (typeRef.kind()) {
|
||||
case UNIT -> TypeView.unit();
|
||||
case SELF -> receiverType == null ? TypeView.unknown() : receiverType;
|
||||
case SIMPLE -> simpleType(typeRef.name(), model);
|
||||
case SIMPLE -> model.contractTypes.isContract(typeRef) ? model.contractView(receiverType == null ? typeRef : p.studio.compiler.pbs.PbsTypeSubstitution.replaceSelf(typeRef, receiverType.name()))
|
||||
: model.withIdentity(simpleType(typeRef.name(), model), typeRef);
|
||||
case FN -> TypeView.function("Fn", typeRef.fields().stream().map(f -> typeFromTypeRef(f.typeRef(), model, receiverType)).toList(),
|
||||
collapseReturnPayload(typeFromTypeRef(typeRef.inner(), model, receiverType)));
|
||||
case ARRAY -> TypeView.array(typeFromTypeRef(typeRef.inner(), model, receiverType));
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ final class PbsInlineHintSurfaceFormatter {
|
||||
.collect(java.util.stream.Collectors.joining(", ")) + ") -> " + format(type.functionOutput());
|
||||
case ARRAY -> {
|
||||
final var inner = format(type.inner());
|
||||
yield inner == null ? null : "array (" + inner + ")";
|
||||
yield inner == null ? null : "array<" + inner + ">";
|
||||
}
|
||||
case OPTIONAL -> {
|
||||
final var inner = format(type.inner());
|
||||
|
||||
+1
@@ -21,6 +21,7 @@ final class PbsTypeSurfaceSemanticsValidator {
|
||||
if (typeRef == null) {
|
||||
continue;
|
||||
}
|
||||
pending.addAll(typeRef.arguments().asList());
|
||||
|
||||
switch (typeRef.kind()) {
|
||||
case FN -> {
|
||||
|
||||
+78
-8
@@ -48,6 +48,24 @@ final class PbsImportedSemanticContextService {
|
||||
for (final var entry : sourcesByModule.entrySet()) {
|
||||
topDeclsByNameByModule.put(entry.getKey(), indexTopDeclsByName(entry.getValue()));
|
||||
}
|
||||
var moduleBySource = new HashMap<FileId, ModuleId>();
|
||||
parsedSourceFiles.forEach(s -> moduleBySource.put(s.fileId(), s.moduleId()));
|
||||
boolean exportedContractsChanged;
|
||||
do {
|
||||
exportedContractsChanged = false;
|
||||
for (var source : parsedSourceFiles) for (var imported : source.ast().imports()) {
|
||||
var target = moduleTable.register(new p.studio.compiler.source.tables.ModuleReference(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
|
||||
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) {
|
||||
var candidates = localIndex.computeIfAbsent(importItemLocalName(item), ignored -> new ArrayList<>());
|
||||
if (candidates.stream().noneMatch(d -> d.span().equals(declaration.span()))) {
|
||||
candidates.add(declaration); exportedContractsChanged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} while (exportedContractsChanged);
|
||||
final var globalInfosByRef = indexGlobalInfos(sourcesByModule, topDeclsByNameByModule, moduleTable);
|
||||
|
||||
final Map<FileId, PbsImportedSemanticContext> contexts = new HashMap<>();
|
||||
@@ -61,6 +79,15 @@ final class PbsImportedSemanticContextService {
|
||||
var importedReservedMetadata = IRReservedMetadata.empty();
|
||||
final var directlyVisibleGlobalRefs = new LinkedHashMap<String, PbsGlobalDependencySupport.GlobalRef>();
|
||||
|
||||
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(
|
||||
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys);
|
||||
if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
|
||||
}
|
||||
}
|
||||
|
||||
for (final var importDecl : parsedSource.ast().imports()) {
|
||||
final var moduleRef = importDecl.moduleRef();
|
||||
final var importedModuleId = moduleTable.register(
|
||||
@@ -83,24 +110,33 @@ final class PbsImportedSemanticContextService {
|
||||
final var directDecls = importedTopDeclsByName.getOrDefault(importName, new ArrayList<>());
|
||||
for (final var topDecl : directDecls) {
|
||||
appendSupplementalTopDecl(topDecl, supplementalTopDecls, supplementalKeys);
|
||||
appendTypeDependencyDecls(topDecl, importedTopDeclsByName, supplementalTopDecls, supplementalKeys);
|
||||
if (isTypeDecl(topDecl)) 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)) {
|
||||
appendSupplementalTopDecl(implementation, supplementalTopDecls, supplementalKeys);
|
||||
appendTypeDependencyDecls(implementation, importedTopDeclsByName, supplementalTopDecls, supplementalKeys);
|
||||
}
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(serviceDecl);
|
||||
appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, serviceDecl.name()+".$instance", 0, 1,
|
||||
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor)));
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, localName+".$instance", 0, 1,
|
||||
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor), serviceDecl.name()+".$instance"));
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
appendImportedCallable(
|
||||
importedCallables,
|
||||
importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(
|
||||
importedModuleId,
|
||||
serviceDecl.name() + "." + method.name(),
|
||||
localName + "." + method.name(),
|
||||
method.parameters().size(),
|
||||
returnSlotsFor(method),
|
||||
method.returnKind(),
|
||||
method.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(method)));
|
||||
frontendCompiler.callableShapeSurfaceOf(method), serviceDecl.name() + "." + method.name()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -114,7 +150,7 @@ final class PbsImportedSemanticContextService {
|
||||
appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId,localName+"."+method.name(),
|
||||
executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(executable)));
|
||||
frontendCompiler.callableShapeSurfaceOf(executable), structDecl.name()+"."+method.name()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -129,7 +165,7 @@ final class PbsImportedSemanticContextService {
|
||||
returnSlotsFor(functionDecl),
|
||||
functionDecl.returnKind(),
|
||||
functionDecl.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(functionDecl)));
|
||||
frontendCompiler.callableShapeSurfaceOf(functionDecl), functionDecl.name()));
|
||||
continue;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.GlobalDecl globalDecl) {
|
||||
@@ -170,6 +206,27 @@ final class PbsImportedSemanticContextService {
|
||||
importedReservedMetadata));
|
||||
}
|
||||
|
||||
// Preserve lexical bindings of provider signatures, including transitive imported aliases.
|
||||
boolean changed;
|
||||
do {
|
||||
changed = false;
|
||||
for (var source : parsedSourceFiles) {
|
||||
var context = contexts.get(source.fileId());
|
||||
var declarations = new ArrayList<>(context.supplementalTopDecls().asList());
|
||||
var keys = new HashSet<String>();
|
||||
declarations.forEach(d -> keys.add(topDeclKey(d)));
|
||||
for (var imported : source.ast().imports()) {
|
||||
var target = moduleTable.register(new p.studio.compiler.source.tables.ModuleReference(imported.moduleRef().project(), imported.moduleRef().pathSegments()));
|
||||
for (var provider : sourcesByModule.getOrDefault(target, new ArrayList<>()))
|
||||
for (var declaration : contexts.get(provider.fileId()).supplementalTopDecls())
|
||||
if (declaration instanceof PbsAst.TypeBindingDecl && keys.add(topDeclKey(declaration))) {
|
||||
declarations.add(declaration); changed = true;
|
||||
}
|
||||
}
|
||||
if (declarations.size() != context.supplementalTopDecls().size()) contexts.put(source.fileId(), new PbsImportedSemanticContext(
|
||||
ReadOnlyList.wrap(declarations), context.importedCallables(), context.importedGlobals(), context.importedReservedMetadata()));
|
||||
}
|
||||
} while (changed);
|
||||
return contexts;
|
||||
}
|
||||
|
||||
@@ -218,6 +275,12 @@ final class PbsImportedSemanticContextService {
|
||||
private void collectReferencedTypeNames(
|
||||
final PbsAst.TopDecl topDecl,
|
||||
final ArrayDeque<String> sink) {
|
||||
if (topDecl instanceof PbsAst.ImplementsDecl implementation) {
|
||||
collectReferencedTypeNames(implementation.contractType(), sink);
|
||||
sink.add(implementation.ownerName());
|
||||
implementation.methods().forEach(m -> collectReferencedTypeNames(m, sink));
|
||||
return;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.StructDecl structDecl) {
|
||||
for (final var field : structDecl.fields()) {
|
||||
collectReferencedTypeNames(field.typeRef(), sink);
|
||||
@@ -311,6 +374,7 @@ final class PbsImportedSemanticContextService {
|
||||
if (typeRef == null) {
|
||||
return;
|
||||
}
|
||||
for (var argument : typeRef.arguments()) collectReferencedTypeNames(argument, sink);
|
||||
switch (typeRef.kind()) {
|
||||
case SIMPLE -> {
|
||||
final var simpleName = typeRef.name();
|
||||
@@ -398,11 +462,17 @@ final class PbsImportedSemanticContextService {
|
||||
}
|
||||
|
||||
private String topDeclKey(final PbsAst.TopDecl topDecl) {
|
||||
if (topDecl instanceof PbsAst.TypeBindingDecl binding) return "binding:" + binding.span().getFileId().getId() + ":" + binding.name() + ":" + sourceKey(binding.declaration().span());
|
||||
if (topDecl instanceof PbsAst.ImplementsDecl implementation) return "implementation:" + sourceKey(implementation.span());
|
||||
final var declName = topDeclName(topDecl);
|
||||
if (declName == null || declName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return topDecl.getClass().getSimpleName() + ":" + declName;
|
||||
return topDecl.getClass().getSimpleName() + ":" + declName + ":" + sourceKey(topDecl.span());
|
||||
}
|
||||
|
||||
private static String sourceKey(p.studio.compiler.source.Span span) {
|
||||
return span.getFileId().getId() + ":" + span.getStart() + ":" + span.getEnd();
|
||||
}
|
||||
|
||||
private String topDeclName(final PbsAst.TopDecl topDecl) {
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@ declare struct ArrayExampleEnemy(pub mut hp: int) {
|
||||
|
||||
fn arrayExample() -> int {
|
||||
let capacity: int = 3;
|
||||
let enemies: array ArrayExampleEnemy = new array(capacity);
|
||||
let enemies = new array<ArrayExampleEnemy>(capacity);
|
||||
let enemy = new ArrayExampleEnemy(50);
|
||||
enemies[1] = enemy;
|
||||
|
||||
@@ -15,7 +15,7 @@ fn arrayExample() -> int {
|
||||
enemies.clear(1);
|
||||
|
||||
// Nested array allocation creates only the outer level.
|
||||
let groups: array[2] int = new array(2);
|
||||
let groups: array<array<int>> = new array<>(2);
|
||||
groups[0] = [20, 22];
|
||||
if let group = groups[0] {
|
||||
let total = (group[0] else 0) + (group[1] else 0);
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@ fn createExampleCounter(start: int) -> Fn() -> int {
|
||||
|
||||
fn closureExample() -> int {
|
||||
let next = createExampleCounter(40);
|
||||
let functions: array (Fn() -> int) = [next];
|
||||
let functions: array<(Fn() -> int)> = [next];
|
||||
if let action = functions[0] {
|
||||
let first = action();
|
||||
return action();
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
// The contract's element type is independent of the strategy receiver.
|
||||
declare contract ExampleIdentity<T> {
|
||||
fn hash(value: T) -> int;
|
||||
fn equals(left: T, right: T) -> bool;
|
||||
}
|
||||
|
||||
declare service ExampleIntIdentity {}
|
||||
|
||||
implements ExampleIdentity<int> for ExampleIntIdentity using strategy {
|
||||
fn hash(value: int) -> int { return value; }
|
||||
fn equals(left: int, right: int) -> bool { return left == right; }
|
||||
}
|
||||
|
||||
fn contractExample() -> int {
|
||||
let identity: ExampleIdentity<int> = ExampleIntIdentity;
|
||||
if identity.equals(7, 7) { return identity.hash(42); }
|
||||
return 0;
|
||||
}
|
||||
+1
@@ -1,2 +1,3 @@
|
||||
pub fn init() -> void;
|
||||
pub fn frame() -> void;
|
||||
pub fn contractExample() -> int;
|
||||
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.models.IRBackendFile;
|
||||
import p.studio.compiler.models.registry.IRRegistry;
|
||||
import p.studio.compiler.pbs.lexer.PbsLexer;
|
||||
import p.studio.compiler.pbs.parser.PbsBarrelParser;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsGenericContractsTest {
|
||||
private static final String IDENTITY = """
|
||||
declare contract Identity<T> { fn hash(e: T) -> int; fn equals(a: T, b: T) -> bool; }
|
||||
declare service IntIdentity {}
|
||||
implements Identity<int> for IntIdentity using strategy {
|
||||
fn hash(e: int) -> int { return e; }
|
||||
fn equals(a: int, b: int) -> bool { return a == b; }
|
||||
}
|
||||
""";
|
||||
|
||||
private IRBackendFile compile(String source) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var file = new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode() + ": " + d.getMessage()).toList().toString());
|
||||
return file;
|
||||
}
|
||||
|
||||
private void rejects(String source, String code) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals(code)), () -> diagnostics.stream().map(d -> d.getCode() + ": " + d.getMessage()).toList().toString());
|
||||
}
|
||||
|
||||
@Test void explicitAndContextualApplicationsProduceConcreteTraits() {
|
||||
var file = compile(IDENTITY + """
|
||||
fn select(value: Identity<int>) -> Identity<int> { return value; }
|
||||
fn demo() -> bool {
|
||||
let identity: Identity<int> = IntIdentity;
|
||||
let explicit = IntIdentity as Identity<int>;
|
||||
return select(identity).equals(7, explicit.hash(7));
|
||||
}
|
||||
""");
|
||||
var traits = file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).toList();
|
||||
assertEquals(1, traits.size());
|
||||
assertEquals("Identity<int>", traits.getFirst().name());
|
||||
assertEquals(1, file.registry().implementations().size());
|
||||
}
|
||||
|
||||
@Test void sameOwnerHasTwoIndependentApplications() {
|
||||
var file = compile("""
|
||||
declare contract Echo<T> { fn echo(value: T) -> T; }
|
||||
declare service Strategy {}
|
||||
implements Echo<int> for Strategy using s { fn echo(value: int) -> int { return value; } }
|
||||
implements Echo<bool> for Strategy using s { fn echo(value: bool) -> bool { return value; } }
|
||||
fn demo() -> int {
|
||||
let ints: Echo<int> = Strategy;
|
||||
let flags: Echo<bool> = Strategy;
|
||||
if flags.echo(true) { return ints.echo(42); }
|
||||
return 0;
|
||||
}
|
||||
""");
|
||||
assertEquals(2, file.registry().implementations().size());
|
||||
assertNotEquals(file.registry().implementations().get(0).trait(), file.registry().implementations().get(1).trait());
|
||||
assertEquals(2, file.executableFunctions().stream().filter(f -> f.callableName().contains(".$impl.")).count());
|
||||
}
|
||||
|
||||
@Test void multipleParametersAndComposedSignaturesAreSubstituted() {
|
||||
compile("""
|
||||
declare contract Convert<A, B> { fn convert(value: A) -> B; }
|
||||
declare service Strategy {}
|
||||
implements Convert<array<int>, (left: int, right: int)> for Strategy using s {
|
||||
fn convert(value: array<int>) -> (left: int, right: int) { return (left: value[0] else 0, right: 2); }
|
||||
}
|
||||
fn demo() -> int {
|
||||
let converter: Convert<array<int>, (left: int, right: int)> = Strategy;
|
||||
let pair = converter.convert([40]);
|
||||
return pair.left + pair.right;
|
||||
}
|
||||
""");
|
||||
}
|
||||
|
||||
@Test void phantomArgumentsAndSharedArrayStorageRemainNominallyDistinct() {
|
||||
var file = compile("""
|
||||
declare contract Marker<T> {}
|
||||
declare service Strategy {}
|
||||
implements Marker<array<int>> for Strategy using s {}
|
||||
implements Marker<array<bool>> for Strategy using s {}
|
||||
fn demo() -> int {
|
||||
let a: Marker<array<int>> = Strategy;
|
||||
let b: Marker<array<bool>> = Strategy;
|
||||
return 42;
|
||||
}
|
||||
""");
|
||||
assertEquals(2, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
|
||||
assertEquals(2, file.registry().implementations().size());
|
||||
}
|
||||
|
||||
@Test void finiteRecursiveSignatureHasANominalAnchor() {
|
||||
var file = compile("""
|
||||
declare contract Node<T> { fn next() -> Node<T>; }
|
||||
fn identity(value: Node<int>) -> Node<int> { return value; }
|
||||
""");
|
||||
assertEquals(1, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
|
||||
}
|
||||
|
||||
@Test void expandingRecursiveSignatureIsDiagnosed() {
|
||||
rejects("""
|
||||
declare contract Growing<T> { fn next() -> Growing<array<T>>; }
|
||||
fn use(value: Growing<int>) {}
|
||||
""", "E_SEM_CONTRACT_EXPANSION");
|
||||
}
|
||||
|
||||
@Test void finiteMutualApplicationsReuseTheirAnchors() {
|
||||
var file = compile("""
|
||||
declare contract Left<T> { fn next() -> Right<T>; }
|
||||
declare contract Right<T> { fn next() -> Left<T>; }
|
||||
fn identity(value: Left<int>) -> Left<int> { return value; }
|
||||
""");
|
||||
assertEquals(2, file.registry().types().stream().filter(t -> t.body() instanceof IRRegistry.Trait).count());
|
||||
}
|
||||
|
||||
@Test void applicationsRequireExplicitExactArity() {
|
||||
rejects("declare contract Identity<T> {} fn use(value: Identity) {}", "E_SEM_CONTRACT_ARITY");
|
||||
rejects("declare contract Identity<T> {} fn use(value: Identity<int, bool>) {}", "E_SEM_CONTRACT_ARITY");
|
||||
}
|
||||
|
||||
@Test void undeclaredAndDuplicateParametersAreRejected() {
|
||||
rejects("declare contract Bad<T> { fn get(value: U); }", "E_SEM_CONTRACT_PARAMETER");
|
||||
rejects("declare contract Bad<T, T> {}", "E_SEM_CONTRACT_PARAMETER");
|
||||
}
|
||||
|
||||
@Test void invalidApplicationsAndImplementationsAreRejected() {
|
||||
rejects("declare contract Echo<T> { fn echo(value: T) -> T; } declare service S {} implements Echo<int> for S using s {}", "E_SEM_CONTRACT_SIGNATURE");
|
||||
rejects(IDENTITY + "implements Identity<int> for IntIdentity using s { fn hash(e: int) -> int { return e; } fn equals(a: int, b: int) -> bool { return true; } }", "E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION");
|
||||
rejects("declare contract C<T> {} fn use(value: int<bool>) {}", "E_SEM_CONTRACT_ARGUMENT");
|
||||
}
|
||||
|
||||
@Test void instantiatedContractsAreInvariant() {
|
||||
rejects(IDENTITY + """
|
||||
fn bad(value: Identity<bool>) { let wrong: Identity<int> = value; }
|
||||
""", "E_SEM_CONTRACT_COERCION");
|
||||
rejects(IDENTITY + "fn bad() { let wrong = IntIdentity as Identity<bool>; }", "E_SEM_CONTRACT_COERCION");
|
||||
}
|
||||
|
||||
@Test void invalidPostSubstitutionArrayElementIsRejected() {
|
||||
rejects("declare contract C<T> { fn accept(values: array<T>); } fn bad(value: C<optional int>) {}", "E_SEM_ARRAY_ELEMENT_TYPE");
|
||||
}
|
||||
|
||||
@Test void composedPositionsKeepTheirExistingRestrictions() {
|
||||
rejects("declare contract C<T> { fn accept(value: Fn(T) -> int); } fn bad(value: C<void>) {}", "E_SEM_FN_PARAMETER");
|
||||
rejects("declare contract C<T> { fn get() -> optional T; } fn bad(value: C<void>) {}", "E_SEM_INVALID_OPTIONAL_VOID_TYPE_SURFACE");
|
||||
rejects("declare contract C<T> {} fn bad(value: C<Self>) {}", "E_SEM_INVALID_SELF_CONTEXT");
|
||||
}
|
||||
|
||||
@Test void functionReturnNormalizationDoesNotCreateAnotherApplication() {
|
||||
compile("""
|
||||
declare contract Marker<T> {}
|
||||
declare service Strategy {}
|
||||
implements Marker<Fn() -> int> for Strategy using s {}
|
||||
fn demo() { let value: Marker<Fn() -> (value: int)> = Strategy; }
|
||||
""");
|
||||
}
|
||||
|
||||
@Test void barrelPreservesOrderedParameters() {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var fileId = new FileId(0);
|
||||
var barrel = PbsBarrelParser.parse(PbsLexer.lex("pub contract Convert<A, B>;", fileId, diagnostics), fileId, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors());
|
||||
var item = assertInstanceOf(PbsAst.BarrelContractItem.class, barrel.items().getFirst());
|
||||
assertEquals(java.util.List.of("A", "B"), item.typeParameters().stream().map(PbsAst.TypeParameter::name).toList());
|
||||
}
|
||||
}
|
||||
+21
@@ -18,6 +18,27 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class PbsModuleVisibilityTest {
|
||||
|
||||
@Test void parameterizedExportsAndReexportsPreserveTheOriginalDeclaration() {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var next = new AtomicInteger(0);
|
||||
var provider = module("app", "provider", List.of("declare contract Identity<T> {}"), "pub contract Identity<T>;", next, diagnostics);
|
||||
var facade = module("app", "facade", List.of("import { Identity } from @app:provider;"), "pub contract Identity<T>;", next, diagnostics);
|
||||
new PbsModuleVisibilityValidator().validate(ReadOnlyList.from(provider, facade), diagnostics);
|
||||
assertTrue(!diagnostics.hasErrors(), diagnostics.stream().map(d -> d.getMessage()).toList().toString());
|
||||
}
|
||||
|
||||
@Test void parameterizedBarrelArityAndOwnerModuleAreChecked() {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var next = new AtomicInteger(0);
|
||||
var provider = module("app", "provider", List.of("declare contract Identity<T> {} declare service Strategy {}"),
|
||||
"pub contract Identity; pub service Strategy;", next, diagnostics);
|
||||
var consumer = module("app", "consumer", List.of("import { Identity, Strategy } from @app:provider; implements Identity<int> for Strategy using s {}"),
|
||||
"", next, diagnostics);
|
||||
new PbsModuleVisibilityValidator().validate(ReadOnlyList.from(provider, consumer), diagnostics);
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_LINK_CONTRACT_PARAMETERS")));
|
||||
assertTrue(diagnostics.stream().anyMatch(d -> d.getCode().equals("E_SEM_CONTRACT_OWNER_MODULE")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldReportMissingBarrelPerModule() {
|
||||
final var diagnostics = DiagnosticSink.empty();
|
||||
|
||||
+12
@@ -10,6 +10,18 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsBarrelParserTest {
|
||||
|
||||
@Test
|
||||
void parametricArraysAndFunctionsUseTheSharedTypeParser() {
|
||||
var source = "pub fn make(a: array<array<int>>) -> array<Fn(int) -> int>;";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(0);
|
||||
var ast = PbsBarrelParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors());
|
||||
var function = (PbsAst.BarrelFunctionItem) ast.items().getFirst();
|
||||
assertEquals(PbsAst.TypeRefKind.ARRAY, function.returnType().kind());
|
||||
assertEquals(PbsAst.TypeRefKind.FN, function.returnType().inner().kind());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldParseBarrelShapeWithFunctionReturnSurfaces() {
|
||||
final var source = """
|
||||
|
||||
+49
@@ -10,6 +10,55 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsExprParserTest {
|
||||
|
||||
@Test
|
||||
void typeCursorPeelsCompoundClosersAndPreservesRemainderSpans() {
|
||||
var cursor = new PbsTokenCursor(p.studio.utilities.structures.ReadOnlyList.from(
|
||||
new p.studio.compiler.pbs.lexer.PbsToken(p.studio.compiler.pbs.lexer.PbsTokenKind.GREATER_EQUAL, ">>=", 10, 13),
|
||||
new p.studio.compiler.pbs.lexer.PbsToken(p.studio.compiler.pbs.lexer.PbsTokenKind.EOF, "", 13, 13)));
|
||||
assertEquals(10, cursor.consumeTypeClose().start());
|
||||
assertEquals(">=", cursor.peek().lexeme());
|
||||
assertEquals(11, cursor.consumeTypeClose().start());
|
||||
assertEquals(p.studio.compiler.pbs.lexer.PbsTokenKind.EQUAL, cursor.peek().kind());
|
||||
assertEquals(12, cursor.peek().start());
|
||||
assertEquals(13, cursor.peek().end());
|
||||
assertNull(cursor.consumeTypeClose());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parametricArraysPreserveArgumentsSpansAndContextualForms() {
|
||||
var source = "fn main() { let a: array<array<int>>=new array<array<int>>(2); "
|
||||
+ "let b: array<int>=new array<>(2); let c: array<int>=new array(2); let cmp = 2 >= 1; }";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(0);
|
||||
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors(), diagnostics.toString());
|
||||
var statements = ast.functions().getFirst().body().statements();
|
||||
var a = (PbsAst.LetStatement) statements.get(0);
|
||||
var explicit = (PbsAst.NewExpr) a.initializer();
|
||||
assertEquals("array<array<int>>", source.substring((int) a.explicitType().span().getStart(), (int) a.explicitType().span().getEnd()));
|
||||
assertEquals("array<int>", source.substring((int) explicit.explicitType().inner().span().getStart(), (int) explicit.explicitType().inner().span().getEnd()));
|
||||
assertEquals("int", explicit.explicitType().inner().inner().name());
|
||||
assertFalse(explicit.diamond());
|
||||
var diamond = (PbsAst.NewExpr) ((PbsAst.LetStatement) statements.get(1)).initializer();
|
||||
assertTrue(diamond.diamond());
|
||||
assertNull(diamond.explicitType());
|
||||
var omitted = (PbsAst.NewExpr) ((PbsAst.LetStatement) statements.get(2)).initializer();
|
||||
assertFalse(omitted.diamond());
|
||||
assertNull(omitted.explicitType());
|
||||
assertEquals(">=", ((PbsAst.BinaryExpr) ((PbsAst.LetStatement) statements.get(3)).initializer()).operator());
|
||||
}
|
||||
|
||||
@Test
|
||||
void excessiveNestingAndMissingClosersAreDiagnosed() {
|
||||
for (var type : java.util.List.of("array<int", "array<".repeat(257) + "int" + ">".repeat(257))) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(0);
|
||||
var source = "fn main() { let a: " + type + " = new array(1); }";
|
||||
PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics);
|
||||
assertTrue(diagnostics.hasErrors(), type);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldParseApplyElseAndPostfixChains() {
|
||||
final var source = """
|
||||
|
||||
+10
-1
@@ -56,12 +56,21 @@ final class PbsEditorialSupportServiceTest {
|
||||
String source = """
|
||||
declare struct Enemy(pub hp: int) { fn health() -> int { return this.hp; } }
|
||||
fn main() {
|
||||
let enemies: array Enemy = new array(2);
|
||||
let enemies = new array<Enemy>(2);
|
||||
if let enemy = enemies[0] { let hp = enemy.health(); }
|
||||
enemies.clear(0);
|
||||
}
|
||||
""";
|
||||
var ast = parseOrdinary(source);
|
||||
int argumentType = source.indexOf("<Enemy>") + 1;
|
||||
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), argumentType).isEmpty());
|
||||
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), argumentType).isPresent());
|
||||
var typeRename = service.rename(source, ast, ReadOnlyList.empty(), argumentType, "Opponent");
|
||||
assertTrue(typeRename.allowed(), typeRename.refusal());
|
||||
assertEquals(2, typeRename.sites().size());
|
||||
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
|
||||
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
|
||||
parseOrdinary(formatted);
|
||||
int use = source.indexOf("enemy.health");
|
||||
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), use).isEmpty());
|
||||
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), use).isPresent());
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
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 PbsGenericContractsEditorialTest {
|
||||
@Test void importedAliasesNavigateToOriginsAndShowCanonicalArguments() {
|
||||
String provider = "declare struct Enemy() {} declare contract Echo<T> { fn echo(value: T) -> T; }";
|
||||
String source = """
|
||||
import { Echo as Policy, Enemy as Opponent } from @sdk:policy;
|
||||
fn use(reader: Policy<Opponent>) {}
|
||||
""";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var providerId = new FileId(1);
|
||||
var localId = new FileId(2);
|
||||
var remote = PbsParser.parse(PbsLexer.lex(provider, providerId, diagnostics), providerId, diagnostics, PbsParser.ParseMode.ORDINARY);
|
||||
var local = PbsParser.parse(PbsLexer.lex(source, localId, diagnostics), localId, diagnostics, PbsParser.ParseMode.ORDINARY);
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getMessage()).toList().toString());
|
||||
var enemy = remote.topDecls().get(0);
|
||||
var contract = remote.topDecls().get(1);
|
||||
var supplemental = ReadOnlyList.wrap(java.util.List.<PbsAst.TopDecl>of(
|
||||
new PbsAst.TypeBindingDecl("Opponent", enemy, local.span()),
|
||||
new PbsAst.TypeBindingDecl("Policy", contract, local.span())));
|
||||
var service = new PbsEditorialSupportService();
|
||||
int application = source.indexOf("Policy<");
|
||||
assertEquals(contract.span(), service.definition(source, local, supplemental, application).getFirst().span());
|
||||
assertEquals(enemy.span(), service.definition(source, local, supplemental, application + 7).getFirst().span());
|
||||
var hover = service.hover(source, local, supplemental, application).orElseThrow();
|
||||
assertEquals("Echo<Enemy>", hover.displayName());
|
||||
assertEquals("echo(value: Enemy) -> Enemy", hover.signatures().getFirst().label());
|
||||
}
|
||||
|
||||
@Test void parameterNavigationAndInstantiatedPresentationShareTheCompilerModel() {
|
||||
String source = """
|
||||
declare contract Echo<T> { fn echo(value: T) -> T; }
|
||||
fn demo(reader: Echo<int>) -> int { return reader.echo(42); }
|
||||
""";
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
var id = new FileId(0);
|
||||
var ast = PbsParser.parse(PbsLexer.lex(source, id, diagnostics), id, diagnostics, PbsParser.ParseMode.ORDINARY);
|
||||
assertFalse(diagnostics.hasErrors());
|
||||
var service = new PbsEditorialSupportService();
|
||||
int parameterUse = source.indexOf("value: T") + 7;
|
||||
var definition = service.definition(source, ast, ReadOnlyList.empty(), parameterUse);
|
||||
assertEquals(source.indexOf("<T>") + 1, definition.getFirst().span().getStart());
|
||||
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), parameterUse).orElseThrow().detail().contains("type parameter"));
|
||||
var application = service.hover(source, ast, ReadOnlyList.empty(), source.indexOf("Echo<int>"));
|
||||
assertEquals("Echo<int>", application.orElseThrow().displayName());
|
||||
assertEquals("echo(value: int) -> int", application.orElseThrow().signatures().getFirst().label());
|
||||
int call = source.indexOf("reader.echo");
|
||||
assertTrue(service.completion(source, ast, ReadOnlyList.empty(), call + 7).stream().anyMatch(c -> c.label().equals("echo") && c.detail().contains("int")));
|
||||
assertEquals("echo(value: int) -> int", service.signatureHelp(source, ast, ReadOnlyList.empty(), source.indexOf("42)")).orElseThrow().signatures().getFirst().label());
|
||||
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), call + 7).isEmpty());
|
||||
var formatted = p.studio.compiler.pbs.PbsDocumentFormatter.format(source);
|
||||
assertEquals(formatted, p.studio.compiler.pbs.PbsDocumentFormatter.format(formatted));
|
||||
var formattedDiagnostics = DiagnosticSink.empty();
|
||||
PbsParser.parse(PbsLexer.lex(formatted, id, formattedDiagnostics), id, formattedDiagnostics, PbsParser.ParseMode.ORDINARY);
|
||||
assertFalse(formattedDiagnostics.hasErrors());
|
||||
}
|
||||
}
|
||||
+32
@@ -9,6 +9,38 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsSemanticsDeclarationsTest {
|
||||
|
||||
@Test
|
||||
void arrayConstructorFormsShareExpectedTypePositions() {
|
||||
for (var construction : java.util.List.of("new array<int>(2)", "new array<>(2)", "new array(2)")) {
|
||||
var source = """
|
||||
declare global values: array<int> = %s;
|
||||
fn make() -> array<int> { return %s; }
|
||||
fn use(items: array<int>) -> int { return items.length as int; }
|
||||
fn main() -> int {
|
||||
let local: array<int> = %s;
|
||||
local = %s;
|
||||
return use(%s);
|
||||
}
|
||||
""".formatted(construction, construction, construction, construction, construction);
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
assertFalse(diagnostics.hasErrors(), () -> diagnostics.stream().map(d -> d.getCode()+":"+d.getMessage()).toList().toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitArraysMustMatchReturnAndArgumentTypes() {
|
||||
for (var source : java.util.List.of(
|
||||
"fn make() -> array<int> { return new array<bool>(1); }",
|
||||
"fn use(items: array<int>) {} fn main() { use(new array<bool>(1)); }",
|
||||
"declare global items: array<int> = new array<bool>(1);",
|
||||
"fn main() { let items: array<int> = new array(1); items = new array<bool>(1); }")) {
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
new PbsFrontendCompiler().compileFile(new FileId(0), source, diagnostics);
|
||||
assertTrue(diagnostics.hasErrors(), source);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldAcceptDocOnNamedApiDeclarations() {
|
||||
final var source = """
|
||||
|
||||
Reference in New Issue
Block a user