pud.dev 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +53 -27
  3. package/THIRD-PARTY-NOTICES +112 -0
  4. package/chunk-224av1ab.js +10 -0
  5. package/chunk-fstxscck.js +3 -0
  6. package/chunk-h90k6v7w.js +3 -0
  7. package/chunk-k7a83qqm.js +3 -0
  8. package/cli.js +37 -0
  9. package/index.js +2 -0
  10. package/lean/index.js +880 -0
  11. package/package.json +28 -19
  12. package/project-runner.js +2 -0
  13. package/types/assistant.d.ts +200 -0
  14. package/types/check.d.ts +55 -0
  15. package/types/expressions.d.ts +47 -0
  16. package/types/input-scope.d.ts +4 -0
  17. package/types/lean/command.d.ts +14 -0
  18. package/types/lean/index.d.ts +5 -0
  19. package/types/lean/number.d.ts +4 -0
  20. package/types/lean/program.d.ts +26 -0
  21. package/types/lean/replay-predicate.d.ts +5 -0
  22. package/types/lean/replay.d.ts +6 -0
  23. package/types/lean/scalar.d.ts +23 -0
  24. package/types/lean/subject.d.ts +25 -0
  25. package/types/lean/syntax.d.ts +42 -0
  26. package/types/module.d.ts +9 -0
  27. package/types/prover-process.d.ts +7 -0
  28. package/types/run.d.ts +30 -0
  29. package/types/source.d.ts +5 -0
  30. package/types/suite-authoring.d.ts +117 -0
  31. package/types/suite-check.d.ts +10 -0
  32. package/types/suite.d.ts +44 -0
  33. package/CLAUDE.md +0 -106
  34. package/scripts/pack.ts +0 -67
  35. package/scripts/setup-lean.ts +0 -88
  36. package/src/assistant.ts +0 -131
  37. package/src/check.ts +0 -173
  38. package/src/cli.ts +0 -70
  39. package/src/expressions.ts +0 -65
  40. package/src/input-scope.ts +0 -71
  41. package/src/lean/command.ts +0 -40
  42. package/src/lean/index.ts +0 -437
  43. package/src/lean/iteration.lean +0 -145
  44. package/src/lean/lean-assets.d.ts +0 -4
  45. package/src/lean/number.lean +0 -427
  46. package/src/lean/number.ts +0 -25
  47. package/src/lean/program.ts +0 -110
  48. package/src/lean/replay-predicate.ts +0 -95
  49. package/src/lean/replay.ts +0 -136
  50. package/src/lean/scalar.lean +0 -183
  51. package/src/lean/scalar.ts +0 -196
  52. package/src/lean/subject.ts +0 -443
  53. package/src/lean/syntax.ts +0 -287
  54. package/src/module.ts +0 -110
  55. package/src/project-runner.ts +0 -26
  56. package/src/prover-process.ts +0 -16
  57. package/src/reporter.ts +0 -173
  58. package/src/run.ts +0 -60
  59. package/src/source.ts +0 -54
  60. package/src/suite-authoring.ts +0 -135
  61. package/src/suite-check.ts +0 -157
  62. package/src/suite.ts +0 -515
  63. package/src/terminal-progress.ts +0 -145
  64. package/src/terminal.ts +0 -41
  65. package/test/authoring.test.ts +0 -151
  66. package/test/lean.test.ts +0 -394
  67. package/test/module.test.ts +0 -55
  68. package/test/number.test.ts +0 -318
  69. package/test/package.test.ts +0 -170
  70. package/test/suite.test.ts +0 -257
  71. package/tsconfig.json +0 -7
  72. package/tsconfig.pack.json +0 -12
  73. /package/{src/index.ts → types/index.d.ts} +0 -0
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{Unsupported2,failure,parseExpression,invalid,parseSourceModule,resolveTypeScriptImport}from"./chunk-224av1ab.js";import{readFileSync as readFileSync2,realpathSync}from"fs";import{resolve as resolve3}from"path";import{readFileSync,statSync}from"fs";import{dirname as dirname2,join,resolve as resolve2}from"path";import{pathToFileURL}from"url";var forward={"===":"eq","<=":"lte",">=":"gte"};var reversed={"===":"eq","<=":"gte",">=":"lte"};function literal(node){if(node.type==="BooleanLiteral")return String(node.value);const negative=node.type==="UnaryExpression"&&node.operator==="-";const value=negative?node.argument:node;if(value.type==="NumericLiteral")return String(negative?-value.value:value.value);if(value.type==="BigIntLiteral")return String(negative?-BigInt(value.value):BigInt(value.value))+"n"}function quantified(spec){if(spec.kind==="quantifier")return true;if(spec.kind==="not")return quantified(spec.operand);return spec.kind==="binary"&&(quantified(spec.left)||quantified(spec.right))}function concreteScope(parameters,claim){if(claim.assertions.some((a)=>(a.kind==="refinement"||a.kind==="proposition")&&quantified(a.predicate)))return;if(!parameters.length)return"no-inputs";const fixed=new Set;const bounds=new Map;function constrain(name,operator,node){const value=literal(node);if(value===undefined)return;if(operator==="eq"){fixed.add(name);return}const range=bounds.get(name)??{lower:new Set,upper:new Set};bounds.set(name,range);range[operator==="gte"?"lower":"upper"].add(value);if(range.lower.has(value)&&range.upper.has(value))fixed.add(name)}function equalities(expression,local){const visit=(node)=>{if(node.type==="LogicalExpression"&&node.operator==="&&"){visit(node.left);visit(node.right)}if(node.type!=="BinaryExpression")return;const{left,right,operator}=node;if(operator!=="==="&&operator!=="<="&&operator!==">=")return;const variable=left.type==="Identifier"?left:right.type==="Identifier"?right:undefined;if(!variable)return;const name=local?.[0]===variable.name?local[1]:expression.bindings.get(variable.name);if(!name)return;if(variable===left)constrain(name,forward[operator],right);else constrain(name,reversed[operator],left)};visit(parseExpression(expression.source,{plugins:["typescript"]}))}function facts(spec,local){if(spec.kind==="boolean")equalities(spec.expression,local);if(spec.kind==="binary"&&spec.operator==="and"){facts(spec.left,local);facts(spec.right,local)}}for(const premise of claim.premises){if(premise.kind==="condition")equalities(premise.expression);if(premise.kind==="proposition")facts(premise.predicate);if(premise.kind==="refinement"&&premise.target.kind==="parameter")facts(premise.predicate,[premise.variable,premise.target.name]);if((premise.kind==="sameValue"||premise.kind==="nearestInteger")&&premise.target.kind==="parameter"){constrain(premise.target.name,"eq",parseExpression(premise.value.source,{plugins:["typescript"]}))}if(premise.kind==="comparison"&&premise.target.kind==="parameter"&&(premise.operator==="eq"||premise.operator==="gte"||premise.operator==="lte")){constrain(premise.target.name,premise.operator,parseExpression(premise.value.source,{plugins:["typescript"]}))}}if(parameters.every((p)=>fixed.has(p.name)))return"literal-inputs"}var package_default={name:"pud.dev",type:"module",version:"0.0.2",description:"Write proofs for TypeScript functions and check them with Lean.",homepage:"https://pud.dev",repository:{type:"git",url:"git+https://github.com/PudHQ/pud.git",directory:"packages/pud"},bugs:"https://github.com/PudHQ/pud/issues",keywords:["typescript","formal-verification","proof-assistant","lean4","bun"],license:"MIT",exports:{".":"./src/index.ts","./lean":"./src/lean/index.ts"},bin:{pud:"./src/cli.ts"},dependencies:{"@babel/parser":"catalog:","@babel/types":"catalog:",chalk:"catalog:"},devDependencies:{"@types/node":"catalog:"},scripts:{pack:'"$npm_execpath" ./scripts/pack.ts',test:'"$npm_execpath" test',typecheck:"tsc --noEmit"}};import{dirname,resolve}from"path";var authoringPackage=package_default.name;var portableHelpers=new Set(["describe","expect","given","it","native","pud"]);var configuredHelpers=new Set(["expect","given","it","pud","use"]);var comparisons=new Set(["eq","gt","gte","lt","lte"]);var assistantId=/^[a-z][a-z0-9_-]*$/;var qualifiedName=/^[A-Za-z_][A-Za-z0-9_']*(\.[A-Za-z_][A-Za-z0-9_']*)*$/;var emptyBindings=new Map;function named(node,name){return name!==undefined&&node?.type==="Identifier"&&node.name===name}function identifier(file,node){if(node?.type!=="Identifier"||node.name==="this"||node.optional||node.decorators?.length){return invalid(file,node??undefined,"Expected a named binding.")}return node.name}function directCall(node,name){if(node?.type==="CallExpression"&&!node.typeArguments&&named(node.callee,name))return node}function memberCall(node,typeArguments=false){if(node?.type!=="CallExpression"||!typeArguments&&node.typeArguments||node.callee.type!=="MemberExpression"||node.callee.computed||node.callee.property.type!=="Identifier")return;return{call:node,receiver:node.callee.object,name:node.callee.property.name}}function arity(file,call,count){if(call.arguments.length!==count)invalid(file,call,`Expected ${count} argument(s).`);return call.arguments}function staticString(file,node){if(node?.type==="StringLiteral")return node.value;if(node?.type==="TemplateLiteral"&&!node.expressions.length&&node.quasis[0]?.value.cooked!=null){return node.quasis[0].value.cooked}return invalid(file,node,"Expected a static string.")}function blockArrow(file,node,count){if(node?.type!=="ArrowFunctionExpression"||node.async||node.typeParameters||node.body.type!=="BlockStatement"||node.params.length!==count){return invalid(file,node,`Expected a synchronous block callback with ${count} parameter(s).`)}return{params:node.params,statements:node.body.body}}function fields(file,node,kind){if(node?.type!==kind)invalid(file,node,"Expected an object of named fields.");const keys=new Set;return node.properties.map((field)=>{if(field.type!=="ObjectProperty"||field.computed||field.key.type!=="Identifier"){return invalid(file,field,"Expected a plain named field.")}const key=field.key.name;if(keys.has(key))invalid(file,field,`Duplicate field '${key}'.`);keys.add(key);return{key,value:field.value}})}var relativeConfig=/^\.\.?\/(?:.*\/)?pud\.config(?:\.ts)?$/;function readSuite(file,origin,source,program,config){const manifest=program.body.find((node)=>node.type==="ExportDefaultDeclaration");if(manifest)invalid(file,manifest,`Declare a suite with describe() from '${authoringPackage}' or pud.describe() from the project config.`);const base=dirname(origin);const helpers=new Map;const native=new Map;const subjects=new Map;const imports=[];const paths=new Map;function resolveImport(specifier){const cached=paths.get(specifier.value);if(cached)return cached;const resolveAgain=()=>resolveTypeScriptImport(file,specifier,base);const path=resolveAgain();if(!specifier.value.endsWith(".ts"))imports.push({path,resolveAgain});paths.set(specifier.value,path);return path}let configBinding;let describe;let configured=false;for(const statement of program.body){if(describe)invalid(file,statement,"Expected one describe() suite after the imports.");if(statement.type==="ImportDeclaration"){if(statement.importKind==="type")continue;if(statement.attributes?.length||statement.phase||!statement.specifiers.length){invalid(file,statement,"Import proof helpers and the subject by name.")}const path=statement.source.value;if(relativeConfig.test(path)){const[spec]=statement.specifiers;if(configBinding||statement.specifiers.length!==1||spec?.type!=="ImportDefaultSpecifier"||resolveImport(statement.source)!==config){invalid(file,statement,"Import the default export of this project's pud.config.ts.")}configBinding=spec.local.name;continue}for(const spec of statement.specifiers){if(spec.type!=="ImportSpecifier"||spec.imported.type!=="Identifier")invalid(file,spec,"Use named imports.");if(spec.importKind==="type")continue;const{imported,local}=spec;if(path===authoringPackage&&portableHelpers.has(imported.name)){if(helpers.has(imported.name))invalid(file,spec,"Import each proof helper once.");helpers.set(imported.name,local.name)}else if(path===`${authoringPackage}/lean`&&imported.name==="lean"){native.set(local.name,"lean")}else{subjects.set(local.name,{file:resolveImport(statement.source),name:imported.name})}}continue}if(statement.type==="VariableDeclaration"&&statement.kind==="const"&&statement.declarations.length===1){const declaration=statement.declarations[0];const call=directCall(declaration.init,helpers.get("native"));if(call){const[argument]=arity(file,call,1);const id=staticString(file,argument);if(!assistantId.test(id))invalid(file,argument,"Use a literal proof assistant identifier.");native.set(identifier(file,declaration.id),id);continue}}if(statement.type!=="ExpressionStatement")invalid(file,statement,"Expected imports and describe().");const call=memberCall(statement.expression);if(call?.name==="describe"&&named(call.receiver,configBinding)){describe=call.call;configured=true}else{describe=directCall(statement.expression,helpers.get("describe"));if(!describe)invalid(file,statement,"Use describe(subject, callback) or pud.describe(subject, callback).")}}if(!describe)invalid(file,undefined,"Expected a describe() suite.");const[target,callback]=arity(file,describe,2);const binding=identifier(file,target);const subject=subjects.get(binding)??invalid(file,target,"The subject must be a named TypeScript import.");const{params,statements}=blockArrow(file,callback,configured?1:0);const numberImported=configBinding==="Number"||subjects.has("Number")||native.has("Number")||[...helpers.values()].includes("Number");if(configured){helpers.clear();for(const{key,value}of fields(file,params[0],"ObjectPattern")){if(!configuredHelpers.has(key))invalid(file,value,`Unknown proof helper '${key}'.`);const name=identifier(file,value);if(subjects.has(name)||native.has(name))invalid(file,value,"Proof helpers cannot shadow an imported function or a native tag.");helpers.set(key,name)}}const schemaBindings=new Set;const schemaHelper=helpers.get("pud");if(schemaHelper)schemaBindings.add(schemaHelper);if(configured&&configBinding&&![...helpers.values()].includes(configBinding))schemaBindings.add(configBinding);const properties=[];const modules=[];const names=new Set;for(const statement of statements){if(statement.type!=="ExpressionStatement")invalid(file,statement,"Use it(), it.todo(), or use() in the suite.");const use=directCall(statement.expression,helpers.get("use"));if(use){if(properties.length)invalid(file,statement,"Declare native modules before properties.");const[argument]=arity(file,use,1);const module=memberCall(argument);const assistant=module?.receiver.type==="Identifier"&&native.get(module.receiver.name);if(module?.name!=="module"||!assistant)invalid(file,argument,"Use an assistant's module() helper.");const[path]=arity(file,module.call,1);const specifier=staticString(file,path);if(!/^\.\.?\//.test(specifier))invalid(file,path,"Use a relative path to the proof module.");modules.push({assistant,file:resolve(base,specifier)});continue}const member=memberCall(statement.expression);const todo=member?.name==="todo"&&named(member.receiver,helpers.get("it"));const by=member?.name==="by"?member:undefined;const call=todo?member.call:directCall(by?by.receiver:statement.expression,helpers.get("it"));if(!call)invalid(file,statement,"Use it() or it.todo() for each property.");const name=staticString(file,call.arguments[0]);if(!name.trim()||names.has(name))invalid(file,call,"Use a unique, non-empty property title.");names.add(name);const line=call.loc.start.line;if(todo){arity(file,call,1);properties.push({kind:"todo",name,line})}else{const proof=by&&arity(file,by.call,1)[0];properties.push({kind:"claim",name,line,call,proof})}}if(!properties.length)invalid(file,describe,"Add at least one property or an it.todo().");const numberGlobal=!numberImported&&![...helpers.values()].includes("Number");return{file,source,subject,subjects,binding,properties,modules,helpers,schemaBindings,native,configured,imports,numberGlobal}}function expression(suite,node,bindings){if(!node||node.type==="SpreadElement"||node.type==="ArgumentPlaceholder"){return invalid(suite.file,node,"Expected a TypeScript expression.")}const at=node.loc.start;return{file:suite.file,source:suite.source.slice(node.start,node.end),line:at.line,column:at.column,offset:node.start,bindings,schemaBindings:suite.schemaBindings,numberGlobal:suite.numberGlobal}}function nativeTerm(suite,node,bindings){const{file,native}=suite;if(!suite.configured)invalid(file,node,"Import pud from pud.config.ts and use pud.describe() for native proof terms.");if(node?.type==="TaggedTemplateExpression"&&!node.typeArguments&&node.tag.type==="Identifier"){const assistant=native.get(node.tag.name);if(assistant){const parts=node.quasi.quasis.map((part)=>part.value.cooked??invalid(file,part,"Invalid escape in the native proof template."));return{kind:"template",assistant,parts,args:node.quasi.expressions.map((arg)=>expression(suite,arg,bindings))}}}const reference=memberCall(node);const assistant=reference?.receiver.type==="Identifier"&&native.get(reference.receiver.name);if(!assistant||reference?.name!=="ref")return invalid(file,node,"Use a native proof template or a named reference.");const[head,...args]=reference.call.arguments;const name=staticString(file,head);if(!qualifiedName.test(name))invalid(file,head,"Expected a qualified theorem or predicate name.");return{kind:"reference",assistant,name,args:args.map((arg)=>expression(suite,arg,bindings))}}function isSchemaBuilder(suite,node){return node.type==="Identifier"&&suite.schemaBindings.has(node.name)}function isSchema(suite,node,type){const schema=memberCall(node,true);if(!schema||!isSchemaBuilder(suite,schema.receiver))return false;const{name,call}=schema;if(type.kind==="opaque"){const args=call.typeArguments;const item=args?.type==="TSTypeParameterInstantiation"&&args.params[0];return name==="opaque"&&!call.arguments.length&&!!item&&args.params.length===1&&item.type==="TSTypeReference"&&!item.typeArguments&&named(item.typeName,type.name)}if(call.typeArguments)return false;switch(type.kind){case"integer":return(name==="bigint"||name==="int")&&!call.arguments.length;case"number":return name==="number"&&!call.arguments.length;case"boolean":return(name==="boolean"||name==="bool")&&!call.arguments.length;case"array":case"textOrArray":return name===type.kind&&call.arguments.length===1&&isSchema(suite,call.arguments[0],type.item)}}function schemaHint(type){switch(type.kind){case"integer":return"pud.bigint()";case"number":return"pud.number()";case"boolean":return"pud.boolean()";case"opaque":return`pud.opaque<${type.name}>()`;case"array":case"textOrArray":return`pud.${type.kind}(${schemaHint(type.item)})`}}function predicateCallback(suite,node,bindings){const{file,schemaBindings}=suite;if(node?.type!=="ArrowFunctionExpression"||node.async||node.typeParameters||node.params.length!==1){return invalid(file,node,"Use a synchronous predicate with one parameter.")}const variable=identifier(file,node.params[0]);if(schemaBindings.has(variable)||suite.native.has(variable)){invalid(file,node.params[0],"The predicate parameter cannot shadow Pud's helpers or a native tag.")}if(node.body.type!=="BlockStatement")return{variable,predicate:proofPredicate(suite,node.body,bindings)};const[statement]=node.body.body;if(node.body.body.length!==1||statement?.type!=="ReturnStatement"||!statement.argument){return invalid(file,node.body,"Return a single predicate expression.")}return{variable,predicate:proofPredicate(suite,statement.argument,bindings)}}function quantifiedType(suite,node){const chain=memberCall(node,true);if(!chain)return;if(!isSchemaBuilder(suite,chain.receiver))return quantifiedType(suite,chain.receiver);if(chain.name==="bigint"||chain.name==="int")return"integer";if(chain.name==="number")return"number";if(chain.name==="boolean"||chain.name==="bool")return"boolean"}function proofPredicate(suite,node,bindings){const call=memberCall(node,true);if(!call||!isSchemaBuilder(suite,call.receiver))return{kind:"boolean",expression:expression(suite,node,bindings)};const read=(part)=>proofPredicate(suite,part,bindings);switch(call.name){case"not":{const[operand]=arity(suite.file,call.call,1);return{kind:"not",operand:read(operand)}}case"and":case"or":case"implies":case"iff":{const[left,right]=arity(suite.file,call.call,2);return{kind:"binary",operator:call.name,left:read(left),right:read(right)}}case"forall":case"exists":{const[input,callback]=arity(suite.file,call.call,2);const type=quantifiedType(suite,input);const domain=type?{kind:"schema",type,constraints:schemaConstraints(suite,input,{kind:type},{kind:"quantified"},bindings)}:{kind:"array",expression:expression(suite,input,bindings)};return{kind:"quantifier",quantifier:call.name,domain,...predicateCallback(suite,callback,bindings)}}default:return{kind:"boolean",expression:expression(suite,node,bindings)}}}function schemaConstraints(suite,node,type,target,bindings){if(isSchema(suite,node,type))return[];const chain=memberCall(node);if(!chain||isSchemaBuilder(suite,chain.receiver)){const value=target.kind==="result"?"the result":target.kind==="quantified"?"the quantified value":`parameter '${target.name}'`;return invalid(suite.file,node,`Use ${schemaHint(type)} for ${value}.`)}const constraints=schemaConstraints(suite,chain.receiver,type,target,bindings);if(type.kind==="number"&&chain.name==="nearestIntegerTo"){const[value,options]=arity(suite.file,chain.call,2);const policy=fields(suite.file,options,"ObjectExpression");if(policy.length!==1||policy[0].key!=="ties")invalid(suite.file,options,'Specify { ties: "up" } or { ties: "down" }.');const ties=staticString(suite.file,policy[0].value);if(ties!=="up"&&ties!=="down")invalid(suite.file,options,'Choose "up" or "down" for half-integer ties.');return[...constraints,{kind:"nearestInteger",target,value:expression(suite,value,bindings),ties}]}const[value]=arity(suite.file,chain.call,1);if(chain.name==="refine"){constraints.push({kind:"refinement",target,...predicateCallback(suite,value,bindings)})}else if(type.kind==="number"&&chain.name==="sameValue"){constraints.push({kind:"sameValue",target,value:expression(suite,value,bindings)})}else if(chain.name==="satisfies"&&type.kind!=="textOrArray"&&type.kind!=="opaque"){constraints.push({kind:"native",target,term:nativeTerm(suite,value,bindings)})}else if((type.kind==="integer"||type.kind==="number")&&comparisons.has(chain.name)||type.kind==="boolean"&&chain.name==="eq"){constraints.push({kind:"comparison",target,operator:chain.name,value:expression(suite,value,bindings)})}else invalid(suite.file,node,`Unknown ${type.kind} matcher '${chain.name}'.`);return constraints}function bindClaim(suite,property,subject){const{file,helpers}=suite;const[,schemas,callback]=arity(file,property.call,3);const{params,statements}=blockArrow(file,callback,1);const parameters=new Map(subject.parameters.map((p)=>[p.name,p.type]));const domain=fields(file,schemas,"ObjectExpression");if(domain.length!==parameters.size)invalid(file,schemas,"Declare one input schema per subject parameter.");const callbackSuite=statements.some((step)=>step.type==="VariableDeclaration"&&step.declarations.some((declaration)=>named(declaration.id,"Number")))?{...suite,numberGlobal:false}:suite;const premises=domain.flatMap(({key,value})=>{const type=parameters.get(key)??invalid(file,value,`No subject parameter named '${key}'.`);return schemaConstraints(suite,value,type,{kind:"parameter",name:key},emptyBindings)});suite=callbackSuite;const bindings=new Map;const reserved=new Set([...helpers.values(),...suite.schemaBindings,...suite.native.keys(),...suite.subjects.keys()]);const inputs=fields(file,params[0],"ObjectPattern");if(inputs.length!==parameters.size)invalid(file,params[0],"Destructure every input in the property callback.");for(const{key,value}of inputs){if(!parameters.has(key))invalid(file,value,`No subject parameter named '${key}'.`);const alias=identifier(file,value);if(bindings.has(alias)||reserved.has(alias))invalid(file,value,"Input bindings cannot shadow the subject or proof helpers.");bindings.set(alias,key)}const results=new Map;const assertions=[];let claim;let observation;let observationKey;let resultType=subject.result;function readCall(node){const callee=node?.type==="CallExpression"&&!node.typeArguments&&node.callee.type==="Identifier"?node.callee.name:undefined;const linked=callee&&suite.subjects.get(callee);if(!linked||node?.type!=="CallExpression"){return invalid(file,node??undefined,"Call a named TypeScript import directly.")}return{kind:"call",callee:callee===suite.binding?"subject":linked,args:node.arguments.map((arg)=>{const parameter=arg.type==="Identifier"&&bindings.get(arg.name);return parameter?{kind:"parameter",name:parameter}:readCall(arg)})}}const includesSubject=(call)=>call.callee==="subject"||call.args.some((arg)=>arg.kind==="call"&&includesSubject(arg));function observe(call,at){const key=JSON.stringify(call);if(observationKey!==undefined&&observationKey!==key){invalid(file,at,"Use one observed call expression per property.")}if(observationKey!==undefined)return;observationKey=key;const direct=call.callee==="subject"&&call.args.every((arg)=>arg.kind==="parameter");if(direct){if(call.args.length!==parameters.size||call.args.some((arg,index)=>arg.kind!=="parameter"||arg.name!==subject.parameters[index].name)){invalid(file,at,"Pass the declared inputs to the subject in parameter order.")}return}if(!includesSubject(call))invalid(file,at,"The observed expression must call the subject of the suite.");if(!subject.inspectCall)invalid(file,at,"The selected assistant does not support composed calls.");resultType=subject.inspectCall(call);observation=call}for(const step of statements){if(step.type==="VariableDeclaration"&&step.kind==="const"&&step.declarations.length===1){const local=step.declarations[0];const name=identifier(file,local.id);if(reserved.has(name)||bindings.has(name)||results.has(name))invalid(file,local.id,"Use a fresh binding for the subject result.");if(claim?.kind==="throw")invalid(file,local,"Keep the throwing call inside expect's callback.");const call=readCall(local.init);observe(call,local);results.set(name,call);continue}if(step.type!=="ExpressionStatement")invalid(file,step,"Use given(), a subject call, or an expect() assertion.");const given=directCall(step.expression,helpers.get("given"));if(given){if(claim)invalid(file,step,"Put given() before the assertions.");const[condition]=arity(file,given,1);const predicate=proofPredicate(suite,condition,bindings);premises.push(predicate.kind==="boolean"?{kind:"condition",expression:predicate.expression}:{kind:"proposition",predicate});continue}const to=memberCall(step.expression);const expect=to&&["to","toExactly","toEqual","toThrow"].includes(to.name)&&directCall(to.receiver,helpers.get("expect"));if(!to||!expect)invalid(file,step,"Use expect() with to(), toExactly(), toEqual(), or toThrow().");const[result]=arity(file,expect,1);const[matcher]=arity(file,to.call,1);if(to.name==="toThrow"){if(claim||results.size)invalid(file,step,"Use one throw assertion with its call inside expect.");if(result?.type!=="ArrowFunctionExpression"||result.async||result.typeParameters||result.params.length||result.body.type==="BlockStatement"){invalid(file,result,"Use a parameterless arrow expression for a throwing call.")}const error=staticString(file,matcher);if(!subject.errors?.some((kind)=>kind===error))invalid(file,matcher,"Select an exception supported by the configured assistant.");observe(readCall(result.body),result);claim={kind:"throw",premises,assertions:[],expectedError:error};continue}if(claim&&(claim.kind!=="return"||claim.exactResult))invalid(file,step,"Use one outcome per property.");const local=result?.type==="Identifier"&&results.get(result.name);observe(local||readCall(result),result);if(to.name==="toEqual"){if(claim)invalid(file,step,"Use toEqual() as the only assertion in its property.");if(!subject.callEquality||!subject.inspectCall)invalid(file,step,"The selected assistant does not support equality between calls.");const reference=readCall(matcher);const expected=subject.inspectCall(reference);if(resultType.kind!=="integer"&&resultType.kind!=="number"&&resultType.kind!=="boolean"||resultType.kind!==expected.kind){invalid(file,matcher,"Use toEqual() with calls returning the same scalar type.")}claim={kind:"equal",premises,assertions:[],reference};continue}const exact=to.name==="toExactly";if(exact){if(claim)invalid(file,step,"Combine the result conditions in one toExactly() schema.");if(!subject.exactResults)invalid(file,step,"The selected assistant does not support exact result schemas.");if(!["integer","number","boolean"].includes(resultType.kind))invalid(file,matcher,"Use toExactly() with a scalar result.")}const clauses=schemaConstraints(suite,matcher,resultType,{kind:"result"},bindings);if(!clauses.length&&!exact)invalid(file,matcher,"Add a constraint to the result schema.");assertions.push(...clauses);claim??={kind:"return",premises,assertions,...exact&&{exactResult:true}}}if(!claim)invalid(file,property.call,"Add an assertion or use it.todo().");const proof=property.proof&&nativeTerm(suite,property.proof,emptyBindings);return{...claim,proof,...observation&&{observation}}}function findConfig(file){for(let dir=dirname2(file);;dir=dirname2(dir)){const candidate=join(dir,"pud.config.ts");if(statSync(candidate,{throwIfNoEntry:false})?.isFile())return candidate;if(dirname2(dir)===dir)return}}async function importConfig({canonical,source}){if(readFileSync(canonical,"utf8")!==source)throw new Error(`${canonical} changed during verification. Rerun pud check.`);return(await import(pathToFileURL(canonical).href)).default?.adapter}async function loadAdapter(config,override,read){const adapter=override??(config?await importConfig(read(config)):undefined);if(!adapter||typeof adapter.id!=="string"||!/^[a-z][a-z0-9_-]*$/.test(adapter.id)||typeof adapter.prepare!=="function"){throw new Error("Select a proof assistant with the adapter field in pud.config.ts or pass an adapter option.")}return adapter}async function prepare(suite,adapter,read){const{canonical,source}=read(suite.subject.file);if(!canonical.endsWith(".ts")||canonical.endsWith(".d.ts")){throw new Unsupported2(`${suite.subject.file} must resolve to a TypeScript implementation file.`)}const subject=await adapter.prepare({file:canonical,source,name:suite.subject.name,readDependency:(dependency)=>read(resolve2(dirname2(canonical),dependency)).source,readModule(path,resolveAgain){if(resolveAgain)suite.imports.push({path,resolveAgain});return read(path)}});if(!subject||!Array.isArray(subject.parameters)||!subject.result||typeof subject.emit!=="function"||typeof subject.verify!=="function"){throw new Error(`The ${adapter.id} adapter must provide a subject signature, emit(), and verify().`)}return subject}function modulesFor(suite,assistant,read){const files=new Set(suite.modules.filter((module)=>module.assistant===assistant).map((module)=>module.file));return[...files].map((file)=>({file,source:read(file).source}))}function*predicateTerms(predicate){switch(predicate.kind){case"boolean":return;case"not":yield*predicateTerms(predicate.operand);return;case"binary":yield*predicateTerms(predicate.left);yield*predicateTerms(predicate.right);return;case"quantifier":if(predicate.domain.kind==="schema")yield*constraintTerms(predicate.domain.constraints);yield*predicateTerms(predicate.predicate)}}function*constraintTerms(constraints){for(const constraint of constraints){if(constraint.kind==="native")yield constraint.term;if(constraint.kind==="refinement"||constraint.kind==="proposition")yield*predicateTerms(constraint.predicate)}}function checkAssistant(claim,assistant){const terms=[claim.proof,...constraintTerms(claim.premises),...constraintTerms(claim.assertions)];const incompatible=terms.find((term)=>term&&term.assistant!==assistant);if(incompatible)throw new Unsupported2(`This property uses ${incompatible.assistant} proof code. The selected adapter is ${assistant}.`)}async function checkSuite(suite,config,options,read,report){const results=[];const finished=new Set;const active=suite.properties.flatMap((property,index)=>property.kind==="claim"?[{property,index}]:[]);let assistant;function finish(index,status){if(!report||finished.has(index))return;finished.add(index);report({kind:"finished",indices:[index],statuses:[status]})}function record(index,result){results[index]=result;finish(index,result.status)}if(active.length){try{const adapter=await loadAdapter(config,options.adapter,read);assistant=adapter.id;const subject=await prepare(suite,adapter,read);const accepted=[];for(const{property,index}of active){try{const claim=bindClaim(suite,property,subject);checkAssistant(claim,assistant);accepted.push({index,claim})}catch(error){record(index,failure(error))}}if(accepted.length){report?.({kind:"running",indices:accepted.map((item)=>item.index)});const outcomes=await subject.verify(accepted.map((item)=>item.claim),modulesFor(suite,assistant,read),report?(offset,state,status)=>{const item=accepted[offset];if(!item||finished.has(item.index))return;if(state==="running")report({kind:"running",indices:[item.index]});else if(status)finish(item.index,status)}:undefined);if(!Array.isArray(outcomes)||outcomes.length!==accepted.length||accepted.some((_,index)=>!["proved","disproved","unproved","unsupported","error"].includes(outcomes[index]?.status??""))){throw new Error("The proof assistant must return one verdict per submitted claim.")}for(const[offset,{index,claim}]of accepted.entries()){const outcome=outcomes[offset];const scope=concreteScope(subject.parameters,claim);record(index,{...outcome,...scope&&{concreteScope:scope},...claim.exactResult&&{exactResult:true},...outcome.status==="disproved"&&{detail:outcome.counterexample.summary}})}}}catch(error){for(const{index}of active)if(!results[index])record(index,failure(error))}}return suite.properties.map((property,index)=>({...property.kind==="todo"?{status:"todo"}:results[index],name:property.name,line:property.line,subject:suite.subject.name,...assistant&&{assistant}}))}async function emitSuite(suite,config,options,read){const active=suite.properties.filter((property)=>property.kind==="claim");const matches=options.property?active.filter((property)=>[suite.binding,property.name,`${suite.binding}.${property.name}`].includes(options.property)):active;if(matches.length!==1){throw new Error(`Select one active property. Available: ${active.map((property)=>property.name).join(", ")||"none"}.`)}const adapter=await loadAdapter(config,options.adapter,read);const subject=await prepare(suite,adapter,read);const claim=bindClaim(suite,matches[0],subject);checkAssistant(claim,adapter.id);return subject.emit(claim,modulesFor(suite,adapter.id,read))}class SourceSnapshots{inputs=new Map;contents=new Map;read(file){const path=resolve3(file);const existing=this.inputs.get(path);if(existing)return existing;let snapshot;try{const canonical=realpathSync(path);let source=this.contents.get(canonical);if(source===undefined){source=readFileSync2(canonical,"utf8");this.contents.set(canonical,source)}snapshot={canonical,source}}catch(error){snapshot={error}}this.inputs.set(path,snapshot);return snapshot}changes(){const current=new SourceSnapshots,changed=new Map;for(const[path,before]of this.inputs){const after=current.read(path);if("error"in before!=="error"in after||"source"in before&&"source"in after&&(before.canonical!==after.canonical||before.source!==after.source)){changed.set(path,new Error(`${path} changed during verification. Rerun pud check.`))}}return changed}}function snapshotReader(snapshots,dependencies){return(file)=>{const path=resolve3(file);dependencies?.add(path);const input=snapshots.read(path);if("error"in input)throw input.error;return input}}function remappedImports(imports){const changed=new Map;for(const{path,resolveAgain}of imports){try{if(resolveAgain()===path)continue}catch{}changed.set(path,new Error(`The import of ${path} changed during verification. Rerun pud check.`))}return changed}function parseSuite(file,read){if(!file.endsWith(".proof.ts"))throw new Error(`Expected a *.proof.ts file: ${file}`);const{canonical:origin,source}=read(file);const config=findConfig(origin);const suite=readSuite(file,origin,source,parseSourceModule(file,source),config);return{suite,config,origin}}async function checkFiles3(files,options={}){const snapshots=new SourceSnapshots;const read=snapshotReader(snapshots);const plans=files.map((file)=>{try{const plan=parseSuite(file,read);if(plan.suite.properties.some((property)=>property.kind==="claim")){snapshots.read(plan.suite.subject.file);if(plan.config&&!options.adapter)snapshots.read(plan.config);for(const module of plan.suite.modules)snapshots.read(module.file)}return{file,...plan,dependencies:new Set,results:[]}}catch(error){return{file,error:failure(error)}}});const progress=options.onProgress;const totalItems=progress?plans.reduce((count,plan)=>count+("error"in plan?0:plan.suite.properties.filter((property)=>property.kind==="claim").length),0):0;for(const[index,plan]of plans.entries()){if(progress){const items="error"in plan?[]:plan.suite.properties.map((property)=>({name:property.name,todo:property.kind==="todo"}));progress({kind:"suite",file:plan.file,index,total:plans.length,totalItems,items})}if("error"in plan)continue;const report=progress&&((event)=>progress({...event,file:plan.file}));plan.results=await checkSuite(plan.suite,plan.config,options,snapshotReader(snapshots,plan.dependencies),report)}if(plans.length&&progress)await progress({kind:"validating"});const changed=snapshots.changes();return plans.map((plan)=>{const{file}=plan;const sidecarChange=changed.get(resolve3(file));if("error"in plan)return{file,results:[sidecarChange?failure(sidecarChange):plan.error]};const dependencyChange=[...plan.dependencies].map((path)=>changed.get(path)).find(Boolean);const hasActive=plan.results.some((result)=>result.status!=="todo");const configChange=hasActive&&!options.adapter&&findConfig(plan.origin)!==plan.config?new Error(`The project configuration for ${file} changed during verification. Rerun pud check.`):undefined;const remapped=hasActive?remappedImports(plan.suite.imports).values().next().value:undefined;const change=configChange??remapped??dependencyChange;return{file,results:plan.results.map((result)=>{const error=sidecarChange??(result.status!=="todo"?change:undefined);const{name,line,subject,assistant}=result;return error?{...failure(error),name,line,subject,assistant}:result})}})}async function emit3(file,options){const snapshots=new SourceSnapshots;const read=snapshotReader(snapshots);const{suite,config,origin}=parseSuite(file,read);const unit=await emitSuite(suite,config,options,read);const changed=snapshots.changes().values().next().value??remappedImports(suite.imports).values().next().value;if(changed)throw changed;if(!options.adapter&&findConfig(origin)!==config)throw new Error(`The project configuration for ${file} changed during emission.`);return unit}
3
+ export{checkFiles3,emit3};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{Unsupported2,failure}from"./chunk-224av1ab.js";import{checkFiles3,emit3}from"./chunk-fstxscck.js";async function runProject(request,onProgress){let reply;let callbackFailure;const child=Bun.spawn([process.execPath,Bun.resolveSync("./project-runner.js",import.meta.dir)],{stdin:"inherit",stdout:2,stderr:"inherit",ipc(message,worker){if(message.kind==="progress"){try{onProgress?.(message.event);if(message.event.kind==="validating")worker.send("continue")}catch(cause){callbackFailure={cause};worker.kill()}}else{reply=message;worker.disconnect()}}});child.send(request);const code=await child.exited;if(callbackFailure)throw callbackFailure.cause;if(reply?.kind==="result")return reply.value;const error=reply?.error??new Error(`Project process exited with ${child.signalCode??code} before returning its result.`);if(reply?.unsupported)Object.setPrototypeOf(error,Unsupported2.prototype);if(reply?.code)Object.assign(error,{code:reply.code});if(request.kind==="emit")throw error;return request.files.map((file)=>({file,results:[failure(error)]}))}function checkFiles2(files,options={}){if(options.adapter||!files.length)return checkFiles3(files,options);return runProject({kind:"check",files,progress:!!options.onProgress},options.onProgress)}async function check2(file,options){return(await checkFiles2([file],options))[0]}function emit2(file,selector){const options=typeof selector==="string"?{property:selector}:selector??{};return options.adapter?emit3(file,options):runProject({kind:"emit",file,property:options.property})}
3
+ export{checkFiles2,check2,emit2};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function sourceOnly(){throw new Error("Pud reads proof declarations from *.proof.ts source. Run pud check.")}var schemaBuilders={bigint:sourceOnly,number:sourceOnly,boolean:sourceOnly,int:sourceOnly,bool:sourceOnly,opaque:sourceOnly,array:sourceOnly,textOrArray:sourceOnly,forall:sourceOnly,exists:sourceOnly,and:sourceOnly,or:sourceOnly,not:sourceOnly,implies:sourceOnly,iff:sourceOnly,length:sourceOnly,sum:sourceOnly,modulo:sourceOnly,quotient:sourceOnly};var pud2=schemaBuilders;var it2=Object.assign(sourceOnly.bind(undefined),{todo:sourceOnly});var given2=sourceOnly;var expect2=sourceOnly;var describe2=sourceOnly;function native2(_id){return Object.assign(sourceOnly.bind(undefined),{ref:sourceOnly,module:sourceOnly})}function defineConfig2(config){return{...schemaBuilders,...config,describe:sourceOnly}}
3
+ export{pud2,it2,given2,expect2,describe2,native2,defineConfig2};
package/cli.js ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ import{failure}from"./chunk-224av1ab.js";import"./chunk-fstxscck.js";import{checkFiles2,emit2}from"./chunk-h90k6v7w.js";import{readdirSync,statSync}from"fs";import{join,resolve as resolve2}from"path";import{dirname,relative,resolve}from"path";import{basename}from"path";function stringReplaceAll(string,substring,postfix){let index=string.indexOf(substring);if(index===-1){return string}const substringLength=substring.length;let endIndex=0;let returnValue="";do{returnValue+=string.slice(endIndex,index)+substring+postfix;endIndex=index+substringLength;index=string.indexOf(substring,endIndex)}while(index!==-1);returnValue+=string.slice(endIndex);return returnValue}function stringEncaseCRLFWithFirstIndex(string,prefix,postfix,index){let endIndex=0;let returnValue="";do{const isGotCR=string[index-1]==="\r";returnValue+=string.slice(endIndex,isGotCR?index-1:index)+prefix+(isGotCR?`\r
4
+ `:`
5
+ `)+postfix;endIndex=index+1;index=string.indexOf(`
6
+ `,endIndex)}while(index!==-1);returnValue+=string.slice(endIndex);return returnValue}var ANSI_BACKGROUND_OFFSET=10;var ANSI_UNDERLINE_OFFSET=20;var wrapAnsi16=(offset=0)=>(code)=>`\x1B[${code+offset}m`;var wrapAnsi256=(offset=0)=>(code)=>`\x1B[${38+offset};5;${code}m`;var wrapAnsi16m=(offset=0)=>(red,green,blue)=>`\x1B[${38+offset};2;${red};${green};${blue}m`;var wrapUnderlineAnsi=(code)=>`\x1B[58;5;${code<90?code-30:code-90+8}m`;var styles={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],underlineDouble:["4:2",24],underlineCurly:["4:3",24],underlineDotted:["4:4",24],underlineDashed:["4:5",24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],gray:[90,39],grey:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgGray:[100,49],bgGrey:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]},underlineColor:{underlineBlack:["58;5;0",59],underlineRed:["58;5;1",59],underlineGreen:["58;5;2",59],underlineYellow:["58;5;3",59],underlineBlue:["58;5;4",59],underlineMagenta:["58;5;5",59],underlineCyan:["58;5;6",59],underlineWhite:["58;5;7",59],underlineBlackBright:["58;5;8",59],underlineGray:["58;5;8",59],underlineGrey:["58;5;8",59],underlineRedBright:["58;5;9",59],underlineGreenBright:["58;5;10",59],underlineYellowBright:["58;5;11",59],underlineBlueBright:["58;5;12",59],underlineMagentaBright:["58;5;13",59],underlineCyanBright:["58;5;14",59],underlineWhiteBright:["58;5;15",59]}};var modifierNames=Object.keys(styles.modifier);var foregroundColorNames=Object.keys(styles.color);var backgroundColorNames=Object.keys(styles.bgColor);var underlineColorNames=Object.keys(styles.underlineColor);var colorNames=[...foregroundColorNames,...backgroundColorNames];function assembleStyles(){const codes=new Map;for(const[groupName,group]of Object.entries(styles)){for(const[styleName,style]of Object.entries(group)){styles[styleName]={open:`\x1B[${style[0]}m`,close:`\x1B[${style[1]}m`};group[styleName]=styles[styleName];codes.set(Number.parseInt(style[0],10),style[1])}Object.defineProperty(styles,groupName,{value:group,enumerable:false})}Object.defineProperty(styles,"codes",{value:codes,enumerable:false});styles.color.close="\x1B[39m";styles.bgColor.close="\x1B[49m";styles.underlineColor.close="\x1B[59m";styles.color.ansi=wrapAnsi16();styles.color.ansi256=wrapAnsi256();styles.color.ansi16m=wrapAnsi16m();styles.bgColor.ansi=wrapAnsi16(ANSI_BACKGROUND_OFFSET);styles.bgColor.ansi256=wrapAnsi256(ANSI_BACKGROUND_OFFSET);styles.bgColor.ansi16m=wrapAnsi16m(ANSI_BACKGROUND_OFFSET);styles.underlineColor.ansi=wrapUnderlineAnsi;styles.underlineColor.ansi256=wrapAnsi256(ANSI_UNDERLINE_OFFSET);styles.underlineColor.ansi16m=wrapAnsi16m(ANSI_UNDERLINE_OFFSET);Object.defineProperties(styles,{rgbToAnsi256:{value(red,green,blue){if(red===green&&green===blue){if(red<8){return 16}if(red>248){return 231}return Math.round((red-8)/247*24)+232}return 16+36*Math.round(red/255*5)+6*Math.round(green/255*5)+Math.round(blue/255*5)},enumerable:false},hexToRgb:{value(hex){const matches=/[\da-f]{6}|[\da-f]{3}/i.exec(hex.toString(16));if(!matches){return[0,0,0]}let[colorString]=matches;if(colorString.length===3){colorString=[...colorString].map((character)=>character+character).join("")}const integer=Number.parseInt(colorString,16);return[integer>>16&255,integer>>8&255,integer&255]},enumerable:false},hexToAnsi256:{value:(hex)=>styles.rgbToAnsi256(...styles.hexToRgb(hex)),enumerable:false},ansi256ToAnsi:{value(code){if(code<8){return 30+code}if(code<16){return 90+(code-8)}let red;let green;let blue;if(code>=232){red=((code-232)*10+8)/255;green=red;blue=red}else{code-=16;const remainder=code%36;red=Math.floor(code/36)/5;green=Math.floor(remainder/6)/5;blue=remainder%6/5}const value=Math.max(red,green,blue)*2;if(value===0){return 30}let result=30+(Math.round(blue)<<2|Math.round(green)<<1|Math.round(red));if(value===2){result+=60}return result},enumerable:false},rgbToAnsi:{value:(red,green,blue)=>styles.ansi256ToAnsi(styles.rgbToAnsi256(red,green,blue)),enumerable:false},hexToAnsi:{value:(hex)=>styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),enumerable:false}});return styles}var ansiStyles=assembleStyles();var ansi_styles_default=ansiStyles;import process2 from"process";import os from"os";import tty from"tty";function hasFlag(flag,argv=globalThis.Deno?globalThis.Deno.args:process2.argv){const prefix=flag.startsWith("-")?"":flag.length===1?"-":"--";const position=argv.indexOf(prefix+flag);const terminatorPosition=argv.indexOf("--");return position!==-1&&(terminatorPosition===-1||position<terminatorPosition)}var{env}=process2;var flagForceColor;if(hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")||hasFlag("color=never")){flagForceColor=0}else if(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always")){flagForceColor=1}function hasNumericForceColor(){return/^\d+$/.test(env.FORCE_COLOR)}function envForceColor(){if(!("FORCE_COLOR"in env)){return}if(env.FORCE_COLOR==="false"){return 0}if(env.FORCE_COLOR==="true"||env.FORCE_COLOR.length===0){return 1}if(!hasNumericForceColor()){return}return Math.min(Number.parseInt(env.FORCE_COLOR,10),3)}function translateLevel(level){if(level===0){return false}return{level,hasBasic:true,has256:level>=2,has16m:level>=3}}function _supportsColor(haveStream,{streamIsTTY,sniffFlags=true}={}){const noFlagForceColor=envForceColor();if(noFlagForceColor!==undefined){flagForceColor=noFlagForceColor}const forceColor=sniffFlags?flagForceColor:noFlagForceColor;if(forceColor===0){return 0}if(sniffFlags){if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor")){return 3}if(hasFlag("color=256")){return 2}}if(forceColor!==undefined&&hasNumericForceColor()){return forceColor}if("TF_BUILD"in env&&"AGENT_NAME"in env){return 1}if(haveStream&&!streamIsTTY&&forceColor===undefined){return 0}const min=forceColor||0;if(env.TERM==="dumb"){return min}if(process2.platform==="win32"){const osRelease=os.release().split(".");if(Number(osRelease[0])>=10&&Number(osRelease[2])>=10586){return Number(osRelease[2])>=14931?3:2}return 1}if("CI"in env){if(["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some((key)=>(key in env))){return 3}if(["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some((sign)=>(sign in env))||env.CI_NAME==="codeship"){return 1}return min}if("TEAMCITY_VERSION"in env){return/^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0}if(env.COLORTERM==="truecolor"){return 3}if(env.TERM==="xterm-kitty"){return 3}if(env.TERM==="xterm-ghostty"){return 3}if(env.TERM==="wezterm"){return 3}if("TERM_PROGRAM"in env){const version=Number.parseInt((env.TERM_PROGRAM_VERSION||"").split(".",1)[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":{return version>=3?3:2}case"Apple_Terminal":{return 2}}}if(/-256(?:color)?$/i.test(env.TERM)){return 2}if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)){return 1}if("COLORTERM"in env){return 1}return min}function createSupportsColor(stream,options={}){const level=_supportsColor(stream,{streamIsTTY:stream&&stream.isTTY,...options});return translateLevel(level)}var supportsColor={stdout:createSupportsColor({isTTY:tty.isatty(1)}),stderr:createSupportsColor({isTTY:tty.isatty(2)})};var supports_color_default=supportsColor;var{stdout:stdoutColor,stderr:stderrColor}=supports_color_default;var GENERATOR=Symbol("GENERATOR");var STYLER=Symbol("STYLER");var IS_EMPTY=Symbol("IS_EMPTY");var LEVEL=Symbol("LEVEL");var styles2=Object.create(null);var assertValidLevel=(level)=>{if(!Number.isSafeInteger(level)||level<0||level>3){throw new Error("The `level` should be an integer from 0 to 3")}};var levelDescriptor={enumerable:true,get(){return this[LEVEL]},set(level){assertValidLevel(level);this[LEVEL]=level}};var applyOptions=(object,options={})=>{if(options.level!==undefined){assertValidLevel(options.level)}const colorLevel=stdoutColor?stdoutColor.level:0;object[LEVEL]=options.level===undefined?colorLevel:options.level};class Chalk{constructor(options){return chalkFactory(options)}}var chalkFactory=(options)=>{const chalk=(...strings)=>strings.join(" ");applyOptions(chalk,options);Object.setPrototypeOf(chalk,createChalk.prototype);return chalk};function createChalk(options){return chalkFactory(options)}Object.setPrototypeOf(createChalk.prototype,Function.prototype);for(const[styleName,style]of Object.entries(ansi_styles_default)){styles2[styleName]={get(){const builder=createBuilder(this,createStyler(style.open,style.close,this[STYLER]),this[IS_EMPTY]);Object.defineProperty(this,styleName,{value:builder});return builder}}}styles2.visible={get(){const builder=createBuilder(this,this[STYLER],true);Object.defineProperty(this,"visible",{value:builder});return builder}};var createModelConverters=(model,type)=>{const style=ansi_styles_default[type];if(model==="rgb"){const ansi=(red,green,blue)=>style.ansi(ansi_styles_default.rgbToAnsi(red,green,blue));const ansi256=(red,green,blue)=>style.ansi256(ansi_styles_default.rgbToAnsi256(red,green,blue));return[ansi,ansi,ansi256,style.ansi16m]}if(model==="hex"){const ansi=(hex)=>style.ansi(ansi_styles_default.hexToAnsi(hex));const ansi256=(hex)=>style.ansi256(ansi_styles_default.hexToAnsi256(hex));return[ansi,ansi,ansi256,(hex)=>style.ansi16m(...ansi_styles_default.hexToRgb(hex))]}const ansi=(code)=>style.ansi(ansi_styles_default.ansi256ToAnsi(code));return[ansi,ansi,style.ansi256,style.ansi256]};var usedModels=["rgb","hex","ansi256"];for(const model of usedModels){const capitalizedModel=model[0].toUpperCase()+model.slice(1);for(const[styleName,type]of[[model,"color"],["bg"+capitalizedModel,"bgColor"],["underline"+capitalizedModel,"underlineColor"]]){const{close}=ansi_styles_default[type];const converters=createModelConverters(model,type);styles2[styleName]={get(){const styleFunction=function(first,second,third){const open=converters[this.level](first,second,third);return createBuilder(this,createStyler(open,close,this[STYLER]),this[IS_EMPTY])};Object.defineProperty(this,styleName,{value:styleFunction});return styleFunction}}}}var proto=Object.defineProperties(()=>{},{...styles2,level:{enumerable:true,get(){return this[GENERATOR].level},set(level){this[GENERATOR].level=level}}});var createStyler=(open,close,parent)=>{let openAll;let closeAll;if(parent===undefined){openAll=open;closeAll=close}else{openAll=parent.openAll+open;closeAll=close+parent.closeAll}return{open,close,openAll,closeAll,parent}};var createBuilder=(self,_styler,_isEmpty)=>{const builder=(...arguments_)=>{if(arguments_.length===1){return applyStyle(builder,""+arguments_[0])}if(arguments_.length===2){return applyStyle(builder,`${arguments_[0]??""} ${arguments_[1]??""}`)}return applyStyle(builder,arguments_.join(" "))};Object.setPrototypeOf(builder,proto);builder[GENERATOR]=self[GENERATOR]??self;builder[STYLER]=_styler;builder[IS_EMPTY]=_isEmpty;return builder};var applyStyle=(self,string)=>{if(self[GENERATOR][LEVEL]<=0||!string){return self[IS_EMPTY]?"":string}let styler=self[STYLER];if(styler===undefined){return string}const{openAll,closeAll}=styler;if(string.includes("\x1B")){while(styler!==undefined){string=stringReplaceAll(string,styler.close,styler.open);styler=styler.parent}}const lfIndex=string.indexOf(`
7
+ `);if(lfIndex!==-1){string=stringEncaseCRLFWithFirstIndex(string,closeAll,openAll,lfIndex)}return openAll+string+closeAll};Object.defineProperties(createChalk.prototype,{...styles2,level:levelDescriptor});var chalk=createChalk();var chalkStderr=createChalk({level:stderrColor?stderrColor.level:0});var source_default=chalk;var monochrome=new Chalk({level:0});function terminalInk(out){if(process.env.NO_COLOR)return monochrome;return out===process.stderr?chalkStderr:source_default}function isInteractiveTerminal(out){return Boolean(out.isTTY&&process.env.TERM!=="dumb")}var appearance={PASS:{text:"green",mark:"\u2713"},FAIL:{text:"red",mark:"\xD7"},UNPROVED:{text:"yellow",mark:"?"},UNSUPPORTED:{text:"yellow",mark:"!"},ERROR:{text:"red",mark:"!"},TODO:{text:"cyan",mark:"\u25CB"}};function verdictColor(ink,verdict){return ink[appearance[verdict].text]}function verdictMark(ink,verdict){return verdictColor(ink,verdict)(appearance[verdict].mark)}function pudBanner(out,title){const ink=terminalInk(out);const brand=[ink.hex("#ff462d").bold("P"),ink.hex("#f381bd").bold("u"),ink.hex("#00bbd5").bold("d")].join("");return`\uD83C\uDF6E ${brand} ${ink.dim("\xB7")} ${title}`}var frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var erase=(lines)=>lines?`\x1B[${lines}F\x1B[J`:"";var width=(text)=>Bun.stringWidth(text);var seconds=(ms)=>`${(ms/1000).toFixed(1)}s`;function clip(text,columns){if(columns<1)return"";return width(text)<=columns?text:Bun.sliceAnsi(text,0,columns-1)+"\u2026"}function safeText(text){return text.replace(/\p{Cc}/gu," ").trim()}function alignRight(label,detail,columns){if(!detail)return clip(label,columns);const available=columns-width(detail);const left=clip(label,available-2);return left+" ".repeat(available-width(left))+detail}function proofTrail(ink,completed,total,active,columns){if(!total)return"";const done=completed.length;const countWidth=width(`${total}/${total}`);const slots=Math.min(total,Math.max(1,Math.floor((columns-countWidth-1)/2)));const queued=ink.hex("#a1a1aa")(ink.level?"\u2022":"\xB7");const proved=verdictColor(ink,"PASS")("\u2022");const failed=verdictColor(ink,"FAIL")(ink.level?"\u2022":"\xD7");const unknown=ink.dim(ink.level?"\u2022":"\u25CB");const cursor=ink.cyan.bold("\u25C6");const markers=Array.from({length:slots},(_,slot)=>{const start=Math.floor(slot*total/slots);const end=Math.floor((slot+1)*total/slots);if(end>done)return active&&start<=done?cursor:queued;const last=completed[end-1];const previous=completed[start-1];if(last.failed>(previous?.failed??0))return failed;return last.proved-(previous?.proved??0)===end-start?proved:unknown});return`${markers.join(" ")} ${ink.dim(`${done}/${total}`)}`}function terminalProgress(out=process.stderr,runStarted=performance.now()){if(!isInteractiveTerminal(process.stdout)||!isInteractiveTerminal(out)||out.columns&&out.columns<28)return;const ink=terminalInk(out);let suite;let written=0,frame=0,remaining=0;let validating=false;const running=new Map;const completed=[];function draw(){if(!suite)return;const now=performance.now();const columns=(out.columns||80)-1;if(columns<27){if(written)out.write(erase(written));written=0;return}const spinner=frames[frame%frames.length];const active=validating?undefined:running.entries().next().value;const item=active&&suite.items[active[0]];const title=validating?"Validating input snapshots":item?safeText(item.name):remaining?"Preparing proofs":"Finishing suite";const totalTime=ink.dim(`total ${seconds(now-runStarted)}`);const proofTime=active?ink.dim(`proof ${seconds(now-active[1])}`):"";const file=safeText(basename(suite.file));const batch=active&&running.size>1?` \xB7 +${running.size-1} running`:"";const lines=[alignRight(` ${ink.cyan(spinner)} ${ink.bold(title)}`,totalTime,columns),alignRight(` ${ink.dim(file+batch)}`,proofTime,columns)];const trail=proofTrail(ink,completed,suite.totalItems,!!item,columns-2);if(trail)lines.push("",` ${trail}`);out.write(erase(written)+lines.map((line)=>clip(line,columns)).join(`
8
+ `)+`
9
+ `);written=lines.length}const timer=setInterval(()=>{frame++;draw()},90);timer.unref();function clear(){if(written)out.write(erase(written));written=0;suite=undefined}function close(){clearInterval(timer);clear();process.off("SIGINT",interrupt);process.off("SIGTERM",interrupt)}function interrupt(signal){close();process.kill(process.pid,signal)}process.once("SIGINT",interrupt);process.once("SIGTERM",interrupt);return{update(event){if(event.kind==="suite"){suite=event;remaining=event.items.reduce((count,item)=>count+Number(!item.todo),0);running.clear();validating=false}else if(event.kind==="validating"){validating=true}else if(event.file===suite?.file){if(event.kind==="running"){const active=running.entries().next().value;running.clear();const now=performance.now();for(const index of event.indices){running.set(index,index===active?.[0]?active[1]:now)}}else{remaining-=event.indices.length;for(const[offset,index]of event.indices.entries()){running.delete(index);const status=event.statuses[offset];const previous=completed.at(-1);completed.push({proved:(previous?.proved??0)+Number(status==="proved"),failed:(previous?.failed??0)+Number(status!=="proved"&&status!=="todo")})}}}if(!written||event.kind==="validating")draw()},close}}var badges={proved:"PASS",disproved:"FAIL",unproved:"UNPROVED",unsupported:"UNSUPPORTED",error:"ERROR",todo:"TODO"};var summaryLabels={proved:"passed",disproved:"failed",unproved:"unproved",unsupported:"unsupported",error:"errors",todo:"todo"};function target(result){const title=result.name??result.subject;if(!title)return;const scope=result.concreteScope==="no-inputs"?" [no inputs]":result.concreteScope?" [literal inputs]":"";return title+(result.exactResult?" [exact result]":"")+scope}function detail(result,verbose,ink){if(result.counterexample?.difference){const{summary,input,difference}=result.counterexample;return[summary,Object.entries(input).map(([key,value])=>`${key}=${value}`).join(" "),difference.subject,` ${ink.green("Expected")} ${difference.expected}`,` ${ink.red("Received")} ${difference.received}`].join(`
10
+ `)}if(result.counterexample){const{summary,input}=result.counterexample;return[summary,Object.entries(input).map(([key,value])=>`${key}=${value}`).join(" ")].filter(Boolean).join(`
11
+ `)}return verbose?result.diagnostic??result.detail:result.detail}function location(file,result){return result.line?`${file}:${result.line}`:file}function display(file,result,verbose,out){const ink=terminalInk(out);const verdict=badges[result.status];const badge=verdictColor(ink,verdict).bold(verdict.padEnd(9));const name=target(result);out.write(`${badge} ${name?name+" ":""}${ink.dim(location(file,result))}
12
+ `);const message=detail(result,verbose,ink);if(message)out.write(` ${message.replaceAll(`
13
+ `,`
14
+ `)}
15
+ `)}function reportRows(results){const rows=[];const printed=new Set;for(const result of results){if(printed.has(result))continue;if(result.subject&&(result.status==="unsupported"||result.status==="error")){const affected=results.filter((other)=>other.subject===result.subject&&other.status===result.status&&other.detail===result.detail);if(affected.length>1){rows.push({result:{...result,name:`${result.subject} (${affected.length} properties)`,line:undefined},affected});for(const item of affected)printed.add(item);continue}}rows.push({result})}return rows}function affectedLocation(file,result){return`${target(result)} ${location(file,result)}`}function displayReport({file,results},verbose,out){for(const{result,affected}of reportRows(results)){display(file,result,verbose,out);if(verbose&&affected)for(const item of affected)out.write(` ${affectedLocation(file,item)}
16
+ `)}}function width2(out){return Math.min(out.columns||80,96)}function writeLine(out,prefix,text,continuation){const indent=Bun.stringWidth(prefix);const wrapped=Bun.wrapAnsi(text,Math.max(1,width2(out)-indent-1),{hard:true,trim:false});out.write(`${prefix}${wrapped.replaceAll(`
17
+ `,`
18
+ ${continuation??" ".repeat(indent)}`)}
19
+ `)}function duration(ms){return ms<1000?`${Math.round(ms)}ms`:`${(ms/1000).toFixed(2)}s`}function displayTerminalReport({file,results},verbose,out,root,elapsedMs){const ink=terminalInk(out);const priority=["error","unsupported","disproved","unproved","proved","todo"];const status=priority.find((status)=>results.some((result)=>result.status===status))??"todo";const lead=` ${verdictMark(ink,badges[status])} `;const label=ink.bold(relative(root,file));const time=ink.dim(duration(elapsedMs));const gap=Math.max(2,width2(out)-2-Bun.stringWidth(lead+label+time));writeLine(out,lead,label+" ".repeat(gap)+time);const rows=reportRows(results);const margin=" ";const edge=ink.dim(`${margin}\u2502 `);const source=relative(process.cwd(),file);for(const[index,{result,affected}]of rows.entries()){const branch=ink.dim(index===rows.length-1?" \u2514\u2500 ":" \u251C\u2500 ");const verdict=badges[result.status];const badge=verdictColor(ink,verdict).bold(verdict.padEnd(4));const line=result.line?ink.dim(` :${result.line}`):"";writeLine(out,`${branch}${badge} `,(target(result)??"")+line);const message=detail(result,verbose,ink);if(message){const assistant=result.assistant;const diagnostic=assistant?`${assistant[0].toUpperCase()}${assistant.slice(1)} diagnostic`:"Diagnostic";const heading=result.counterexample?"Counterexample":diagnostic;writeLine(out,margin,ink.bold(heading));out.write(`${margin}${ink.dim(location(source,result))}
20
+ `);writeLine(out,edge,message,edge)}if(verbose&&affected)for(const item of affected)writeLine(out,margin,affectedLocation(source,item))}}function displaySummary(counts,elapsedMs,out,fileCount){const statuses=Object.keys(counts).filter((status)=>counts[status]);const label=(status)=>`${counts[status]} ${status==="error"&&counts.error===1?"error":summaryLabels[status]}`;if(!fileCount){out.write(`
21
+ ${statuses.map(label).join(" \xB7 ")} ${(elapsedMs/1000).toFixed(1)}s
22
+ `);return}const ink=terminalInk(out);const tally=statuses.map((status)=>verdictColor(ink,badges[status]).bold(label(status)));out.write(`
23
+ ${ink.dim("\u2500".repeat(width2(out)-4))}
24
+ `);writeLine(out," ",[...tally,ink.dim(fileCount),ink.dim(duration(elapsedMs))].join(ink.dim(" \xB7 ")))}function proofReporter(files,started,verbose){const progress=files.length?terminalProgress(process.stderr,started):undefined;const cwd=process.cwd();const directories=new Set(files.map((file)=>dirname(resolve(file))));const root=directories.size===1?directories.values().next().value:cwd;const fileCount=`${files.length} proof file${files.length===1?"":"s"}`;if(progress){const out=process.stderr;const scope=relative(cwd,root);out.write(`
25
+ ${pudBanner(out,"Proof check")}
26
+ `);writeLine(out," ",terminalInk(out).dim(scope?`${fileCount} \xB7 ${scope}`:fileCount));out.write(`
27
+ `)}const times=new Map;let active;return{update:progress&&((event)=>{if(event.kind==="suite"||event.kind==="validating"){const now=performance.now();if(active)times.set(active.file,now-active.started);active=event.kind==="suite"?{file:event.file,started:now}:undefined}progress.update(event)}),close:progress?.close,report(reports,counts,errors,out){const rich=progress&&(!out.columns||out.columns>=28);for(const report of reports){if(rich)displayTerminalReport(report,verbose,out,root,times.get(report.file)??0);else displayReport(report,verbose,out)}for(const error of errors)out.write(error+`
28
+ `);if(reports.length)displaySummary(counts,performance.now()-started,out,rich?fileCount:undefined)}}}var synopsis=`Usage: pud [check] [DIR | FILE.proof.ts ...] [--verbose | --json] [--deny-cases]
29
+ pud --emit FILE.proof.ts [PROPERTY | SUBJECT[.PROPERTY]]`;var usage=`${synopsis}
30
+
31
+ With no paths, Pud discovers *.proof.ts under the current directory.
32
+ The nearest pud.config.ts selects the proof assistant.
33
+ --emit Print the verification unit for one property without running the prover or replay.
34
+ --verbose Show full diagnostics and affected properties.
35
+ --json Print machine-readable results.
36
+ --deny-cases Fail on zero-input claims or explicit literal constraints on every input. Quantified postconditions are allowed.
37
+ Exit: 0 all active properties proved, 1 unproved or disproved, 2 unsupported, invalid input or tool error.`;var skipped=new Set(["node_modules","dist","out","build","coverage"]);function discover(dir){return readdirSync(dir,{withFileTypes:true}).flatMap((entry)=>{if(entry.name.startsWith(".")||skipped.has(entry.name))return[];const path=join(dir,entry.name);if(entry.isDirectory())return discover(path);return(entry.isFile()||entry.isSymbolicLink())&&entry.name.endsWith(".proof.ts")?[path]:[]}).sort()}async function main(args){if(args[0]==="check")args=args.slice(1);if(args.length===1&&["--help","-h"].includes(args[0])){console.log(usage);return 0}if(args[0]==="--emit"&&args.length>=2&&args.length<=3&&!args.includes("--json")){try{process.stdout.write(await emit2(args[1],args[2]));return 0}catch(error){display(args[1],failure(error),false,process.stderr);return 2}}const started=performance.now();const verbose=args.includes("--verbose"),json=args.includes("--json");const denyCases=args.includes("--deny-cases");const paths=args.filter((a)=>a!=="--verbose"&&a!=="--json"&&a!=="--deny-cases");const files=new Map,errors=[];if(paths.some((path)=>path.startsWith("-"))||json&&verbose)errors.push(synopsis);else for(const path of paths.length?paths:["."]){try{if(statSync(path,{throwIfNoEntry:false})?.isDirectory()){const matches=discover(path);if(!matches.length)errors.push(`No *.proof.ts files found in ${path}. Add a proof file beside the function you want to check.`);for(const file of matches)files.set(resolve2(file),file)}else if(path.endsWith(".proof.ts"))files.set(resolve2(path),path);else errors.push(`Expected a directory or a *.proof.ts file. Received ${path}.`)}catch(e){errors.push(e.message)}}const selected=[...files.values()];const reporter=json?undefined:proofReporter(selected,started,verbose);const reports=await checkFiles2(selected,{onProgress:reporter?.update}).finally(reporter?.close);if(denyCases)for(const report of reports)for(const result of report.results){if(result.concreteScope)errors.push(`${report.file}:${result.line}: "${result.name}" has ${result.concreteScope==="no-inputs"?"no inputs":"a literal constraint on every input"}. State a law over a domain or move the case to a runtime test.`)}const counts={proved:0,disproved:0,unproved:0,unsupported:0,error:errors.length,todo:0};for(const report of reports)for(const r of report.results)counts[r.status]++;const code=counts.error||counts.unsupported?2:counts.disproved||counts.unproved?1:0;if(json)console.log(JSON.stringify({files:reports,counts,...errors.length?{errors}:{}},null,2));else reporter?.report(reports,counts,errors,code?process.stderr:process.stdout);return code}if(import.meta.main)process.exitCode=await main(process.argv.slice(2));
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Unsupported2}from"./chunk-224av1ab.js";import"./chunk-fstxscck.js";import{pud2,it2,given2,expect2,describe2,native2,defineConfig2}from"./chunk-k7a83qqm.js";import{checkFiles2,check2,emit2}from"./chunk-h90k6v7w.js";export{Unsupported2 as Unsupported,check2 as check,checkFiles2 as checkFiles,defineConfig2 as defineConfig,describe2 as describe,emit2 as emit,expect2 as expect,given2 as given,it2 as it,native2 as native,pud2 as pud};