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

Function flattenFactory

ark/aot/flat.ts:1232–1360  ·  view source on GitHub ↗
(d: Factory)

Source from the content-addressed store, hash-verified

1230 )
1231 }
1232 const flattenFactory = (d: Factory) => {
1233 const body = d.fn.body as Block
1234 const renamed = new Map<Binding, string>()
1235 let aliases = ""
1236 // a parameter reads what the function already holds, if no local hides it
1237 const alias = (binding: Binding, value: string) => {
1238 if (binding.name === value) return
1239 // a primitive is written where it's read
1240 if (
1241 primitive.test(value) &&
1242 !binding.writes.length &&
1243 binding.references.every(
1244 ({ id }) =>
1245 id.parent?.type !== "MemberExpression" || id.parent.object !== id
1246 )
1247 ) {
1248 renamed.set(binding, value)
1249 return
1250 }
1251 // e.g. what a factory flattened before declares
1252 const holder =
1253 holders.get(value) ?? (values.get(value) === value ? value : undefined)
1254 const isHidden = bindingsNamed
1255 .get(holder!)
1256 ?.some(
1257 other =>
1258 other !== binding &&
1259 d.fn.start <= other.id.start &&
1260 other.id.start < d.fn.end
1261 )
1262 if (holder && !isHidden) {
1263 if (holder !== binding.name) renamed.set(binding, holder)
1264 return
1265 }
1266 const name = isFree(binding.name) ? binding.name : fresh(binding.name)
1267 values.set(name, value)
1268 holders.set(value, name)
1269 aliases += `const ${name} = ${value}\n`
1270 if (name !== binding.name) renamed.set(binding, name)
1271 }
1272 for (const [i, param] of d.fn.params.entries()) {
1273 const arg = d.call.arguments[i]
1274 if (param.type === "Identifier") {
1275 const value =
1276 arg.type === "Identifier" && membersOf.has(arg.name) ?
1277 wholeOf(arg.name)
1278 : code.slice(arg.start, arg.end)
1279 const binding = scopes.bindingsById.get(param)!
1280 // a runtime value only passed on, e.g. a failure site, needs no constant
1281 if (
1282 runtimeMember.test(value) &&
1283 binding.references.every(
1284 ({ id }) =>
1285 id.parent?.type === "CallExpression" &&
1286 id.parent.arguments.includes(id as never)
1287 )
1288 )
1289 renamed.set(binding, value)

Callers 1

writeFlatFunction · 0.85

Calls 10

wholeOfFunction · 0.85
isFreeFunction · 0.85
testMethod · 0.80
aliasFunction · 0.70
freshFunction · 0.70
replaceFunction · 0.70
getMethod · 0.65
mapMethod · 0.65
hasMethod · 0.45
setMethod · 0.45

Tested by

no test coverage detected