From 38cb11f7a884f628d25405308c668bf80e8363c3 Mon Sep 17 00:00:00 2001 From: Rodrigo Quelhas Date: Tue, 18 Aug 2026 19:37:41 +0100 Subject: [PATCH] Add --ir-hook to hand each stage of the program to a consumer's Scheme file Signed-off-by: Rodrigo Quelhas --- compiler/compactc.ss | 23 +++- compiler/config-params.ss | 3 + compiler/passes.ss | 21 +++ tests-e2e/src/binary-utils.ts | 1 + tests-e2e/src/resources/compiler_man_page.txt | 6 + .../compiler/compiler.irhook.e2e.test.ts | 125 ++++++++++++++++++ 6 files changed, 178 insertions(+), 1 deletion(-) create mode 100644 tests-e2e/src/tests/compiler/compiler.irhook.e2e.test.ts diff --git a/compiler/compactc.ss b/compiler/compactc.ss index cfd6571c5..da847bf9a 100755 --- a/compiler/compactc.ss +++ b/compiler/compactc.ss @@ -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 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 " ... ") (parameterize ([reset-handler abort]) @@ -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)) @@ -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))] diff --git a/compiler/config-params.ss b/compiler/config-params.ss index ecae20589..e5a1d825f 100644 --- a/compiler/config-params.ss +++ b/compiler/config-params.ss @@ -41,4 +41,7 @@ ; feature flags (export-parameter feature-zkir-v3 #f) + + ; hooks + (export-parameter ir-hook #f) ) diff --git a/compiler/passes.ss b/compiler/passes.ss index fc6db8081..394cbe78e 100644 --- a/compiler/passes.ss +++ b/compiler/passes.ss @@ -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) @@ -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) diff --git a/tests-e2e/src/binary-utils.ts b/tests-e2e/src/binary-utils.ts index d6ead2d0c..231bd55bd 100644 --- a/tests-e2e/src/binary-utils.ts +++ b/tests-e2e/src/binary-utils.ts @@ -33,6 +33,7 @@ export enum Arguments { RUNTIME_VERSION = '--runtime-version', VSCODE = '--vscode', LINES_LENGTH = '--line-length', + IR_HOOK = '--ir-hook', } type FailedContract = { diff --git a/tests-e2e/src/resources/compiler_man_page.txt b/tests-e2e/src/resources/compiler_man_page.txt index db59a6041..3db28d2f4 100644 --- a/tests-e2e/src/resources/compiler_man_page.txt +++ b/tests-e2e/src/resources/compiler_man_page.txt @@ -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 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. diff --git a/tests-e2e/src/tests/compiler/compiler.irhook.e2e.test.ts b/tests-e2e/src/tests/compiler/compiler.irhook.e2e.test.ts new file mode 100644 index 000000000..fcbc482e9 --- /dev/null +++ b/tests-e2e/src/tests/compiler/compiler.irhook.e2e.test.ts @@ -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 = { + 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)', + ); + }); +});