MCPcopy Create free account
hub / github.com/arktypeio/arktype / shareFailuresAs

Function shareFailuresAs

ark/aot/flat.ts:2048–2112  ·  view source on GitHub ↗
(writesArrows: boolean)

Source from the content-addressed store, hash-verified

2046// the frame
2047const shareFailuresAs =
2048 (writesArrows: boolean): UnitsPass =>
2049 ({ code, program }, s) => {
2050 // by the call each would share, then its parameters
2051 const callsByShared = new Map<string, FailingCall[]>()
2052 const paramsByShared = new Map<string, string>()
2053 walk(program, node => {
2054 if (
2055 node.type !== "CallExpression" ||
2056 node.callee.type !== "MemberExpression" ||
2057 node.callee.object.type !== "Identifier" ||
2058 node.callee.property.type !== "Identifier"
2059 )
2060 return true
2061 const fails = node.callee.property.name
2062 const onRuntime = node.callee.object.name === "runtime"
2063 const passed = (onRuntime ? passedToFailing : passedToErrors).get(fails)
2064 const args = node.arguments
2065 if (
2066 !passed ||
2067 args.length <= passed.length ||
2068 args.some(
2069 (arg, i) =>
2070 arg.type === "SpreadElement" ||
2071 (i >= passed.length && arg.type !== "Literal")
2072 )
2073 )
2074 return true
2075 const literals = {
2076 start: args[passed.length - 1].end,
2077 end: args[args.length - 1].end
2078 }
2079 const shared = `${onRuntime ? "runtime" : "ctx"}.${fails}(${passed.join(", ")}${code.slice(literals.start, literals.end)})`
2080 paramsByShared.set(
2081 shared,
2082 (onRuntime ? passed : ["ctx", ...passed]).join(", ")
2083 )
2084 pushTo(callsByShared, shared, {
2085 callee: node.callee,
2086 on: onRuntime ? undefined : node.callee.object.name,
2087 first: args[0],
2088 literals
2089 })
2090 // an Apply a key is entered by may be written where it's passed
2091 return true
2092 })
2093 const declarations: string[] = []
2094 for (const [shared, calls] of callsByShared) {
2095 const { start, end } = calls[0].literals
2096 if ((calls.length - 1) * (end - start) < minSavedByShared) continue
2097 const name = nameFreeIn(code, `fails${declarations.length}`)
2098 const params = paramsByShared.get(shared)!
2099 declarations.push(
2100 writesArrows ?
2101 `const ${name} = (${params}) => ${shared}\n`
2102 : `const ${name} = function (${params}) { return ${shared} }\n`
2103 )
2104 for (const { callee, on, first, literals } of calls) {
2105 s.overwrite(callee.start, callee.end, name)

Callers 1

writtenUnitsOfFunction · 0.85

Calls 7

walkFunction · 0.90
pushToFunction · 0.85
nameFreeInFunction · 0.85
removeMethod · 0.80
getMethod · 0.65
setMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected