feat(studio): improve compiler reliability and AI diagnostics
Test / Tests and coverage occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/pr-master There was a failure building this commit

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:
2026-11-10 12:36:25 +00:00
parent 38f201a9c9
commit ea1cc26fe3
1216 changed files with 168017 additions and 354 deletions
@@ -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() {
@@ -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;
}
@@ -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);}
}
@@ -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() {
@@ -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));
}
}
@@ -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;
}
@@ -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);
}
@@ -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()) {
@@ -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));
}
@@ -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);
}
}
@@ -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();
@@ -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));
@@ -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));
}
@@ -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));
}
@@ -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
@@ -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));
}
}
@@ -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,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();
@@ -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,
@@ -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() {
@@ -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)));
}
}
}
@@ -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());
}
}
@@ -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, "."));
@@ -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, "."));
@@ -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, "."));
@@ -0,0 +1,8 @@
{
"name": "caseapp",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -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; } }
@@ -0,0 +1,8 @@
{
"name": "caseapp",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -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; } }
@@ -0,0 +1,8 @@
{
"name": "caseapp",
"version": "1.0.0",
"language": "pbs",
"stdlib": "1",
"target": "Game",
"dependencies": []
}
@@ -0,0 +1 @@
fn increment(value: int) -> int { return value+1; }
@@ -0,0 +1 @@
[Frame] fn frame() -> void { let value=increment(2); }