feat(studio): improve compiler reliability and AI diagnostics
Preserve structured diagnostics, source attribution, phase outcomes and revision context through compiler, Studio, LSP, MCP and JavaFX. Add project service discovery and resilient VS Code reconnection. Correct all eight reproduced PBS production failures in expression context, sibling executable bindings and nominal owner identity. Consolidate specs, lessons, immutable baseline evidence and the maintained source-to-guest qualification runner. Validation: required Gradle gate recorded 724 tests, with 711 passed and 13 skipped. Full corpus passed 168 compilation observations and 108 guest runs (104 successes and four deliberate faults); supplemental controls passed 42 compilations and 16 guest runs. TypeScript compilation, two Node discovery tests and discussion validation passed.
This commit is contained in:
+26
@@ -0,0 +1,26 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import java.util.*;
|
||||
|
||||
/** Records observations from a detector; never resolves another symbol for reporting. */
|
||||
public final class PbsDiagnosticFacts {
|
||||
private PbsDiagnosticFacts() { }
|
||||
public static String symbol(PbsAst.Expression expression) {
|
||||
if (expression instanceof PbsAst.ThisExpr) return "this";
|
||||
if (expression instanceof PbsAst.IdentifierExpr name) return name.name();
|
||||
if (expression instanceof PbsAst.MemberExpr member) return symbol(member.receiver()) + "." + member.memberName();
|
||||
if (expression instanceof PbsAst.CallExpr call) return symbol(call.callee()) + "()";
|
||||
if (expression instanceof PbsAst.GroupExpr group) return symbol(group.expression());
|
||||
return expression.getClass().getSimpleName();
|
||||
}
|
||||
public static DiagnosticSink error(DiagnosticSink sink, String code, String message, Span span,
|
||||
String check, Map<String, Object> facts, FailureKind kind) {
|
||||
var observed = new LinkedHashMap<>(facts);
|
||||
if (span != null && !span.isNone()) observed.putIfAbsent("scopeFileId", span.getFileId().getId());
|
||||
return sink.report(DiagnosticDescriptions.attach(new Diagnostic(Severity.Error, code, message, span, List.of()),
|
||||
check, observed, kind));
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -210,7 +210,7 @@ public final class PbsFrontendCompiler {
|
||||
effectiveNameTable,
|
||||
effectiveFESurfaceContext,
|
||||
diagnosticView,
|
||||
effectiveImportedCallables);
|
||||
effectiveImportedCallables, effectiveImportedGlobals);
|
||||
if (diagnostics.errorCount() > loweringErrorBaseline) {
|
||||
return IRBackendFile.empty(fileId);
|
||||
}
|
||||
@@ -579,12 +579,17 @@ public final class PbsFrontendCompiler {
|
||||
PbsAst.ReturnKind returnKind,
|
||||
PbsAst.TypeRef returnType,
|
||||
String shapeSurface,
|
||||
String targetName) {
|
||||
String targetName, p.studio.compiler.source.Span ownerDeclaration) {
|
||||
public ImportedCallableSurface(ModuleId moduleId, String callableName, int arity, int returnSlots,
|
||||
PbsAst.ReturnKind returnKind, PbsAst.TypeRef returnType, String shapeSurface, String targetName) {
|
||||
this(moduleId, callableName, arity, returnSlots, returnKind, returnType, shapeSurface, targetName, p.studio.compiler.source.Span.none());
|
||||
}
|
||||
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 {
|
||||
ownerDeclaration = ownerDeclaration == null ? p.studio.compiler.source.Span.none() : ownerDeclaration;
|
||||
moduleId = moduleId == null ? ModuleId.none() : moduleId;
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -44,7 +44,8 @@ public final class PbsGenericDiagnostics extends DiagnosticSink {
|
||||
related.add(new RelatedSpan("Application requested here", origin.requestedAt()));
|
||||
}
|
||||
delegate.report(new Diagnostic(diagnostic.getSeverity(), diagnostic.getCode(), diagnostic.getPhase(),
|
||||
diagnostic.getTemplateId(), diagnostic.getPlaceholders(), message, diagnostic.getSpan(), related));
|
||||
diagnostic.getTemplateId(), diagnostic.getPlaceholders(), message, diagnostic.getSpan(), related,
|
||||
diagnostic.getContext(), diagnostic.getReportedPhase()));
|
||||
return this;
|
||||
}
|
||||
@Override public Collection<Diagnostic> asCollection() { return delegate.asCollection(); }
|
||||
|
||||
+18
@@ -20,6 +20,24 @@ import static p.studio.compiler.pbs.PbsReservedMetadataExtractor.typeSurfaceKey;
|
||||
|
||||
public final class PbsModuleVisibilityValidator {
|
||||
|
||||
/** Declaration/signature-level sibling admission, using the same keys as barrel validation. */
|
||||
public Set<Span> siblingDeclarations(ModuleUnit module, NameTable names) {
|
||||
var interning = new SignatureInterning(new TypeSurfaceTable(), new CallableShapeTable());
|
||||
var declarations = collectDeclarations(module, names, interning);
|
||||
var admitted = new HashSet<Span>();
|
||||
for (var barrel : module.barrelFiles()) for (var item : barrel.ast().items()) {
|
||||
if (item instanceof PbsAst.BarrelFunctionItem f) {
|
||||
var key = functionKey(f.name(), f.typeParameters().size(), f.parameterTypes().asList(),
|
||||
f.returnKind(), f.returnType(), f.resultErrorType(), names, interning);
|
||||
admitted.addAll(declarations.functionsBySignature.getOrDefault(key, List.of()));
|
||||
} else {
|
||||
var key = new NonFunctionSymbolKey(nonFunctionKind(item), names.register(nonFunctionName(item)));
|
||||
admitted.addAll(declarations.nonFunctionsByKindAndName.getOrDefault(key, List.of()));
|
||||
}
|
||||
}
|
||||
return Set.copyOf(admitted);
|
||||
}
|
||||
|
||||
public void validate(
|
||||
final ReadOnlyList<ModuleUnit> modules,
|
||||
final DiagnosticSink diagnostics) {
|
||||
|
||||
+72
-25
@@ -98,13 +98,12 @@ final class PbsExecutableBodyLowerer {
|
||||
try {
|
||||
maxStackSlots = stackAnalyzer.analyzeMaxStackSlots(ReadOnlyList.wrap(context.instructions()), returnSlots);
|
||||
} catch (PbsExecutableStackAnalyzer.ExecutableLoweringAnalysisException e) {
|
||||
diagnostics.error(
|
||||
DiagnosticPhase.STATIC_SEMANTICS,
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(),
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(),
|
||||
Map.of(),
|
||||
e.getMessage(),
|
||||
functionDecl.span());
|
||||
p.studio.compiler.pbs.PbsDiagnosticFacts.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(), e.getMessage(), functionDecl.span(),
|
||||
"pbs.lowering.stack-shape", p.studio.utilities.json.ImmutableJson.fields("construction", "function",
|
||||
"symbol", functionDecl.name(), "declaredTypes", context.types().canonical(functionDecl.returnType()),
|
||||
"declaredResultSlots", returnSlots, "instructionCount", context.instructions().size(),
|
||||
"condition", e.getMessage()), p.studio.compiler.source.diagnostics.FailureKind.INTERNAL_FAILURE);
|
||||
return null;
|
||||
}
|
||||
final var localSlots = Math.max(0, context.nextLocalSlot() - functionDecl.parameters().stream().mapToInt(p -> context.types().slots(p.typeRef())).sum());
|
||||
@@ -441,8 +440,20 @@ final class PbsExecutableBodyLowerer {
|
||||
case PbsAst.CallExpr callExpr -> lowerCallExpression(callExpr, context);
|
||||
case PbsAst.ApplyExpr applyExpr -> lowerApply(applyExpr, context);
|
||||
case PbsAst.BinaryExpr binaryExpr -> {
|
||||
lowerExpression(binaryExpr.left(), context);
|
||||
lowerExpression(binaryExpr.right(), context);
|
||||
// Comparison result context belongs to the comparison, not its operands.
|
||||
boolean comparison = java.util.Set.of("==", "!=", "<", "<=", ">", ">=").contains(binaryExpr.operator());
|
||||
if (comparison) {
|
||||
var previous = context.expectedType;
|
||||
PbsAst.TypeRef leftType, rightType;
|
||||
context.expectedType = null;
|
||||
try { leftType = expressionType(binaryExpr.left(), context); rightType = expressionType(binaryExpr.right(), context); }
|
||||
finally { context.expectedType = previous; }
|
||||
lowerExpected(binaryExpr.left(), leftType != null ? leftType : rightType, context);
|
||||
lowerExpected(binaryExpr.right(), rightType != null ? rightType : leftType, context);
|
||||
} else {
|
||||
lowerExpression(binaryExpr.left(), context);
|
||||
lowerExpression(binaryExpr.right(), context);
|
||||
}
|
||||
emitBinaryOperatorInstruction(binaryExpr.operator(), binaryExpr.span(), context);
|
||||
}
|
||||
case PbsAst.UnaryExpr unaryExpr -> {
|
||||
@@ -570,6 +581,7 @@ final class PbsExecutableBodyLowerer {
|
||||
return;
|
||||
}
|
||||
if (lowerStructuredCall(callExpr, context)) return;
|
||||
final var failedStructuredCallFacts = context.lastCallFacts;
|
||||
if (callExpr.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var receiverType = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), context));
|
||||
if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.OPTIONAL
|
||||
@@ -593,6 +605,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
lowerCallsiteReceiver(callExpr.callee(), context);
|
||||
lowerCallArguments(callExpr, context);
|
||||
context.lastCallFacts = failedStructuredCallFacts;
|
||||
callsiteEmitter.emitCallsite(callExpr, context);
|
||||
}
|
||||
|
||||
@@ -644,7 +657,7 @@ 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());
|
||||
var service = receiverType == null ? null : context.types().service(receiverType);
|
||||
if (service != null) {
|
||||
var key = service.name() + "." + memberExpr.memberName();
|
||||
if (context.types().constants.containsKey(key)) {
|
||||
@@ -687,7 +700,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
reportUnsupportedLowering("Unknown native field",memberExpr.span(),context);return;
|
||||
}
|
||||
var struct = receiverType == null ? null : context.types().structs.get(receiverType.name());
|
||||
var struct = receiverType == null ? null : context.types().struct(receiverType);
|
||||
if (struct != null) {
|
||||
for (int i=0;i<struct.fields().size();i++) if (struct.fields().get(i).name().equals(memberExpr.memberName())) {
|
||||
lowerExpected(memberExpr.receiver(), receiverType, context);
|
||||
@@ -1112,7 +1125,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
if (call.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));
|
||||
var service=owner==null?null:c.types().services.get(owner.name());
|
||||
var service=owner==null?null:c.types().service(owner);
|
||||
if (service!=null) {
|
||||
var methods=service.methods().stream().filter(m -> m.name().equals(member.memberName())
|
||||
&& m.parameters().size()==signature.parameters().size()
|
||||
@@ -1129,7 +1142,7 @@ final class PbsExecutableBodyLowerer {
|
||||
private boolean lowerNamedStructApply(PbsAst.ApplyExpr apply,PbsAst.TupleExpr tuple,PbsExecutableLoweringContext c) {
|
||||
if(!(apply.callee() instanceof PbsAst.MemberExpr member))return false;
|
||||
var owner=PbsRuntimeTypes.unwrap(expressionType(member.receiver(),c));
|
||||
var declaration=owner==null?null:c.types().structs.get(owner.name());
|
||||
var declaration=owner==null?null:c.types().struct(owner);
|
||||
if(declaration==null)return false;
|
||||
var methods=declaration.methods().stream().filter(m->m.name().equals(member.memberName())&&m.parameters().size()==tuple.items().size()).toList();
|
||||
if(methods.size()!=1)return false;
|
||||
@@ -1188,14 +1201,14 @@ final class PbsExecutableBodyLowerer {
|
||||
if (e instanceof PbsAst.IndexExpr index) {
|
||||
var array = PbsRuntimeTypes.unwrap(expressionType(index.receiver(), c));
|
||||
if(array==null)return null;
|
||||
var declaration=c.types().structs.get(array.name());
|
||||
var declaration=c.types().struct(array);
|
||||
return p.studio.compiler.pbs.PbsSdkCollections.hasIndexer(declaration)
|
||||
? declaration.methods().stream().filter(m->m.name().equals("_at")).findFirst().orElseThrow().returnType()
|
||||
: 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());
|
||||
var service = serviceType == null ? null : c.types().service(serviceType);
|
||||
if (service != null) {
|
||||
var constant = c.types().constants.get(service.name() + "." + member.memberName());
|
||||
if (constant != null) return constant.explicitType();
|
||||
@@ -1204,7 +1217,7 @@ final class PbsExecutableBodyLowerer {
|
||||
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)
|
||||
for (var field : receiver.fields()) if (field.label().equals(member.memberName())) return field.typeRef();
|
||||
var struct = receiver == null ? null : c.types().structs.get(receiver.name());
|
||||
var struct = receiver == null ? null : c.types().struct(receiver);
|
||||
if (struct != null) for (var field : struct.fields()) if (field.name().equals(member.memberName())) return field.typeRef();
|
||||
var builtinFields=receiver==null?null:c.types().fields.get(receiver.name());
|
||||
if(builtinFields!=null)for(var field:builtinFields)if(field.name().equals(member.memberName()))return field.typeRef();
|
||||
@@ -1232,7 +1245,7 @@ final class PbsExecutableBodyLowerer {
|
||||
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") ? (value.explicitType() != null ? value.explicitType() : c.expectedType) : PbsRuntimeTypes.type(value.typeName());
|
||||
if (e instanceof PbsAst.NewExpr value) return value.typeName().equals("array") ? (value.explicitType() != null ? value.explicitType() : c.expectedType) : c.types().sourceType(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();
|
||||
@@ -1254,8 +1267,8 @@ final class PbsExecutableBodyLowerer {
|
||||
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 struct = c.types().struct(owner);
|
||||
var service = c.types().service(owner);
|
||||
var methods = struct != null ? struct.methods() : service != null ? service.methods() : ReadOnlyList.<PbsAst.FunctionDecl>empty();
|
||||
var applicable=methods.stream().filter(candidate -> candidate.name().equals(member.memberName())
|
||||
&& parametersMatch(candidate.parameters(),call.arguments(),c)).toList();
|
||||
@@ -1734,7 +1747,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
|
||||
private boolean lowerCollectionIndex(PbsAst.IndexExpr index, PbsAst.Expression value, PbsAst.TypeRef type, PbsExecutableLoweringContext c) {
|
||||
var declaration=type==null?null:c.types().structs.get(type.name());
|
||||
var declaration=type==null?null:c.types().struct(type);
|
||||
if(!p.studio.compiler.pbs.PbsSdkCollections.hasIndexer(declaration))return false;
|
||||
var name=value==null?"_at":"_put";
|
||||
var method=declaration.methods().stream().filter(m->m.name().equals(name)).findFirst().orElseThrow();
|
||||
@@ -2014,7 +2027,7 @@ final class PbsExecutableBodyLowerer {
|
||||
return hasElseBranch(stmt)&&yes&&no;
|
||||
}
|
||||
private void lowerStructNew(PbsAst.NewExpr expr,PbsExecutableLoweringContext c) {
|
||||
var declaration=c.types().structs.get(expr.typeName());
|
||||
var declaration=c.types().struct(c.types().sourceType(expr.typeName()));
|
||||
if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaration) && !c.types().allowedFactoryOrigins.contains(declaration.span())) {
|
||||
reportUnsupportedLowering("Stdlib construction requires its canonical declaring module", expr.span(), c); return;
|
||||
}
|
||||
@@ -2072,7 +2085,7 @@ final class PbsExecutableBodyLowerer {
|
||||
var target=statement.target();
|
||||
PbsAst.Expression receiver=target.rootName().equals("this")?new PbsAst.ThisExpr(target.span()):new PbsAst.IdentifierExpr(target.rootName(),target.span());
|
||||
for(int i=0;i<target.pathSegments().size()-1;i++)receiver=new PbsAst.MemberExpr(receiver,target.pathSegments().get(i),target.span());
|
||||
var type=expressionType(receiver,c);var struct=c.types().structs.get(type.name());
|
||||
var type=expressionType(receiver,c);var struct=c.types().struct(type);
|
||||
var name=target.pathSegments().getLast();int field=0;
|
||||
while(!struct.fields().get(field).name().equals(name))field++;
|
||||
var fieldType=struct.fields().get(field).typeRef();int width=c.types().slots(fieldType);
|
||||
@@ -2084,6 +2097,7 @@ final class PbsExecutableBodyLowerer {
|
||||
registry(STRUCT_SET,c.types().registryType(type),field,1+storageWidth(fieldType,c),0,statement.span(),c);
|
||||
}
|
||||
private boolean lowerStructuredCall(PbsAst.CallExpr call,PbsExecutableLoweringContext c) {
|
||||
recordCallFacts(call, c);
|
||||
if (call.callee() instanceof PbsAst.IdentifierExpr name && c.types().functions.containsKey(name.name())) {
|
||||
var method = sourceFunction(call,c);
|
||||
if (method == null) return false;
|
||||
@@ -2115,7 +2129,7 @@ final class PbsExecutableBodyLowerer {
|
||||
emitLoadLocalSlots(receiverView, 2, member.receiver().span(), c);
|
||||
registry(CALL_TRAIT,c.types().registryType(owner),ordinal,pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var service=c.types().services.get(owner.name());
|
||||
var service=c.types().service(owner);
|
||||
if(service!=null) {
|
||||
var method=service.methods().stream().filter(m->m.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
|
||||
if(method==null)return false;
|
||||
@@ -2131,7 +2145,7 @@ final class PbsExecutableBodyLowerer {
|
||||
}
|
||||
emitStructuredFunction(owner.name()+"."+method.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(),PbsTypeSubstitution.replaceSelf(method.returnType(),owner.name()),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c);return true;
|
||||
}
|
||||
var struct=c.types().structs.get(owner.name());if(struct==null)return false;
|
||||
var struct=c.types().struct(owner);if(struct==null)return false;
|
||||
boolean listIndex=p.studio.compiler.pbs.PbsSdkCollections.isIndexedCollection(struct) && java.util.Set.of("insert","clearAt","removeAt","resize","reserve").contains(member.memberName());
|
||||
var method=struct.methods().stream().filter(m->m.name().equals(member.memberName())&¶metersMatch(m.parameters(),call.arguments(),c,listIndex) && returnMatches(m.returnType(),owner.name(),c)).findFirst().orElse(null);
|
||||
if(method==null)return false;
|
||||
@@ -2228,7 +2242,14 @@ final class PbsExecutableBodyLowerer {
|
||||
PbsAst.ReturnKind kind, PbsAst.TypeRef errorType, int pops, int pushes, Span span, PbsExecutableLoweringContext c) {
|
||||
var callableId = c.exactLocalCallable(name, parameters, returnType, kind, errorType);
|
||||
if (callableId == null) {
|
||||
reportUnsupportedLowering("Structured call requires exact overload: " + name, span, c);
|
||||
var facts = new java.util.LinkedHashMap<>(c.lastCallFacts);
|
||||
facts.put("requestedSymbol", name); facts.put("lookupOwnerKey", name);
|
||||
facts.put("parameterTypes", parameters.stream().map(c.types()::canonical).toList());
|
||||
facts.put("lookupReturnType", c.types().canonical(returnType)); facts.put("lookupResult", "unresolved");
|
||||
p.studio.compiler.pbs.PbsDiagnosticFacts.error(c.diagnostics(),
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(),
|
||||
"Structured call requires exact overload: " + name, span, "pbs.lowering.structured-overload", facts,
|
||||
p.studio.compiler.source.diagnostics.FailureKind.PROGRAM_REJECTION);
|
||||
return;
|
||||
}
|
||||
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.CALL_FUNC,
|
||||
@@ -2236,6 +2257,32 @@ final class PbsExecutableBodyLowerer {
|
||||
c.callableSignatureByCallableId().get(callableId).callableName(), callableId, null, null, pops, pushes, span));
|
||||
}
|
||||
|
||||
private void recordCallFacts(PbsAst.CallExpr call, PbsExecutableLoweringContext c) {
|
||||
var facts = new java.util.LinkedHashMap<String, Object>();
|
||||
facts.put("construction", "call"); facts.put("requestedSymbol", p.studio.compiler.pbs.PbsDiagnosticFacts.symbol(call.callee()));
|
||||
facts.put("argumentCount", call.arguments().size());
|
||||
facts.put("resolutionConstraints", c.expectedType == null ? null : c.types().canonical(c.expectedType));
|
||||
facts.put("enclosingReturnType", c.types().canonical(c.returnType));
|
||||
facts.put("serviceOwner", c.serviceOwner);
|
||||
if (call.callee() instanceof PbsAst.MemberExpr member) {
|
||||
var receiver = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c));
|
||||
facts.put("receiver", p.studio.compiler.pbs.PbsDiagnosticFacts.symbol(member.receiver()));
|
||||
facts.put("receiverType", receiver == null ? null : c.types().canonical(receiver));
|
||||
if (receiver != null) {
|
||||
var struct = c.types().struct(receiver);
|
||||
var service = c.types().service(receiver);
|
||||
var methods = struct != null ? struct.methods().asList() : service != null ? service.methods().asList() : java.util.List.<PbsAst.FunctionDecl>of();
|
||||
facts.put("declaredTypes", methods.stream().filter(m -> m.name().equals(member.memberName()))
|
||||
.map(m -> c.types().canonical(m.returnType())).toList());
|
||||
facts.put("lookupOwnerKey", receiver.name() + "." + member.memberName());
|
||||
}
|
||||
} else if (call.callee() instanceof PbsAst.IdentifierExpr name) {
|
||||
facts.put("declaredTypes", c.types().functions.getOrDefault(name.name(), java.util.List.of()).stream()
|
||||
.map(f -> c.types().canonical(f.returnType())).toList());
|
||||
}
|
||||
c.lastCallFacts = p.studio.utilities.json.ImmutableJson.object(facts);
|
||||
}
|
||||
|
||||
private void lowerServiceValue(String name,Span span,PbsExecutableLoweringContext c) {
|
||||
var slot=c.resolveGlobalSlot("$service."+name);
|
||||
if(slot==null){emitStructuredFunction(name+".$instance",java.util.List.of(),PbsRuntimeTypes.type(name),0,1,span,c);return;}
|
||||
|
||||
+7
-1
@@ -59,6 +59,11 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
importedCallables,
|
||||
builtinCanonicalBySourceType);
|
||||
|
||||
var ownerDeclarations = new HashMap<CallableId,java.util.Set<p.studio.compiler.source.Span>>();
|
||||
for (var imported : importedCallables) if (!imported.ownerDeclaration().isNone()) {
|
||||
var id = callableIdTable.register(imported.moduleId(),imported.targetName(),imported.arity(),imported.shapeSurface());
|
||||
ownerDeclarations.computeIfAbsent(id, ignored -> new java.util.HashSet<>()).add(imported.ownerDeclaration());
|
||||
}
|
||||
final var callableSignatureByCallableId = new HashMap<CallableId, CallableSignatureRef>();
|
||||
final var callableSignatures = new ArrayList<CallableSignatureRef>(callableIdTable.size());
|
||||
for (final var callableId : callableIdTable.identifiers()) {
|
||||
@@ -71,6 +76,7 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
callableIdByDeclaration,
|
||||
callableIdsByNameAndArity,
|
||||
callableSignatureByCallableId,
|
||||
ownerDeclarations,
|
||||
returnSlotsByCallableId,
|
||||
returnOwnerByCallableId,
|
||||
tupleProjectionByCallableId,
|
||||
@@ -139,7 +145,7 @@ public final class PbsExecutableCallableRegistryFactory {
|
||||
|
||||
public static PbsAst.FunctionDecl withReceiver(PbsAst.FunctionDecl function,String owner,String receiver) {
|
||||
var params=new ArrayList<PbsAst.Parameter>();
|
||||
params.add(new PbsAst.Parameter(receiver,PbsRuntimeTypes.type(owner),function.span()));
|
||||
params.add(new PbsAst.Parameter(receiver,PbsAst.TypeRef.simple(owner,function.span()),function.span()));
|
||||
for(var p:function.parameters()) params.add(new PbsAst.Parameter(p.name(),PbsTypeSubstitution.replaceSelf(p.typeRef(),owner),p.span()));
|
||||
return new PbsAst.FunctionDecl(function.name(),ReadOnlyList.wrap(params),function.returnKind(),
|
||||
PbsTypeSubstitution.replaceSelf(function.returnType(),owner),function.resultErrorType(),function.attributes(),function.lifecycleMarker(),function.body(),function.span());
|
||||
|
||||
+4
-7
@@ -442,12 +442,9 @@ final class PbsExecutableCallsiteEmitter {
|
||||
final String message,
|
||||
final p.studio.compiler.source.Span span,
|
||||
final PbsExecutableLoweringContext context) {
|
||||
context.diagnostics().error(
|
||||
DiagnosticPhase.STATIC_SEMANTICS,
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(),
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(),
|
||||
Map.of(),
|
||||
message,
|
||||
span);
|
||||
p.studio.compiler.pbs.PbsDiagnosticFacts.error(context.diagnostics(),
|
||||
PbsSemanticsErrors.E_SEM_EXEC_LOWERING_UNRESOLVED_CALLEE.name(), message, span,
|
||||
"pbs.lowering.call-resolution", context.lastCallFacts,
|
||||
p.studio.compiler.source.diagnostics.FailureKind.PROGRAM_REJECTION);
|
||||
}
|
||||
}
|
||||
|
||||
+5
@@ -30,6 +30,7 @@ final class PbsExecutableLoweringContext {
|
||||
p.studio.compiler.pbs.ast.PbsAst.ReturnKind returnKind;
|
||||
p.studio.compiler.pbs.ast.PbsAst.TypeRef resultErrorType;
|
||||
String serviceOwner;
|
||||
java.util.Map<String, Object> lastCallFacts = java.util.Map.of();
|
||||
private int nextLabelId = 0;
|
||||
private int nextLocalSlot;
|
||||
|
||||
@@ -127,8 +128,12 @@ final class PbsExecutableLoweringContext {
|
||||
output = "result<" + formatter.typeSurfaceKey(errorType) + ">" + formatter.typeSurfaceKey(returnType);
|
||||
final var expectedOutput = output;
|
||||
var importedIds = callableIdsByNameAndArity().getOrDefault(new PbsCallableResolutionKey(nameTable().register(name), parameterTypes.size()), java.util.List.of());
|
||||
var separator = name.indexOf('.');
|
||||
var ownerDeclaration = separator < 0 ? null : types().contractTypes.declaration(types().sourceType(name.substring(0,separator)));
|
||||
var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry ->
|
||||
importedIds.contains(entry.getKey()) && entry.getValue().arity() == parameterTypes.size()
|
||||
&& (ownerDeclaration == null || callableRegistry.ownerDeclarations().getOrDefault(entry.getKey(), java.util.Set.of()).isEmpty()
|
||||
|| callableRegistry.ownerDeclarations().get(entry.getKey()).contains(ownerDeclaration.span()))
|
||||
&& normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + expectedOutput))).toList();
|
||||
if (candidates.size() == 1) return candidates.getFirst().getKey();
|
||||
return null;
|
||||
|
||||
+1
@@ -60,6 +60,7 @@ public class PbsExecutableLoweringModels {
|
||||
Map<PbsLowerableCallable, CallableId> callableIdByDeclaration,
|
||||
Map<PbsCallableResolutionKey, List<CallableId>> callableIdsByNameAndArity,
|
||||
Map<CallableId, CallableSignatureRef> callableSignatureByCallableId,
|
||||
Map<CallableId, java.util.Set<p.studio.compiler.source.Span>> ownerDeclarations,
|
||||
Map<CallableId, Integer> returnSlotsByCallableId,
|
||||
Map<CallableId, String> returnOwnerByCallableId,
|
||||
Map<CallableId, PbsTupleProjection> tupleProjectionByCallableId,
|
||||
|
||||
+7
-3
@@ -32,7 +32,8 @@ public final class PbsExecutableLoweringService {
|
||||
final NameTable nameTable,
|
||||
final FESurfaceContext feSurfaceContext,
|
||||
final DiagnosticSink diagnostics,
|
||||
final ReadOnlyList<PbsFrontendCompiler.ImportedCallableSurface> importedCallables) {
|
||||
final ReadOnlyList<PbsFrontendCompiler.ImportedCallableSurface> importedCallables,
|
||||
final ReadOnlyList<PbsFrontendCompiler.ImportedGlobalSurface> importedGlobals) {
|
||||
final var normalizedModuleId = moduleId == null ? ModuleId.none() : moduleId;
|
||||
final var metadataIndex = metadataIndexFactory.create(
|
||||
ast,
|
||||
@@ -40,7 +41,7 @@ public final class PbsExecutableLoweringService {
|
||||
reservedMetadata,
|
||||
nameTable,
|
||||
feSurfaceContext,
|
||||
diagnostics);
|
||||
diagnostics, importedGlobals);
|
||||
final var callableRegistry = callableRegistryFactory.create(
|
||||
ast,
|
||||
normalizedModuleId,
|
||||
@@ -157,7 +158,10 @@ public final class PbsExecutableLoweringService {
|
||||
loweredBody.maxStackSlots(),
|
||||
loweredBody.instructions(),
|
||||
functionDecl.span(),
|
||||
metadataIndex.types().metadata(functionDecl));
|
||||
metadataIndex.types().metadata(functionDecl),
|
||||
p.studio.utilities.json.ImmutableJson.fields("construction", "function", "symbol", callable.callableName(),
|
||||
"declaredTypes", metadataIndex.types().canonical(functionDecl.returnType()),
|
||||
"parameterTypes", functionDecl.parameters().stream().map(p -> metadataIndex.types().canonical(p.typeRef())).toList()));
|
||||
}
|
||||
|
||||
private int safeToInt(final long value) {
|
||||
|
||||
+9
-1
@@ -26,12 +26,20 @@ final class PbsExecutableMetadataIndexFactory {
|
||||
final IRReservedMetadata reservedMetadata,
|
||||
final NameTable nameTable,
|
||||
final FESurfaceContext feSurfaceContext,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final DiagnosticSink diagnostics,
|
||||
final ReadOnlyList<p.studio.compiler.pbs.PbsFrontendCompiler.ImportedGlobalSurface> importedGlobals) {
|
||||
final var hostByMethodName = indexHostBindingsByMethodName(reservedMetadata, nameTable);
|
||||
final var builtinCanonicalBySourceType = indexBuiltinCanonicalBySourceType(reservedMetadata);
|
||||
final var builtinConstOwnerByNameId = indexBuiltinConstOwners(reservedMetadata, nameTable);
|
||||
final var builtinConstByNameId = indexBuiltinConstSurfaces(reservedMetadata, nameTable);
|
||||
final var globalSlotByNameId = indexGlobalSlots(ast, nameTable);
|
||||
var ownedNames = new java.util.HashSet<String>();
|
||||
for (var declaration : ast.topDecls()) {
|
||||
if (declaration instanceof PbsAst.GlobalDecl global) ownedNames.add(global.name());
|
||||
if (declaration instanceof PbsAst.ServiceDecl service) ownedNames.add("$service."+service.name());
|
||||
}
|
||||
final var importedGlobalsBySlot = PbsImportedGlobalSlots.index(ownedNames, importedGlobals);
|
||||
importedGlobalsBySlot.forEach((slot,global) -> globalSlotByNameId.put(nameTable.register(global.localName()),slot));
|
||||
final var constDeclByNameId = indexConstDecls(ast, nameTable);
|
||||
final var addressableByAddress = indexAddressables(feSurfaceContext);
|
||||
final var builtinSignatureByOwnerAndMethod = indexBuiltinSignatures(
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package p.studio.compiler.pbs.lowering;
|
||||
|
||||
import p.studio.compiler.pbs.PbsFrontendCompiler.ImportedGlobalSurface;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
/** PBS-private temporary operands; all are resolved before common IR is published. */
|
||||
public final class PbsImportedGlobalSlots {
|
||||
private PbsImportedGlobalSlots() {}
|
||||
public static Map<Integer, ImportedGlobalSurface> index(Set<String> ownedNames, ReadOnlyList<ImportedGlobalSurface> imports) {
|
||||
var result = new LinkedHashMap<Integer, ImportedGlobalSurface>();
|
||||
var names = new HashSet<>(ownedNames);
|
||||
for (var imported : imports) if (imported.directlyVisible() && names.add(imported.localName()))
|
||||
result.put(Integer.MAX_VALUE - result.size(), imported);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+21
-5
@@ -11,6 +11,7 @@ final class PbsRuntimeTypes {
|
||||
record ClosureBody(PbsAst.FunctionDecl function, java.util.List<PbsAst.NamedTypeField> captures) {}
|
||||
final java.util.List<ClosureBody> closureBodies = new ArrayList<>();
|
||||
final Map<String, java.util.List<PbsAst.NamedTypeField>> capturesByFunction = new HashMap<>();
|
||||
private final Span sourceScope;
|
||||
final Map<String, String> builtinNames;
|
||||
final Map<String, String> aliases = new HashMap<>();
|
||||
final Map<String, ReadOnlyList<PbsAst.BuiltinFieldDecl>> fields = new HashMap<>();
|
||||
@@ -30,6 +31,7 @@ final class PbsRuntimeTypes {
|
||||
final List<IRRegistry.Implementation> runtimeImplementations = new ArrayList<>();
|
||||
|
||||
PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList<PbsAst.TopDecl> supplemental, Map<String,String> builtins) {
|
||||
sourceScope = ast.span();
|
||||
builtinNames = builtins;
|
||||
ast.topDecls().forEach(d -> allowedFactoryOrigins.add(d.span()));
|
||||
supplemental.forEach(d -> { if (d instanceof PbsAst.TypeBindingDecl b && b.sameModule() && b.span().getFileId().equals(ast.span().getFileId())) allowedFactoryOrigins.add(b.declaration().span()); });
|
||||
@@ -82,9 +84,23 @@ final class PbsRuntimeTypes {
|
||||
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.TypeRef sourceType(String name) { return PbsAst.TypeRef.simple(name, sourceScope); }
|
||||
private PbsAst.TypeRef lexical(PbsAst.TypeRef type) {
|
||||
type = unwrap(type);
|
||||
return type != null && type.kind() == PbsAst.TypeRefKind.SIMPLE && type.span().isNone()
|
||||
? sourceType(type.name()) : type;
|
||||
}
|
||||
PbsAst.StructDecl struct(PbsAst.TypeRef type) {
|
||||
var declaration = contractTypes.declaration(lexical(type));
|
||||
return declaration instanceof PbsAst.StructDecl struct ? struct : declaration == null && type != null ? structs.get(type.name()) : null;
|
||||
}
|
||||
PbsAst.ServiceDecl service(PbsAst.TypeRef type) {
|
||||
var declaration = contractTypes.declaration(lexical(type));
|
||||
return declaration instanceof PbsAst.ServiceDecl service ? service : declaration == null && type != null ? services.get(type.name()) : null;
|
||||
}
|
||||
boolean isContract(PbsAst.TypeRef type) { return contractTypes.isContract(lexical(type)); }
|
||||
PbsAst.ContractDecl contract(PbsAst.TypeRef type) {
|
||||
var instance = contractTypes.resolve(unwrap(type));
|
||||
var instance = contractTypes.resolve(lexical(type));
|
||||
return instance == null ? null : instance.declaration();
|
||||
}
|
||||
String implementationCallableName(PbsAst.ImplementsDecl implementation, String method) {
|
||||
@@ -109,7 +125,7 @@ final class PbsRuntimeTypes {
|
||||
return t;
|
||||
}
|
||||
String key(PbsAst.TypeRef t) {
|
||||
t = unwrap(t);
|
||||
t = lexical(t);
|
||||
if (t == null) return "void";
|
||||
if (t.kind() == PbsAst.TypeRefKind.FN) return "Fn(" + t.fields().stream().map(f->key(f.typeRef())).collect(java.util.stream.Collectors.joining(",")) + ")->" + shapeKey(t.inner());
|
||||
if (t.kind() == PbsAst.TypeRefKind.ARRAY) return "array("+key(t.inner())+")";
|
||||
@@ -128,7 +144,7 @@ final class PbsRuntimeTypes {
|
||||
return canonical(t);
|
||||
}
|
||||
String shapeKey(PbsAst.TypeRef type) {
|
||||
var t = unwrap(type);
|
||||
var t = lexical(type);
|
||||
if (t == null || t.kind() == PbsAst.TypeRefKind.UNIT) return "";
|
||||
if (t.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream()
|
||||
.map(field -> shapeKey(field.typeRef())).collect(java.util.stream.Collectors.joining(","));
|
||||
@@ -169,7 +185,7 @@ final class PbsRuntimeTypes {
|
||||
return ref;
|
||||
}
|
||||
IRRegistry.TypeRef registryType(PbsAst.TypeRef type) {
|
||||
var t = unwrap(type);
|
||||
var t = lexical(type);
|
||||
if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(contractTypes.declaration(t))) return memcardBufferStorage();
|
||||
if (t.kind() == PbsAst.TypeRefKind.FN) {
|
||||
var ref = new IRRegistry.TypeRef("pbs:" + key(t));
|
||||
|
||||
+10
-4
@@ -127,10 +127,13 @@ final class PbsFlowAssignmentAnalyzer {
|
||||
return new AssignmentTargetResolution(TypeView.unknown(), false);
|
||||
}
|
||||
|
||||
Diagnostics.error(diagnostics,
|
||||
p.studio.compiler.pbs.PbsDiagnosticFacts.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_ASSIGN_TARGET_UNRESOLVED.name(),
|
||||
"Assignment target '%s' does not resolve".formatted(rootName),
|
||||
lValue.span());
|
||||
lValue.span(), "pbs.flow.assignment-target", p.studio.utilities.json.ImmutableJson.fields(
|
||||
"construction", "assignment", "requestedSymbol", rootName, "binding", "unresolved",
|
||||
"scopeFileId", lValue.span().getFileId().getId()),
|
||||
p.studio.compiler.source.diagnostics.FailureKind.PROGRAM_REJECTION);
|
||||
return new AssignmentTargetResolution(TypeView.unknown(), false);
|
||||
}
|
||||
|
||||
@@ -156,10 +159,13 @@ final class PbsFlowAssignmentAnalyzer {
|
||||
} else if (model.constTypes.containsKey(rootName)) {
|
||||
currentType = model.constTypes.get(rootName);
|
||||
} else {
|
||||
Diagnostics.error(diagnostics,
|
||||
p.studio.compiler.pbs.PbsDiagnosticFacts.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_ASSIGN_TARGET_UNRESOLVED.name(),
|
||||
"Assignment target '%s' does not resolve".formatted(rootName),
|
||||
lValue.span());
|
||||
lValue.span(), "pbs.flow.assignment-target", p.studio.utilities.json.ImmutableJson.fields(
|
||||
"construction", "assignment", "requestedSymbol", rootName, "binding", "unresolved",
|
||||
"scopeFileId", lValue.span().getFileId().getId()),
|
||||
p.studio.compiler.source.diagnostics.FailureKind.PROGRAM_REJECTION);
|
||||
return new AssignmentTargetResolution(TypeView.unknown(), false);
|
||||
}
|
||||
}
|
||||
|
||||
+10
-5
@@ -79,7 +79,7 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
callee,
|
||||
argumentType,
|
||||
context.expectedType(),
|
||||
context.diagnostics());
|
||||
context.diagnostics(), p.studio.compiler.pbs.PbsDiagnosticFacts.symbol(callExpr.callee()));
|
||||
}
|
||||
|
||||
ExprResult analyzeApplyExpression(
|
||||
@@ -125,7 +125,7 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
callee,
|
||||
argument,
|
||||
context.expectedType(),
|
||||
context.diagnostics());
|
||||
context.diagnostics(), p.studio.compiler.pbs.PbsDiagnosticFacts.symbol(applyExpr.callee()));
|
||||
}
|
||||
|
||||
ExprResult analyzeMemberExpression(
|
||||
@@ -295,13 +295,18 @@ final class PbsFlowCallableResolutionAnalyzer {
|
||||
final ExprResult callee,
|
||||
final TypeView argumentType,
|
||||
final TypeView expectedType,
|
||||
final DiagnosticSink diagnostics) {
|
||||
final DiagnosticSink diagnostics, final String requestedSymbol) {
|
||||
final var candidates = callee.callables();
|
||||
if (candidates.isEmpty()) {
|
||||
Diagnostics.error(diagnostics,
|
||||
p.studio.compiler.pbs.PbsDiagnosticFacts.error(diagnostics,
|
||||
PbsSemanticsErrors.E_SEM_APPLY_NON_CALLABLE_TARGET.name(),
|
||||
"Apply/call target is not callable",
|
||||
calleeSpan);
|
||||
calleeSpan, "pbs.flow.call-target", p.studio.utilities.json.ImmutableJson.fields(
|
||||
"construction", "application", "requestedSymbol", requestedSymbol,
|
||||
"calleeClassification", callee.type().kind().name(), "argumentType", argumentType.kind().name(),
|
||||
"resolutionConstraints", expectedType == null ? null : expectedType.kind().name(),
|
||||
"candidateCount", candidates.size(), "scopeFileId", calleeSpan.getFileId().getId()),
|
||||
p.studio.compiler.source.diagnostics.FailureKind.PROGRAM_REJECTION);
|
||||
return ExprResult.type(TypeView.unknown());
|
||||
}
|
||||
|
||||
|
||||
+10
-7
@@ -58,16 +58,17 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
final var nameTable = ctx.nameTable();
|
||||
final var feSurfaceContext = ctx.feSurfaceContext();
|
||||
final var assembly = moduleAssemblyService.assemble(ctx, nameTable, diagnostics, issues);
|
||||
final var sourceContexts = importedSemanticContextService.build(assembly.parsedSourceFiles(), assembly.moduleTable());
|
||||
final var sourceContexts = importedSemanticContextService.build(assembly.parsedSourceFiles(), assembly.moduleTable(), assembly.siblingDeclarationsByModule());
|
||||
final var parsedSourceFiles = new PbsGenericProgramService().prepare(assembly.parsedSourceFiles(), sourceContexts,
|
||||
assembly.moduleTable(), diagnostics, feSurfaceContext);
|
||||
final var importedSemanticContexts = importedSemanticContextService.build(parsedSourceFiles, assembly.moduleTable());
|
||||
final var importedSemanticContexts = importedSemanticContextService.build(parsedSourceFiles, assembly.moduleTable(), assembly.siblingDeclarationsByModule());
|
||||
projectLifecycleSemanticsValidator.validate(parsedSourceFiles.asList(), diagnostics);
|
||||
final var failedModuleIds = assembly.mutableFailedModuleIds();
|
||||
final var moduleDependencyGraph = assembly.moduleDependencyGraph();
|
||||
final var canonicalModulePool = assembly.canonicalModulePool();
|
||||
|
||||
final var compiledSourceFiles = new ArrayList<CompiledSourceFile>(parsedSourceFiles.size());
|
||||
final var importedGlobalsByFile = new HashMap<FileId,ReadOnlyList<PbsFrontendCompiler.ImportedGlobalSurface>>();
|
||||
for (final var parsedSource : parsedSourceFiles) {
|
||||
final var blockedModuleIds = blockedModulesByDependency(failedModuleIds, moduleDependencyGraph);
|
||||
if (blockedModuleIds.contains(parsedSource.moduleId())) {
|
||||
@@ -96,12 +97,13 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
failedModuleIds.add(parsedSource.moduleId());
|
||||
}
|
||||
compiledSourceFiles.add(new CompiledSourceFile(parsedSource.moduleId(), irBackendFile));
|
||||
importedGlobalsByFile.put(parsedSource.fileId(), importedSemanticContext.importedGlobals());
|
||||
}
|
||||
|
||||
final var irBackend = mergeCompiledSources(
|
||||
compiledSourceFiles,
|
||||
failedModuleIds,
|
||||
moduleDependencyGraph);
|
||||
moduleDependencyGraph, importedGlobalsByFile);
|
||||
logs.using(log).debug("PBS frontend lowered to IR BE:\n%s".formatted(irBackend));
|
||||
return irBackend;
|
||||
}
|
||||
@@ -128,10 +130,10 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
final var assembly = service.moduleAssemblyService.assemble(ctx, ctx.nameTable(), diagnostics, issues);
|
||||
final var importedSemanticContexts = service.importedSemanticContextService.build(
|
||||
assembly.parsedSourceFiles(),
|
||||
assembly.moduleTable());
|
||||
assembly.moduleTable(), assembly.siblingDeclarationsByModule());
|
||||
final var semanticFiles = new PbsGenericProgramService().prepare(assembly.parsedSourceFiles(), importedSemanticContexts,
|
||||
assembly.moduleTable(), diagnostics, ctx.feSurfaceContext());
|
||||
final var semanticContexts = service.importedSemanticContextService.build(semanticFiles, assembly.moduleTable());
|
||||
final var semanticContexts = service.importedSemanticContextService.build(semanticFiles, assembly.moduleTable(), assembly.siblingDeclarationsByModule());
|
||||
final var semanticAstByFile = new HashMap<FileId, p.studio.compiler.pbs.ast.PbsAst.File>();
|
||||
semanticFiles.forEach(f -> semanticAstByFile.put(f.fileId(), f.ast()));
|
||||
final var flowSemanticsValidator = new PbsFlowSemanticsValidator();
|
||||
@@ -246,7 +248,8 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
private IRBackend mergeCompiledSources(
|
||||
final ArrayList<CompiledSourceFile> compiledSourceFiles,
|
||||
final Set<ModuleId> failedModuleIds,
|
||||
final Map<ModuleId, ReadOnlyList<ModuleId>> moduleDependencyGraph) {
|
||||
final Map<ModuleId, ReadOnlyList<ModuleId>> moduleDependencyGraph,
|
||||
final Map<FileId,ReadOnlyList<PbsFrontendCompiler.ImportedGlobalSurface>> importedGlobalsByFile) {
|
||||
final var irBackendAggregator = IRBackend.aggregator();
|
||||
final var blockedModuleIds = blockedModulesByDependency(failedModuleIds, moduleDependencyGraph);
|
||||
|
||||
@@ -260,7 +263,7 @@ public class PBSFrontendPhaseService implements FrontendPhaseService {
|
||||
compiledSourceFiles,
|
||||
blockedModuleIds,
|
||||
moduleDependencyGraph));
|
||||
return irBackendAggregator.emit();
|
||||
return PbsGlobalReferenceLinker.resolve(irBackendAggregator.emit(),importedGlobalsByFile);
|
||||
}
|
||||
|
||||
private ReadOnlyList<ModuleId> lifecycleModuleOrder(
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package p.studio.compiler.services;
|
||||
|
||||
import p.studio.compiler.models.*;
|
||||
import p.studio.compiler.source.identifiers.ModuleId;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
|
||||
/** Resolves PBS-private symbolic global references before publishing common IR. No storage is cloned. */
|
||||
final class PbsGlobalReferenceLinker {
|
||||
private record Key(p.studio.compiler.source.identifiers.FileId file, String name) {}
|
||||
static IRBackend resolve(IRBackend backend, Map<p.studio.compiler.source.identifiers.FileId,ReadOnlyList<p.studio.compiler.pbs.PbsFrontendCompiler.ImportedGlobalSurface>> imports) {
|
||||
if (imports.values().stream().noneMatch(values -> values.stream().anyMatch(p.studio.compiler.pbs.PbsFrontendCompiler.ImportedGlobalSurface::directlyVisible))) return backend;
|
||||
var globals = new HashMap<Key, IRGlobal>();
|
||||
for (var global : backend.getGlobals()) globals.put(new Key(global.fileId(),global.name()), global);
|
||||
var functions = new ArrayList<IRBackendExecutableFunction>();
|
||||
for (var function : backend.getExecutableFunctions()) {
|
||||
var ownedNames = new HashSet<String>();
|
||||
for (var global : backend.getGlobals()) if (global.fileId().equals(function.fileId())) ownedNames.add(global.name());
|
||||
var importedSlots = p.studio.compiler.pbs.lowering.PbsImportedGlobalSlots.index(ownedNames,imports.getOrDefault(function.fileId(),ReadOnlyList.empty()));
|
||||
if (importedSlots.isEmpty()) { functions.add(function); continue; }
|
||||
var instructions = new ArrayList<IRBackendExecutableFunction.Instruction>();
|
||||
for (var instruction : function.instructions()) {
|
||||
if ((instruction.kind()==IRBackendExecutableFunction.InstructionKind.GET_GLOBAL || instruction.kind()==IRBackendExecutableFunction.InstructionKind.SET_GLOBAL)
|
||||
&& importedSlots.containsKey(instruction.expectedArgSlots())) {
|
||||
var imported = importedSlots.get(instruction.expectedArgSlots());
|
||||
var global = Objects.requireNonNull(globals.get(new Key(imported.span().getFileId(),imported.globalName())), "Visible PBS global binding has no defining storage");
|
||||
instruction = new IRBackendExecutableFunction.Instruction(instruction.kind(),ModuleId.none(),"",null,null,null,
|
||||
instruction.label(),instruction.targetLabel(),global.slot(),instruction.expectedRetSlots(),instruction.span(),instruction.registryInstruction());
|
||||
}
|
||||
instructions.add(instruction);
|
||||
}
|
||||
functions.add(new IRBackendExecutableFunction(function.fileId(),function.moduleId(),function.callableName(),function.callableId(),function.sourceStart(),function.sourceEnd(),
|
||||
function.paramSlots(),function.localSlots(),function.returnSlots(),function.maxStackSlots(),ReadOnlyList.wrap(instructions),function.span(),function.metadata(),function.semanticFacts()));
|
||||
}
|
||||
return IRBackend.builder().entryPointCallableName(backend.getEntryPointCallableName()).entryPointModuleId(backend.getEntryPointModuleId())
|
||||
.functions(backend.getFunctions()).syntheticFunctions(backend.getSyntheticFunctions()).globals(backend.getGlobals()).executableFunctions(ReadOnlyList.wrap(functions))
|
||||
.modulePool(backend.getModulePool()).callableSignatures(backend.getCallableSignatures()).intrinsicPool(backend.getIntrinsicPool())
|
||||
.reservedMetadata(backend.getReservedMetadata()).registry(backend.getRegistry()).lifecycleDeclaration(backend.getLifecycleDeclaration()).build();
|
||||
}
|
||||
}
|
||||
+39
-8
@@ -26,7 +26,8 @@ final class PbsImportedSemanticContextService {
|
||||
|
||||
Map<FileId, PbsImportedSemanticContext> build(
|
||||
final ReadOnlyList<PbsParsedSourceFile> parsedSourceFiles,
|
||||
final ModuleTable moduleTable) {
|
||||
final ModuleTable moduleTable,
|
||||
final Map<ModuleId, Set<p.studio.compiler.source.Span>> siblingDeclarationsByModule) {
|
||||
final Map<ModuleId, ArrayList<PbsParsedSourceFile>> sourcesByModule = new HashMap<>();
|
||||
for (final var parsedSource : parsedSourceFiles) {
|
||||
sourcesByModule
|
||||
@@ -83,9 +84,39 @@ final class PbsImportedSemanticContextService {
|
||||
for (var sibling : sourcesByModule.getOrDefault(parsedSource.moduleId(), new ArrayList<>())) {
|
||||
if (sibling.fileId().equals(parsedSource.fileId())) continue;
|
||||
for (var declaration : sibling.ast().topDecls()) {
|
||||
if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl(
|
||||
new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span(), true), supplementalTopDecls, supplementalKeys);
|
||||
if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
|
||||
boolean admitted = siblingDeclarationsByModule.getOrDefault(parsedSource.moduleId(), Set.of()).contains(declaration.span());
|
||||
if (admitted) {
|
||||
if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty())
|
||||
appendSupplementalTopDecl(new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span(), true), supplementalTopDecls, supplementalKeys);
|
||||
else appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys);
|
||||
appendTypeDependencyDecls(declaration, topDeclsByNameByModule.get(parsedSource.moduleId()), supplementalTopDecls, supplementalKeys);
|
||||
if (declaration instanceof PbsAst.FunctionDecl function && function.typeParameters().isEmpty())
|
||||
appendImportedCallable(importedCallables, importedCallableKeys, new PbsFrontendCompiler.ImportedCallableSurface(
|
||||
parsedSource.moduleId(), function.name(), function.parameters().size(), returnSlotsFor(function),
|
||||
function.returnKind(), function.returnType(), frontendCompiler.callableShapeSurfaceOf(function), function.name()));
|
||||
if (declaration instanceof PbsAst.GlobalDecl global)
|
||||
directlyVisibleGlobalRefs.putIfAbsent(global.name(), new PbsGlobalDependencySupport.GlobalRef(parsedSource.moduleId(),global.name()));
|
||||
if (declaration instanceof PbsAst.ServiceDecl service) {
|
||||
var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(service);
|
||||
appendImportedCallable(importedCallables, importedCallableKeys, new PbsFrontendCompiler.ImportedCallableSurface(
|
||||
parsedSource.moduleId(),service.name()+".$instance",0,1,accessor.returnKind(),accessor.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(accessor),service.name()+".$instance", service.span()));
|
||||
for (var method : service.methods()) appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(parsedSource.moduleId(), service.name()+"."+method.name(),
|
||||
method.parameters().size(),returnSlotsFor(method),method.returnKind(),method.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(method),service.name()+"."+method.name(), service.span()));
|
||||
}
|
||||
}
|
||||
if (declaration instanceof PbsAst.ImplementsDecl implementation) {
|
||||
boolean ownerVisible = parsedSource.ast().topDecls().stream().anyMatch(d -> implementation.ownerName().equals(topDeclName(d)))
|
||||
|| sourcesByModule.get(parsedSource.moduleId()).stream().flatMap(source -> source.ast().topDecls().stream())
|
||||
.anyMatch(d -> implementation.ownerName().equals(topDeclName(d))
|
||||
&& siblingDeclarationsByModule.getOrDefault(parsedSource.moduleId(),Set.of()).contains(d.span()));
|
||||
if (ownerVisible) {
|
||||
appendSupplementalTopDecl(implementation, supplementalTopDecls, supplementalKeys);
|
||||
appendTypeDependencyDecls(implementation, topDeclsByNameByModule.get(parsedSource.moduleId()), supplementalTopDecls, supplementalKeys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,7 +156,7 @@ final class PbsImportedSemanticContextService {
|
||||
var accessor = p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.singletonAccessor(serviceDecl);
|
||||
appendImportedCallable(importedCallables, importedCallableKeys,
|
||||
new PbsFrontendCompiler.ImportedCallableSurface(importedModuleId, localName+".$instance", 0, 1,
|
||||
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor), serviceDecl.name()+".$instance"));
|
||||
accessor.returnKind(), accessor.returnType(), frontendCompiler.callableShapeSurfaceOf(accessor), serviceDecl.name()+".$instance", serviceDecl.span()));
|
||||
for (final var method : serviceDecl.methods()) {
|
||||
appendImportedCallable(
|
||||
importedCallables,
|
||||
@@ -137,7 +168,7 @@ final class PbsImportedSemanticContextService {
|
||||
returnSlotsFor(method),
|
||||
method.returnKind(),
|
||||
method.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(method), serviceDecl.name() + "." + method.name()));
|
||||
frontendCompiler.callableShapeSurfaceOf(method), serviceDecl.name() + "." + method.name(), serviceDecl.span()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -151,7 +182,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), structDecl.name()+"."+method.name()));
|
||||
frontendCompiler.callableShapeSurfaceOf(executable), structDecl.name()+"."+method.name(), structDecl.span()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@@ -249,7 +280,7 @@ final class PbsImportedSemanticContextService {
|
||||
var executable=p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.withReceiver(method,struct.name(),"this");
|
||||
appendImportedCallable(callables,callableKeys,new PbsFrontendCompiler.ImportedCallableSurface(definingModule,local+"."+method.name(),
|
||||
executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(),
|
||||
frontendCompiler.callableShapeSurfaceOf(executable),struct.name()+"."+method.name()));
|
||||
frontendCompiler.callableShapeSurfaceOf(executable),struct.name()+"."+method.name(), struct.span()));
|
||||
}
|
||||
for(var provider:sourcesByModule.getOrDefault(definingModule,new ArrayList<>()))for(var member:provider.ast().topDecls())
|
||||
if(member instanceof PbsAst.ImplementsDecl implementation&&implementation.ownerName().equals(struct.name())) {
|
||||
|
||||
+3
-1
@@ -18,8 +18,10 @@ record PbsModuleAssembly(
|
||||
ReadOnlyList<ModuleReference> canonicalModulePool,
|
||||
Set<ModuleId> failedModuleIds,
|
||||
ModuleTable moduleTable,
|
||||
Map<ModuleId, Map<String, IRGlobalVisibility>> globalVisibilityByModule) {
|
||||
Map<ModuleId, Map<String, IRGlobalVisibility>> globalVisibilityByModule,
|
||||
Map<ModuleId, Set<p.studio.compiler.source.Span>> siblingDeclarationsByModule) {
|
||||
PbsModuleAssembly {
|
||||
siblingDeclarationsByModule = Map.copyOf(siblingDeclarationsByModule);
|
||||
parsedSourceFiles = parsedSourceFiles == null ? ReadOnlyList.empty() : parsedSourceFiles;
|
||||
canonicalModulePool = canonicalModulePool == null ? ReadOnlyList.empty() : canonicalModulePool;
|
||||
failedModuleIds = failedModuleIds == null ? Set.of() : Set.copyOf(failedModuleIds);
|
||||
|
||||
+3
-1
@@ -118,13 +118,15 @@ final class PbsModuleAssemblyService {
|
||||
moduleVisibilityValidator.validate(ReadOnlyList.wrap(modules), nameTable, diagnostics);
|
||||
markModulesWithLinkingErrors(diagnostics, moduleIdByFile, failedModuleIds);
|
||||
|
||||
var siblingDeclarations = new LinkedHashMap<ModuleId, Set<Span>>();
|
||||
for (var module : modules) siblingDeclarations.put(moduleId(moduleTable, module.coordinates()), moduleVisibilityValidator.siblingDeclarations(module, nameTable));
|
||||
return new PbsModuleAssembly(
|
||||
ReadOnlyList.wrap(parsedSourceFiles),
|
||||
buildModuleDependencyGraph(parsedSourceFiles, moduleTable),
|
||||
emitModulePool(moduleTable),
|
||||
failedModuleIds,
|
||||
moduleTable,
|
||||
collectGlobalVisibilityByModule(modulesByCoordinates, moduleTable));
|
||||
collectGlobalVisibilityByModule(modulesByCoordinates, moduleTable), siblingDeclarations);
|
||||
}
|
||||
|
||||
private Map<ModuleId, Map<String, IRGlobalVisibility>> collectGlobalVisibilityByModule(
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package p.studio.compiler.pbs;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.pbs.ast.PbsAst;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class GenericDiagnosticContextTest {
|
||||
@Test void specializationWrapperPreservesDetectorAndReportedPhase() {
|
||||
var span = new Span(new FileId(0), 0, 4);
|
||||
var declaration = new PbsAst.HostDecl("Fixture", ReadOnlyList.empty(), ReadOnlyList.empty(), span);
|
||||
var application = new PbsAst.ApplicationOrigin(declaration, ReadOnlyList.empty(), "fixture", "Fixture<int>", span);
|
||||
var original = DiagnosticDescriptions.attach(new Diagnostic(Severity.Error, "E_SEM_UNSUPPORTED_LOWERING", "failed", span, List.of()),
|
||||
"pbs.lowering.call-resolution", Map.of("requestedSymbol", "probe", "argumentCount", 0), FailureKind.PROGRAM_REJECTION);
|
||||
var sink = DiagnosticSink.empty(); PbsGenericDiagnostics.forOrigin(application, sink).report(original);
|
||||
var output = sink.asCollection().iterator().next();
|
||||
assertEquals(original.getContext(), output.getContext()); assertEquals(original.getReportedPhase(), output.getReportedPhase());
|
||||
assertEquals(original.getCode(), output.getCode()); assertEquals(2, output.getRelated().size());
|
||||
assertTrue(output.getMessage().contains("Fixture<int>"));
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package p.studio.compiler.pbs.lowering;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.AppMode;
|
||||
import p.studio.compiler.models.*;
|
||||
import p.studio.compiler.messages.FrontendPhaseContext;
|
||||
import p.studio.compiler.services.PBSFrontendPhaseService;
|
||||
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.Span;
|
||||
import p.studio.compiler.source.tables.*;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticSink;
|
||||
import p.studio.compiler.utilities.SourceProviderFactory;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsNominalOwnerRegressionTest {
|
||||
@TempDir Path temporary;
|
||||
@Test void declarationScopeAndSyntheticReceiverHaveDistinctResolutionEvidence() throws Exception {
|
||||
var json=new ObjectMapper();var reports=new ArrayList<Map<String,Object>>();
|
||||
var cases=json.readTree(getClass().getResourceAsStream("/production-regressions/cases.json")).path("cases");
|
||||
for(var example:cases) {
|
||||
String id=example.path("id").asText();
|
||||
if(!Set.of("F4-distinct","F4-same-no-dependency","F4-same-dependency","F4-rename-a").contains(id))continue;
|
||||
var root=Files.createDirectory(temporary.resolve(id)).toRealPath();var projects=new ProjectTable();var files=new FileTable(1);
|
||||
var project=projects.register(ProjectDescriptor.builder().rootPath(root).name("caseapp").version("1").sourceRoots(ReadOnlyList.from(root.resolve("src"))).build());
|
||||
var entries=example.path("files").fields();p.studio.compiler.source.identifiers.FileId main=null;
|
||||
while(entries.hasNext()) {
|
||||
var entry=entries.next();var path=root.resolve(entry.getKey());Files.createDirectories(path.getParent());Files.writeString(path,entry.getValue().asText());
|
||||
if(entry.getKey().endsWith(".pbs")||entry.getKey().endsWith(".barrel")) {
|
||||
var file=files.register(new SourceHandle(project,root.relativize(path),path,Files.size(path),0,SourceProviderFactory.filesystem()));
|
||||
if(entry.getKey().equals("src/a/main.pbs"))main=file;
|
||||
}
|
||||
}
|
||||
assertNotNull(main);
|
||||
var context=new FrontendPhaseContext(projects,files,new BuildStack(ReadOnlyList.from(project)),1,AppMode.Game);
|
||||
var supplemental=PBSFrontendPhaseService.importedSupplementalTopDeclsByFile(context,DiagnosticSink.empty(),p.studio.compiler.messages.BuildingIssueSink.empty()).get(main);
|
||||
var diagnostics=DiagnosticSink.empty();var ast=PbsParser.parse(PbsLexer.lex(files.get(main).readUtf8().orElseThrow(),main,diagnostics),main,diagnostics);
|
||||
var types=new PbsRuntimeTypes(ast,supplemental,Map.of());
|
||||
var global=(PbsAst.GlobalDecl)ast.topDecls().stream().filter(d->d instanceof PbsAst.GlobalDecl).findFirst().orElseThrow();
|
||||
var declaration=types.contractTypes.declaration(global.explicitType());assertNotNull(declaration);
|
||||
var flattened=types.structs.get(global.explicitType().name());assertNotNull(flattened);
|
||||
assertEquals(declaration.span(), types.struct(global.explicitType()).span());
|
||||
assertEquals(types.key(global.explicitType()), types.key(PbsRuntimeTypes.type(global.explicitType().name())));
|
||||
reports.add(Map.of("case",id,"source",root.relativize(files.get(declaration.span().getFileId()).getCanonPath()).toString(),
|
||||
"flatOwnerSource",root.relativize(files.get(flattened.span().getFileId()).getCanonPath()).toString(),
|
||||
"declaredReceiverKey",types.key(global.explicitType()),"syntheticReceiverKey",types.key(PbsRuntimeTypes.type(global.explicitType().name())),
|
||||
"flatOwnerMatches",declaration.span().equals(flattened.span())));
|
||||
}
|
||||
var directory=Path.of("build/production-regressions");Files.createDirectories(directory);
|
||||
json.writerWithDefaultPrettyPrinter().writeValue(Files.createTempFile(directory,"nominal-trace-",".json").toFile(),reports);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package p.studio.compiler.services;
|
||||
|
||||
import com.fasterxml.jackson.databind.*;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import p.studio.AppMode;
|
||||
import p.studio.compiler.messages.*;
|
||||
import p.studio.compiler.models.*;
|
||||
import p.studio.compiler.source.tables.*;
|
||||
import p.studio.compiler.utilities.SourceProviderFactory;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import p.studio.utilities.logs.LogAggregator;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class PbsProductionLoweringRegressionTest {
|
||||
@TempDir Path root;
|
||||
static Stream<String> cases() throws Exception {
|
||||
try(var input=PbsProductionLoweringRegressionTest.class.getResourceAsStream("/production-regressions/cases.json")) {
|
||||
byte[] corpus=input.readAllBytes();
|
||||
assertEquals("0ad291942af21e990f5cae3348a5be368dee865aa2843ba0d0effd1a9136cb87",
|
||||
HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(corpus)));
|
||||
return new ObjectMapper().readTree(corpus).path("cases").findValuesAsText("id").stream();
|
||||
}
|
||||
}
|
||||
@ParameterizedTest(name="{0}") @MethodSource("cases")
|
||||
void originalCorpusKeepsSourceAndExpectedFrontendResult(String id) throws Exception {
|
||||
var corpus=new ObjectMapper().readTree(getClass().getResourceAsStream("/production-regressions/cases.json"));
|
||||
JsonNode example=null; for(var c:corpus.path("cases"))if(c.path("id").asText().equals(id))example=c;
|
||||
assertNotNull(example); checkCase(example);
|
||||
}
|
||||
static Stream<String> focusedCases() throws Exception {
|
||||
return new ObjectMapper().readTree(PbsProductionLoweringRegressionTest.class.getResourceAsStream("/production-regressions/focused-cases.json")).path("cases").findValuesAsText("id").stream();
|
||||
}
|
||||
@ParameterizedTest(name="{0}") @MethodSource("focusedCases")
|
||||
void focusedContextVisibilityAndSharedIdentity(String id) throws Exception {
|
||||
var examples=new ObjectMapper().readTree(getClass().getResourceAsStream("/production-regressions/focused-cases.json")).path("cases");
|
||||
for(var example:examples)if(example.path("id").asText().equals(id)){checkCase(example);return;}
|
||||
fail("Unknown focused case "+id);
|
||||
}
|
||||
void checkCase(JsonNode example) throws Exception {
|
||||
var id=example.path("id").asText(); var files=new LinkedHashMap<String,String>();
|
||||
var entries=example.path("files").fields();while(entries.hasNext()){var entry=entries.next();files.put(entry.getKey(),entry.getValue().asText());}
|
||||
var result=compile(files);
|
||||
assertEquals(example.path("expectedCompile").asText().equals("rejected"),result.diagnostics().hasErrors(),id+": "+result.diagnostics().asCollection());
|
||||
if(id.equals("F3-global"))assertEquals(1,result.backend().getGlobals().stream().filter(g->g.name().equals("count")).count());
|
||||
for(var entry:files.entrySet())assertEquals(entry.getValue(),Files.readString(root.resolve(entry.getKey())));
|
||||
}
|
||||
@Test void expectedReturnOverloadsRemainContextual() throws Exception {
|
||||
var result=compile(Map.of("src/mod.barrel","pub fn frame() -> void;\n", "src/main.pbs", """
|
||||
declare struct Probe() { fn value() -> int { return 1; } fn value() -> bool { return true; } }
|
||||
declare global data: Probe = new Probe();
|
||||
fn check() -> bool { return data.value(); }
|
||||
[Frame] fn frame() -> void { let number: int=data.value(); let flag: bool=data.value(); if !check() || !flag || number!=1 { let failure=1/0; } }
|
||||
"""));
|
||||
assertFalse(result.diagnostics().hasErrors(), result.diagnostics().asCollection().toString());
|
||||
}
|
||||
record Compiled(IRBackend backend, DiagnosticSink diagnostics) {}
|
||||
Compiled compile(Map<String,String> sources) throws Exception {
|
||||
root=root.toRealPath(); var projects=new ProjectTable();var files=new FileTable(1);
|
||||
var owner=projects.register(ProjectDescriptor.builder().rootPath(root).name("caseapp").version("1.0.0")
|
||||
.sourceRoots(ReadOnlyList.from(root.resolve("src"))).build());
|
||||
for(var entry:sources.entrySet()) {
|
||||
var path=root.resolve(entry.getKey());Files.createDirectories(path.getParent());Files.writeString(path,entry.getValue());
|
||||
if(entry.getKey().endsWith(".pbs")||entry.getKey().endsWith(".barrel"))files.register(new SourceHandle(owner,root.relativize(path),path,Files.size(path),0,SourceProviderFactory.filesystem()));
|
||||
}
|
||||
var diagnostics=DiagnosticSink.empty(); var backend=new PBSFrontendPhaseService().compile(
|
||||
new FrontendPhaseContext(projects,files,new BuildStack(ReadOnlyList.from(owner)),1,AppMode.Game),diagnostics,LogAggregator.empty(),BuildingIssueSink.empty());
|
||||
return new Compiled(backend,diagnostics);
|
||||
}
|
||||
}
|
||||
+451
@@ -0,0 +1,451 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"cases": [
|
||||
{
|
||||
"id": "F1-local",
|
||||
"family": "call-comparison-return",
|
||||
"description": "Control: method result materialized before comparison",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare struct Probe() { fn value() -> int { return 1; } }\ndeclare global data: Probe = new Probe();\nfn check() -> bool { let value=data.value(); return value!=0; }\n[Frame] fn frame() -> void { if !check() { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "35df5a71b9d508b20e8b293a769ba1397a3209d99246c39240e8788cda932990"
|
||||
},
|
||||
{
|
||||
"id": "F1-direct",
|
||||
"family": "call-comparison-return",
|
||||
"description": "Method call compared directly in returned expression",
|
||||
"control": "F1-local",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare struct Probe() { fn value() -> int { return 1; } }\ndeclare global data: Probe = new Probe();\nfn check() -> bool { return data.value()!=0; }\n[Frame] fn frame() -> void { if !check() { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "382223b4c520762a93e3ee767255175adec8b24f69949b335c1a0030c9d75e61"
|
||||
},
|
||||
{
|
||||
"id": "F1-two-calls",
|
||||
"family": "call-comparison-return",
|
||||
"description": "Two method calls as comparison operands",
|
||||
"control": "F1-local",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare struct Probe() { fn value() -> int { return 1; } }\ndeclare global data: Probe = new Probe();\nfn check() -> bool { return data.value()==data.value(); }\n[Frame] fn frame() -> void { if !check() { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "2e3da1c805c18b5cdc34ca372fae737804a9274205ef377ac21d5b0034d60c4f"
|
||||
},
|
||||
{
|
||||
"id": "F1-service-this",
|
||||
"family": "call-comparison-return",
|
||||
"description": "Service receiver this inside a returned comparison",
|
||||
"control": "F1-service-local",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare service Probe { fn value() -> int { return 1; } fn check() -> bool { return this.value()!=0; } }\n[Frame] fn frame() -> void { if !Probe.check() { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "78a7ba39a880d9136b49f82ecbee7d409333c26861ff0a6b429ae6a55f08d089"
|
||||
},
|
||||
{
|
||||
"id": "F1-service-local",
|
||||
"family": "call-comparison-return",
|
||||
"description": "Control: identical service call materialized before returned comparison",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare service Probe { fn value() -> int { return 1; } fn check() -> bool { let value=this.value(); return value!=0; } }\n[Frame] fn frame() -> void { if !Probe.check() { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "f07038dc6f42923a65b1df8c4d17aa61eb1714ae7907d82b87fcda9e6c4b73fb"
|
||||
},
|
||||
{
|
||||
"id": "F1-condition",
|
||||
"family": "call-comparison-return",
|
||||
"description": "Control: direct method comparison in an if condition",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare struct Probe() { fn value() -> int { return 1; } }\ndeclare global data: Probe = new Probe();\n[Frame] fn frame() -> void { if data.value()!=1 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "415d08d0155fc8e8b4e0df3c1eb47c0a6aa7bda6481fdc4f5024c14d0f70d014"
|
||||
},
|
||||
{
|
||||
"id": "F2-locals",
|
||||
"family": "nested-call-expression",
|
||||
"description": "Control: effectful call arguments stored in locals",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare global calls: int=0;\nfn next() -> int { calls+=1; return calls; }\nfn add(a: int,b: int) -> int { return a+b; }\n[Frame] fn frame() -> void { calls=0; let a=next(); let b=next(); let value=add(a,b); if value!=3 || calls!=2 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "1eb4dbd0bfa6fbc9e002793e6c23eefa80eb091d40ccf2253520b532b3420218"
|
||||
},
|
||||
{
|
||||
"id": "F2-arguments",
|
||||
"family": "nested-call-expression",
|
||||
"description": "Effectful call arguments evaluate once, left to right",
|
||||
"control": "F2-locals",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare global calls: int=0;\nfn next() -> int { calls+=1; return calls; }\nfn add(a: int,b: int) -> int { return a+b; }\n[Frame] fn frame() -> void { calls=0; let value=add(next(),next()); if value!=3 || calls!=2 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "b8713121ffe7afacdd9d4ad6046768ff4ad681b44fcc153f84a432f6df75717c"
|
||||
},
|
||||
{
|
||||
"id": "F2-expression",
|
||||
"family": "nested-call-expression",
|
||||
"description": "Effectful calls nested inside arithmetic argument",
|
||||
"control": "F2-locals",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare global calls: int=0;\nfn next() -> int { calls+=1; return calls; }\nfn add(a: int,b: int) -> int { return a+b; }\n[Frame] fn frame() -> void { calls=0; let value=add(next()+next(),next()); if value!=6 || calls!=3 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "c6ede06ecfad7bdd167b8f3afb849df362787484db1968f74b62c24909818073"
|
||||
},
|
||||
{
|
||||
"id": "F2-struct-method",
|
||||
"family": "nested-call-expression",
|
||||
"description": "Struct method used as another method argument",
|
||||
"control": "F2-locals",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare struct Probe() { fn value() -> int { return 1; } }\ndeclare global data: Probe = new Probe();\nfn add(a: int,b: int) -> int { return a+b; }\n[Frame] fn frame() -> void { let value=add(data.value(),data.value()); if value!=2 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "8ed2b002ef5c20f01ae09949dc0ae75c574cce782dbe27bd304b25fa94045894"
|
||||
},
|
||||
{
|
||||
"id": "F3-single-file",
|
||||
"family": "same-module-files",
|
||||
"description": "Control: function and caller in the same file",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "fn increment(value: int) -> int { return value+1; }\n[Frame] fn frame() -> void { let value=increment(2); if value!=3 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "aff9dbc6f5e3b67b713da29e7e20eb97913464bedcc5f858964ec110ed7b8c4a"
|
||||
},
|
||||
{
|
||||
"id": "F3-function",
|
||||
"family": "same-module-files",
|
||||
"description": "mod function called from another file",
|
||||
"control": "F3-single-file",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\nmod fn increment(value: int) -> int;\n",
|
||||
"src/helpers.pbs": "fn increment(value: int) -> int { return value+1; }\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { let value=increment(2); if value!=3 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "bcf9162dd44b7b7a50428e368789d10ab929301f382bae7c35cab06f1595c4b1"
|
||||
},
|
||||
{
|
||||
"id": "F3-global",
|
||||
"family": "same-module-files",
|
||||
"description": "mod global mutated from another file",
|
||||
"control": "F3-global-local",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\nmod global count;\n",
|
||||
"src/state.pbs": "declare global count: int=0;\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { count=4; if count!=4 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "89c0749385172457659ca2e337ebc368e349065626a815198c314a089d95fc34"
|
||||
},
|
||||
{
|
||||
"id": "F3-service",
|
||||
"family": "same-module-files",
|
||||
"description": "mod service called from another file",
|
||||
"control": "F3-service-local",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\nmod service Helper;\n",
|
||||
"src/helpers.pbs": "declare service Helper { fn value() -> int { return 3; } }\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { let value=Helper.value(); if value!=3 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "37b6c3b4c7d94d1f6f1cc258c84791fdd32c20ea38a88940b735fccf1c7f3b22"
|
||||
},
|
||||
{
|
||||
"id": "F3-global-local",
|
||||
"family": "same-module-files",
|
||||
"description": "Control: identical global and caller in the same file",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare global count: int=0;\n[Frame] fn frame() -> void { count=4; if count!=4 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "e175339cc069d0e14deb8e4e098b1310d877851f2415991ad65b446563aea924"
|
||||
},
|
||||
{
|
||||
"id": "F3-service-local",
|
||||
"family": "same-module-files",
|
||||
"description": "Control: identical service and caller in the same file",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare service Helper { fn value() -> int { return 3; } }\n[Frame] fn frame() -> void { let value=Helper.value(); if value!=3 { let failure=1/0; } }\n"
|
||||
},
|
||||
"sourceSha256": "387e15a0de25644a8862b6f88b74fc7839795e10c8736ebc5ada31670ffd79cb"
|
||||
},
|
||||
{
|
||||
"id": "F3-file-private",
|
||||
"family": "same-module-files",
|
||||
"description": "Negative control: function absent from barrel stays file-private",
|
||||
"control": "F3-function",
|
||||
"expectedCompile": "rejected",
|
||||
"expectedRuntime": "not_run",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/helpers.pbs": "fn increment(value: int) -> int { return value+1; }\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { let value=increment(2); }\n"
|
||||
},
|
||||
"sourceSha256": "b9359695e141c6fd14d5fbfcab68a8829ef4d87c3c7408dbc366465184ec2cfb"
|
||||
},
|
||||
{
|
||||
"id": "F4-distinct",
|
||||
"family": "homonymous-types",
|
||||
"description": "Types ARoomData/BRoomData; dependency=True; direct=False",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { A } from @caseapp:a;\nimport { B } from @caseapp:b;\n[Frame] fn frame() -> void { let value=A.value(); if value!=3 { let failure=1/0; } let other=B.value(); if other!=2 { let failure=1/0; } }\n",
|
||||
"src/a/mod.barrel": "pub service A;\nmod struct ARoomData;\n",
|
||||
"src/a/data.pbs": "declare struct ARoomData() { fn value() -> int { return 1; } }\n",
|
||||
"src/a/main.pbs": "import { B } from @caseapp:b;\ndeclare global room: ARoomData = new ARoomData();\ndeclare service A { fn value() -> int { let own=room.value(); let other=B.value(); return own+other; } }\n",
|
||||
"src/b/mod.barrel": "pub service B;\nmod struct BRoomData;\n",
|
||||
"src/b/data.pbs": "declare struct BRoomData() { fn value() -> int { return 2; } }\n",
|
||||
"src/b/main.pbs": "declare global room: BRoomData = new BRoomData();\ndeclare service B { fn value() -> int { return room.value(); } }\n"
|
||||
},
|
||||
"sourceSha256": "99c527e7749e4ea7c1cecce4063467e4f411b5481cdd641186975fee42299811"
|
||||
},
|
||||
{
|
||||
"id": "F4-same-no-dependency",
|
||||
"family": "homonymous-types",
|
||||
"description": "Types RoomData/RoomData; dependency=False; direct=False",
|
||||
"control": "F4-distinct",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { A } from @caseapp:a;\nimport { B } from @caseapp:b;\n[Frame] fn frame() -> void { let value=A.value(); if value!=1 { let failure=1/0; } let other=B.value(); if other!=2 { let failure=1/0; } }\n",
|
||||
"src/a/mod.barrel": "pub service A;\nmod struct RoomData;\n",
|
||||
"src/a/data.pbs": "declare struct RoomData() { fn value() -> int { return 1; } }\n",
|
||||
"src/a/main.pbs": "declare global room: RoomData = new RoomData();\ndeclare service A { fn value() -> int { let own=room.value(); return own; } }\n",
|
||||
"src/b/mod.barrel": "pub service B;\nmod struct RoomData;\n",
|
||||
"src/b/data.pbs": "declare struct RoomData() { fn value() -> int { return 2; } }\n",
|
||||
"src/b/main.pbs": "declare global room: RoomData = new RoomData();\ndeclare service B { fn value() -> int { return room.value(); } }\n"
|
||||
},
|
||||
"sourceSha256": "db3c59d1f4f618856ed554310e5774f60d64f70e9ed0b122a5ab57d4e9870ce5"
|
||||
},
|
||||
{
|
||||
"id": "F4-same-dependency",
|
||||
"family": "homonymous-types",
|
||||
"description": "Types RoomData/RoomData; dependency=True; direct=False",
|
||||
"control": "F4-distinct",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { A } from @caseapp:a;\nimport { B } from @caseapp:b;\n[Frame] fn frame() -> void { let value=A.value(); if value!=3 { let failure=1/0; } let other=B.value(); if other!=2 { let failure=1/0; } }\n",
|
||||
"src/a/mod.barrel": "pub service A;\nmod struct RoomData;\n",
|
||||
"src/a/data.pbs": "declare struct RoomData() { fn value() -> int { return 1; } }\n",
|
||||
"src/a/main.pbs": "import { B } from @caseapp:b;\ndeclare global room: RoomData = new RoomData();\ndeclare service A { fn value() -> int { let own=room.value(); let other=B.value(); return own+other; } }\n",
|
||||
"src/b/mod.barrel": "pub service B;\nmod struct RoomData;\n",
|
||||
"src/b/data.pbs": "declare struct RoomData() { fn value() -> int { return 2; } }\n",
|
||||
"src/b/main.pbs": "declare global room: RoomData = new RoomData();\ndeclare service B { fn value() -> int { return room.value(); } }\n"
|
||||
},
|
||||
"sourceSha256": "c4c624cb3556b8d05927ceda69e596482f4ec1d7b82f7f4ca7442483e2b8b831"
|
||||
},
|
||||
{
|
||||
"id": "F4-rename-a",
|
||||
"family": "homonymous-types",
|
||||
"description": "Types StartRoomData/RoomData; dependency=True; direct=False",
|
||||
"control": "F4-distinct",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { A } from @caseapp:a;\nimport { B } from @caseapp:b;\n[Frame] fn frame() -> void { let value=A.value(); if value!=3 { let failure=1/0; } let other=B.value(); if other!=2 { let failure=1/0; } }\n",
|
||||
"src/a/mod.barrel": "pub service A;\nmod struct StartRoomData;\n",
|
||||
"src/a/data.pbs": "declare struct StartRoomData() { fn value() -> int { return 1; } }\n",
|
||||
"src/a/main.pbs": "import { B } from @caseapp:b;\ndeclare global room: StartRoomData = new StartRoomData();\ndeclare service A { fn value() -> int { let own=room.value(); let other=B.value(); return own+other; } }\n",
|
||||
"src/b/mod.barrel": "pub service B;\nmod struct RoomData;\n",
|
||||
"src/b/data.pbs": "declare struct RoomData() { fn value() -> int { return 2; } }\n",
|
||||
"src/b/main.pbs": "declare global room: RoomData = new RoomData();\ndeclare service B { fn value() -> int { return room.value(); } }\n"
|
||||
},
|
||||
"sourceSha256": "6cab04b1fbc3724cec1670a11ab46a792e5b83ea1fb12b4bf80f98d178c1290e"
|
||||
},
|
||||
{
|
||||
"id": "F4-same-direct",
|
||||
"family": "homonymous-types",
|
||||
"description": "Types RoomData/RoomData; dependency=True; direct=True",
|
||||
"control": "F4-distinct",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { A } from @caseapp:a;\nimport { B } from @caseapp:b;\n[Frame] fn frame() -> void { let value=A.value(); if value!=3 { let failure=1/0; } let other=B.value(); if other!=2 { let failure=1/0; } }\n",
|
||||
"src/a/mod.barrel": "pub service A;\nmod struct RoomData;\n",
|
||||
"src/a/data.pbs": "declare struct RoomData() { fn value() -> int { return 1; } }\n",
|
||||
"src/a/main.pbs": "import { B } from @caseapp:b;\ndeclare global room: RoomData = new RoomData();\ndeclare service A { fn value() -> int { return room.value()+B.value(); } }\n",
|
||||
"src/b/mod.barrel": "pub service B;\nmod struct RoomData;\n",
|
||||
"src/b/data.pbs": "declare struct RoomData() { fn value() -> int { return 2; } }\n",
|
||||
"src/b/main.pbs": "declare global room: RoomData = new RoomData();\ndeclare service B { fn value() -> int { return room.value(); } }\n"
|
||||
},
|
||||
"sourceSha256": "79fc0901e3e60e7b50b83f5d10ba4e548bd57b0c83d281def25369cadb74633e"
|
||||
},
|
||||
{
|
||||
"id": "F4-public-aliases",
|
||||
"family": "homonymous-types",
|
||||
"description": "Two distinct nominal RoomData declarations imported with aliases",
|
||||
"control": "F4-distinct",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { RoomData as LeftData } from @caseapp:a;\nimport { RoomData as RightData } from @caseapp:b;\ndeclare global left: LeftData = new LeftData(1);\ndeclare global right: RightData = new RightData(2);\n[Frame] fn frame() -> void { let a=left.value(); let b=right.value(); if a!=1 || b!=2 { let failure=1/0; } }\n",
|
||||
"src/a/mod.barrel": "pub struct RoomData;\n",
|
||||
"src/a/main.pbs": "declare struct RoomData(number: int) { fn value() -> int { return this.number; } }\n",
|
||||
"src/b/mod.barrel": "pub struct RoomData;\n",
|
||||
"src/b/main.pbs": "declare struct RoomData(number: int) { fn value() -> int { return this.number; } }\n"
|
||||
},
|
||||
"sourceSha256": "9379bc7c71cd6c1ff287f5771a78590a2e25b8dead05e78c563ff25ee8d1c207"
|
||||
},
|
||||
{
|
||||
"id": "F5-shopvisit",
|
||||
"family": "imported-struct-construction",
|
||||
"description": "Imported ShopVisit, alias=None, positional=False",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { ShopVisit } from @caseapp:scene;\nimport { Link } from @caseapp:link;\ndeclare global scene: ShopVisit = new ShopVisit.make(10);\n[Frame] fn frame() -> void { let value=Link.read(scene); if value!=10 { let failure=1/0; } }\n",
|
||||
"src/scene/mod.barrel": "pub struct ShopVisit;\n",
|
||||
"src/scene/main.pbs": "declare struct ShopVisit(value: int) { ctor make(value: int) { this.value=value; } fn read() -> int { return this.value; } }\n",
|
||||
"src/link/mod.barrel": "pub service Link;\n",
|
||||
"src/link/main.pbs": "import { ShopVisit } from @caseapp:scene;\ndeclare service Link { fn read(scene: ShopVisit) -> int { return scene.read(); } }\n"
|
||||
},
|
||||
"sourceSha256": "5373eaa6bece79658cb4cbd74fecc47d7d2a5954eee1812576243155fecb4c38"
|
||||
},
|
||||
{
|
||||
"id": "F5-scene",
|
||||
"family": "imported-struct-construction",
|
||||
"description": "Imported Scene, alias=None, positional=False",
|
||||
"control": "F5-shopvisit",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { Scene } from @caseapp:scene;\nimport { Link } from @caseapp:link;\ndeclare global scene: Scene = new Scene.make(10);\n[Frame] fn frame() -> void { let value=Link.read(scene); if value!=10 { let failure=1/0; } }\n",
|
||||
"src/scene/mod.barrel": "pub struct Scene;\n",
|
||||
"src/scene/main.pbs": "declare struct Scene(value: int) { ctor make(value: int) { this.value=value; } fn read() -> int { return this.value; } }\n",
|
||||
"src/link/mod.barrel": "pub service Link;\n",
|
||||
"src/link/main.pbs": "import { Scene } from @caseapp:scene;\ndeclare service Link { fn read(scene: Scene) -> int { return scene.read(); } }\n"
|
||||
},
|
||||
"sourceSha256": "f84b4a4f6eb21100dfff74f26e4f453d4300d3e2dd79d70ee9b3992ed4c8d09f"
|
||||
},
|
||||
{
|
||||
"id": "F5-scene-alias",
|
||||
"family": "imported-struct-construction",
|
||||
"description": "Imported Scene, alias=WorldScene, positional=False",
|
||||
"control": "F5-shopvisit",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { Scene as WorldScene } from @caseapp:scene;\nimport { Link } from @caseapp:link;\ndeclare global scene: WorldScene = new WorldScene.make(10);\n[Frame] fn frame() -> void { let value=Link.read(scene); if value!=10 { let failure=1/0; } }\n",
|
||||
"src/scene/mod.barrel": "pub struct Scene;\n",
|
||||
"src/scene/main.pbs": "declare struct Scene(value: int) { ctor make(value: int) { this.value=value; } fn read() -> int { return this.value; } }\n",
|
||||
"src/link/mod.barrel": "pub service Link;\n",
|
||||
"src/link/main.pbs": "import { Scene } from @caseapp:scene;\ndeclare service Link { fn read(scene: Scene) -> int { return scene.read(); } }\n"
|
||||
},
|
||||
"sourceSha256": "0f53a73f0f969919df0ad0df8a93e5b8e8db552310b69d37cae0f3ff9d625959"
|
||||
},
|
||||
{
|
||||
"id": "F5-scene-positional",
|
||||
"family": "imported-struct-construction",
|
||||
"description": "Imported Scene, alias=None, positional=True",
|
||||
"control": "F5-shopvisit",
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "import { Scene } from @caseapp:scene;\nimport { Link } from @caseapp:link;\ndeclare global scene: Scene = new Scene(10);\n[Frame] fn frame() -> void { let value=Link.read(scene); if value!=10 { let failure=1/0; } }\n",
|
||||
"src/scene/mod.barrel": "pub struct Scene;\n",
|
||||
"src/scene/main.pbs": "declare struct Scene(value: int) { ctor make(value: int) { this.value=value; } fn read() -> int { return this.value; } }\n",
|
||||
"src/link/mod.barrel": "pub service Link;\n",
|
||||
"src/link/main.pbs": "import { Scene } from @caseapp:scene;\ndeclare service Link { fn read(scene: Scene) -> int { return scene.read(); } }\n"
|
||||
},
|
||||
"sourceSha256": "65b3452b0e30037b1e744de8e36dc629f2f5d11f5fb97068566d1a4b38baaeb7"
|
||||
},
|
||||
{
|
||||
"id": "runtime-trap-control",
|
||||
"family": "harness-control",
|
||||
"description": "Deliberate guest fault proves frame assertions are executed",
|
||||
"control": null,
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "fault",
|
||||
"files": {
|
||||
"prometeu.json": "{\n \"name\": \"caseapp\",\n \"version\": \"1.0.0\",\n \"language\": \"pbs\",\n \"stdlib\": \"1\",\n \"target\": \"Game\",\n \"dependencies\": []\n}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { let failure=1/0; }\n"
|
||||
},
|
||||
"sourceSha256": "60013483001b50eb3e7f8a9360142ec5ab49f8ca56edf1d6b0ca5b32251510d9"
|
||||
}
|
||||
]
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"cases": [
|
||||
{
|
||||
"id": "contextual-overloads",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare struct Probe() { fn value() -> int { return 1; } fn value() -> bool { return true; } }\ndeclare global data: Probe = new Probe();\nfn check() -> bool { return data.value(); }\n[Frame] fn frame() -> void { let number: int=data.value(); let flag: bool=data.value(); if !check() || !flag || number!=1 { let failure=1/0; } }\n"
|
||||
},
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"sourceSha256": "c86450c4288ddbe77a90160b93a4d1df6c394fafdbd6de2541f9e3a296eafc07"
|
||||
},
|
||||
{
|
||||
"id": "receiver-argument-order",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/main.pbs": "declare global calls: int=0;\ndeclare struct Probe() { fn read(value: int) -> int { return value; } }\ndeclare global data: Probe=new Probe();\nfn receiver() -> Probe { calls=calls*10+1; return data; }\nfn arg() -> int { calls=calls*10+2; return 3; }\n[Frame] fn frame() -> void { calls=0; let value=receiver().read(arg()); if value!=3 || calls!=12 { let failure=1/0; } }\n"
|
||||
},
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"sourceSha256": "c37878a556424c11771db991be61c589a8243667c5b0c957216f23990ef88ca6"
|
||||
},
|
||||
{
|
||||
"id": "shared-global-storage",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\nmod global count;\nmod fn increment() -> int;\n",
|
||||
"src/state.pbs": "declare global count: int=0;\nfn increment() -> int { count+=1; return count; }\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { count=4; let value=increment(); if value!=5 || count!=5 { let failure=1/0; } }\n"
|
||||
},
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"sourceSha256": "95b641e1371de5bae0339f29bd32d44c81e5861b18ab0d1054e738c958b3ce9f"
|
||||
},
|
||||
{
|
||||
"id": "shared-service-singleton",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\nmod service Counter;\nmod fn instance() -> Counter;\n",
|
||||
"src/state.pbs": "declare service Counter {}\nfn instance() -> Counter { return Counter; }\n",
|
||||
"src/main.pbs": "import { referenceEquals } from @sdk:hash;\n[Frame] fn frame() -> void { if !referenceEquals<Counter>(Counter,instance()) { let failure=1/0; } }\n"
|
||||
},
|
||||
"expectedCompile": "compiled",
|
||||
"expectedRuntime": "passed",
|
||||
"sourceSha256": "e5a21998b2eb8f7e47a5818f59081d080dd332cc36bbb032ddcff07b3335f3d5"
|
||||
},
|
||||
{
|
||||
"id": "private-overload",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\nmod fn helper(value: int) -> int;\n",
|
||||
"src/helper.pbs": "fn helper(value: int) -> int { return value; }\nfn helper(value: bool) -> bool { return value; }\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { let flag=helper(true); }\n"
|
||||
},
|
||||
"expectedCompile": "rejected",
|
||||
"expectedRuntime": "not_run",
|
||||
"sourceSha256": "59d9ab7560f89be231bd82243bcb9114a23c3de2e40b0f02c78669ed56dc917d"
|
||||
},
|
||||
{
|
||||
"id": "private-global",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/state.pbs": "declare global count: int=0;\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { count=4; }\n"
|
||||
},
|
||||
"expectedCompile": "rejected",
|
||||
"expectedRuntime": "not_run",
|
||||
"sourceSha256": "d001a6d5c611d76d3fbf7dd08dcd3391dfe4e69c40b3aa18c69c2fec4c1f8114"
|
||||
},
|
||||
{
|
||||
"id": "private-service",
|
||||
"files": {
|
||||
"prometeu.json": "{\"name\": \"caseapp\", \"version\": \"1.0.0\", \"language\": \"pbs\", \"stdlib\": \"1\", \"target\": \"Game\", \"dependencies\": []}\n",
|
||||
"src/mod.barrel": "pub fn frame() -> void;\n",
|
||||
"src/state.pbs": "declare service Counter { fn value() -> int { return 1; } }\n",
|
||||
"src/main.pbs": "[Frame] fn frame() -> void { let value=Counter.value(); }\n"
|
||||
},
|
||||
"expectedCompile": "rejected",
|
||||
"expectedRuntime": "not_run",
|
||||
"sourceSha256": "1c5386df70cde3889fd16f20fafb7ace636aa32c457a9bea0bef0b35cfc99a07"
|
||||
}
|
||||
]
|
||||
}
|
||||
+34
-2
@@ -1,5 +1,8 @@
|
||||
package p.studio.compiler.backend.bytecode;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.SourceAttribution;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -335,7 +338,20 @@ public class BytecodeEmitter {
|
||||
int returnSlots,
|
||||
int maxStackSlots,
|
||||
ReadOnlyList<Operation> operations,
|
||||
p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata) {
|
||||
p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata,
|
||||
String moduleName,
|
||||
SourceAttribution attribution,
|
||||
java.util.Map<String, Object> semanticFacts) {
|
||||
public FunctionPlan(String name, int paramSlots, int localSlots, int returnSlots, int maxStackSlots,
|
||||
ReadOnlyList<Operation> operations,
|
||||
p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata, String moduleName, SourceAttribution attribution) {
|
||||
this(name, paramSlots, localSlots, returnSlots, maxStackSlots, operations, metadata, moduleName, attribution, java.util.Map.of());
|
||||
}
|
||||
public FunctionPlan(String name, int paramSlots, int localSlots, int returnSlots, int maxStackSlots,
|
||||
ReadOnlyList<Operation> operations,
|
||||
p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata) {
|
||||
this(name, paramSlots, localSlots, returnSlots, maxStackSlots, operations, metadata, null, null);
|
||||
}
|
||||
public FunctionPlan(
|
||||
String name,
|
||||
int paramSlots,
|
||||
@@ -349,6 +365,7 @@ public class BytecodeEmitter {
|
||||
public FunctionPlan {
|
||||
Objects.requireNonNull(name, "name");
|
||||
operations = operations == null ? ReadOnlyList.empty() : operations;
|
||||
semanticFacts = p.studio.utilities.json.ImmutableJson.object(semanticFacts);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,7 +413,16 @@ public class BytecodeEmitter {
|
||||
Integer expectedArgSlots,
|
||||
Integer expectedRetSlots,
|
||||
BytecodeModule.SourceSpan span,
|
||||
p.studio.compiler.backend.irvm.IRVMInstruction registryInstruction) {
|
||||
p.studio.compiler.backend.irvm.IRVMInstruction registryInstruction,
|
||||
SourceAttribution attribution) {
|
||||
public Operation(OperationKind kind, int immediate, BytecodeModule.SyscallDecl syscallDecl,
|
||||
Integer expectedArgSlots, Integer expectedRetSlots, BytecodeModule.SourceSpan span,
|
||||
p.studio.compiler.backend.irvm.IRVMInstruction registryInstruction) {
|
||||
this(kind, immediate, syscallDecl, expectedArgSlots, expectedRetSlots, span, registryInstruction,
|
||||
SourceAttribution.source(span == null || span.fileId() < 0 ? null
|
||||
: new Span(new FileId(span.fileId()),
|
||||
span.start(), span.end())));
|
||||
}
|
||||
public Operation(
|
||||
OperationKind kind,
|
||||
int immediate,
|
||||
@@ -409,6 +435,12 @@ public class BytecodeEmitter {
|
||||
|
||||
public Operation {
|
||||
Objects.requireNonNull(kind, "kind");
|
||||
attribution = attribution == null
|
||||
? SourceAttribution.unknown("no-source-span") : attribution;
|
||||
}
|
||||
|
||||
public Operation withAttribution(SourceAttribution origin) {
|
||||
return new Operation(kind, immediate, syscallDecl, expectedArgSlots, expectedRetSlots, span, registryInstruction, origin);
|
||||
}
|
||||
|
||||
public static Operation halt() {
|
||||
|
||||
+15
@@ -1,15 +1,30 @@
|
||||
package p.studio.compiler.backend.bytecode;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticContext;
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import java.util.Map;
|
||||
|
||||
public class BytecodeMarshalingException extends RuntimeException {
|
||||
private final BytecodeMarshalingErrorCode code;
|
||||
private final DiagnosticContext context;
|
||||
|
||||
public BytecodeMarshalingException(
|
||||
final BytecodeMarshalingErrorCode code,
|
||||
final String message) {
|
||||
this(code, message, FailureKind.UNKNOWN, Map.of());
|
||||
}
|
||||
|
||||
public BytecodeMarshalingException(BytecodeMarshalingErrorCode code, String message,
|
||||
FailureKind kind, Map<String, Object> parameters) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.context = new DiagnosticContext(null, null, null, kind, parameters)
|
||||
.withEnrichment(kind == FailureKind.VERIFICATION_LIMIT
|
||||
? p.studio.compiler.source.diagnostics.DiagnosticDescriptions.describe("compiler.verify.resource-limit", Map.of()) : Map.of());
|
||||
}
|
||||
|
||||
public DiagnosticContext context() { return context; }
|
||||
|
||||
public BytecodeMarshalingErrorCode code() {
|
||||
return code;
|
||||
}
|
||||
|
||||
+11
-3
@@ -1,5 +1,6 @@
|
||||
package p.studio.compiler.backend.bytecode;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import p.studio.compiler.backend.registry.LinkedRegistry;
|
||||
import p.studio.compiler.backend.irvm.IRVMIntrinsicRegistry;
|
||||
import p.studio.compiler.backend.irvm.IRVMIntrinsicDefinition.Carrier;
|
||||
@@ -12,7 +13,8 @@ public class BytecodePreloadVerifierService {
|
||||
public void verify(BytecodeModule module) {
|
||||
try { verifyRegistry(module); }
|
||||
catch (IllegalArgumentException | ArithmeticException error) {
|
||||
throw new BytecodeMarshalingException(BytecodeMarshalingErrorCode.MARSHAL_VERIFY_REGISTRY_INVALID, error.getMessage());
|
||||
throw new BytecodeMarshalingException(BytecodeMarshalingErrorCode.MARSHAL_VERIFY_REGISTRY_INVALID, error.getMessage(),
|
||||
FailureKind.INTERNAL_FAILURE, Map.of());
|
||||
}
|
||||
}
|
||||
private void verifyRegistry(BytecodeModule module) {
|
||||
@@ -101,11 +103,11 @@ public class BytecodePreloadVerifierService {
|
||||
long work=0;
|
||||
while(!queue.isEmpty()) {
|
||||
int pc=queue.remove();var state=states.get(pc).copy();var instruction=code.get(pc);
|
||||
check((work+=1L+state.locals.length+state.stack.size())<=268_435_456L,"verification work limit");
|
||||
checkResourceLimit(work+=1L+state.locals.length+state.stack.size(),268_435_456L,"work");
|
||||
transfer(m,r,index,instruction,state,false);
|
||||
for(int successor:successors(instruction,f.codeOffset(),end)) {
|
||||
if(successor==end) {check(state.stack.size()==f.returnSlots(),"function-end result height");continue;}
|
||||
var old=states.get(successor);if(old==null){check((long)(states.size()+1)*(locals.length+f.maxStackSlots())*24<=128L*1024*1024,"verification scratch limit");states.put(successor,state.copy());queue.add(successor);}
|
||||
var old=states.get(successor);if(old==null){checkResourceLimit((long)(states.size()+1)*(locals.length+f.maxStackSlots())*24,128L*1024*1024,"scratch");states.put(successor,state.copy());queue.add(successor);}
|
||||
else {check(old.stack.size()==state.stack.size(),"join height mismatch");boolean changed=false;
|
||||
for(int i=0;i<old.locals.length;i++)if(!old.locals[i].equals(state.locals[i])&&!old.locals[i].equals(Fact.UNKNOWN)){old.locals[i]=Fact.UNKNOWN;changed=true;}
|
||||
for(int i=0;i<old.stack.size();i++)if(!old.stack.get(i).equals(state.stack.get(i))&&!old.stack.get(i).equals(Fact.UNKNOWN)){old.stack.set(i,Fact.UNKNOWN);changed=true;}
|
||||
@@ -277,5 +279,11 @@ public class BytecodePreloadVerifierService {
|
||||
private static Array array(LinkedRegistry r,int id){check(type(r,id).body() instanceof Array,"Array category");return (Array)type(r,id).body();}
|
||||
private static int u16(byte[] code,int offset){return ByteBuffer.wrap(code,offset,2).order(ByteOrder.LITTLE_ENDIAN).getShort()&65535;}
|
||||
private static int i32(byte[] code,int offset){return ByteBuffer.wrap(code,offset,4).order(ByteOrder.LITTLE_ENDIAN).getInt();}
|
||||
static void checkResourceLimit(long actual, long limit, String resource) {
|
||||
if (actual > limit) throw new BytecodeMarshalingException(
|
||||
BytecodeMarshalingErrorCode.MARSHAL_VERIFY_REGISTRY_INVALID, "verification " + resource + " limit",
|
||||
FailureKind.VERIFICATION_LIMIT,
|
||||
Map.of("resource", resource, "actual", actual, "limit", limit));
|
||||
}
|
||||
private static void check(boolean ok,String message){if(!ok)throw new IllegalArgumentException(message);}
|
||||
}
|
||||
|
||||
+42
-1
@@ -1,19 +1,60 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class IRVMValidationException extends RuntimeException {
|
||||
private final IRVMValidationErrorCode code;
|
||||
private final int functionIndex;
|
||||
private final int pc;
|
||||
private final DiagnosticContext context;
|
||||
private final List<RelatedSpan> related;
|
||||
|
||||
public IRVMValidationException(
|
||||
final IRVMValidationErrorCode code,
|
||||
final String message,
|
||||
final int functionIndex,
|
||||
final int pc) {
|
||||
super(message);
|
||||
this(code, message, functionIndex, pc, DiagnosticContext.unknown(), List.of(), null);
|
||||
}
|
||||
|
||||
private IRVMValidationException(IRVMValidationErrorCode code, String message, int functionIndex, int pc,
|
||||
DiagnosticContext context, List<RelatedSpan> related, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = code;
|
||||
this.functionIndex = functionIndex;
|
||||
this.pc = pc;
|
||||
this.context = context;
|
||||
this.related = List.copyOf(related);
|
||||
}
|
||||
|
||||
public DiagnosticContext context() { return context; }
|
||||
public List<RelatedSpan> related() { return related; }
|
||||
|
||||
public IRVMValidationException withParameters(Map<String, Object> parameters) {
|
||||
return enriched(context.withParameters(parameters), related);
|
||||
}
|
||||
|
||||
public IRVMValidationException enriched(DiagnosticContext context, List<RelatedSpan> related) {
|
||||
return new IRVMValidationException(code, getMessage(), functionIndex, pc, context, related, this);
|
||||
}
|
||||
|
||||
public IRVMValidationException at(String stage, String point, String passName) {
|
||||
var verification = context.verification();
|
||||
if (verification != null) verification = verification.at(point, passName);
|
||||
return enriched(new DiagnosticContext(stage, verification, context.attribution(), context.failureKind(),
|
||||
context.parameters(), context.enrichment()), related);
|
||||
}
|
||||
|
||||
public p.studio.compiler.messages.BuildingIssue toIssue(String stage, String message) {
|
||||
var span = context.attribution().span();
|
||||
return p.studio.compiler.messages.BuildingIssue.builder().error(true).code(code.name()).phase(stage)
|
||||
.message(message).exception(this).functionIndex(functionIndex).pc(pc)
|
||||
.sourceSpan(span).fileId(span == null ? null : span.getFileId().getId())
|
||||
.start(span == null ? null : (int) Math.min(Integer.MAX_VALUE, span.getStart()))
|
||||
.end(span == null ? null : (int) Math.min(Integer.MAX_VALUE, span.getEnd()))
|
||||
.context(context.withStage(stage)).related(related).build();
|
||||
}
|
||||
|
||||
public IRVMValidationErrorCode code() {
|
||||
|
||||
+39
-2
@@ -1,6 +1,7 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import p.studio.compiler.backend.bytecode.BytecodeEmitter;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.HashMap;
|
||||
@@ -45,6 +46,42 @@ public class IRVMValidator {
|
||||
}
|
||||
|
||||
private void validateFunction(
|
||||
final IRVMModule module, final BytecodeEmitter.FunctionPlan functionPlan,
|
||||
final int functionIndex, final boolean rejectInternalOpcodes) {
|
||||
try {
|
||||
validateFunctionBody(module, functionPlan, functionIndex, rejectInternalOpcodes);
|
||||
} catch (IRVMValidationException failure) {
|
||||
var function = module.functions().get(functionIndex);
|
||||
var attribution = SourceAttribution.unknown(functionPlan == null ? "no-emission-plan" : "no-source-span");
|
||||
if (functionPlan != null) {
|
||||
var pc = 0;
|
||||
for (var i = 0; i < function.instructions().size(); i++) {
|
||||
if (pc == failure.pc()) {
|
||||
attribution = functionPlan.operations().get(i).attribution();
|
||||
break;
|
||||
}
|
||||
pc += function.instructions().get(i).encodedSize();
|
||||
}
|
||||
}
|
||||
var related = new java.util.ArrayList<>(failure.related());
|
||||
if (functionPlan != null && functionPlan.attribution() != null && functionPlan.attribution().span() != null) {
|
||||
related.add(new RelatedSpan("Enclosing function", functionPlan.attribution().span(), "function", "context"));
|
||||
}
|
||||
var check = switch (failure.code()) {
|
||||
case MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT -> "compiler.verify.ret-stack-height";
|
||||
case MARSHAL_VERIFY_PRECHECK_STACK_MISMATCH_JOIN -> "compiler.verify.join-stack-height";
|
||||
default -> null;
|
||||
};
|
||||
var enrichment = check == null ? failure.context().enrichment() : DiagnosticDescriptions.describe(check,
|
||||
functionPlan == null ? java.util.Map.of() : functionPlan.semanticFacts());
|
||||
throw failure.enriched(new DiagnosticContext(null,
|
||||
new VerificationContext(null, null, "irvm-function", "byte", functionIndex, failure.pc(),
|
||||
function.name(), functionPlan == null ? null : functionPlan.moduleName()),
|
||||
attribution, FailureKind.INTERNAL_FAILURE, failure.context().parameters(), enrichment), related);
|
||||
}
|
||||
}
|
||||
|
||||
private void validateFunctionBody(
|
||||
final IRVMModule module,
|
||||
final BytecodeEmitter.FunctionPlan functionPlan,
|
||||
final int functionIndex,
|
||||
@@ -165,7 +202,7 @@ public class IRVMValidator {
|
||||
IRVMValidationErrorCode.MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT,
|
||||
"ret stack height mismatch. expected=%d actual=%d".formatted(function.returnSlots(), outHeight),
|
||||
functionIndex,
|
||||
instrPc);
|
||||
instrPc).withParameters(java.util.Map.of("expectedHeight", function.returnSlots(), "actualHeight", outHeight));
|
||||
}
|
||||
enqueueSuccessors(
|
||||
module,
|
||||
@@ -284,7 +321,7 @@ public class IRVMValidator {
|
||||
IRVMValidationErrorCode.MARSHAL_VERIFY_PRECHECK_STACK_MISMATCH_JOIN,
|
||||
"stack height mismatch at join. existing=%d new=%d".formatted(existing, newHeight),
|
||||
functionIndex,
|
||||
pc);
|
||||
pc).withParameters(java.util.Map.of("existingHeight", existing, "incomingHeight", newHeight));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+19
-3
@@ -7,6 +7,7 @@ import p.studio.compiler.models.IRBackendExecutableFunction;
|
||||
import p.studio.compiler.models.IRSyntheticCallableKind;
|
||||
import p.studio.compiler.models.IRHiddenGlobalKind;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.SourceAttribution;
|
||||
import p.studio.compiler.source.identifiers.CallableId;
|
||||
import p.studio.compiler.source.identifiers.ModuleId;
|
||||
import p.studio.compiler.source.tables.ModuleReference;
|
||||
@@ -64,6 +65,9 @@ public class LowerToIRVMService {
|
||||
final var fn = ordered.get(i);
|
||||
if (fn.metadata() == null) throw new IllegalArgumentException("typed function metadata required: " + fn.callableName());
|
||||
final var parameterSlots = registry.parameterSlots(fn.metadata().signature());
|
||||
final var synthetic = backend.getSyntheticFunctions().stream().filter(candidate ->
|
||||
candidate.moduleId().equals(fn.moduleId()) && candidate.callableName().equals(fn.callableName()))
|
||||
.findFirst();
|
||||
final var resultSlots = registry.resultSlots(fn.metadata().signature());
|
||||
final var instructions = new ArrayList<IRVMInstruction>(fn.instructions().size());
|
||||
final var operations = new ArrayList<BytecodeEmitter.Operation>(fn.instructions().size());
|
||||
@@ -71,6 +75,7 @@ public class LowerToIRVMService {
|
||||
final var jumpPatches = new ArrayList<JumpPatch>();
|
||||
var functionPc = 0;
|
||||
for (final var instr : fn.instructions()) {
|
||||
final var firstOperation = operations.size();
|
||||
final var sourceSpan = toBytecodeSpan(fn.fileId().getId(), instr.span());
|
||||
switch (instr.kind()) {
|
||||
case REGISTRY -> {
|
||||
@@ -429,6 +434,11 @@ public class LowerToIRVMService {
|
||||
functionPc += IRVMOp.JMP_IF_FALSE.immediateSize() + 2;
|
||||
}
|
||||
}
|
||||
final var origin = synthetic.isPresent()
|
||||
? SourceAttribution.generated(synthetic.get().origin().span()) : SourceAttribution.source(instr.span());
|
||||
for (var opIndex = firstOperation; opIndex < operations.size(); opIndex++) {
|
||||
operations.set(opIndex, operations.get(opIndex).withAttribution(origin));
|
||||
}
|
||||
}
|
||||
for (final var patch : jumpPatches) {
|
||||
final var targetPc = labelToPc.get(patch.targetLabel());
|
||||
@@ -449,7 +459,7 @@ public class LowerToIRVMService {
|
||||
} else {
|
||||
throw new IllegalStateException("unexpected jump op: " + patch.op().name());
|
||||
}
|
||||
operations.set(patch.operationIndex(), operation);
|
||||
operations.set(patch.operationIndex(), operation.withAttribution(operations.get(patch.operationIndex()).attribution()));
|
||||
}
|
||||
loweredFunctions.add(new IRVMFunction(
|
||||
fn.callableName(),
|
||||
@@ -464,7 +474,9 @@ public class LowerToIRVMService {
|
||||
fn.localSlots(),
|
||||
resultSlots,
|
||||
fn.maxStackSlots(),
|
||||
ReadOnlyList.wrap(operations), fn.metadata()));
|
||||
ReadOnlyList.wrap(operations), fn.metadata(),
|
||||
fn.moduleId().isNone() || moduleSortKey(backend, fn.moduleId()).isBlank() ? null : moduleSortKey(backend, fn.moduleId()),
|
||||
synthetic.isPresent() ? SourceAttribution.generated(synthetic.get().origin().span()) : SourceAttribution.function(fn.span()), fn.semanticFacts()));
|
||||
}
|
||||
|
||||
final var imageImplementations = new ArrayList<p.studio.compiler.models.registry.IRRegistry.Implementation>();
|
||||
@@ -485,7 +497,11 @@ public class LowerToIRVMService {
|
||||
ReadOnlyList.wrap(constPool),
|
||||
ReadOnlyList.empty(),
|
||||
ReadOnlyList.wrap(emissionFunctions), imageRegistry));
|
||||
validator.validate(program, false);
|
||||
try {
|
||||
validator.validate(program, false);
|
||||
} catch (IRVMValidationException failure) {
|
||||
throw failure.at("BACKEND_LOWER_TO_IRVM", "lowering-output", null);
|
||||
}
|
||||
return program;
|
||||
}
|
||||
|
||||
|
||||
+15
-7
@@ -41,7 +41,7 @@ public class OptimizeIRVMService {
|
||||
}
|
||||
var current = program;
|
||||
final var executedPassNames = new ArrayList<String>();
|
||||
validator.validate(current, false);
|
||||
validateAt(current, "optimization-input", null);
|
||||
for (final var pass : passes) {
|
||||
if (pass == null || !pass.enabled()) {
|
||||
continue;
|
||||
@@ -52,7 +52,7 @@ public class OptimizeIRVMService {
|
||||
if (!beforeProfile.equals(current.module().vmProfile())) {
|
||||
throw new IllegalArgumentException("pass changed vm profile: " + pass.name());
|
||||
}
|
||||
validator.validate(current, false);
|
||||
validateAt(current, "optimization-pass-output", pass.name());
|
||||
}
|
||||
lastExecutedPassNames = List.copyOf(executedPassNames);
|
||||
return current;
|
||||
@@ -62,6 +62,14 @@ public class OptimizeIRVMService {
|
||||
return lastExecutedPassNames;
|
||||
}
|
||||
|
||||
private void validateAt(IRVMProgram program, String point, String pass) {
|
||||
try {
|
||||
validator.validate(program, false);
|
||||
} catch (IRVMValidationException failure) {
|
||||
throw failure.at("BACKEND_OPTIMIZE_IRVM", point, pass);
|
||||
}
|
||||
}
|
||||
|
||||
static IRVMPass unreachableInstructionEliminationPass() {
|
||||
return new UnreachableInstructionEliminationPass();
|
||||
}
|
||||
@@ -225,7 +233,7 @@ public class OptimizeIRVMService {
|
||||
functionPlan.localSlots(),
|
||||
functionPlan.returnSlots(),
|
||||
functionPlan.maxStackSlots(),
|
||||
ReadOnlyList.wrap(newOperations), functionPlan.metadata());
|
||||
ReadOnlyList.wrap(newOperations), functionPlan.metadata(), functionPlan.moduleName(), functionPlan.attribution(), functionPlan.semanticFacts());
|
||||
return new FunctionRewrite(rewrittenFunction, rewrittenPlan, changed);
|
||||
}
|
||||
|
||||
@@ -256,13 +264,13 @@ public class OptimizeIRVMService {
|
||||
final int targetPc) {
|
||||
final var span = operation == null ? null : operation.span();
|
||||
if (jumpOp == IRVMOp.JMP) {
|
||||
return BytecodeEmitter.Operation.jmp(targetPc, span);
|
||||
return BytecodeEmitter.Operation.jmp(targetPc, span).withAttribution(operation.attribution());
|
||||
}
|
||||
if (jumpOp == IRVMOp.JMP_IF_TRUE) {
|
||||
return BytecodeEmitter.Operation.jmpIfTrue(targetPc, span);
|
||||
return BytecodeEmitter.Operation.jmpIfTrue(targetPc, span).withAttribution(operation.attribution());
|
||||
}
|
||||
if (jumpOp == IRVMOp.JMP_IF_FALSE) {
|
||||
return BytecodeEmitter.Operation.jmpIfFalse(targetPc, span);
|
||||
return BytecodeEmitter.Operation.jmpIfFalse(targetPc, span).withAttribution(operation.attribution());
|
||||
}
|
||||
throw new IllegalArgumentException("unexpected jump op for remap: " + jumpOp.name());
|
||||
}
|
||||
@@ -390,7 +398,7 @@ public class OptimizeIRVMService {
|
||||
functionPlan.localSlots(),
|
||||
functionPlan.returnSlots(),
|
||||
functionPlan.maxStackSlots(),
|
||||
ReadOnlyList.wrap(operations), functionPlan.metadata()),
|
||||
ReadOnlyList.wrap(operations), functionPlan.metadata(), functionPlan.moduleName(), functionPlan.attribution(), functionPlan.semanticFacts()),
|
||||
true);
|
||||
}
|
||||
|
||||
|
||||
+34
-6
@@ -3,6 +3,9 @@ package p.studio.compiler.workspaces;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.exceptions.BuildException;
|
||||
import p.studio.compiler.messages.BuildingIssue;
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticContext;
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import p.studio.compiler.source.diagnostics.SourceReference;
|
||||
import p.studio.compiler.models.AnalysisSnapshot;
|
||||
import p.studio.compiler.models.BuildResult;
|
||||
import p.studio.compiler.models.BuilderPipelineContext;
|
||||
@@ -72,7 +75,10 @@ public class BuilderPipelineService {
|
||||
final LogAggregator logs) {
|
||||
final var analysisSnapshot = this.analyze(ctx, logs);
|
||||
if (hasErrors(analysisSnapshot.diagnostics())) {
|
||||
throw new BuildException("issues found on pipeline stage: analyze");
|
||||
var stage = analysisSnapshot.diagnostics().stream().filter(BuildingIssue::isError)
|
||||
.map(issue -> issue.getContext().stageId()).filter(java.util.Objects::nonNull)
|
||||
.findFirst().orElse("analyze");
|
||||
throw failure("issues found on pipeline stage: analyze", null, analysisSnapshot.diagnostics(), stage, ctx);
|
||||
}
|
||||
final var diagnostics = run(ctx, logs, compile, new ArrayList<>(analysisSnapshot.diagnostics()), true);
|
||||
return new CompileResult(
|
||||
@@ -102,20 +108,42 @@ public class BuilderPipelineService {
|
||||
final List<BuildingIssue> diagnostics,
|
||||
final boolean failFast) {
|
||||
for (final var builderPipelineStage : stages) {
|
||||
final var issues = builderPipelineStage.run(ctx, logs);
|
||||
diagnostics.addAll(issues.asCollection());
|
||||
final p.studio.compiler.messages.BuildingIssueSink issues;
|
||||
var stage = builderPipelineStage.getClass().getSimpleName();
|
||||
try {
|
||||
issues = builderPipelineStage.run(ctx, logs);
|
||||
} catch (RuntimeException exception) {
|
||||
if (exception instanceof BuildException build && build.hasDiagnosticPayload()) {
|
||||
diagnostics.addAll(build.getDiagnostics());
|
||||
} else {
|
||||
// The boundary knows an operation failed, but does not guess its cause from exception text.
|
||||
diagnostics.add(BuildingIssue.builder().error(true).code("COMPILER_STAGE_OPERATION_FAILURE")
|
||||
.phase(stage).message(exception.getMessage()).exception(exception)
|
||||
.context(DiagnosticContext.unknown().withStage(stage).withFailureKind(FailureKind.UNKNOWN)).build());
|
||||
}
|
||||
throw failure("pipeline operation failed on stage: " + stage, exception, diagnostics, stage, ctx);
|
||||
}
|
||||
for (var issue : issues.asCollection()) {
|
||||
diagnostics.add(issue.getContext().stageId() == null
|
||||
? issue.toBuilder().context(issue.getContext().withStage(stage)).build() : issue);
|
||||
}
|
||||
printIssues(issues, logs);
|
||||
if (issues.hasErrors()) {
|
||||
if (failFast) {
|
||||
throw new BuildException("issues found on pipeline stage: " + builderPipelineStage.getClass().getSimpleName());
|
||||
throw failure("issues found on pipeline stage: " + stage, null, diagnostics, stage, ctx);
|
||||
}
|
||||
break;
|
||||
return List.copyOf(diagnostics);
|
||||
}
|
||||
}
|
||||
logs.using(log).info("builder pipeline completed successfully");
|
||||
logs.using(log).info("builder pipeline stage group completed successfully");
|
||||
return List.copyOf(diagnostics);
|
||||
}
|
||||
|
||||
private BuildException failure(String message, Throwable cause, List<BuildingIssue> diagnostics,
|
||||
String stage, BuilderPipelineContext ctx) {
|
||||
return new BuildException(message, cause, diagnostics, stage, SourceReference.snapshot(ctx.fileTable));
|
||||
}
|
||||
|
||||
private boolean hasErrors(final List<BuildingIssue> diagnostics) {
|
||||
for (final var diagnostic : diagnostics) {
|
||||
if (diagnostic.isError()) {
|
||||
|
||||
+4
@@ -1,5 +1,6 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.backend.bytecode.BytecodeEmitter;
|
||||
import p.studio.compiler.backend.bytecode.BytecodeMarshalingException;
|
||||
@@ -55,6 +56,9 @@ public class EmitBytecodePipelineStage implements PipelineStage {
|
||||
.error(true)
|
||||
.phase("BACKEND_EMIT_BYTECODE")
|
||||
.code(e.code().name())
|
||||
.context(e.context().withStage("BACKEND_EMIT_BYTECODE")
|
||||
.withFailureKind(e.context().failureKind() == FailureKind.UNKNOWN
|
||||
? FailureKind.INTERNAL_FAILURE : e.context().failureKind()))
|
||||
.message("[BUILD]: bytecode marshaling failed: " + e.getMessage())
|
||||
.exception(e));
|
||||
}
|
||||
|
||||
+9
-20
@@ -1,5 +1,6 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.FrontendRegistryService;
|
||||
import p.studio.compiler.messages.BuildingIssueSink;
|
||||
@@ -38,33 +39,21 @@ public class FrontendPhasePipelineStage implements PipelineStage {
|
||||
surface);
|
||||
final var diagnostics = DiagnosticSink.empty();
|
||||
ctx.irBackend = provider.compiler().compile(frontendPhaseContext, diagnostics, logs, issues);
|
||||
logs.using(log).debug("Frontend phase completed successfully!");
|
||||
adaptDiagnostics(diagnostics, issues);
|
||||
if (!issues.hasErrors()) logs.using(log).debug("Frontend phase completed successfully!");
|
||||
return issues;
|
||||
}
|
||||
|
||||
private void adaptDiagnostics(
|
||||
void adaptDiagnostics(
|
||||
final DiagnosticSink diagnostics,
|
||||
final BuildingIssueSink issues) {
|
||||
for (final var diagnostic : diagnostics) {
|
||||
final var span = diagnostic.getSpan();
|
||||
issues.report(builder -> builder
|
||||
.error(diagnostic.getSeverity().isError())
|
||||
.phase(diagnostic.getPhase().id())
|
||||
.code(diagnostic.getCode())
|
||||
.fileId(span.getFileId().isNone() ? null : span.getFileId().getId())
|
||||
.start(safeToInt(span.getStart()))
|
||||
.end(safeToInt(span.getEnd()))
|
||||
.message("[BUILD] %s :: %s @ %s:[%d,%d)".formatted(
|
||||
diagnostic.getCode(),
|
||||
diagnostic.getMessage(),
|
||||
span.getFileId(),
|
||||
span.getStart(),
|
||||
span.getEnd())));
|
||||
var context = diagnostic.getContext().withStage("FrontendPhasePipelineStage");
|
||||
if (diagnostic.getSeverity().isError()
|
||||
&& context.failureKind() == FailureKind.UNKNOWN) {
|
||||
context = context.withFailureKind(FailureKind.PROGRAM_REJECTION);
|
||||
}
|
||||
issues.add(p.studio.compiler.messages.BuildingIssue.fromDiagnostic(diagnostic).toBuilder().context(context).build());
|
||||
}
|
||||
}
|
||||
|
||||
private int safeToInt(final long value) {
|
||||
return value > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) Math.max(0L, value);
|
||||
}
|
||||
}
|
||||
|
||||
+14
-10
@@ -1,5 +1,7 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticContext;
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.backend.irvm.IRVMLoweringException;
|
||||
import p.studio.compiler.backend.irvm.IRVMValidationException;
|
||||
@@ -28,6 +30,9 @@ public class LowerToIRVMPipelineStage implements PipelineStage {
|
||||
.report(builder -> builder
|
||||
.error(true)
|
||||
.phase("BACKEND_LOWER_TO_IRVM")
|
||||
.context(DiagnosticContext.unknown()
|
||||
.withStage("BACKEND_LOWER_TO_IRVM")
|
||||
.withFailureKind(FailureKind.INTERNAL_FAILURE))
|
||||
.code("MARSHAL_FORMAT_STAGE_INPUT_MISSING")
|
||||
.message("[BUILD]: IRBackend is missing before LowerToIRVM stage"));
|
||||
}
|
||||
@@ -38,6 +43,9 @@ public class LowerToIRVMPipelineStage implements PipelineStage {
|
||||
.report(builder -> builder
|
||||
.error(true)
|
||||
.phase("BACKEND_LOWER_TO_IRVM")
|
||||
.context(DiagnosticContext.unknown()
|
||||
.withStage("BACKEND_LOWER_TO_IRVM")
|
||||
.withFailureKind(FailureKind.INTERNAL_FAILURE))
|
||||
.code(e.code().name())
|
||||
.fileId(e.fileId())
|
||||
.start(e.start())
|
||||
@@ -45,18 +53,14 @@ public class LowerToIRVMPipelineStage implements PipelineStage {
|
||||
.message("[BUILD]: lower to irvm failed: " + e.getMessage())
|
||||
.exception(e));
|
||||
} catch (IRVMValidationException e) {
|
||||
return BuildingIssueSink.empty()
|
||||
.report(builder -> builder
|
||||
.error(true)
|
||||
.phase("BACKEND_LOWER_TO_IRVM")
|
||||
.code(e.code().name())
|
||||
.functionIndex(e.functionIndex())
|
||||
.pc(e.pc())
|
||||
.message("[BUILD]: lower to irvm validation failed: " + e.getMessage())
|
||||
.exception(e));
|
||||
return BuildingIssueSink.empty().add(e.toIssue("BACKEND_LOWER_TO_IRVM",
|
||||
"[BUILD]: lower to irvm validation failed: " + e.getMessage()));
|
||||
} catch (IllegalArgumentException e) {
|
||||
return BuildingIssueSink.empty().report(builder -> builder.error(true)
|
||||
.phase("BACKEND_LOWER_TO_IRVM").code("LOWER_IRVM_INVALID_TYPED_REGISTRY")
|
||||
.phase("BACKEND_LOWER_TO_IRVM")
|
||||
.context(DiagnosticContext.unknown()
|
||||
.withStage("BACKEND_LOWER_TO_IRVM")
|
||||
.withFailureKind(FailureKind.INTERNAL_FAILURE)).code("LOWER_IRVM_INVALID_TYPED_REGISTRY")
|
||||
.message("[BUILD]: invalid common typed IR: " + e.getMessage()).exception(e));
|
||||
}
|
||||
return BuildingIssueSink.empty();
|
||||
|
||||
+7
-9
@@ -1,5 +1,7 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticContext;
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.backend.irvm.IRVMValidationException;
|
||||
import p.studio.compiler.backend.irvm.OptimizeIRVMService;
|
||||
@@ -33,20 +35,16 @@ public class OptimizeIRVMPipelineStage implements PipelineStage {
|
||||
try {
|
||||
ctx.optimizedIrvm = optimizeIRVMService.optimize(ctx.irvm);
|
||||
} catch (IRVMValidationException e) {
|
||||
return BuildingIssueSink.empty()
|
||||
.report(builder -> builder
|
||||
.error(true)
|
||||
.phase("BACKEND_OPTIMIZE_IRVM")
|
||||
.code(e.code().name())
|
||||
.functionIndex(e.functionIndex())
|
||||
.pc(e.pc())
|
||||
.message("[BUILD]: optimize irvm validation failed: " + e.getMessage())
|
||||
.exception(e));
|
||||
return BuildingIssueSink.empty().add(e.toIssue("BACKEND_OPTIMIZE_IRVM",
|
||||
"[BUILD]: optimize irvm validation failed: " + e.getMessage()));
|
||||
} catch (RuntimeException e) {
|
||||
return BuildingIssueSink.empty()
|
||||
.report(builder -> builder
|
||||
.error(true)
|
||||
.phase("BACKEND_OPTIMIZE_IRVM")
|
||||
.context(DiagnosticContext.unknown()
|
||||
.withStage("BACKEND_OPTIMIZE_IRVM")
|
||||
.withFailureKind(FailureKind.INTERNAL_FAILURE))
|
||||
.code("MARSHAL_VERIFY_PRECHECK_OPTIMIZE_RUNTIME_FAILURE")
|
||||
.message("[BUILD]: optimize irvm failed: " + e.getMessage())
|
||||
.exception(e));
|
||||
|
||||
+4
@@ -1,5 +1,6 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.backend.bytecode.BytecodeMarshalingException;
|
||||
import p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService;
|
||||
@@ -39,6 +40,9 @@ public class VerifyBytecodePipelineStage implements PipelineStage {
|
||||
.error(true)
|
||||
.phase("BACKEND_VERIFY_PRELOAD")
|
||||
.code(e.code().name())
|
||||
.context(e.context().withStage("BACKEND_VERIFY_PRELOAD")
|
||||
.withFailureKind(e.context().failureKind() == FailureKind.UNKNOWN
|
||||
? FailureKind.INTERNAL_FAILURE : e.context().failureKind()))
|
||||
.message("[BUILD]: preload verifier failed: " + e.getMessage())
|
||||
.exception(e));
|
||||
}
|
||||
|
||||
+5
@@ -1,5 +1,7 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import p.studio.compiler.source.diagnostics.DiagnosticContext;
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import p.studio.compiler.messages.BuildingIssueSink;
|
||||
import p.studio.compiler.models.BuilderPipelineContext;
|
||||
@@ -55,6 +57,9 @@ public class WriteBytecodeArtifactPipelineStage implements PipelineStage {
|
||||
.error(true)
|
||||
.phase("BACKEND_WRITE_ARTIFACT")
|
||||
.code("MARSHAL_ARTIFACT_WRITE_FAILED")
|
||||
.context(new DiagnosticContext("BACKEND_WRITE_ARTIFACT", null, null,
|
||||
FailureKind.INFRASTRUCTURE_FAILURE,
|
||||
java.util.Map.of("outputPath", outputPath.toString())))
|
||||
.message("[BUILD]: failed to write bytecode artifact: " + outputPath)
|
||||
.exception(e));
|
||||
}
|
||||
|
||||
+13
@@ -10,6 +10,19 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class BytecodePreloadVerifierServiceTest {
|
||||
|
||||
@Test
|
||||
void resourceGuardsMustKeepLimitCategoryAndValuesWithoutMessageParsing() {
|
||||
for (var resource : java.util.List.of("work", "scratch")) {
|
||||
var failure = assertThrows(BytecodeMarshalingException.class,
|
||||
() -> BytecodePreloadVerifierService.checkResourceLimit(11, 10, resource));
|
||||
assertEquals(BytecodeMarshalingErrorCode.MARSHAL_VERIFY_REGISTRY_INVALID, failure.code());
|
||||
assertEquals(p.studio.compiler.source.diagnostics.FailureKind.VERIFICATION_LIMIT, failure.context().failureKind());
|
||||
assertEquals("compiler.verify.resource-limit", failure.context().enrichment().get("checkId"));
|
||||
assertEquals(java.util.Map.of("resource", resource, "actual", 11L, "limit", 10L), failure.context().parameters());
|
||||
assertDoesNotThrow(() -> BytecodePreloadVerifierService.checkResourceLimit(10, 10, resource));
|
||||
}
|
||||
}
|
||||
|
||||
private final BytecodePreloadVerifierService service = new BytecodePreloadVerifierService();
|
||||
|
||||
@Test
|
||||
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package p.studio.compiler.backend.irvm;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.backend.bytecode.BytecodeEmitter;
|
||||
import p.studio.compiler.backend.bytecode.BytecodeEmitter.Operation;
|
||||
import p.studio.compiler.backend.bytecode.BytecodeModule;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import p.studio.utilities.structures.ReadOnlyList;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class IRVMAttributionTest {
|
||||
static final Span SOURCE = new Span(new FileId(7), 0, 9);
|
||||
|
||||
@Test
|
||||
void retMustRetainOriginCoordinatesAndStructuredHeights() {
|
||||
var failure = reject(program(1, List.of(Operation.ret().withAttribution(SourceAttribution.source(SOURCE)))));
|
||||
assertEquals(IRVMValidationErrorCode.MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT, failure.code());
|
||||
assertEquals("compiler.verify.ret-stack-height", failure.context().enrichment().get("checkId"));
|
||||
assertEquals(Map.of("expectedHeight", 1, "actualHeight", 0), failure.context().parameters());
|
||||
assertSame(SOURCE, failure.context().attribution().span());
|
||||
assertEquals("detection", failure.context().attribution().role());
|
||||
assertEquals("irvm-function", failure.context().verification().pcSpace());
|
||||
assertEquals("byte", failure.context().verification().pcUnit());
|
||||
assertEquals(0, failure.pc());
|
||||
assertEquals("probe", failure.context().verification().functionName());
|
||||
assertEquals("fixture:main", failure.context().verification().moduleName());
|
||||
assertEquals(FailureKind.INTERNAL_FAILURE, failure.context().failureKind());
|
||||
var issue = failure.at("BACKEND_LOWER_TO_IRVM", "lowering-output", null).toIssue("BACKEND_LOWER_TO_IRVM", failure.getMessage());
|
||||
assertEquals(7, issue.getFileId());
|
||||
assertEquals(0, issue.getStart());
|
||||
assertSame(SOURCE, issue.toDiagnostic().getSpan());
|
||||
assertEquals("lowering-output", issue.getContext().verification().validationPoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
void joinMustPointAtDestinationAndRetainConflictingHeights() {
|
||||
var failure = reject(program(0, List.of(Operation.pushI32(1, null), Operation.jmpIfTrue(18, null),
|
||||
Operation.pushI32(2, null), Operation.ret().withAttribution(SourceAttribution.source(SOURCE)))));
|
||||
assertEquals(IRVMValidationErrorCode.MARSHAL_VERIFY_PRECHECK_STACK_MISMATCH_JOIN, failure.code());
|
||||
assertEquals("compiler.verify.join-stack-height", failure.context().enrichment().get("checkId"));
|
||||
assertEquals(18, failure.pc());
|
||||
assertEquals(Map.of("existingHeight", 0, "incomingHeight", 1), failure.context().parameters());
|
||||
assertSame(SOURCE, failure.context().attribution().span());
|
||||
assertTrue(failure.related().stream().noneMatch(location -> location.getRelation().equals("cause")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void generatedAndMissingOriginsMustBeExplicit() {
|
||||
for (var origin : List.of(SourceAttribution.generated(SOURCE), SourceAttribution.generated(null),
|
||||
SourceAttribution.unknown("no-source-span"), SourceAttribution.unknown("unknown"))) {
|
||||
var failure = reject(program(1, List.of(Operation.ret().withAttribution(origin))));
|
||||
assertEquals(origin, failure.context().attribution());
|
||||
assertEquals(0, failure.pc());
|
||||
assertEquals("probe", failure.context().verification().functionName());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void functionContextMustNotReplaceMissingInstructionSpan() {
|
||||
var failure = reject(program(1, List.of(Operation.ret())));
|
||||
assertNull(failure.context().attribution().span());
|
||||
assertEquals("no-source-span", failure.context().attribution().absenceReason());
|
||||
assertEquals("function", failure.related().getFirst().getRelation());
|
||||
assertEquals("context", failure.related().getFirst().getRole());
|
||||
assertSame(SOURCE, failure.related().getFirst().getSpan());
|
||||
}
|
||||
|
||||
@Test
|
||||
void moduleOnlyValidationMustPreserveFailureWithoutInventingSource() {
|
||||
var p = program(1, List.of(Operation.ret().withAttribution(SourceAttribution.source(SOURCE))));
|
||||
var failure = assertThrows(IRVMValidationException.class, () -> new IRVMValidator().validate(p.module(), false));
|
||||
assertEquals("no-emission-plan", failure.context().attribution().absenceReason());
|
||||
assertNull(failure.context().attribution().span());
|
||||
assertEquals(0, failure.pc());
|
||||
assertEquals("probe", failure.context().verification().functionName());
|
||||
var withoutPlan = reject(new IRVMProgram(p.module()));
|
||||
assertEquals("no-emission-plan", withoutPlan.context().attribution().absenceReason());
|
||||
}
|
||||
|
||||
@Test
|
||||
void optimizationInputMustHaveItsOwnValidationPoint() {
|
||||
var failure = assertThrows(IRVMValidationException.class,
|
||||
() -> new OptimizeIRVMService().optimize(program(1, List.of(Operation.ret()))));
|
||||
assertEquals("optimization-input", failure.context().verification().validationPoint());
|
||||
assertNull(failure.context().verification().passName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failingPassMustUseShiftedOutputAndSurvivingOrigin() {
|
||||
var origin = SourceAttribution.generated(SOURCE);
|
||||
var input = program(0, List.of(Operation.jmp(6, null), Operation.ret().withAttribution(origin)));
|
||||
var simplify = OptimizeIRVMService.simplifyJumpToNextPcPass();
|
||||
var corrupt = new OptimizeIRVMService.IRVMPass() {
|
||||
public String name() { return "ControlledRetMismatch"; }
|
||||
public IRVMProgram apply(IRVMProgram checked) {
|
||||
return program(1, checked.emissionPlan().functions().getFirst().operations().asCollection().stream().toList());
|
||||
}
|
||||
};
|
||||
var failure = assertThrows(IRVMValidationException.class,
|
||||
() -> new OptimizeIRVMService(new IRVMValidator(), List.of(simplify, corrupt)).optimize(input));
|
||||
assertEquals(0, failure.pc(), "RET moved from PC 6 to PC 0");
|
||||
assertEquals(origin, failure.context().attribution());
|
||||
assertEquals("optimization-pass-output", failure.context().verification().validationPoint());
|
||||
assertEquals("ControlledRetMismatch", failure.context().verification().passName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void jumpRemappingMustRetainGeneratedOriginAndFunctionContext() {
|
||||
var origin = SourceAttribution.generated(SOURCE);
|
||||
var input = program(0, List.of(Operation.jmp(12, null).withAttribution(origin),
|
||||
Operation.jmp(18, null), Operation.jmp(18, null), Operation.ret()));
|
||||
var output = OptimizeIRVMService.normalizeRedundantJumpTargetsPass().apply(input);
|
||||
var plan = output.emissionPlan().functions().getFirst();
|
||||
assertEquals(18, plan.operations().getFirst().immediate());
|
||||
assertEquals(origin, plan.operations().getFirst().attribution());
|
||||
assertEquals("fixture:main", plan.moduleName());
|
||||
assertEquals("function", plan.attribution().locationKind());
|
||||
assertDoesNotThrow(() -> new IRVMValidator().validate(output, false));
|
||||
}
|
||||
|
||||
static IRVMProgram program(int resultSlots, List<Operation> operations) {
|
||||
var plan = new BytecodeEmitter.FunctionPlan("probe", 0, 0, resultSlots, 2,
|
||||
ReadOnlyList.wrap(operations), resultSlots == 0
|
||||
? p.studio.compiler.models.registry.IRRegistry.FunctionMetadata.empty() : null,
|
||||
"fixture:main", SourceAttribution.function(SOURCE));
|
||||
return new IRVMProgram(false, new BytecodeEmitter.EmissionPlan(0, ReadOnlyList.empty(),
|
||||
ReadOnlyList.empty(), ReadOnlyList.from(plan)));
|
||||
}
|
||||
|
||||
static IRVMValidationException reject(IRVMProgram program) {
|
||||
return assertThrows(IRVMValidationException.class, () -> new IRVMValidator().validate(program, false));
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package p.studio.compiler.integration;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.compiler.exceptions.BuildException;
|
||||
import p.studio.compiler.messages.BuilderPipelineConfig;
|
||||
import p.studio.compiler.models.BuilderPipelineContext;
|
||||
import p.studio.compiler.source.diagnostics.FailureKind;
|
||||
import p.studio.compiler.workspaces.BuilderPipelineService;
|
||||
import p.studio.utilities.logs.LogAggregator;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Exact source fixtures from AGD-0113: this qualifies diagnostics, not the PBS fix. */
|
||||
class PbsFacadeDiagnosticTest {
|
||||
@TempDir Path root;
|
||||
|
||||
@Test
|
||||
void realPbsRejectionMustKeepStructuredSourceAndNoFalseSuccess() throws Exception {
|
||||
var project = writeProject("F3-file-private");
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, project.toString()));
|
||||
var logs = new ArrayList<String>();
|
||||
var failure = assertThrows(BuildException.class,
|
||||
() -> BuilderPipelineService.INSTANCE.compile(ctx, LogAggregator.with(logs::add)));
|
||||
assertTrue(failure.hasDiagnosticPayload());
|
||||
var issue = failure.getDiagnostics().stream().filter(item ->
|
||||
"E_SEM_APPLY_NON_CALLABLE_TARGET".equals(item.getCode())).findFirst().orElseThrow();
|
||||
assertEquals(FailureKind.PROGRAM_REJECTION, issue.getContext().failureKind());
|
||||
assertEquals("FrontendPhasePipelineStage", failure.getFailedStage());
|
||||
assertNotNull(issue.getStart());
|
||||
assertTrue(issue.getEnd() > issue.getStart());
|
||||
assertEquals(project.resolve("src/main.pbs").toRealPath().toString(),
|
||||
failure.getSourceReferences().get(issue.getFileId()).canonicalPath());
|
||||
assertNull(issue.getPc());
|
||||
assertTrue(logs.stream().noneMatch(line -> line.contains("builder pipeline") && line.contains("completed successfully")));
|
||||
assertTrue(logs.stream().noneMatch(line -> line.contains("Frontend phase completed successfully")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void materializedControlMustStillCompileThroughPublicFacade() throws Exception {
|
||||
var project = writeProject("F1-local");
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, project.toString()));
|
||||
var result = BuilderPipelineService.INSTANCE.compile(ctx, LogAggregator.empty());
|
||||
assertNotNull(result.bytecodeBytes());
|
||||
assertTrue(result.diagnostics().stream().noneMatch(issue -> issue.isError()));
|
||||
}
|
||||
|
||||
private Path writeProject(String id) throws Exception {
|
||||
var project = root.resolve(id);
|
||||
for (var relative : id.equals("F3-file-private") ? List.of("prometeu.json", "src/mod.barrel", "src/main.pbs", "src/helpers.pbs") : List.of("prometeu.json", "src/mod.barrel", "src/main.pbs")) {
|
||||
var file = project.resolve(relative);
|
||||
Files.createDirectories(file.getParent());
|
||||
try (var source = getClass().getResourceAsStream("/production-diagnostics/" + id + "/" + relative)) {
|
||||
assertNotNull(source);
|
||||
Files.copy(source, file);
|
||||
}
|
||||
}
|
||||
return project;
|
||||
}
|
||||
}
|
||||
+25
@@ -25,6 +25,31 @@ class SyntheticFrontendPipelineTest {
|
||||
@TempDir
|
||||
Path projectRoot;
|
||||
|
||||
@Test
|
||||
void invalidCommonIrMustReachFacadeWithSourceWithoutPbs() throws IOException {
|
||||
writeSyntheticProject();
|
||||
Files.writeString(projectRoot.resolve("src/probe.synth"), "x");
|
||||
var provider = new SyntheticFrontendProvider(true);
|
||||
FrontendRegistryService.register(provider);
|
||||
try {
|
||||
var context = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, projectRoot.toString()));
|
||||
var failure = org.junit.jupiter.api.Assertions.assertThrows(p.studio.compiler.exceptions.BuildException.class,
|
||||
() -> BuilderPipelineService.INSTANCE.compile(context, LogAggregator.empty()));
|
||||
var issue = failure.getDiagnostics().stream().filter(item ->
|
||||
"MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT".equals(item.getCode())).findFirst().orElseThrow();
|
||||
assertTrue(failure.hasDiagnosticPayload());
|
||||
assertEquals("lowering-output", issue.getContext().verification().validationPoint());
|
||||
assertEquals(p.studio.compiler.source.diagnostics.FailureKind.INTERNAL_FAILURE, issue.getContext().failureKind());
|
||||
assertEquals(0, issue.getStart());
|
||||
assertEquals(projectRoot.resolve("src/probe.synth").toRealPath().toString(),
|
||||
failure.getSourceReferences().get(issue.getFileId()).canonicalPath());
|
||||
assertTrue(noPbsSources(projectRoot));
|
||||
org.junit.jupiter.api.Assertions.assertNull(context.irvm);
|
||||
} finally {
|
||||
FrontendRegistryService.unregister(SyntheticFrontendProvider.LANGUAGE_ID);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void compileMustEmitVerifiedBytecodeWithoutPbs() throws IOException {
|
||||
writeSyntheticProject();
|
||||
|
||||
+11
-6
@@ -23,6 +23,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class SyntheticFrontendPhaseService implements FrontendPhaseService {
|
||||
private final AtomicBoolean invoked = new AtomicBoolean();
|
||||
private final boolean invalidRet;
|
||||
|
||||
public SyntheticFrontendPhaseService() { this(false); }
|
||||
|
||||
public SyntheticFrontendPhaseService(boolean invalidRet) { this.invalidRet = invalidRet; }
|
||||
|
||||
public boolean invoked() {
|
||||
return invoked.get();
|
||||
@@ -40,6 +45,11 @@ public final class SyntheticFrontendPhaseService implements FrontendPhaseService
|
||||
final var fileId = new FileId(0);
|
||||
final var callableId = new CallableId(0);
|
||||
final var span = new Span(fileId, 0, 1);
|
||||
var instructions = new java.util.ArrayList<IRBackendExecutableFunction.Instruction>();
|
||||
if (invalidRet) instructions.add(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.PUSH_I32, ModuleId.none(), "", null, null, null, "1", null, null, null, span));
|
||||
instructions.add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,
|
||||
"", null, null, span));
|
||||
final var frame = new IRBackendExecutableFunction(
|
||||
fileId,
|
||||
moduleId,
|
||||
@@ -51,12 +61,7 @@ public final class SyntheticFrontendPhaseService implements FrontendPhaseService
|
||||
0,
|
||||
0,
|
||||
1,
|
||||
ReadOnlyList.from(new IRBackendExecutableFunction.Instruction(
|
||||
IRBackendExecutableFunction.InstructionKind.RET,
|
||||
"",
|
||||
null,
|
||||
null,
|
||||
span)),
|
||||
ReadOnlyList.wrap(instructions),
|
||||
span);
|
||||
final var frameRoot = new IRLifecycleCallableReference(
|
||||
moduleId,
|
||||
|
||||
+5
-1
@@ -13,7 +13,11 @@ public final class SyntheticFrontendProvider implements FrontendProvider {
|
||||
.allowedExtensions(ReadOnlySet.from("synth"))
|
||||
.sourceRoots(ReadOnlySet.from("src"))
|
||||
.build();
|
||||
private final SyntheticFrontendPhaseService compiler = new SyntheticFrontendPhaseService();
|
||||
private final SyntheticFrontendPhaseService compiler;
|
||||
|
||||
public SyntheticFrontendProvider() { this(false); }
|
||||
|
||||
public SyntheticFrontendProvider(boolean invalidRet) { compiler = new SyntheticFrontendPhaseService(invalidRet); }
|
||||
|
||||
@Override
|
||||
public FrontendSpec specification() {
|
||||
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package p.studio.compiler.workspaces;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.AppMode;
|
||||
import p.studio.compiler.exceptions.BuildException;
|
||||
import p.studio.compiler.messages.*;
|
||||
import p.studio.compiler.models.*;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import p.studio.compiler.source.identifiers.ProjectId;
|
||||
import p.studio.compiler.source.tables.FileTable;
|
||||
import p.studio.utilities.logs.LogAggregator;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class CompilerFailurePayloadTest {
|
||||
@Test
|
||||
void rejectedAnalysisMustReturnIssuesWithoutSuccessOrLaterStages() {
|
||||
var log = new ArrayList<String>();
|
||||
var pipeline = pipeline(List.of(new Rejected()), List.of((ctx, logs) -> fail("compile must not run")), List.of());
|
||||
var snapshot = pipeline.analyze(context("left"), LogAggregator.with(log::add));
|
||||
assertEquals("E_SEM_FIXTURE", snapshot.diagnostics().getFirst().getCode());
|
||||
assertEquals("Rejected", snapshot.diagnostics().getFirst().getContext().stageId());
|
||||
assertTrue(log.stream().noneMatch(line -> line.contains("completed successfully")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void compileMustPreserveAnalysisDiagnosticsAndIndependentSourceIdentities() {
|
||||
var pipeline = pipeline(List.of(new Rejected()), List.of((ctx, logs) -> fail("compile must not run")), List.of());
|
||||
var left = context("left");
|
||||
var right = context("right");
|
||||
var a = assertThrows(BuildException.class, () -> pipeline.compile(left, LogAggregator.empty()));
|
||||
var b = assertThrows(BuildException.class, () -> pipeline.compile(right, LogAggregator.empty()));
|
||||
left.fileTable = null; right.fileTable = null;
|
||||
assertTrue(a.hasDiagnosticPayload());
|
||||
assertEquals("Rejected", a.getFailedStage());
|
||||
assertEquals("E_SEM_FIXTURE", a.getDiagnostics().getFirst().getCode());
|
||||
assertEquals("/left/main.pbs", a.getSourceReferences().get(0).canonicalPath());
|
||||
assertEquals("/right/main.pbs", b.getSourceReferences().get(0).canonicalPath());
|
||||
assertEquals(FailureKind.PROGRAM_REJECTION, a.getDiagnostics().getFirst().getContext().failureKind());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failFastCompileAndBuildMustPreserveEarlierWarnings() {
|
||||
PipelineStage warning = (ctx, logs) -> BuildingIssueSink.empty().report(b -> b.code("W_FIXTURE").message("warning"));
|
||||
var compile = pipeline(List.of(warning), List.of(new Rejected()), List.of((ctx, logs) -> fail("build must not run")));
|
||||
var a = assertThrows(BuildException.class, () -> compile.compile(context("compile"), LogAggregator.empty()));
|
||||
assertEquals(List.of("W_FIXTURE", "E_SEM_FIXTURE"), a.getDiagnostics().stream().map(BuildingIssue::getCode).toList());
|
||||
var build = pipeline(List.of(warning), List.of(), List.of(new Rejected(), (ctx, logs) -> fail("later stage must not run")));
|
||||
var b = assertThrows(BuildException.class, () -> build.build(context("build"), LogAggregator.empty()));
|
||||
assertEquals(List.of("W_FIXTURE", "E_SEM_FIXTURE"), b.getDiagnostics().stream().map(BuildingIssue::getCode).toList());
|
||||
assertEquals("Rejected", b.getFailedStage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void technicalFailureMustNotBecomeAnEmptyAnalysis() {
|
||||
var cause = new IllegalStateException("technical fixture");
|
||||
var pipeline = pipeline(List.of((ctx, logs) -> { throw cause; }), List.of(), List.of());
|
||||
var failure = assertThrows(BuildException.class, () -> pipeline.analyze(context("technical"), LogAggregator.empty()));
|
||||
assertTrue(failure.hasDiagnosticPayload());
|
||||
assertSame(cause, failure.getCause());
|
||||
assertEquals("COMPILER_STAGE_OPERATION_FAILURE", failure.getDiagnostics().getFirst().getCode());
|
||||
assertEquals(FailureKind.UNKNOWN, failure.getDiagnostics().getFirst().getContext().failureKind());
|
||||
}
|
||||
|
||||
private BuilderPipelineService pipeline(List<PipelineStage> a, List<PipelineStage> c, List<PipelineStage> b) {
|
||||
return new BuilderPipelineService(a, c, b);
|
||||
}
|
||||
|
||||
private BuilderPipelineContext context(String root) {
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
ctx.resolvedWorkspace = new ResolvedWorkspace(new ProjectId(0), null, 1, AppMode.Game, null, null);
|
||||
var files = new FileTable(1);
|
||||
files.register(new SourceHandle(new ProjectId(0), Path.of("main.pbs"), Path.of("/" + root + "/main.pbs"),
|
||||
0, 0, path -> () -> { throw new AssertionError("snapshot must not read source"); }));
|
||||
ctx.fileTable = files;
|
||||
return ctx;
|
||||
}
|
||||
|
||||
private static class Rejected implements PipelineStage {
|
||||
public BuildingIssueSink run(BuilderPipelineContext ctx, LogAggregator logs) {
|
||||
return BuildingIssueSink.empty().report(b -> b.error(true).code("E_SEM_FIXTURE").phase("static-semantics")
|
||||
.message("rejected fixture").fileId(0).start(0).end(1)
|
||||
.context(DiagnosticContext.unknown().withFailureKind(FailureKind.PROGRAM_REJECTION)));
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package p.studio.compiler.workspaces.stages;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.messages.BuildingIssueSink;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class FrontendDiagnosticProjectionTest {
|
||||
@Test
|
||||
void frontendProjectionMustRetainMessageRelatedAndParameters() {
|
||||
var original = new Diagnostic(Severity.Error, "E_SEM_FIXTURE", DiagnosticPhase.STATIC_SEMANTICS,
|
||||
"fixture", Map.of("receiver", "Probe"), "original message", new Span(new FileId(2), 0, 3),
|
||||
List.of(new RelatedSpan("declaration", new Span(new FileId(3), 8, 12), "declaration", "context")),
|
||||
new DiagnosticContext(null, null, null, FailureKind.UNKNOWN, Map.of("arity", 2)));
|
||||
var diagnostics = DiagnosticSink.empty();
|
||||
diagnostics.report(original);
|
||||
var issues = BuildingIssueSink.empty();
|
||||
new FrontendPhasePipelineStage().adaptDiagnostics(diagnostics, issues);
|
||||
var issue = issues.asCollection().iterator().next();
|
||||
assertTrue(issues.hasErrors());
|
||||
assertEquals("original message", issue.getMessage());
|
||||
assertEquals("static-semantics", issue.getPhase());
|
||||
assertEquals(Map.of("receiver", "Probe"), issue.getPlaceholders());
|
||||
assertEquals(Map.of("arity", 2), issue.getContext().parameters());
|
||||
assertEquals(FailureKind.PROGRAM_REJECTION, issue.getContext().failureKind());
|
||||
assertEquals("FrontendPhasePipelineStage", issue.getContext().stageId());
|
||||
assertEquals("declaration", issue.toDiagnostic().getRelated().getFirst().getRelation());
|
||||
assertNull(issue.getPc());
|
||||
}
|
||||
}
|
||||
+27
@@ -17,6 +17,33 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LowerToIRVMPipelineStageTest {
|
||||
|
||||
@Test
|
||||
void validationMustPreserveOriginBeforeIrvmIsAssigned() {
|
||||
var span = new Span(new FileId(9), 12, 24);
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
ctx.irBackend = IRBackend.builder()
|
||||
.entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0))
|
||||
.modulePool(ReadOnlyList.from(new p.studio.compiler.source.tables.ModuleReference("fixture", ReadOnlyList.from("main"))))
|
||||
.executableFunctions(ReadOnlyList.from(new IRBackendExecutableFunction(
|
||||
new FileId(9), new p.studio.compiler.source.identifiers.ModuleId(0), "main", new CallableId(1),
|
||||
0, 30, 0, 0, 0, 1,
|
||||
ReadOnlyList.from(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.PUSH_I32,
|
||||
p.studio.compiler.source.identifiers.ModuleId.none(), "", null, null, null, "1", null, null, null, span),
|
||||
new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,
|
||||
"", null, null, span)), new Span(new FileId(9), 0, 30))))
|
||||
.build();
|
||||
var issues = new LowerToIRVMPipelineStage().run(ctx, LogAggregator.empty());
|
||||
var issue = issues.asCollection().iterator().next();
|
||||
assertNull(ctx.irvm);
|
||||
assertEquals("MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT", issue.getCode());
|
||||
assertEquals(9, issue.getFileId());
|
||||
assertEquals(12, issue.getStart());
|
||||
assertEquals(6, issue.getPc());
|
||||
assertEquals("lowering-output", issue.getContext().verification().validationPoint());
|
||||
assertEquals("fixture:main", issue.getContext().verification().moduleName());
|
||||
assertEquals(java.util.Map.of("expectedHeight", 0, "actualHeight", 1), issue.getContext().parameters());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runMustFailWhenIrBackendIsMissing() {
|
||||
final var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
|
||||
+20
@@ -15,6 +15,26 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class VerifyBytecodePipelineStageTest {
|
||||
|
||||
@Test
|
||||
void stageMustPreserveTypedVerificationLimit() {
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
ctx.bytecodeModule = new BytecodeModule(0, ReadOnlyList.empty(), ReadOnlyList.empty(), new byte[0], null,
|
||||
ReadOnlyList.empty(), ReadOnlyList.empty());
|
||||
var verifier = new p.studio.compiler.backend.bytecode.BytecodePreloadVerifierService() {
|
||||
public void verify(BytecodeModule module) {
|
||||
throw new p.studio.compiler.backend.bytecode.BytecodeMarshalingException(
|
||||
p.studio.compiler.backend.bytecode.BytecodeMarshalingErrorCode.MARSHAL_VERIFY_REGISTRY_INVALID,
|
||||
"controlled resource refusal", p.studio.compiler.source.diagnostics.FailureKind.VERIFICATION_LIMIT,
|
||||
java.util.Map.of("resource", "scratch", "actual", 11L, "limit", 10L));
|
||||
}
|
||||
};
|
||||
var issues = new VerifyBytecodePipelineStage(verifier).run(ctx, LogAggregator.empty());
|
||||
var issue = issues.asCollection().iterator().next();
|
||||
assertEquals(p.studio.compiler.source.diagnostics.FailureKind.VERIFICATION_LIMIT, issue.getContext().failureKind());
|
||||
assertEquals("BACKEND_VERIFY_PRELOAD", issue.getContext().stageId());
|
||||
assertEquals(11L, issue.getContext().parameters().get("actual"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void runMustFailWhenBytecodeModuleIsMissing() {
|
||||
final var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
|
||||
+14
@@ -18,6 +18,20 @@ class WriteBytecodeArtifactPipelineStageTest {
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Test
|
||||
void ioFailureMustBeInfrastructureWithStructuredOutputPath() throws Exception {
|
||||
var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
ctx.rootProjectPathCanon = tempDir;
|
||||
ctx.bytecodeBytes = new byte[] { 1 };
|
||||
Files.writeString(tempDir.resolve("build"), "blocks output directory");
|
||||
var issues = new WriteBytecodeArtifactPipelineStage().run(ctx, LogAggregator.empty());
|
||||
var issue = issues.asCollection().iterator().next();
|
||||
assertEquals("MARSHAL_ARTIFACT_WRITE_FAILED", issue.getCode());
|
||||
assertEquals(p.studio.compiler.source.diagnostics.FailureKind.INFRASTRUCTURE_FAILURE, issue.getContext().failureKind());
|
||||
assertEquals(tempDir.resolve("build/program.pbx").toString(), issue.getContext().parameters().get("outputPath"));
|
||||
assertNull(ctx.bytecodeArtifactPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
void runMustFailWhenRootProjectPathIsMissing() {
|
||||
final var ctx = BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false, "."));
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "caseapp",
|
||||
"version": "1.0.0",
|
||||
"language": "pbs",
|
||||
"stdlib": "1",
|
||||
"target": "Game",
|
||||
"dependencies": []
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
declare struct Probe() { fn value() -> int { return 1; } }
|
||||
declare global data: Probe = new Probe();
|
||||
fn check() -> bool { return data.value()!=0; }
|
||||
[Frame] fn frame() -> void { if !check() { let failure=1/0; } }
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub fn frame() -> void;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "caseapp",
|
||||
"version": "1.0.0",
|
||||
"language": "pbs",
|
||||
"stdlib": "1",
|
||||
"target": "Game",
|
||||
"dependencies": []
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
declare struct Probe() { fn value() -> int { return 1; } }
|
||||
declare global data: Probe = new Probe();
|
||||
fn check() -> bool { let value=data.value(); return value!=0; }
|
||||
[Frame] fn frame() -> void { if !check() { let failure=1/0; } }
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub fn frame() -> void;
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "caseapp",
|
||||
"version": "1.0.0",
|
||||
"language": "pbs",
|
||||
"stdlib": "1",
|
||||
"target": "Game",
|
||||
"dependencies": []
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
fn increment(value: int) -> int { return value+1; }
|
||||
+1
@@ -0,0 +1 @@
|
||||
[Frame] fn frame() -> void { let value=increment(2); }
|
||||
+1
@@ -0,0 +1 @@
|
||||
pub fn frame() -> void;
|
||||
+29
-1
@@ -1,11 +1,39 @@
|
||||
package p.studio.compiler.exceptions;
|
||||
|
||||
import p.studio.compiler.messages.BuildingIssue;
|
||||
import p.studio.compiler.source.diagnostics.SourceReference;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BuildException extends RuntimeException {
|
||||
private final boolean diagnosticPayloadAvailable;
|
||||
private final List<BuildingIssue> diagnostics;
|
||||
private final String failedStage;
|
||||
private final Map<Integer, SourceReference> sourceReferences;
|
||||
|
||||
public BuildException(String message) {
|
||||
super(message);
|
||||
this(message, null);
|
||||
}
|
||||
|
||||
public BuildException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
diagnosticPayloadAvailable = false;
|
||||
diagnostics = List.of();
|
||||
failedStage = null;
|
||||
sourceReferences = Map.of();
|
||||
}
|
||||
|
||||
public BuildException(String message, Throwable cause, List<BuildingIssue> diagnostics,
|
||||
String failedStage, Map<Integer, SourceReference> sourceReferences) {
|
||||
super(message, cause);
|
||||
this.diagnosticPayloadAvailable = true;
|
||||
this.diagnostics = List.copyOf(diagnostics);
|
||||
this.failedStage = failedStage;
|
||||
this.sourceReferences = Map.copyOf(sourceReferences);
|
||||
}
|
||||
|
||||
public boolean hasDiagnosticPayload() { return diagnosticPayloadAvailable; }
|
||||
public List<BuildingIssue> getDiagnostics() { return diagnostics; }
|
||||
public String getFailedStage() { return failedStage; }
|
||||
public Map<Integer, SourceReference> getSourceReferences() { return sourceReferences; }
|
||||
}
|
||||
|
||||
+62
-1
@@ -3,8 +3,13 @@ package p.studio.compiler.messages;
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import p.studio.utilities.logs.LogAggregator;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.diagnostics.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Builder
|
||||
@Builder(toBuilder = true)
|
||||
@Getter
|
||||
public class BuildingIssue {
|
||||
private final boolean error;
|
||||
@@ -17,6 +22,62 @@ public class BuildingIssue {
|
||||
private final Integer end;
|
||||
private final Integer functionIndex;
|
||||
private final Integer pc;
|
||||
private final Span sourceSpan;
|
||||
@Builder.Default private final DiagnosticContext context = DiagnosticContext.unknown();
|
||||
@Builder.Default private final List<RelatedSpan> related = List.of();
|
||||
private final String templateId;
|
||||
@Builder.Default private final Map<String, String> placeholders = Map.of();
|
||||
|
||||
BuildingIssue(boolean error, String message, Throwable exception, String phase, String code,
|
||||
Integer fileId, Integer start, Integer end, Integer functionIndex, Integer pc,
|
||||
Span sourceSpan, DiagnosticContext context, List<RelatedSpan> related,
|
||||
String templateId, Map<String, String> placeholders) {
|
||||
this.error = error;
|
||||
this.message = message;
|
||||
this.exception = exception;
|
||||
this.phase = phase;
|
||||
this.code = code;
|
||||
this.fileId = fileId;
|
||||
this.start = start;
|
||||
this.end = end;
|
||||
this.functionIndex = functionIndex;
|
||||
this.pc = pc;
|
||||
this.sourceSpan = sourceSpan;
|
||||
this.context = context == null ? DiagnosticContext.unknown() : context;
|
||||
this.related = List.copyOf(related);
|
||||
this.templateId = templateId;
|
||||
this.placeholders = Map.copyOf(placeholders);
|
||||
}
|
||||
|
||||
BuildingIssue(boolean error, String message, Throwable exception, String phase, String code,
|
||||
Integer fileId, Integer start, Integer end, Integer functionIndex, Integer pc) {
|
||||
this(error, message, exception, phase, code, fileId, start, end, functionIndex, pc,
|
||||
null, DiagnosticContext.unknown(), List.of(), null, Map.of());
|
||||
}
|
||||
|
||||
public Severity getSeverity() { return error ? Severity.Error : Severity.Warning; }
|
||||
|
||||
public static BuildingIssue fromDiagnostic(Diagnostic diagnostic) {
|
||||
var span = diagnostic.getSpan();
|
||||
return builder().error(diagnostic.getSeverity().isError()).code(diagnostic.getCode())
|
||||
.phase(diagnostic.getReportedPhase()).message(diagnostic.getMessage())
|
||||
.sourceSpan(span).fileId(span.isNone() ? null : span.getFileId().getId())
|
||||
.start(span.isNone() ? null : safeInt(span.getStart()))
|
||||
.end(span.isNone() ? null : safeInt(span.getEnd()))
|
||||
.templateId(diagnostic.getTemplateId()).placeholders(Map.copyOf(diagnostic.getPlaceholders()))
|
||||
.related(List.copyOf(diagnostic.getRelated().asCollection())).context(diagnostic.getContext()).build();
|
||||
}
|
||||
|
||||
public Diagnostic toDiagnostic() {
|
||||
var span = sourceSpan != null ? sourceSpan : fileId == null || fileId < 0 || start == null || end == null ? Span.none()
|
||||
: new Span(new FileId(fileId), start, end);
|
||||
var diagnosticPhase = java.util.Arrays.stream(DiagnosticPhase.values())
|
||||
.filter(value -> value.id().equals(phase)).findFirst().orElse(DiagnosticPhase.fromCode(code));
|
||||
return new Diagnostic(getSeverity(), code, diagnosticPhase, templateId == null ? code : templateId,
|
||||
placeholders, message, span, related, context, phase == null ? diagnosticPhase.id() : phase);
|
||||
}
|
||||
|
||||
private static int safeInt(long value) { return (int) Math.min(Integer.MAX_VALUE, Math.max(0, value)); }
|
||||
|
||||
public void print(LogAggregator logs) {
|
||||
final var composed = composeMessage();
|
||||
|
||||
+4
@@ -26,6 +26,10 @@ public class BuildingIssueSink implements ReadOnlyCollection<BuildingIssue> {
|
||||
final var builder = BuildingIssue.builder();
|
||||
consumer.accept(builder);
|
||||
final var issue = builder.build();
|
||||
return add(issue);
|
||||
}
|
||||
|
||||
public BuildingIssueSink add(BuildingIssue issue) {
|
||||
hasErrors |= issue.isError();
|
||||
issues.add(issue);
|
||||
return this;
|
||||
|
||||
+26
-2
@@ -33,6 +33,9 @@ public class SourceHandle {
|
||||
@Getter
|
||||
private final long lastModified;
|
||||
private final SourceProvider provider;
|
||||
private volatile String observedSha256;
|
||||
private volatile boolean mixedRevisions;
|
||||
private volatile byte[] observedBytes;
|
||||
|
||||
public SourceHandle(
|
||||
final ProjectId projectId,
|
||||
@@ -53,12 +56,33 @@ public class SourceHandle {
|
||||
|
||||
public Optional<byte[]> readBytes() {
|
||||
try {
|
||||
return Optional.ofNullable(provider.read());
|
||||
var bytes = provider.read();
|
||||
if (bytes != null) observe(bytes);
|
||||
return Optional.ofNullable(bytes);
|
||||
} catch (IOException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void observe(byte[] bytes) {
|
||||
final String digest;
|
||||
try { digest = java.util.HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); }
|
||||
catch (java.security.NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); }
|
||||
if (observedSha256 != null && !observedSha256.equals(digest)) mixedRevisions = true;
|
||||
observedSha256 = digest;
|
||||
observedBytes = bytes.clone();
|
||||
}
|
||||
|
||||
public String observedSha256() { return observedSha256; }
|
||||
public boolean mixedRevisions() { return mixedRevisions; }
|
||||
/** Already consumed bytes only; this accessor never invokes the provider. */
|
||||
public Optional<String> observedText() {
|
||||
var bytes = observedBytes;
|
||||
if (bytes == null) return Optional.empty();
|
||||
try { return Optional.of(StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString()); }
|
||||
catch (java.nio.charset.CharacterCodingException invalidUtf8) { return Optional.empty(); }
|
||||
}
|
||||
|
||||
public Optional<String> readUtf8() {
|
||||
return readBytes().map(bytes -> new String(bytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
@@ -70,4 +94,4 @@ public class SourceHandle {
|
||||
size / 1024,
|
||||
LocalDateTime.ofInstant(Instant.ofEpochMilli(lastModified), ZoneId.systemDefault()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import p.studio.compiler.messages.BuildingIssue;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.tables.FileTableReader;
|
||||
import p.studio.utilities.json.DiagnosticPayloads;
|
||||
import p.studio.utilities.json.ImmutableJson;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Projects recorded compiler facts. No live source reads, language inference or transport DTOs. */
|
||||
public final class CompilerDiagnosticProjection {
|
||||
private CompilerDiagnosticProjection() { }
|
||||
|
||||
public static List<Map<String, Object>> issues(List<BuildingIssue> issues, Map<Integer, SourceReference> sources,
|
||||
Map<Integer, String> text, Path root, String analysisId) {
|
||||
var result = new ArrayList<Map<String, Object>>();
|
||||
for (int i = 0; i < issues.size(); i++) result.add(issue(issues.get(i), sources, text, root, analysisId + ":" + i));
|
||||
return List.copyOf(result);
|
||||
}
|
||||
|
||||
public static Map<Integer, String> capturedText(FileTableReader files) {
|
||||
var result = new LinkedHashMap<Integer, String>();
|
||||
if (files != null) for (var id : files.identifiers()) files.get(id).observedText().ifPresent(value -> result.put(id.getId(), value));
|
||||
return Map.copyOf(result);
|
||||
}
|
||||
|
||||
public static List<Map<String, Object>> inputs(Map<Integer, SourceReference> sources, Path root) {
|
||||
return sources.values().stream().sorted(Comparator.comparingInt(SourceReference::fileId))
|
||||
.filter(source -> source.sha256() != null).map(source -> source(source, root)).toList();
|
||||
}
|
||||
|
||||
public static Map<String, Object> issue(BuildingIssue issue, Map<Integer, SourceReference> sources,
|
||||
Map<Integer, String> texts, Path root, String id) {
|
||||
var result = new LinkedHashMap<>(DiagnosticPayloads.issue(
|
||||
issue.getCode() == null ? "COMPILER_DIAGNOSTIC" : issue.getCode(), issue.getSeverity().name().toUpperCase(Locale.ROOT),
|
||||
Objects.requireNonNullElse(issue.getMessage(), "Compiler diagnostic")));
|
||||
var context = issue.getContext();
|
||||
result.put("issueId", id); result.put("codeOrigin", issue.getCode() == null ? "studio-adapter" : "producer");
|
||||
result.put("templateId", issue.getTemplateId()); result.put("templateParameters", issue.getPlaceholders());
|
||||
result.put("phase", issue.getPhase()); result.put("stageId", context.stageId());
|
||||
result.put("failureKind", context.failureKind().id()); result.put("facts", context.parameters());
|
||||
result.putAll(context.enrichment());
|
||||
if (!context.enrichment().containsKey("producer")) result.put("producer", ImmutableJson.fields("component", "compiler",
|
||||
"owner", "compiler", "languageId", null));
|
||||
Span primary = issue.getSourceSpan();
|
||||
if ((primary == null || primary.isNone()) && issue.getFileId() != null && issue.getFileId() >= 0
|
||||
&& issue.getStart() != null && issue.getEnd() != null) {
|
||||
primary = new Span(new FileId(issue.getFileId()), issue.getStart(), issue.getEnd());
|
||||
}
|
||||
var origin = new LinkedHashMap<>(origin(primary, sources, texts, root));
|
||||
var attribution = context.attribution();
|
||||
origin.put("attribution", ImmutableJson.fields("originKind", attribution.originKind(), "locationKind", attribution.locationKind(),
|
||||
"role", attribution.role(), "absenceReason", attribution.absenceReason()));
|
||||
var v = context.verification();
|
||||
origin.put("verification", v == null ? null : ImmutableJson.fields("functionIndex", v.functionIndex(), "pc", v.pc(),
|
||||
"functionName", v.functionName(), "moduleName", v.moduleName(), "pcSpace", v.pcSpace(), "pcUnit", v.pcUnit(),
|
||||
"validationPoint", v.validationPoint(), "passName", v.passName(), "stageId", context.stageId()));
|
||||
result.put("origin", ImmutableJson.object(origin));
|
||||
result.put("related", issue.getRelated().stream().map(related -> ImmutableJson.fields("relation", related.getRelation(),
|
||||
"role", related.getRole(), "message", related.getMessage(), "origin", origin(related.getSpan(), sources, texts, root))).toList());
|
||||
return ImmutableJson.object(result);
|
||||
}
|
||||
|
||||
public static Map<String, Object> source(SourceReference source, Path root) {
|
||||
var path = Path.of(source.canonicalPath()).toAbsolutePath().normalize();
|
||||
boolean local = root != null && path.startsWith(root.toAbsolutePath().normalize());
|
||||
return ImmutableJson.fields("fileId", source.fileId(), "projectId", source.projectId(), "inputKind", "source", "observationScope", "compiler",
|
||||
"uri", local ? path.toUri().toString() : null, "relativePath", source.relativePath(),
|
||||
"originScope", local ? "project" : "external", "sha256", source.sha256(),
|
||||
"revisionAvailability", source.sha256() == null ? "not-recorded" : source.mixedRevisions() ? "mixed" : "available",
|
||||
"readOnly", !local);
|
||||
}
|
||||
|
||||
private static Map<String, Object> origin(Span span, Map<Integer, SourceReference> sources,
|
||||
Map<Integer, String> texts, Path root) {
|
||||
if (span == null || span.isNone()) return ImmutableJson.fields("uri", null, "fileId", null, "span", null,
|
||||
"range", null, "revision", null, "availability", "unavailable");
|
||||
int file = span.getFileId().getId();
|
||||
var source = sources.get(file);
|
||||
var reference = source == null ? Map.<String, Object>of() : source(source, root);
|
||||
var text = texts.get(file);
|
||||
Map<String, Object> range = null;
|
||||
if (source != null && !source.mixedRevisions() && text != null && span.getStart() >= 0 && span.getEnd() >= span.getStart()
|
||||
&& span.getEnd() <= text.getBytes(java.nio.charset.StandardCharsets.UTF_8).length) {
|
||||
var start = position(text, span.getStart()); var end = position(text, span.getEnd());
|
||||
if (start != null && end != null) range = ImmutableJson.fields("start", start, "end", end, "unit", "utf16");
|
||||
}
|
||||
return ImmutableJson.fields("uri", reference.get("uri"), "fileId", file,
|
||||
"span", ImmutableJson.fields("start", span.getStart(), "end", span.getEnd(), "unit", "utf8-byte"),
|
||||
"range", range, "revision", source == null ? null : source.sha256(), "source", reference,
|
||||
"availability", source == null ? "partial" : "available");
|
||||
}
|
||||
|
||||
private static Map<String, Object> position(String text, long target) {
|
||||
long bytes = 0; int line = 0, character = 0;
|
||||
for (int i = 0; i < text.length() && bytes < target;) {
|
||||
int cp = text.codePointAt(i), width = Character.charCount(cp);
|
||||
int encoded = new String(Character.toChars(cp)).getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
|
||||
if (bytes + encoded > target) break;
|
||||
bytes += encoded; i += width;
|
||||
if (cp == '\n') { line++; character = 0; } else character += width;
|
||||
}
|
||||
return bytes == target ? ImmutableJson.fields("line", line, "character", character) : null;
|
||||
}
|
||||
}
|
||||
+18
@@ -18,6 +18,8 @@ public class Diagnostic {
|
||||
private final String message;
|
||||
private final Span span;
|
||||
private final ReadOnlyList<RelatedSpan> related;
|
||||
private final DiagnosticContext context;
|
||||
private final String reportedPhase;
|
||||
|
||||
public Diagnostic(
|
||||
final Severity severity,
|
||||
@@ -45,6 +47,20 @@ public class Diagnostic {
|
||||
final String message,
|
||||
final Span span,
|
||||
final List<RelatedSpan> related) {
|
||||
this(severity, code, phase, templateId, placeholders, message, span, related, DiagnosticContext.unknown());
|
||||
}
|
||||
|
||||
public Diagnostic(
|
||||
final Severity severity, final String code, final DiagnosticPhase phase,
|
||||
final String templateId, final Map<String, String> placeholders, final String message,
|
||||
final Span span, final List<RelatedSpan> related, final DiagnosticContext context) {
|
||||
this(severity, code, phase, templateId, placeholders, message, span, related, context, phase.id());
|
||||
}
|
||||
|
||||
public Diagnostic(
|
||||
final Severity severity, final String code, final DiagnosticPhase phase,
|
||||
final String templateId, final Map<String, String> placeholders, final String message,
|
||||
final Span span, final List<RelatedSpan> related, final DiagnosticContext context, final String reportedPhase) {
|
||||
this.severity = Objects.requireNonNull(severity);
|
||||
this.code = Objects.requireNonNull(code);
|
||||
this.phase = Objects.requireNonNull(phase);
|
||||
@@ -53,6 +69,8 @@ public class Diagnostic {
|
||||
this.message = Objects.requireNonNull(message);
|
||||
this.span = Objects.requireNonNull(span);
|
||||
this.related = ReadOnlyList.wrap(List.copyOf(Objects.requireNonNull(related)));
|
||||
this.context = Objects.requireNonNull(context);
|
||||
this.reportedPhase = Objects.requireNonNull(reportedPhase);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Small shared diagnostic value, independent of Studio and transport DTOs. */
|
||||
public record DiagnosticContext(
|
||||
String stageId, VerificationContext verification, SourceAttribution attribution,
|
||||
FailureKind failureKind, Map<String, Object> parameters, Map<String, Object> enrichment) {
|
||||
public DiagnosticContext(String stageId, VerificationContext verification, SourceAttribution attribution,
|
||||
FailureKind failureKind, Map<String, Object> parameters) {
|
||||
this(stageId, verification, attribution, failureKind, parameters, Map.of());
|
||||
}
|
||||
public DiagnosticContext {
|
||||
attribution = attribution == null ? SourceAttribution.unknown("unknown") : attribution;
|
||||
failureKind = failureKind == null ? FailureKind.UNKNOWN : failureKind;
|
||||
parameters = freeze(parameters == null ? Map.of() : parameters);
|
||||
enrichment = p.studio.utilities.json.ImmutableJson.object(enrichment);
|
||||
}
|
||||
|
||||
public static DiagnosticContext unknown() {
|
||||
return new DiagnosticContext(null, null, null, FailureKind.UNKNOWN, Map.of());
|
||||
}
|
||||
|
||||
public DiagnosticContext withStage(String stage) {
|
||||
return new DiagnosticContext(stage, verification, attribution, failureKind, parameters, enrichment);
|
||||
}
|
||||
|
||||
public DiagnosticContext withFailureKind(FailureKind kind) {
|
||||
return new DiagnosticContext(stageId, verification, attribution, kind, parameters, enrichment);
|
||||
}
|
||||
|
||||
public DiagnosticContext withAttribution(SourceAttribution origin) {
|
||||
return new DiagnosticContext(stageId, verification, origin, failureKind, parameters, enrichment);
|
||||
}
|
||||
|
||||
public DiagnosticContext withEnrichment(Map<String, Object> details) {
|
||||
return new DiagnosticContext(stageId, verification, attribution, failureKind, parameters, details);
|
||||
}
|
||||
|
||||
public DiagnosticContext withParameters(Map<String, Object> facts) {
|
||||
return new DiagnosticContext(stageId, verification, attribution, failureKind, facts, enrichment);
|
||||
}
|
||||
|
||||
private static Map<String, Object> freeze(Map<String, ?> input) {
|
||||
var output = new LinkedHashMap<String, Object>();
|
||||
input.forEach((key, value) -> output.put(key, freezeValue(value)));
|
||||
return Map.copyOf(output);
|
||||
}
|
||||
|
||||
private static Object freezeValue(Object value) {
|
||||
if (value instanceof String || value instanceof Boolean || value instanceof Byte || value instanceof Short
|
||||
|| value instanceof Integer || value instanceof Long || value instanceof Float || value instanceof Double
|
||||
|| value instanceof java.math.BigInteger || value instanceof java.math.BigDecimal) return value;
|
||||
if (value instanceof List<?> values) return values.stream().map(DiagnosticContext::freezeValue).toList();
|
||||
if (value instanceof Map<?, ?> values) {
|
||||
var output = new LinkedHashMap<String, Object>();
|
||||
values.forEach((key, item) -> output.put((String) key, freezeValue(item)));
|
||||
return Map.copyOf(output);
|
||||
}
|
||||
throw new IllegalArgumentException("diagnostic parameters must be structured scalar/list/map values");
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import p.studio.utilities.json.DiagnosticPayloads;
|
||||
import p.studio.utilities.json.ImmutableJson;
|
||||
import java.util.*;
|
||||
|
||||
/** Owner-maintained descriptions of detector behavior. They do not infer root cause. */
|
||||
public final class DiagnosticDescriptions {
|
||||
private DiagnosticDescriptions() { }
|
||||
public static Map<String, Object> describe(String check, Map<String, Object> semanticFacts) {
|
||||
boolean frontend = check.startsWith("pbs.");
|
||||
String rule = switch (check) {
|
||||
case "compiler.verify.ret-stack-height" -> "The stack at RET must match the function's declared result slot count.";
|
||||
case "compiler.verify.join-stack-height" -> "Incoming control-flow paths must agree on stack height at the join destination.";
|
||||
case "compiler.verify.resource-limit" -> "Producer verification must remain within its configured resource budget.";
|
||||
case "pbs.lowering.call-resolution" -> "Executable call lowering must identify an admitted callable using the actual resolution constraints.";
|
||||
case "pbs.lowering.structured-overload" -> "A structured call requires an exact signature in the owner index consulted by lowering.";
|
||||
case "pbs.flow.call-target" -> "An applied expression must resolve to a callable target in its current semantic scope.";
|
||||
case "pbs.flow.assignment-target" -> "An assignment must resolve its target binding in the current semantic scope.";
|
||||
case "pbs.lowering.stack-shape" -> "The executable body produced by frontend lowering must have a consistent stack shape.";
|
||||
default -> null;
|
||||
};
|
||||
var facts = new LinkedHashMap<String, Object>();
|
||||
semanticFacts.forEach((name, value) -> facts.put(name, DiagnosticPayloads.fact(value)));
|
||||
if (frontend) for (var name : List.of("expressionTypes", "moduleIdentity", "dependencyIdentity"))
|
||||
facts.putIfAbsent(name, DiagnosticPayloads.missingFact("Not recorded by this detector; source identity is carried separately"));
|
||||
var semantics = frontend || !facts.isEmpty()
|
||||
? ImmutableJson.fields("availability", "partial", "facts", facts)
|
||||
: ImmutableJson.fields("availability", "not-applicable", "facts", Map.of());
|
||||
var explanation = rule == null ? DiagnosticPayloads.unavailableExplanation()
|
||||
: ImmutableJson.fields("id", check, "summary", rule, "rule", rule, "availability", "available");
|
||||
var suggested = rule == null ? List.of() : List.of(ImmutableJson.fields("id", check + ".inspect-context",
|
||||
"description", frontend ? "Inspect the recorded declaration, expression types and actual resolution constraints."
|
||||
: "Inspect the produced IR and its recorded origin at the detection point; the location does not establish cause.",
|
||||
"evidenceFields", frontend ? List.of("semanticContext", "origin", "facts") : List.of("facts", "origin", "related")));
|
||||
return ImmutableJson.fields("checkId", check, "producer", ImmutableJson.fields("component",
|
||||
frontend ? "compiler-frontend" : "compiler-backend", "owner", frontend ? "compiler/pbs" : "compiler",
|
||||
"languageId", frontend ? "pbs" : null), "explanation", explanation,
|
||||
"semanticContext", semantics, "suggestedChecks", suggested);
|
||||
}
|
||||
|
||||
public static Diagnostic attach(Diagnostic diagnostic, String check, Map<String, Object> semantics, FailureKind kind) {
|
||||
return new Diagnostic(diagnostic.getSeverity(), diagnostic.getCode(), diagnostic.getPhase(),
|
||||
diagnostic.getTemplateId(), diagnostic.getPlaceholders(), diagnostic.getMessage(), diagnostic.getSpan(),
|
||||
diagnostic.getRelated().asList(), diagnostic.getContext().withEnrichment(describe(check, semantics))
|
||||
.withFailureKind(kind), diagnostic.getReportedPhase());
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
/** Evidence supplied by the detecting boundary, never inferred from message text. */
|
||||
public enum FailureKind {
|
||||
PROGRAM_REJECTION("program-rejection"),
|
||||
INTERNAL_FAILURE("internal-failure"),
|
||||
VERIFICATION_LIMIT("verification-limit"),
|
||||
INFRASTRUCTURE_FAILURE("infrastructure-failure"),
|
||||
UNKNOWN("unknown");
|
||||
|
||||
private final String id;
|
||||
|
||||
FailureKind(String id) { this.id = id; }
|
||||
|
||||
public String id() { return id; }
|
||||
}
|
||||
+9
@@ -7,9 +7,18 @@ import p.studio.compiler.source.Span;
|
||||
public class RelatedSpan {
|
||||
private final String message;
|
||||
private final Span span;
|
||||
private final String relation;
|
||||
private final String role;
|
||||
|
||||
public RelatedSpan(String message, Span span) {
|
||||
this(message, span, "unspecified", "context");
|
||||
}
|
||||
|
||||
public RelatedSpan(String message, Span span, String relation, String role) {
|
||||
this.message = message;
|
||||
this.span = span;
|
||||
this.relation = java.util.Objects.requireNonNull(relation);
|
||||
if (!"context".equals(role)) throw new IllegalArgumentException("related locations are context only");
|
||||
this.role = role;
|
||||
}
|
||||
}
|
||||
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import p.studio.compiler.source.Span;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
/** Provenance and location precision are independent. An anchor never proves cause. */
|
||||
public record SourceAttribution(
|
||||
String originKind, String locationKind, String role, Span span, String absenceReason) {
|
||||
public SourceAttribution {
|
||||
if (!Set.of("source", "generated", "unknown").contains(originKind)
|
||||
|| !Set.of("instruction", "function", "none").contains(locationKind)
|
||||
|| !Set.of("detection", "context").contains(role)) {
|
||||
throw new IllegalArgumentException("invalid source attribution kind or role");
|
||||
}
|
||||
if (span != null && span.isNone()) span = null;
|
||||
if ("none".equals(locationKind)) {
|
||||
if (span != null || !Set.of("no-emission-plan", "no-source-span", "generated-without-anchor", "unknown")
|
||||
.contains(absenceReason)) throw new IllegalArgumentException("missing attribution requires an absence reason");
|
||||
} else if (span == null || absenceReason != null) {
|
||||
throw new IllegalArgumentException("located attribution requires a real span and no absence reason");
|
||||
}
|
||||
if (("function".equals(locationKind) || "generated".equals(originKind))
|
||||
&& span != null && !"context".equals(role)) {
|
||||
throw new IllegalArgumentException("function and generated anchors are context only");
|
||||
}
|
||||
}
|
||||
|
||||
public static SourceAttribution source(Span span) {
|
||||
return span == null || span.isNone() ? unknown("no-source-span")
|
||||
: new SourceAttribution("source", "instruction", "detection", span, null);
|
||||
}
|
||||
|
||||
public static SourceAttribution function(Span span) {
|
||||
return span == null || span.isNone() ? unknown("no-source-span")
|
||||
: new SourceAttribution("source", "function", "context", span, null);
|
||||
}
|
||||
|
||||
public static SourceAttribution generated(Span anchor) {
|
||||
return anchor == null || anchor.isNone()
|
||||
? new SourceAttribution("generated", "none", "context", null, "generated-without-anchor")
|
||||
: new SourceAttribution("generated", "instruction", "context", anchor, null);
|
||||
}
|
||||
|
||||
public static SourceAttribution unknown(String reason) {
|
||||
return new SourceAttribution("unknown", "none", "detection", null, reason);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (!(other instanceof SourceAttribution that)) return false;
|
||||
return originKind.equals(that.originKind) && locationKind.equals(that.locationKind) && role.equals(that.role)
|
||||
&& java.util.Objects.equals(absenceReason, that.absenceReason)
|
||||
&& (span == null ? that.span == null : that.span != null
|
||||
&& span.getFileId().getId() == that.span.getFileId().getId()
|
||||
&& span.getStart() == that.span.getStart() && span.getEnd() == that.span.getEnd());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return java.util.Objects.hash(originKind, locationKind, role, absenceReason,
|
||||
span == null ? null : span.getFileId().getId(), span == null ? null : span.getStart(),
|
||||
span == null ? null : span.getEnd());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import p.studio.compiler.source.tables.FileTableReader;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/** Compilation-local identity only. Paths and timestamps do not establish a content revision. */
|
||||
public record SourceReference(int fileId, int projectId, String canonicalPath, String relativePath,
|
||||
String sha256, boolean mixedRevisions) {
|
||||
public SourceReference(int fileId, int projectId, String canonicalPath, String relativePath) {
|
||||
this(fileId, projectId, canonicalPath, relativePath, null, false);
|
||||
}
|
||||
public static Map<Integer, SourceReference> snapshot(FileTableReader files) {
|
||||
if (files == null) return Map.of();
|
||||
var result = new LinkedHashMap<Integer, SourceReference>();
|
||||
for (var id : files.identifiers()) {
|
||||
var file = files.get(id);
|
||||
if (file == null) continue;
|
||||
result.put(id.getId(), new SourceReference(id.getId(), file.getProjectId().getIndex(),
|
||||
file.getCanonPath().toString(), file.getRelativePath().toString(), file.observedSha256(), file.mixedRevisions()));
|
||||
}
|
||||
return Map.copyOf(result);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
/** Coordinates belong to one checked program, not to an executed instruction. */
|
||||
public record VerificationContext(
|
||||
String validationPoint, String passName, String pcSpace, String pcUnit,
|
||||
int functionIndex, int pc, String functionName, String moduleName) {
|
||||
public VerificationContext at(String point, String pass) {
|
||||
return new VerificationContext(point, pass, pcSpace, pcUnit, functionIndex, pc, functionName, moduleName);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.models.SourceHandle;
|
||||
import p.studio.compiler.messages.BuildingIssue;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.*;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ConsumedSourceProjectionTest {
|
||||
@Test void observationAccessNeverRereadsProviderAndDetectsMixedBytes() {
|
||||
var reads = new AtomicInteger();
|
||||
var handle = new SourceHandle(new ProjectId(0), Path.of("main.pbs"), Path.of("/fixture/main.pbs"), 0, 0,
|
||||
path -> () -> (reads.incrementAndGet() == 1 ? "first" : "changed").getBytes(StandardCharsets.UTF_8));
|
||||
assertNull(handle.observedSha256()); assertTrue(handle.observedText().isEmpty()); assertEquals(0, reads.get());
|
||||
handle.readBytes(); String first = handle.observedSha256();
|
||||
assertEquals("first", handle.observedText().orElseThrow()); assertEquals(1, reads.get());
|
||||
handle.readBytes(); assertNotEquals(first, handle.observedSha256()); assertTrue(handle.mixedRevisions());
|
||||
assertEquals("changed", handle.observedText().orElseThrow()); assertEquals(2, reads.get());
|
||||
}
|
||||
@Test void malformedObservedUtf8DoesNotSupplyInventedTextForRangeConversion() {
|
||||
var handle = new SourceHandle(new ProjectId(0), Path.of("main.pbs"), Path.of("/fixture/main.pbs"), 1, 0,
|
||||
path -> () -> new byte[]{(byte)0xff});
|
||||
handle.readBytes(); assertNotNull(handle.observedSha256()); assertTrue(handle.observedText().isEmpty());
|
||||
}
|
||||
@Test void unicodeRangesRequireMatchingObservedRevisionAndFileIdIsAnalysisLocal() {
|
||||
var root = Path.of("/fixture"); var id = new FileId(7); String text = "// á 😀\r\nfn x() {}\n";
|
||||
int start = text.substring(0, text.indexOf("x")).getBytes(StandardCharsets.UTF_8).length;
|
||||
var issue = BuildingIssue.fromDiagnostic(new Diagnostic(Severity.Error, "E_SEM_TEST", "observed", new Span(id, start, start+1), List.of()));
|
||||
var first = new SourceReference(7, 0, "/fixture/main.pbs", "main.pbs", "first-digest", false);
|
||||
var value = CompilerDiagnosticProjection.issues(List.of(issue), Map.of(7, first), Map.of(7, text), root, "analysis-a").getFirst();
|
||||
var origin = (Map<?, ?>)value.get("origin"); var range = (Map<?, ?>)origin.get("range");
|
||||
assertEquals(Map.of("line", 1, "character", 3), range.get("start"));
|
||||
assertEquals("first-digest", origin.get("revision"));
|
||||
var second = new SourceReference(7, 1, "/fixture/other.pbs", "other.pbs", "second-digest", true);
|
||||
var other = CompilerDiagnosticProjection.issues(List.of(issue), Map.of(7, second), Map.of(7, text), root, "analysis-b").getFirst();
|
||||
assertNotEquals(value.get("issueId"), other.get("issueId"));
|
||||
assertEquals("file:///fixture/other.pbs", ((Map<?, ?>)other.get("origin")).get("uri"));
|
||||
assertNull(((Map<?, ?>)other.get("origin")).get("range"));
|
||||
var missing = BuildingIssue.fromDiagnostic(new Diagnostic(Severity.Error, "E_SEM_TEST", "locationless", Span.none(), List.of()));
|
||||
assertNull(((Map<?, ?>)CompilerDiagnosticProjection.issues(List.of(missing), Map.of(), Map.of(), root, "c").getFirst().get("origin")).get("range"));
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package p.studio.compiler.source.diagnostics;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.compiler.exceptions.BuildException;
|
||||
import p.studio.compiler.messages.BuildingIssue;
|
||||
import p.studio.compiler.models.SourceHandle;
|
||||
import p.studio.compiler.source.Span;
|
||||
import p.studio.compiler.source.identifiers.FileId;
|
||||
import p.studio.compiler.source.identifiers.ProjectId;
|
||||
import p.studio.compiler.source.tables.FileTable;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class StructuredDiagnosticTest {
|
||||
@Test
|
||||
void backendPhaseMustRoundTripWithoutInventingASemanticPhase() {
|
||||
var issue = BuildingIssue.builder().error(true).code("MARSHAL_VERIFY_PRECHECK_BAD_RET_STACK_HEIGHT")
|
||||
.phase("BACKEND_LOWER_TO_IRVM").message("ret mismatch")
|
||||
.context(DiagnosticContext.unknown().withStage("BACKEND_LOWER_TO_IRVM")
|
||||
.withFailureKind(FailureKind.INTERNAL_FAILURE)).build();
|
||||
var diagnostic = issue.toDiagnostic();
|
||||
assertEquals(DiagnosticPhase.UNKNOWN, diagnostic.getPhase());
|
||||
assertEquals("BACKEND_LOWER_TO_IRVM", diagnostic.getReportedPhase());
|
||||
assertEquals(issue.getPhase(), BuildingIssue.fromDiagnostic(diagnostic).getPhase());
|
||||
assertEquals(issue.getContext(), BuildingIssue.fromDiagnostic(diagnostic).getContext());
|
||||
}
|
||||
@Test
|
||||
void projectionMustPreservePhaseParametersRelatedAndLongSpan() {
|
||||
var span = new Span(new FileId(2), 0, (long) Integer.MAX_VALUE + 12);
|
||||
var related = new RelatedSpan("declared here", new Span(new FileId(3), 20, 25), "declaration", "context");
|
||||
var context = new DiagnosticContext("FrontendPhasePipelineStage", null, null,
|
||||
FailureKind.PROGRAM_REJECTION, Map.of("argument", 7));
|
||||
var original = new Diagnostic(Severity.Error, "E_SEM_TEST", DiagnosticPhase.STATIC_SEMANTICS,
|
||||
"semantic.test", Map.of("name", "value"), "Original message", span, List.of(related), context);
|
||||
var issue = BuildingIssue.fromDiagnostic(original);
|
||||
var projected = issue.toDiagnostic();
|
||||
assertEquals(0, issue.getStart());
|
||||
assertSame(span, projected.getSpan());
|
||||
assertEquals(original.getPhase(), projected.getPhase());
|
||||
assertEquals(original.getCode(), projected.getCode());
|
||||
assertEquals(original.getMessage(), projected.getMessage());
|
||||
assertEquals(original.getTemplateId(), projected.getTemplateId());
|
||||
assertEquals(original.getPlaceholders(), projected.getPlaceholders());
|
||||
assertEquals(context, projected.getContext());
|
||||
assertEquals("declaration", projected.getRelated().getFirst().getRelation());
|
||||
assertEquals("context", projected.getRelated().getFirst().getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void provenanceMustRemainIndependentFromAvailability() {
|
||||
var zero = new Span(new FileId(0), 0, 1);
|
||||
assertEquals("detection", SourceAttribution.source(zero).role());
|
||||
assertEquals("context", SourceAttribution.generated(zero).role());
|
||||
assertEquals("generated-without-anchor", SourceAttribution.generated(null).absenceReason());
|
||||
assertEquals("unknown", SourceAttribution.source(Span.none()).originKind());
|
||||
assertEquals("function", SourceAttribution.function(zero).locationKind());
|
||||
assertEquals("context", SourceAttribution.function(zero).role());
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> new SourceAttribution("generated", "instruction", "detection", zero, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void structuredParametersMustBeCopiedRecursively() {
|
||||
var list = new ArrayList<>(List.of("before"));
|
||||
var parameters = new HashMap<String, Object>();
|
||||
parameters.put("values", list);
|
||||
var context = new DiagnosticContext(null, null, null, null, parameters);
|
||||
list.clear(); parameters.clear();
|
||||
assertEquals(List.of("before"), context.parameters().get("values"));
|
||||
assertThrows(UnsupportedOperationException.class, () -> context.parameters().put("x", 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failuresMustKeepIndependentFileIdsAfterTablesAreCleared() {
|
||||
var left = table("left");
|
||||
var right = table("right");
|
||||
var issues = new ArrayList<>(List.of(BuildingIssue.builder().error(true).code("E_SEM_TEST").build()));
|
||||
var a = new BuildException("rejected", null, issues, "analyze", SourceReference.snapshot(left));
|
||||
var b = new BuildException("rejected", null, issues, "analyze", SourceReference.snapshot(right));
|
||||
left.clear(); right.clear(); issues.clear();
|
||||
assertEquals("/left/main.pbs", a.getSourceReferences().get(0).canonicalPath());
|
||||
assertEquals("/right/main.pbs", b.getSourceReferences().get(0).canonicalPath());
|
||||
assertEquals(1, a.getDiagnostics().size());
|
||||
assertTrue(a.hasDiagnosticPayload());
|
||||
assertThrows(UnsupportedOperationException.class, () -> a.getSourceReferences().clear());
|
||||
assertFalse(new BuildException("legacy").hasDiagnosticPayload());
|
||||
assertFalse(new BuildException("legacy", new IllegalStateException()).hasDiagnosticPayload());
|
||||
}
|
||||
|
||||
private FileTable table(String root) {
|
||||
var files = new FileTable(1);
|
||||
files.register(new SourceHandle(new ProjectId(0), Path.of("main.pbs"), Path.of("/" + root + "/main.pbs"),
|
||||
0, 0, path -> () -> { throw new AssertionError("identity snapshots must not read live source"); }));
|
||||
return files;
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -234,7 +234,7 @@ public class IRBackend implements IRBackendReader {
|
||||
function.returnSlots(),
|
||||
function.maxStackSlots(),
|
||||
ReadOnlyList.wrap(remappedInstructions),
|
||||
function.span(), function.metadata());
|
||||
function.span(), function.metadata(), function.semanticFacts());
|
||||
}
|
||||
|
||||
private IRLifecycleFileDeclaration remapLifecycleFileDeclaration(
|
||||
|
||||
+9
-1
@@ -22,7 +22,14 @@ public record IRBackendExecutableFunction(
|
||||
int maxStackSlots,
|
||||
ReadOnlyList<Instruction> instructions,
|
||||
Span span,
|
||||
p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata) {
|
||||
p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata,
|
||||
java.util.Map<String, Object> semanticFacts) {
|
||||
public IRBackendExecutableFunction(FileId fileId, ModuleId moduleId, String callableName, CallableId callableId,
|
||||
int sourceStart, int sourceEnd, int paramSlots, int localSlots, int returnSlots, int maxStackSlots,
|
||||
ReadOnlyList<Instruction> instructions, Span span, p.studio.compiler.models.registry.IRRegistry.FunctionMetadata metadata) {
|
||||
this(fileId, moduleId, callableName, callableId, sourceStart, sourceEnd, paramSlots, localSlots, returnSlots,
|
||||
maxStackSlots, instructions, span, metadata, java.util.Map.of());
|
||||
}
|
||||
public IRBackendExecutableFunction(
|
||||
FileId fileId,
|
||||
ModuleId moduleId,
|
||||
@@ -68,6 +75,7 @@ public record IRBackendExecutableFunction(
|
||||
}
|
||||
|
||||
public IRBackendExecutableFunction {
|
||||
semanticFacts = p.studio.utilities.json.ImmutableJson.object(semanticFacts);
|
||||
fileId = Objects.requireNonNull(fileId, "fileId");
|
||||
moduleId = moduleId == null ? ModuleId.none() : moduleId;
|
||||
if (!moduleId.isNone()) {
|
||||
|
||||
Reference in New Issue
Block a user