feat(pbs): add service constants and runtime math integration
This commit is contained in:
+5
@@ -41,6 +41,11 @@ public final class PbsReservedMetadataExtractor {
|
||||
extractBuiltinTypeSurface(builtinTypeDecl, inferredLayoutsByName, builtinTypeSurfaces);
|
||||
continue;
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ServiceDecl service) {
|
||||
for (var constant : service.constants()) extractBuiltinConstSurface(
|
||||
new PbsAst.ConstDecl(service.name() + "." + constant.name(), constant.explicitType(),
|
||||
constant.initializer(), constant.attributes(), constant.span()), builtinConstSurfaces);
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||
extractBuiltinConstSurface(constDecl, builtinConstSurfaces);
|
||||
}
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Constant identities retain their service owner, including across imports. */
|
||||
public final class PbsServiceConstants {
|
||||
private PbsServiceConstants() {}
|
||||
|
||||
public static Map<String, PbsAst.ConstDecl> collect(ReadOnlyList<PbsAst.TopDecl> declarations) {
|
||||
var result = new LinkedHashMap<String, PbsAst.ConstDecl>();
|
||||
for (var declaration : declarations) {
|
||||
if (declaration instanceof PbsAst.ConstDecl constant) result.putIfAbsent(constant.name(), constant);
|
||||
if (declaration instanceof PbsAst.ServiceDecl service)
|
||||
for (var constant : service.constants()) result.putIfAbsent(service.name() + "." + constant.name(), constant);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static String path(PbsAst.Expression expression) {
|
||||
if (expression instanceof PbsAst.IdentifierExpr name) return name.name();
|
||||
if (expression instanceof PbsAst.MemberExpr member) {
|
||||
var owner = path(member.receiver());
|
||||
return owner == null ? null : owner + "." + member.memberName();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+5
@@ -180,8 +180,13 @@ public final class PbsAst {
|
||||
public record ServiceDecl(
|
||||
String name,
|
||||
ReadOnlyList<FunctionDecl> methods,
|
||||
ReadOnlyList<ConstDecl> constants,
|
||||
ReadOnlyList<Attribute> attributes,
|
||||
Span span) implements TopDecl {
|
||||
public ServiceDecl(String name, ReadOnlyList<FunctionDecl> methods,
|
||||
ReadOnlyList<Attribute> attributes, Span span) {
|
||||
this(name, methods, ReadOnlyList.empty(), attributes, span);
|
||||
}
|
||||
}
|
||||
|
||||
public record ErrorDecl(
|
||||
|
||||
+82
-7
@@ -58,7 +58,29 @@ final class PbsExecutableBodyLowerer {
|
||||
int slot = context.declareLocalSlots(capture.label(), context.types().slots(type));
|
||||
emitStoreLocalSlots(slot, context.types().slots(type), capture.span(), context);
|
||||
}
|
||||
final var terminated = lowerBlock(functionDecl.body(), context);
|
||||
var binding = functionDecl.attributes().stream().filter(a -> "IntrinsicCall".equals(a.name())).findFirst();
|
||||
final boolean terminated;
|
||||
if (binding.isPresent()) {
|
||||
var attribute = binding.get();
|
||||
var name = attribute.arguments().stream().filter(a -> "name".equals(a.name()))
|
||||
.map(a -> ((PbsAst.AttributeStringValue) a.value()).value()).findFirst().orElseThrow();
|
||||
if (name.startsWith("\"")) name = name.substring(1, name.length()-1);
|
||||
long version = attribute.arguments().stream().filter(a -> "version".equals(a.name()))
|
||||
.mapToLong(a -> ((PbsAst.AttributeIntValue) a.value()).value()).findFirst().orElseThrow();
|
||||
int slots = 0;
|
||||
for (var parameter : functionDecl.parameters()) {
|
||||
int width = context.types().slots(parameter.typeRef());
|
||||
emitLoadLocalSlots(slots, width, parameter.span(), context);
|
||||
slots += width;
|
||||
}
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.CALL_INTRINSIC, "", null,
|
||||
new IRBackendExecutableFunction.IntrinsicCallMetadata(name, version, intrinsicIdTable.register(name, version)),
|
||||
slots, context.types().slots(functionDecl.returnType()), functionDecl.span()));
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.RET, "", null, null, null, functionDecl.span()));
|
||||
terminated = true;
|
||||
} else terminated = lowerBlock(functionDecl.body(), context);
|
||||
finalizeFunctionInstructions(functionDecl, context, terminated);
|
||||
|
||||
final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0;
|
||||
@@ -612,6 +634,21 @@ final class PbsExecutableBodyLowerer {
|
||||
final PbsAst.MemberExpr memberExpr,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
var receiverType = PbsRuntimeTypes.unwrap(expressionType(memberExpr.receiver(), context));
|
||||
var service = receiverType == null ? null : context.types().services.get(receiverType.name());
|
||||
if (service != null) {
|
||||
var key = service.name() + "." + memberExpr.memberName();
|
||||
if (context.types().constants.containsKey(key)) {
|
||||
boolean staticOwner = memberExpr.receiver() instanceof PbsAst.IdentifierExpr name
|
||||
&& !context.localTypes.containsKey(name.name()) && context.types().services.containsKey(name.name());
|
||||
if (!staticOwner && !(memberExpr.receiver() instanceof PbsAst.ThisExpr)) {
|
||||
lowerExpected(memberExpr.receiver(), receiverType, context);
|
||||
context.instructions().add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.POP, "", null, null, memberExpr.span()));
|
||||
}
|
||||
lowerConstant(key, memberExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.ARRAY && memberExpr.memberName().equals("length")) {
|
||||
lowerExpected(memberExpr.receiver(), receiverType, context);
|
||||
registry(ARRAY_LEN, context.types().arrayStorage(), 0, 1, 1, memberExpr.span(), context);
|
||||
@@ -753,6 +790,11 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
return;
|
||||
}
|
||||
var memberKey = context.serviceOwner + "." + identifierExpr.name();
|
||||
if (context.types().constants.containsKey(memberKey)) {
|
||||
lowerConstant(memberKey, identifierExpr.span(), context);
|
||||
return;
|
||||
}
|
||||
final var globalSlot = context.resolveGlobalSlot(identifierExpr.name());
|
||||
if (globalSlot != null) {
|
||||
emitGetGlobal(globalSlot, identifierExpr.span(), context);
|
||||
@@ -774,6 +816,25 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
}
|
||||
|
||||
private void lowerConstant(String key, Span span, PbsExecutableLoweringContext context) {
|
||||
var constant = context.types().constants.get(key);
|
||||
var previousOwner = context.serviceOwner;
|
||||
var previousExpected = context.expectedType;
|
||||
try {
|
||||
context.serviceOwner = key.contains(".") ? key.substring(0, key.lastIndexOf('.')) : "";
|
||||
context.expectedType = constant.explicitType();
|
||||
if (constant.initializer() != null) lowerConstExpression(constant.initializer(), context);
|
||||
else {
|
||||
var builtin = context.builtinConstByNameId().get(context.nameTable().register(key));
|
||||
if (builtin == null) reportUnsupportedLowering("Missing builtin constant: " + key, span, context);
|
||||
else emitBuiltinConstFetch(builtin, span, context);
|
||||
}
|
||||
} finally {
|
||||
context.serviceOwner = previousOwner;
|
||||
context.expectedType = previousExpected;
|
||||
}
|
||||
}
|
||||
|
||||
private void emitBuiltinConstFetch(
|
||||
final p.studio.compiler.models.IRReservedMetadata.BuiltinConstSurface builtinConst,
|
||||
final p.studio.compiler.source.Span span,
|
||||
@@ -904,7 +965,8 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
return context.resolveLocalSlot(identifierExpr.name()) != null
|
||||
|| context.resolveGlobalSlot(identifierExpr.name()) != null
|
||||
|| context.resolveConstDecl(identifierExpr.name()) != null;
|
||||
|| context.resolveConstDecl(identifierExpr.name()) != null
|
||||
|| context.types().constants.containsKey(context.serviceOwner + "." + identifierExpr.name());
|
||||
}
|
||||
|
||||
private int identifierValueSlots(
|
||||
@@ -944,6 +1006,8 @@ final class PbsExecutableBodyLowerer {
|
||||
lowerIntLiteral(new PbsAst.IntLiteralExpr(boundedLiteralExpr.value(), boundedLiteralExpr.span()), context);
|
||||
case PbsAst.StringLiteralExpr stringLiteralExpr -> emitPushConst(stringLiteralExpr.value(), stringLiteralExpr.span(), context);
|
||||
case PbsAst.BoolLiteralExpr boolLiteralExpr -> emitPushBool(boolLiteralExpr.value(), boolLiteralExpr.span(), context);
|
||||
case PbsAst.FloatLiteralExpr literal -> lowerExpression(literal, context);
|
||||
case PbsAst.MemberExpr member -> lowerMemberExpression(member, context);
|
||||
case PbsAst.GroupExpr groupExpr -> lowerConstExpression(groupExpr.expression(), context);
|
||||
case PbsAst.UnaryExpr unaryExpr -> {
|
||||
lowerConstExpression(unaryExpr.expression(), context);
|
||||
@@ -955,9 +1019,10 @@ final class PbsExecutableBodyLowerer {
|
||||
emitBinaryOperatorInstruction(binaryExpr.operator(), binaryExpr.span(), context);
|
||||
}
|
||||
case PbsAst.IdentifierExpr identifierExpr -> {
|
||||
final var referenced = context.resolveConstDecl(identifierExpr.name());
|
||||
if (referenced != null && referenced.initializer() != null) {
|
||||
lowerConstExpression(referenced.initializer(), context);
|
||||
var key = context.serviceOwner + "." + identifierExpr.name();
|
||||
if (!context.types().constants.containsKey(key)) key = identifierExpr.name();
|
||||
if (context.types().constants.containsKey(key)) {
|
||||
lowerConstant(key, identifierExpr.span(), context);
|
||||
} else {
|
||||
reportUnsupportedLowering("const identifier is not lowerable: " + identifierExpr.name(), identifierExpr.span(), context);
|
||||
}
|
||||
@@ -1046,6 +1111,12 @@ final class PbsExecutableBodyLowerer {
|
||||
if (e instanceof PbsAst.ElseExpr fallback) {var opt = PbsRuntimeTypes.unwrap(expressionType(fallback.optionalExpression(), c)); return opt == null ? null : opt.inner();}
|
||||
if (e instanceof PbsAst.IndexExpr index) {var array = PbsRuntimeTypes.unwrap(expressionType(index.receiver(), c)); return array == null ? null : PbsAst.TypeRef.optional(array.inner(), index.span());}
|
||||
if (e instanceof PbsAst.MemberExpr member) {
|
||||
var serviceType = expressionType(member.receiver(), c);
|
||||
var service = serviceType == null ? null : c.types().services.get(serviceType.name());
|
||||
if (service != null) {
|
||||
var constant = c.types().constants.get(service.name() + "." + member.memberName());
|
||||
if (constant != null) return constant.explicitType();
|
||||
}
|
||||
var receiver = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c));
|
||||
if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.ARRAY && member.memberName().equals("length")) return PbsRuntimeTypes.type("long");
|
||||
if (receiver != null && receiver.kind() == PbsAst.TypeRefKind.NAMED_TUPLE)
|
||||
@@ -1055,7 +1126,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
if (e instanceof PbsAst.IdentifierExpr i) {
|
||||
if(c.types().services.containsKey(i.name()))return PbsRuntimeTypes.type(i.name());
|
||||
var local = c.localTypes.getOrDefault(i.name(), c.types().values.get(i.name()));
|
||||
var local = c.localTypes.getOrDefault(i.name(), c.types().values.getOrDefault(c.serviceOwner + "." + i.name(), c.types().values.get(i.name())));
|
||||
if (local != null) return local;
|
||||
var functions = c.types().functions.get(i.name());
|
||||
if (functions != null && !functions.isEmpty()) {
|
||||
@@ -1107,6 +1178,10 @@ final class PbsExecutableBodyLowerer {
|
||||
return sig == null ? null : sig.returnType();
|
||||
}
|
||||
if (e instanceof PbsAst.MemberExpr m && m.receiver() instanceof PbsAst.IdentifierExpr i) {
|
||||
if (!c.localTypes.containsKey(i.name())) {
|
||||
var key = c.types().aliases.getOrDefault(i.name(), i.name()) + "." + m.memberName();
|
||||
if (c.types().constants.containsKey(key)) return c.types().constants.get(key).explicitType();
|
||||
}
|
||||
if (c.types().enums.containsKey(i.name())) return PbsRuntimeTypes.type(i.name());
|
||||
var owner = c.localTypes.get(i.name());
|
||||
var fields = owner == null ? null : c.types().fields.get(owner.name());
|
||||
@@ -1694,7 +1769,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(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;
|
||||
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;
|
||||
}
|
||||
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);
|
||||
|
||||
+3
@@ -18,6 +18,7 @@ final class PbsRuntimeTypes {
|
||||
final Map<String, PbsAst.FunctionSignature> signatures = new HashMap<>();
|
||||
final Map<String, List<PbsAst.FunctionDecl>> functions = new HashMap<>();
|
||||
final Map<String, PbsAst.TypeRef> values = new HashMap<>();
|
||||
final Map<String, PbsAst.ConstDecl> constants = new HashMap<>();
|
||||
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<>();
|
||||
@@ -52,6 +53,8 @@ final class PbsRuntimeTypes {
|
||||
}
|
||||
if (decl instanceof PbsAst.HostDecl h) for(var f:h.signatures()) signatures.put(h.name()+"."+f.name()+"#"+f.parameters().size(), f);
|
||||
}
|
||||
constants.putAll(p.studio.compiler.pbs.PbsServiceConstants.collect(ReadOnlyList.wrap(declarations)));
|
||||
constants.forEach((name, constant) -> values.put(name, constant.explicitType()));
|
||||
for (var imported : ast.imports()) for (var item : imported.items()) {
|
||||
if (item.alias() == null || item.alias().isBlank()) continue;
|
||||
aliases.put(item.alias(), item.name());
|
||||
|
||||
+15
-3
@@ -454,24 +454,36 @@ final class PbsDeclarationParser {
|
||||
final var name = consume(PbsTokenKind.IDENTIFIER, "Expected service name");
|
||||
consume(PbsTokenKind.LEFT_BRACE, "Expected '{' to start service body");
|
||||
final var methods = new ArrayList<PbsAst.FunctionDecl>();
|
||||
final var constants = new ArrayList<PbsAst.ConstDecl>();
|
||||
while (!cursor.check(PbsTokenKind.RIGHT_BRACE) && !cursor.isAtEnd()) {
|
||||
var methodAttributes = ReadOnlyList.<PbsAst.Attribute>empty();
|
||||
if (cursor.check(PbsTokenKind.LEFT_BRACKET)) {
|
||||
methodAttributes = attributeParser.parseAttributeList();
|
||||
}
|
||||
if (cursor.match(PbsTokenKind.DECLARE)) {
|
||||
var declaration = cursor.previous();
|
||||
consume(PbsTokenKind.CONST, "Expected const in service declaration");
|
||||
constants.add(parseConstDeclaration(declaration, methodAttributes));
|
||||
continue;
|
||||
}
|
||||
if (!cursor.match(PbsTokenKind.FN)) {
|
||||
if (!methodAttributes.isEmpty()) {
|
||||
reportAttributesNotAllowed(methodAttributes, "Attributes are valid only on service methods in service bodies");
|
||||
}
|
||||
report(cursor.peek(), ParseErrors.E_PARSE_INVALID_DECL_SHAPE,
|
||||
"Service body accepts only method declarations");
|
||||
"Service body accepts methods and declare const declarations");
|
||||
cursor.advance();
|
||||
continue;
|
||||
}
|
||||
methods.add(parseFunctionLike(cursor.previous(), methodAttributes));
|
||||
if (methodAttributes.stream().anyMatch(a -> "IntrinsicCall".equals(a.name()))) {
|
||||
var signature = parseFunctionSignature(cursor.previous(), methodAttributes);
|
||||
methods.add(new PbsAst.FunctionDecl(signature.name(), signature.parameters(), signature.returnKind(),
|
||||
signature.returnType(), signature.resultErrorType(), signature.attributes(), PbsAst.LifecycleMarker.NONE,
|
||||
new PbsAst.Block(ReadOnlyList.empty(), null, signature.span()), signature.span()));
|
||||
} else methods.add(parseFunctionLike(cursor.previous(), methodAttributes));
|
||||
}
|
||||
final var rightBrace = consume(PbsTokenKind.RIGHT_BRACE, "Expected '}' to end service body");
|
||||
return new PbsAst.ServiceDecl(name.lexeme(), ReadOnlyList.wrap(methods), attributes, span(declareToken.start(), rightBrace.end()));
|
||||
return new PbsAst.ServiceDecl(name.lexeme(), ReadOnlyList.wrap(methods), ReadOnlyList.wrap(constants), attributes, span(declareToken.start(), rightBrace.end()));
|
||||
}
|
||||
|
||||
private PbsAst.ErrorDecl parseErrorDeclaration(
|
||||
|
||||
+3
-1
@@ -38,12 +38,14 @@ final class PbsAstDocumentSymbols {
|
||||
return structSymbol(structDecl);
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
var members = new ArrayList<>(methodSymbols(serviceDecl.methods()));
|
||||
for (var constant : serviceDecl.constants()) symbolFor(constant).ifPresent(members::add);
|
||||
return namedSymbol(
|
||||
serviceDecl.name(),
|
||||
PbsEditorialSymbolKind.SERVICE,
|
||||
"",
|
||||
serviceDecl.span(),
|
||||
methodSymbols(serviceDecl.methods()));
|
||||
List.copyOf(members));
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ContractDecl contractDecl) {
|
||||
return namedSymbol(
|
||||
|
||||
+17
-15
@@ -30,7 +30,7 @@ final class PbsConstSemanticsValidator {
|
||||
}
|
||||
|
||||
final var declaredType = typeOps.typeFromTypeRef(constDecl.explicitType(), model, null);
|
||||
final var analysis = analyzeConstExpression(constDecl.initializer(), constByName, model, diagnostics);
|
||||
final var analysis = analyzeConstExpression(constDecl.initializer(), constByName, model, diagnostics, entry.getKey().contains(".") ? entry.getKey().substring(0, entry.getKey().lastIndexOf('.')) : "", declaredType);
|
||||
dependencyGraph.put(entry.getKey(), analysis.dependencies());
|
||||
|
||||
if (!analysis.constant()) {
|
||||
@@ -55,11 +55,7 @@ final class PbsConstSemanticsValidator {
|
||||
|
||||
private LinkedHashMap<String, PbsAst.ConstDecl> collectConstDeclarations(final PbsAst.File ast) {
|
||||
final var constByName = new LinkedHashMap<String, PbsAst.ConstDecl>();
|
||||
for (final var topDecl : ast.topDecls()) {
|
||||
if (topDecl instanceof PbsAst.ConstDecl constDecl) {
|
||||
constByName.putIfAbsent(constDecl.name(), constDecl);
|
||||
}
|
||||
}
|
||||
constByName.putAll(p.studio.compiler.pbs.PbsServiceConstants.collect(ast.topDecls()));
|
||||
return constByName;
|
||||
}
|
||||
|
||||
@@ -67,9 +63,10 @@ final class PbsConstSemanticsValidator {
|
||||
final PbsAst.Expression expression,
|
||||
final Map<String, PbsAst.ConstDecl> constByName,
|
||||
final Model model,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final DiagnosticSink diagnostics, final String owner, final TypeView expectedType) {
|
||||
if (expression instanceof PbsAst.IntLiteralExpr || expression instanceof PbsAst.BoundedLiteralExpr) {
|
||||
return new ConstAnalysis(TypeView.intType(), true, null, Set.of());
|
||||
return new ConstAnalysis(expectedType != null && expectedType.kind() == PbsFlowSemanticSupport.Kind.LONG
|
||||
? TypeView.longType() : TypeView.intType(), true, null, Set.of());
|
||||
}
|
||||
if (expression instanceof PbsAst.FloatLiteralExpr) {
|
||||
return new ConstAnalysis(TypeView.floatType(), true, null, Set.of());
|
||||
@@ -81,12 +78,13 @@ final class PbsConstSemanticsValidator {
|
||||
return new ConstAnalysis(TypeView.bool(), true, null, Set.of());
|
||||
}
|
||||
if (expression instanceof PbsAst.GroupExpr groupExpr) {
|
||||
return analyzeConstExpression(groupExpr.expression(), constByName, model, diagnostics);
|
||||
return analyzeConstExpression(groupExpr.expression(), constByName, model, diagnostics, owner, expectedType);
|
||||
}
|
||||
if (expression instanceof PbsAst.IdentifierExpr identifierExpr) {
|
||||
final var depName = identifierExpr.name();
|
||||
final var depName = !owner.isEmpty() && constByName.containsKey(owner + "." + identifierExpr.name())
|
||||
? owner + "." + identifierExpr.name() : identifierExpr.name();
|
||||
final var depDecl = constByName.get(depName);
|
||||
if (depDecl == null || depDecl.explicitType() == null || depDecl.initializer() == null) {
|
||||
if (depDecl == null || depDecl.explicitType() == null) {
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_CONST_UNRESOLVED_REFERENCE.name(),
|
||||
"Const initializer references unresolved const '%s'".formatted(depName),
|
||||
@@ -100,6 +98,10 @@ final class PbsConstSemanticsValidator {
|
||||
Set.of(depName));
|
||||
}
|
||||
if (expression instanceof PbsAst.MemberExpr memberExpr) {
|
||||
var path = p.studio.compiler.pbs.PbsServiceConstants.path(memberExpr);
|
||||
var constant = constByName.get(path);
|
||||
if (constant != null) return new ConstAnalysis(
|
||||
typeOps.typeFromTypeRef(constant.explicitType(), model, null), true, null, Set.of(path));
|
||||
if (memberExpr.receiver() instanceof PbsAst.IdentifierExpr enumIdentifier) {
|
||||
final var cases = model.enums.get(enumIdentifier.name());
|
||||
if (cases != null && cases.contains(memberExpr.memberName())) {
|
||||
@@ -109,7 +111,7 @@ final class PbsConstSemanticsValidator {
|
||||
return new ConstAnalysis(TypeView.unknown(), false, memberExpr.span(), Set.of());
|
||||
}
|
||||
if (expression instanceof PbsAst.UnaryExpr unaryExpr) {
|
||||
final var operand = analyzeConstExpression(unaryExpr.expression(), constByName, model, diagnostics);
|
||||
final var operand = analyzeConstExpression(unaryExpr.expression(), constByName, model, diagnostics, owner, expectedType);
|
||||
if (!operand.constant()) {
|
||||
return operand;
|
||||
}
|
||||
@@ -122,8 +124,8 @@ final class PbsConstSemanticsValidator {
|
||||
return new ConstAnalysis(TypeView.unknown(), false, unaryExpr.span(), operand.dependencies());
|
||||
}
|
||||
if (expression instanceof PbsAst.BinaryExpr binaryExpr) {
|
||||
final var left = analyzeConstExpression(binaryExpr.left(), constByName, model, diagnostics);
|
||||
final var right = analyzeConstExpression(binaryExpr.right(), constByName, model, diagnostics);
|
||||
final var left = analyzeConstExpression(binaryExpr.left(), constByName, model, diagnostics, owner, expectedType);
|
||||
final var right = analyzeConstExpression(binaryExpr.right(), constByName, model, diagnostics, owner, expectedType);
|
||||
final var deps = mergeDependencies(left.dependencies(), right.dependencies());
|
||||
if (!left.constant()) {
|
||||
return new ConstAnalysis(TypeView.unknown(), false, left.invalidSpan(), deps);
|
||||
@@ -230,7 +232,7 @@ final class PbsConstSemanticsValidator {
|
||||
}
|
||||
|
||||
private boolean isNumeric(final TypeView type) {
|
||||
return typeOps.isInt(type) || typeOps.isFloat(type);
|
||||
return typeOps.isInt(type) || type.kind() == PbsFlowSemanticSupport.Kind.LONG || typeOps.isFloat(type);
|
||||
}
|
||||
|
||||
private boolean isArithmeticOperator(final String operator) {
|
||||
|
||||
+15
@@ -232,9 +232,24 @@ public final class PbsDeclarationSemanticsValidator {
|
||||
final PbsDeclarationRuleValidator rules,
|
||||
final boolean interfaceModule,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final var members = new java.util.HashSet<String>();
|
||||
for (var constant : serviceDecl.constants()) {
|
||||
validateDocAttributes(constant.attributes(), "service constants", diagnostics);
|
||||
var missingAllowed = validateConstDeclarationAttributes(constant, interfaceModule, diagnostics);
|
||||
rules.validateConstDeclaration(constant, !missingAllowed);
|
||||
if (!members.add(constant.name()) || serviceDecl.methods().stream().anyMatch(m -> m.name().equals(constant.name())))
|
||||
p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,
|
||||
"E_SEM_DUPLICATE_SERVICE_MEMBER", "Duplicate service member: " + constant.name(), constant.span());
|
||||
}
|
||||
final var methodScope = PbsCallableScope.serviceMethods(nameTable.register(serviceDecl.name()));
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
validateDocAttributes(method.attributes(), "service methods", diagnostics);
|
||||
if (method.attributes().stream().anyMatch(a -> ATTR_INTRINSIC_CALL.equals(a.name()))) {
|
||||
if (!interfaceModule) reportInterfaceNonDeclarativeDecl(method.span(),
|
||||
"Intrinsic service signatures are valid only in SDK interfaces", diagnostics);
|
||||
validateIntrinsicCallAttributes(new PbsAst.FunctionSignature(method.name(), method.parameters(),
|
||||
method.returnKind(), method.returnType(), method.resultErrorType(), method.attributes(), method.span()), diagnostics);
|
||||
}
|
||||
validateCallable(
|
||||
methodScope,
|
||||
method.name(),
|
||||
|
||||
+14
-1
@@ -757,6 +757,12 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
}
|
||||
} else if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) {
|
||||
var prefix = receiverType.name() + ".";
|
||||
model.serviceConstants.forEach((name, constant) -> {
|
||||
if (name.startsWith(prefix)) completions.put(constant.name(), new PbsEditorialCompletionCandidate(
|
||||
constant.name(), PbsEditorialSymbolKind.CONST, formatType(model.constTypes.get(name)),
|
||||
receiverType.name(), 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());
|
||||
@@ -864,6 +870,11 @@ public final class PbsEditorialSupportService {
|
||||
}
|
||||
}
|
||||
if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) {
|
||||
var key = receiverType.name() + "." + memberName;
|
||||
var constant = model.serviceConstants.get(key);
|
||||
if (constant != null) return Optional.of(new PbsEditorialResolvedSymbol(memberName,
|
||||
PbsEditorialSymbolKind.CONST, formatType(model.constTypes.get(key)), receiverType.name(),
|
||||
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());
|
||||
@@ -981,6 +992,8 @@ public final class PbsEditorialSupportService {
|
||||
return callableLocations(structInfo.methods().get(memberName));
|
||||
}
|
||||
if (receiverType.kind() == Kind.SERVICE || receiverType.kind() == Kind.CONTRACT) {
|
||||
var constant = model.serviceConstants.get(receiverType.name() + "." + memberName);
|
||||
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());
|
||||
@@ -2146,7 +2159,7 @@ public final class PbsEditorialSupportService {
|
||||
builtinTypeDecl.span());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
return new PbsAst.ServiceDecl(newName, serviceDecl.methods(), serviceDecl.attributes(), serviceDecl.span());
|
||||
return new PbsAst.ServiceDecl(newName, serviceDecl.methods(), serviceDecl.constants(), serviceDecl.attributes(), serviceDecl.span());
|
||||
}
|
||||
if (topDecl instanceof PbsAst.HostDecl hostDecl) {
|
||||
return new PbsAst.HostDecl(newName, hostDecl.signatures(), hostDecl.attributes(), hostDecl.span());
|
||||
|
||||
+1
@@ -172,6 +172,7 @@ final class PbsFlowBodyAnalyzer {
|
||||
final DiagnosticSink diagnostics) {
|
||||
final var receiverType = TypeView.service(serviceDecl.name());
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
if (method.attributes().stream().anyMatch(a -> "IntrinsicCall".equals(a.name()))) continue;
|
||||
validateCallableBody(
|
||||
method.parameters(),
|
||||
method.body(),
|
||||
|
||||
+3
-1
@@ -217,6 +217,8 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
if (service == null) {
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
var constant = model.constTypes.get(receiver.name() + "." + memberExpr.memberName());
|
||||
if (constant != null) return ExprResult.type(constant);
|
||||
final var methods = service.methods().get(memberExpr.memberName());
|
||||
if (methods != null && !methods.isEmpty()) {
|
||||
if (use == ExprUse.VALUE) {
|
||||
@@ -293,7 +295,7 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
if (compatible.isEmpty()) {
|
||||
Diagnostics.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_APPLY_UNRESOLVED_OVERLOAD.name(),
|
||||
"No callable overload matches the provided argument",
|
||||
"No callable overload matches the provided argument; numeric carriers require explicit conversion",
|
||||
wholeSpan);
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
|
||||
+12
-1
@@ -197,6 +197,7 @@ final class PbsFlowSemanticSupport {
|
||||
final Map<String, Set<String>> enums = new HashMap<>();
|
||||
final Map<String, Set<String>> errors = new HashMap<>();
|
||||
final Map<String, TypeView> constTypes = new HashMap<>();
|
||||
final Map<String, PbsAst.ConstDecl> serviceConstants = new HashMap<>();
|
||||
final Map<String, TypeView> globalTypes = new HashMap<>();
|
||||
final Map<String, TypeView> serviceSingletons = new HashMap<>();
|
||||
final Set<String> knownBuiltinTypeNames = new HashSet<>();
|
||||
@@ -230,6 +231,11 @@ final class PbsFlowSemanticSupport {
|
||||
for (final var topDecl : supplementalTopDecls) {
|
||||
model.ingestTopDecl(topDecl);
|
||||
}
|
||||
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.ingestAssetSurface(feSurfaceContext, diagnostics);
|
||||
return model;
|
||||
}
|
||||
@@ -333,6 +339,11 @@ final class PbsFlowSemanticSupport {
|
||||
method.span(),
|
||||
documentationFromAttributes(method.attributes())));
|
||||
}
|
||||
for (var constant : serviceDecl.constants()) {
|
||||
var key = serviceDecl.name() + "." + constant.name();
|
||||
constTypes.put(key, typeFrom(constant.explicitType()));
|
||||
serviceConstants.put(key, constant);
|
||||
}
|
||||
services.put(serviceDecl.name(), new ServiceInfo(methods));
|
||||
serviceSingletons.put(serviceDecl.name(), TypeView.service(serviceDecl.name()));
|
||||
return;
|
||||
@@ -494,7 +505,7 @@ final class PbsFlowSemanticSupport {
|
||||
return new CallableSymbol(name, semanticParameters, input, callableReturn(returnKind, returnType, resultErrorType), span, documentation);
|
||||
}
|
||||
|
||||
private String documentationFromAttributes(final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||
static String documentationFromAttributes(final ReadOnlyList<PbsAst.Attribute> attributes) {
|
||||
for (final var attribute : attributes) {
|
||||
if (!"Doc".equals(attribute.name()) || attribute.arguments().isEmpty()) {
|
||||
continue;
|
||||
|
||||
+4
@@ -114,6 +114,10 @@ final class PbsFlowStructuralExpressionAnalyzer {
|
||||
return ExprResult.type(serviceType);
|
||||
}
|
||||
|
||||
if (receiverType != null && receiverType.kind() == Kind.SERVICE) {
|
||||
var member = model.constTypes.get(receiverType.name() + "." + identifierExpr.name());
|
||||
if (member != null) return ExprResult.type(member);
|
||||
}
|
||||
final var constType = model.constTypes.get(identifierExpr.name());
|
||||
if (constType != null) {
|
||||
return ExprResult.type(constType);
|
||||
|
||||
+2
-2
@@ -87,7 +87,7 @@ final class PbsImportedSemanticContextService {
|
||||
if (topDecl instanceof PbsAst.ServiceDecl serviceDecl) {
|
||||
var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(serviceDecl);
|
||||
appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, localName+".$instance", 0, 1,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, serviceDecl.name()+".$instance", 0, 1,
|
||||
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor)));
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
appendImportedCallable(
|
||||
@@ -95,7 +95,7 @@ final class PbsImportedSemanticContextService {
|
||||
importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(
|
||||
importedModuleId,
|
||||
localName + "." + method.name(),
|
||||
serviceDecl.name() + "." + method.name(),
|
||||
method.parameters().size(),
|
||||
returnSlotsFor(method),
|
||||
method.returnKind(),
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
[Doc(markdown = """
|
||||
Runtime-owned numeric operations with exact carrier signatures.
|
||||
""")]
|
||||
declare service math {
|
||||
[IntrinsicCall(name = "math.i32.min", version = 1)]
|
||||
fn min(a: int, b: int) -> int;
|
||||
[IntrinsicCall(name = "math.i32.max", version = 1)]
|
||||
fn max(a: int, b: int) -> int;
|
||||
[IntrinsicCall(name = "math.i32.clamp", version = 1)]
|
||||
fn clamp(value: int, min: int, max: int) -> int;
|
||||
[IntrinsicCall(name = "math.i32.abs", version = 1)]
|
||||
fn abs(value: int) -> int;
|
||||
[IntrinsicCall(name = "math.i32.to_i64", version = 1)]
|
||||
fn to_i64(value: int) -> long;
|
||||
[IntrinsicCall(name = "math.i32.to_float", version = 1)]
|
||||
fn to_float(value: int) -> float;
|
||||
[IntrinsicCall(name = "math.i64.min", version = 1)]
|
||||
fn min(a: long, b: long) -> long;
|
||||
[IntrinsicCall(name = "math.i64.max", version = 1)]
|
||||
fn max(a: long, b: long) -> long;
|
||||
[IntrinsicCall(name = "math.i64.clamp", version = 1)]
|
||||
fn clamp(value: long, min: long, max: long) -> long;
|
||||
[IntrinsicCall(name = "math.i64.abs", version = 1)]
|
||||
fn abs(value: long) -> long;
|
||||
[IntrinsicCall(name = "math.i64.to_i32", version = 1)]
|
||||
fn to_i32(value: long) -> int;
|
||||
[IntrinsicCall(name = "math.i64.to_float", version = 1)]
|
||||
fn to_float(value: long) -> float;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub service math;
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
[Doc(markdown = """
|
||||
Runtime-owned numeric operations with exact carrier signatures.
|
||||
""")]
|
||||
declare service mathf {
|
||||
[IntrinsicCall(name = "mathf.min", version = 1)]
|
||||
fn min(a: float, b: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.max", version = 1)]
|
||||
fn max(a: float, b: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.clamp", version = 1)]
|
||||
fn clamp(value: float, min: float, max: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.abs", version = 1)]
|
||||
fn abs(value: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.floor", version = 1)]
|
||||
fn floor(value: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.ceil", version = 1)]
|
||||
fn ceil(value: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.trunc", version = 1)]
|
||||
fn trunc(value: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.round", version = 1)]
|
||||
fn round(value: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.sqrt", version = 1)]
|
||||
fn sqrt(value: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.sin", version = 1)]
|
||||
fn sin(angle: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.cos", version = 1)]
|
||||
fn cos(angle: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.atan2", version = 1)]
|
||||
fn atan2(y: float, x: float) -> float;
|
||||
[IntrinsicCall(name = "mathf.to_i32", version = 1)]
|
||||
fn to_i32(value: float) -> int;
|
||||
[IntrinsicCall(name = "mathf.to_i64", version = 1)]
|
||||
fn to_i64(value: float) -> long;
|
||||
[BuiltinConst(target = "mathf", name = "pi", version = 1)]
|
||||
declare const pi: float;
|
||||
[BuiltinConst(target = "mathf", name = "tau", version = 1)]
|
||||
declare const tau: float;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub service mathf;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
import { math } from @sdk:math;
|
||||
import { mathf as numbers } from @sdk:mathf;
|
||||
|
||||
fn mathExample() -> float {
|
||||
let counter: long = 42;
|
||||
let bounded = math.clamp(counter, 0 as long, 100 as long);
|
||||
return math.to_float(bounded) + numbers.sin(0.0) + numbers.pi;
|
||||
}
|
||||
+9
@@ -16,6 +16,15 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
final class PbsEditorialSupportServiceTest {
|
||||
private final PbsEditorialSupportService service = new PbsEditorialSupportService();
|
||||
|
||||
@Test void serviceConstantsHaveCompletionHoverAndDefinition() {
|
||||
String source = "declare service Settings { declare const answer: int = 42; } fn main() -> int { return Settings.answer; }";
|
||||
var ast = parseOrdinary(source);
|
||||
int use = source.indexOf("Settings.answer");
|
||||
assertTrue(service.completion(source, ast, ReadOnlyList.empty(), use+9).stream().anyMatch(c -> c.label().equals("answer") && c.kind() == PbsEditorialSymbolKind.CONST));
|
||||
assertTrue(service.hover(source, ast, ReadOnlyList.empty(), use+10).isPresent());
|
||||
assertFalse(service.definition(source, ast, ReadOnlyList.empty(), use+10).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void closuresExposeCapturedObjectsAndOwnParameters() {
|
||||
String source = """
|
||||
|
||||
Reference in New Issue
Block a user