Skip to content
Merged
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
7 changes: 4 additions & 3 deletions src/math/leanSource.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { maskLeanCommentsAndStrings, leanScopeCommands, leanScopeNamespace, updateLeanScopes, type LeanScope } from './leanSyntax';
import { leanNameWithoutRoot, maskLeanCommentsAndStrings, leanScopeCommands, leanScopeNamespace, updateLeanScopes, type LeanScope } from './leanSyntax';
import { mathDigest } from './mathRuntimeIo';

export const inspectLeanSource = (
Expand Down Expand Up @@ -97,8 +97,9 @@ export function repeatedLeanLocalNames(names: readonly string[]): string {
/** The declaration a closed type query reopens; a same-named declaration in another namespace is not it. */
export function findLeanTypeQueryDeclaration(source: string, theoremName: string) {
const declarations = inspectScopedLeanDeclarations(source);
return declarations.find(declaration => declaration.qualifiedName === theoremName) ??
declarations.find(declaration => declaration.name === theoremName);
const requested = leanNameWithoutRoot(theoremName);
return declarations.find(declaration => declaration.qualifiedName === requested) ??
(requested === theoremName ? declarations.find(declaration => declaration.name === theoremName) : undefined);
}

/** Reopen a declaration's namespaces and active lookup scopes for a closed type query. */
Expand Down
45 changes: 44 additions & 1 deletion src/math/leanSyntax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
export const isSimpleLeanName = (value: unknown): value is string => typeof value === 'string' &&
/^[\p{L}_][\p{L}\p{M}\p{N}_'?!]*(?:\.[\p{L}_][\p{L}\p{M}\p{N}_'?!]*)*$/u.test(value);

/** `_root_.` qualifies a Lean reference; it is not part of the constant's name. */
export const leanNameWithoutRoot = (name: string): string => name.replace(/^_root_\./u, '');

/** Recognize a single pasted declaration reference, without interpreting Lean expressions. */
export function leanLookupReference(query: string) {
const reference = query.trim().replace(/^#check\s+/u, '').replace(/^@/u, '');
if (!isSimpleLeanName(reference)) return undefined;
const rooted = reference.startsWith('_root_.');
return { name: rooted ? reference.slice(7) : reference, rooted };
return { name: leanNameWithoutRoot(reference), rooted };
}

/** Ordinary qualified names explicitly written in prose; preserve first mention and normalize root prefixes. */
Expand All @@ -21,6 +24,46 @@ export function maskLeanCommentsAndStrings(source: string, onDocComment?: (start
return maskLeanText(source, true, onDocComment);
}

export const MAX_LEAN_EXPECTED_TYPE_BYTES = 24_000;

/** Convert a pasted declaration signature to a type term. Lean still checks the type and universe parameters. */
export function parseLeanDeclarationType(type: string, declarationNames: readonly string[]): { type: string; universes?: string[] } {
const masked = maskLeanCommentsAndStrings(type);
const first = masked.search(/\S/u);
if (first < 0) return { type };
const nameStart = masked.startsWith('_root_.', first) ? first + '_root_.'.length : first;
const name = declarationNames.map(leanNameWithoutRoot).find(candidate => {
const end = nameStart + candidate.length;
return masked.startsWith(candidate, nameStart) &&
(masked.startsWith('.{', end) || /[\s:([{⦃]/u.test(masked[end] ?? ''));
});
let start = name ? nameStart + name.length : first;
let universes: string[] | undefined;
if (name && masked.startsWith('.{', start)) {
const end = masked.indexOf('}', start + 2);
if (end < 0) return { type };
universes = masked.slice(start + 2, end).trim().split(/\s*,\s*/u);
if (!universes.every(universe => isSimpleLeanName(universe) && !universe.includes('.'))) return { type };
start = end + 1;
}
const pairs: Readonly<Record<string, string>> = { '(': ')', '[': ']', '{': '}', '⦃': '⦄', '⟨': '⟩' };
const closing: string[] = [];
for (let position = start; position < masked.length; position++) {
const character = masked[position]!;
if (!closing.length && character === ':' && masked[position + 1] !== '=') {
// Removing binder comments prevents a trailing line comment from swallowing the inserted comma.
const binders = maskLeanComments(type.slice(start, position)).trim();
const conclusion = type.slice(position + 1).trim();
if (!conclusion) return { type };
return { type: binders ? `∀ ${binders}, ${conclusion}` : conclusion, ...(universes && { universes }) };
}
if (character === closing.at(-1)) closing.pop();
else if (Object.hasOwn(pairs, character) && (closing.length || character !== '⟨')) closing.push(pairs[character]!);
else if (!closing.length && !/\s/u.test(character)) return { type };
}
return { type };
}

/** Ordinary source scopes are lookup hints; Lean remains the authority on elaborated names.
* A `mutual` block is closed by a bare `end` too, so it is tracked as a scope that opens no namespace. */
export const leanScopeCommands = (cleaned: string) => cleaned.matchAll(
Expand Down
7 changes: 4 additions & 3 deletions src/math/leanTypeDiagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { assertMathConstructionSources, LAKE_CONFIGURATION_FILES as configs, mathLocalModuleBuildOrder } from './mathConstructionSources';
import { inspectLeanDeclarationRegions, leanDeclarationContextCommands } from './leanSource';
import { MAX_LEAN_EXPECTED_TYPE_BYTES } from './leanSyntax';
import { bindLeanPackages, prepareLeanDiagnosticOverrides, runLeanDiagnostics } from './leanDiagnostics';
import { resolveMathematicsRuntimeEnvironment } from './mathRuntimeEnvironment';
import { resolveMathProofEnvironment } from './mathProofEnvironment';
Expand All @@ -22,7 +23,7 @@ export function leanTypeDiagnosticCommands(type: string, output: string, applica
' if expression.hasMVar || expression.hasFVar || expression.hasLooseBVars then',
' throwError "Requested type must be closed without free variables or metavariables"',
' let rendered := (<- Lean.Meta.ppExpr expression).pretty',
' if rendered.utf8ByteSize > 24000 then throwError "Elaborated type exceeds its export bound"',
` if rendered.utf8ByteSize > ${MAX_LEAN_EXPECTED_TYPE_BYTES} then throwError "Elaborated type exceeds its export bound"`,
...(application === undefined ? [' let report := Lean.Json.mkObj [("type", Lean.toJson rendered)]'] : [
` let term <- match Lean.Parser.runParserCategory (<- Lean.getEnv) (Lean.Name.mkSimple "term") ${JSON.stringify(application)} with`,
' | .ok stx => pure stx', ' | .error message => throwError "{message}"',
Expand Down Expand Up @@ -71,7 +72,7 @@ export type LeanTypeDiagnosticInput = { projectRoot: string; file: string; conte

/** The host's advisory consumers and the executed clone must describe the same complete input. */
export function prepareLeanTypeDiagnostic(input: LeanTypeDiagnosticInput) {
if (!input.type.trim() || Buffer.byteLength(input.type) > 12000 || !input.context.trim() || input.context.length > 1000 ||
if (!input.type.trim() || Buffer.byteLength(input.type) > MAX_LEAN_EXPECTED_TYPE_BYTES || !input.context.trim() || input.context.length > 1000 ||
input.expression !== undefined && (!input.expression.trim() || Buffer.byteLength(input.expression) > 12000))
throw new Error('math_type_diagnostics_input_invalid');
const project = fs.realpathSync(input.projectRoot);
Expand Down Expand Up @@ -138,7 +139,7 @@ export async function checkLeanType(input: LeanTypeDiagnosticInput) {
let elaboratedType: string | undefined, constants: string[] | undefined;
if (diagnostics.exitCode === 0 && !diagnostics.timedOut && !diagnostics.aborted) {
const value = readMathJson(path.join(clone, projection.output)) as Record<string, unknown>;
if (typeof value.type !== 'string' || !value.type.trim() || Buffer.byteLength(value.type) > 24000)
if (typeof value.type !== 'string' || !value.type.trim() || Buffer.byteLength(value.type) > MAX_LEAN_EXPECTED_TYPE_BYTES)
throw new Error('math_type_diagnostics_export_invalid');
elaboratedType = value.type;
if (input.expression !== undefined) {
Expand Down
46 changes: 31 additions & 15 deletions src/math/verifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ import { createMathOperationLimiter, forEachWithConcurrency } from "./concurrenc
import { canonicalMathJson, mathDigest, mathFileIdentity, readMathFile, readMathText } from './mathRuntimeIo';
import { repositoryRelativePath } from './paths';
import { leanReferenceCommands, parseLeanReferences, type LeanDeclarationReferences } from './leanReferences';
import { leanDeclarationContextCommands } from './leanSource';
import { findLeanTypeQueryDeclaration, leanDeclarationContextCommands } from './leanSource';
import { leanNameWithoutRoot, MAX_LEAN_EXPECTED_TYPE_BYTES, parseLeanDeclarationType } from './leanSyntax';
import { withVerifierCheckout, type VerifierCheckoutCleanupFailure } from './verifierCheckout';

export type MathematicsVerifierBatchItem = {
Expand Down Expand Up @@ -237,6 +238,8 @@ type ResultBase = Omit<
>;

const MAX_OUTPUT = MATH_PROCESS_OUTPUT_LIMIT;
// A declaration export can carry two bounded reference reports along with its signature.
const LEAN_DECLARATION_QUERY_OUTPUT_LIMIT = MAX_LEAN_EXPECTED_TYPE_BYTES + 2 * MATH_PROCESS_OUTPUT_LIMIT;
const MAX_PROOF_BYTES = 16 * 1024 * 1024;
// Construction-time JSON adapters use stdin for one bounded request. Keep the
// public sandbox entry point bounded too, so a future protocol adapter cannot
Expand Down Expand Up @@ -1908,13 +1911,16 @@ const prepareLeanDeclarationQuery = async (
const queries = theoremQueries
.map(
({ name, declarationBegin, declarationEnd, axiomBegin, axiomEnd }) =>
`#eval IO.println ${JSON.stringify(declarationBegin)}\n#check ${name}\n#eval IO.println ${JSON.stringify(declarationEnd)}\n#eval IO.println ${JSON.stringify(axiomBegin)}\n#print axioms ${name}\n#eval IO.println ${JSON.stringify(axiomEnd)}`
`#eval IO.println ${JSON.stringify(declarationBegin)}\nset_option pp.deepTerms true in\n#check ${name}\n#eval IO.println ${JSON.stringify(declarationEnd)}\n#eval IO.println ${JSON.stringify(axiomBegin)}\n#print axioms ${name}\n#eval IO.println ${JSON.stringify(axiomEnd)}`
)
.join('\n');
const expectedType = options?.expectedDeclarationType;
const expectedTypes = theoremNames.flatMap(name => {
const type = options?.expectedDeclarationTypes?.[name] ?? expectedType;
return type === undefined ? [] : [{ name, type, context: leanDeclarationContextCommands(file.source, name) }];
if (type === undefined) return [];
const declaration = findLeanTypeQueryDeclaration(file.source, name);
return [{ name, rawType: type, context: leanDeclarationContextCommands(file.source, name),
...parseLeanDeclarationType(type, [name, ...(declaration ? [declaration.name, declaration.qualifiedName] : [])]) }];
});
const dependencyCandidates = options?.dependencyCandidates;
if (
Expand All @@ -1928,7 +1934,8 @@ const prepareLeanDeclarationQuery = async (
theoremNames.map((name) => [name, `DS_PROOF_DEPENDENCIES_${crypto.randomBytes(16).toString('hex')}:`])
);
const referenceMarkers = new Map(theoremNames.map(name => [name, `DS_DECL_REFERENCES_${crypto.randomBytes(16).toString('hex')}:`]));
if ((expectedType && theoremNames.length !== 1) || expectedTypes.some(item => !item.type || item.type.length > 12_000))
if ((expectedType && theoremNames.length !== 1) || expectedTypes.some(item => !item.rawType ||
Buffer.byteLength(item.rawType) > MAX_LEAN_EXPECTED_TYPE_BYTES))
throw new Error('Helper expected type requires one bounded declaration.');
const externalChecks = options
? [
Expand All @@ -1942,17 +1949,26 @@ const prepareLeanDeclarationQuery = async (
' if forbidden.contains moduleName.toString then throwError "Forbidden helper dependency: {moduleName}"',
]
: []),
...expectedTypes.flatMap(({ name, type, context }) => [
...expectedTypes.flatMap(({ name, type, context, universes }) => [
...context.before,
'run_cmd Lean.Elab.Command.liftTermElabM do',
` let parsedType <- match Lean.Parser.runParserCategory (<- Lean.getEnv) (Lean.Name.mkSimple "term") ${JSON.stringify(type)} with`,
' | .ok stx => pure stx',
' | .error message => throwError "{message}"',
' | .error message => throwError "Invalid expected declaration type. Supply a closed Lean type, for example (∀ (n : Nat), n = n). Parser: {message}"',
` let name := (${JSON.stringify(leanNameWithoutRoot(name))} : String).toName`,
...(universes ? [
' let info <- Lean.getConstInfo name',
` let levels : List Lean.Name := (${JSON.stringify(universes)} : List String).map String.toName`,
' unless levels.length == info.levelParams.length && levels.eraseDups.length == levels.length do',
' throwError "Helper declaration has different universe parameters"',
' Lean.Elab.Term.setLevelNames levels',
] : []),
' let expected <- Lean.Elab.Term.elabType parsedType',
' Lean.Elab.Term.synthesizeSyntheticMVarsNoPostponing',
' let expected <- Lean.instantiateMVars expected',
' if expected.hasMVar || expected.hasFVar then throwError "Helper expected type must be closed without metavariables"',
` let declaration <- Lean.Meta.mkConstWithFreshMVarLevels (${JSON.stringify(name)}.toName)`,
universes ? ' let declaration := Lean.mkConst name (levels.map Lean.Level.param)' :
' let declaration <- Lean.Meta.mkConstWithFreshMVarLevels name',
' let actual <- Lean.Meta.inferType declaration',
' unless (<- Lean.Meta.isDefEq actual expected) do throwError "Helper declaration has a different type or additional assumptions"',
...context.after,
Expand All @@ -1961,7 +1977,7 @@ const prepareLeanDeclarationQuery = async (
? theoremNames.flatMap((theoremName) => [
'run_cmd do',
' let env <- Lean.getEnv',
` let root <- Lean.getConstInfo (${JSON.stringify(theoremName)}.toName)`,
` let root <- Lean.getConstInfo (${JSON.stringify(leanNameWithoutRoot(theoremName))}.toName)`,
' let some proof := root.value? (allowOpaque := true) | throwError "Declaration has no proof value"',
' let mut todo := Lean.Expr.getUsedConstants proof |>.toList',
' let mut visited : Lean.NameSet := {}',
Expand All @@ -1981,11 +1997,11 @@ const prepareLeanDeclarationQuery = async (
])
: []),
...(options.referenceModules ? theoremNames.flatMap(name =>
leanReferenceCommands(name, options.referenceModules!, referenceMarkers.get(name)!)) : []),
leanReferenceCommands(leanNameWithoutRoot(name), options.referenceModules!, referenceMarkers.get(name)!)) : []),
...(options.directProof && options.referenceModules ? theoremNames.flatMap(name => [
'run_cmd do', ' let env <- Lean.getEnv',
` let modules : List (String × String) := [${options.referenceModules!.map(item => `(${JSON.stringify(item.module)}, ${JSON.stringify(item.file)})`).join(', ')}]`,
` let root <- Lean.getConstInfo (${JSON.stringify(name)}.toName)`,
` let root <- Lean.getConstInfo (${JSON.stringify(leanNameWithoutRoot(name))}.toName)`,
' let some proof := root.value? (allowOpaque := true) | return',
' let refs := (Lean.Expr.getUsedConstants proof).toList.filterMap fun n => Id.run do',
' let m := match env.getModuleIdxFor? n with | some i => env.header.moduleNames[i.toNat]!.toString | none => ""',
Expand Down Expand Up @@ -2042,8 +2058,7 @@ const prepareLeanDeclarationQuery = async (
}
const elaboratedType = stdout
.slice(start + query.declarationBegin.length, finish)
.trim()
.replace(/\s+/gu, ' ');
.trim();
if (!elaboratedType) return { error: `Lean exported an empty theorem declaration: ${query.name}` };
const hash = mathDigest(elaboratedType);
types.set(query.name, elaboratedType);
Expand Down Expand Up @@ -2294,7 +2309,7 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat
const regions = new Map(inspectLeanDeclarationRegions(file.source).map(region => [region.startOffset, region]));
const inspections = file.declarationInspections = new Map();
verifiableItems = verifiableItems.filter(item => {
const start = item.theoremName ? positions.get(item.theoremName) : undefined;
const start = item.theoremName ? positions.get(leanNameWithoutRoot(item.theoremName)) : undefined;
const region = start === undefined ? undefined : regions.get(start);
if (!item.theoremName || !item.expectedSourceDeclarationHash || !region) {
reject('A helper check in a draft requires one exact source-bound declaration name.', [item]);
Expand Down Expand Up @@ -2364,7 +2379,8 @@ async function verifyFormalFile(file: PreparedFile, context: FormalFileVerificat
sandboxCapability: context.sandboxCapability,
signal: options.signal,
timeoutMs: Math.min(requestedTimeoutMs, availableMs),
outputLimit: MATH_PROCESS_OUTPUT_LIMIT * Math.min(64, verifiableItems.length),
outputLimit: (declarationQuery ? LEAN_DECLARATION_QUERY_OUTPUT_LIMIT : MATH_PROCESS_OUTPUT_LIMIT) *
Math.min(64, verifiableItems.length),
captureSourceDiagnostics: true,
lakePackagesPath,
});
Expand Down Expand Up @@ -3021,7 +3037,7 @@ async function buildFormalVerificationCacheKey(
const environment = Object.fromEntries(environmentEntries);
const cacheKey = mathDigest(
JSON.stringify({
schema: 'deepscientist.formal-verification-cache.v1',
schema: 'deepscientist.formal-verification-cache.v3',
projectRootHash: mathDigest(projectRoot),
targetCommit: resolvedTarget,
verifierCommandPath: options.verifierCommandPath || null,
Expand Down
Loading
Loading