Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion compiler/compactc.ss
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,26 @@ The following flags, if present, affect the compiler's behavior as follows:

--trace-passes causes the compiler to print tracing information that is
generally useful only to compiler developers.

--ir-hook <pathname> loads a Scheme file that defines `hook`. The compiler
calls it with the compilation stages, proof circuit names, selected compiler
values, and the target directory. The hook controls its own output. It uses
internal compiler structures, so it can require updates between compiler
versions. Load only files you trust.
"))

(define (load-hook pathname)
(define (complain)
(external-errorf "the file loaded by --ir-hook must define a procedure named hook"))
(check-pathname pathname)
(unless (file-exists? pathname)
(external-errorf "the file named by --ir-hook does not exist: ~a" pathname))
(load pathname)
(unless (top-level-bound? 'hook (interaction-environment)) (complain))
(let ([hook (eval 'hook (interaction-environment))])
(unless (procedure? hook) (complain))
hook))

(usage "<flag> ... <source-pathname> <target-directory-pathname>")

(parameterize ([reset-handler abort])
Expand All @@ -100,6 +118,7 @@ The following flags, if present, affect the compiler's behavior as follows:
[(--compact-path) (string search-list)]
[(--trace-search)]
[(--trace-passes)]
[(--ir-hook) (string ir-hook-pathname)]
[(--feature-zkir-v3)])
(string source-pathname)
(string target-directory-pathname))
Expand All @@ -113,7 +132,9 @@ The following flags, if present, affect the compiler's behavior as follows:
[trace-search ?--trace-search])
(when source-root (register-source-root! source-root))
(handle-exceptions ?--vscode
(generate-everything source-pathname target-directory-pathname)))]
;; Report hook loading failures through the compiler error handler.
(parameterize ([ir-hook (and ?--ir-hook (load-hook ir-hook-pathname))])
(generate-everything source-pathname target-directory-pathname))))]
[((flags [(--help) $ (begin (print-help) (exit))]
[(--version) $ (begin (print-compiler-version) (exit))]
[(--language-version) $ (begin (print-language-version) (exit))]
Expand Down
3 changes: 3 additions & 0 deletions compiler/config-params.ss
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,7 @@

; feature flags
(export-parameter feature-zkir-v3 #f)

; hooks
(export-parameter ir-hook #f)
)
21 changes: 21 additions & 0 deletions compiler/passes.ss
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
(frontend-passes)
(analysis-passes)
(save-contract-info-passes)
(vm)
(compiler-version)
(language-version)
(runtime-version)
(typescript-passes)
(circuit-passes)
(zkir-passes)
Expand Down Expand Up @@ -193,6 +197,23 @@
(run-passes manifest-passes circuit-ir
output-directory-pathname
output-subdirectories)))
;; Run the hook last because the compiler cannot roll back its output after a later failure.
(cond
[(ir-hook) =>
(lambda (hook)
(define (stage-with-unparser name ir pass*)
(list name ir (passrec-unparse (car (last-pair pass*)))))
(hook (list (stage-with-unparser 'lsrc lsrc-ir parser-passes)
(stage-with-unparser 'frontend frontend-ir frontend-passes)
(stage-with-unparser 'analyzed analyzed-ir analysis-passes)
(stage-with-unparser 'circuit circuit-ir circuit-passes))
proof-circuit-name*
`((expand-vm-code . ,expand-vm-code)
(align . ,VMalign)
(compiler-version . ,compiler-version-string)
(language-version . ,language-version-string)
(runtime-version . ,runtime-version-string))
output-directory-pathname))])
(when final-pass (internal-errorf 'generate-everything "never encountered final pass ~s" final-pass)))])))))))]))

(define-pass extract-circuit-names : Lflattened (ir) -> * (ls)
Expand Down
1 change: 1 addition & 0 deletions tests-e2e/src/binary-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export enum Arguments {
RUNTIME_VERSION = '--runtime-version',
VSCODE = '--vscode',
LINES_LENGTH = '--line-length',
IR_HOOK = '--ir-hook',
}

type FailedContract = {
Expand Down
6 changes: 6 additions & 0 deletions tests-e2e/src/resources/compiler_man_page.txt
Original file line number Diff line number Diff line change
Expand Up @@ -56,3 +56,9 @@ The following flags, if present, affect the compiler's behavior as follows:

--trace-passes causes the compiler to print tracing information that is
generally useful only to compiler developers.

--ir-hook <pathname> loads a Scheme file that defines `hook`. The compiler
calls it with the compilation stages, proof circuit names, selected compiler
values, and the target directory. The hook controls its own output. It uses
internal compiler structures, so it can require updates between compiler
versions. Load only files you trust.
125 changes: 125 additions & 0 deletions tests-e2e/src/tests/compiler/compiler.irhook.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// This file is part of Compact.
// Copyright (C) 2025 Midnight Foundation
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import fs from 'node:fs';
import path from 'node:path';
import { Result } from 'execa';
import { describe, expect, test } from 'vitest';
import { Arguments, compile, createTempFolder, ExitCodes, saveContract } from '@';

const CONTRACT = [
'import CompactStandardLibrary;',
'export ledger round: Counter;',
'export circuit increment(): [] { round.increment(1); }',
].join('\n');

// CONTRACT through each stage's own unparser. The names and the safe-cast bound
// come from the passes, so a pass that changes either rewrites these.
const STAGE_OUTPUT: Record<string, string> = {
lsrc: `(program
(import CompactStandardLibrary () "")
(public-ledger-declaration #t #f round (type-ref Counter))
(circuit #t #f increment () () (ttuple)
(block (elt-call round increment 1))))
`,
frontend: `(program
(import CompactStandardLibrary () "")
(public-ledger-declaration #t #f round (type-ref Counter))
(circuit #t #f increment () () (ttuple)
(seq (elt-call round increment 1) (tuple))))
`,
analyzed: `(program
(kernel-declaration (%kernel.0 () (Kernel)))
(public-ledger-declaration
((%round.1 (0) (Counter)))
(constructor () (tuple)))
(circuit
%increment.2
()
(ttuple)
(seq (let* ([(%tmp.3 (tunsigned 65535)) (safe-cast
(tunsigned 65535)
(tunsigned 1)
1)])
(public-ledger %round.1 (0) increment %tmp.3))
(tuple))))
`,
circuit: `(program
(kernel-declaration (%kernel.0 () (Kernel)))
(public-ledger-declaration ((%round.1 (0) (Counter))))
(circuit %increment.2 () (ty () ())
(= 1 () (public-ledger %round.1 (0) increment 1)) ()))
`,
};

// Writes one stage, named by its key, through the unparser that stage carries.
function stageHook(stage: string): string {
return [
'(define hook',
' (lambda (stage* proof-circuit-name* compiler target-directory)',
` (let* ([stage (assq '${stage} stage*)]`,
' [program (cadr stage)]',
' [unparse (caddr stage)])',
` (call-with-output-file (string-append target-directory "/compiler/${stage}.sexp")`,
' (lambda (op) (pretty-print (unparse program) op))',
" 'replace))))",
].join('\n');
}

function saveHook(source: string): string {
const hookPath = createTempFolder() + 'hook.ss';
fs.writeFileSync(hookPath, source, 'utf8');
return hookPath;
}

describe(`[Compiler] ${Arguments.IR_HOOK}`, () => {
test.each(Object.entries(STAGE_OUTPUT))('should hand over the %s stage', async (stage: string, expected: string) => {
const target = createTempFolder();
const result: Result = await compile([
Arguments.SKIP_ZK,
Arguments.IR_HOOK,
saveHook(stageHook(stage)),
saveContract(CONTRACT),
target,
]);

expect(result.exitCode).toBe(ExitCodes.Success);
expect(fs.readFileSync(path.join(target, 'compiler', `${stage}.sexp`), 'utf8')).toBe(expected);
});

test('should let the hook read more than one stage', async () => {
const target = createTempFolder();
const hook = [
'(define hook',
' (lambda (stage* proof-circuit-name* compiler target-directory)',
' (call-with-output-file (string-append target-directory "/compiler/stages.txt")',
' (lambda (op) (write (map car stage*) op))',
" 'replace)))",
].join('\n');

const result: Result = await compile([
Arguments.SKIP_ZK,
Arguments.IR_HOOK,
saveHook(hook),
saveContract(CONTRACT),
target,
]);

expect(result.exitCode).toBe(ExitCodes.Success);
expect(fs.readFileSync(path.join(target, 'compiler', 'stages.txt'), 'utf8')).toBe(
'(lsrc frontend analyzed circuit)',
);
});
});
Loading