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

Function inlineCalls

ark/aot/flat.ts:1638–1713  ·  view source on GitHub ↗
({ code, program, scopes }, s, body)

Source from the content-addressed store, hash-verified

1636
1637// a function read once, as a call passing its own parameters, is its body where it's called
1638const inlineCalls: UnitsPass = ({ code, program, scopes }, s, body) => {
1639 const declared = new Map<string, number>()
1640 for (const { name } of scopes.bindingsById.values())
1641 declared.set(name, (declared.get(name) ?? 0) + 1)
1642 // by position, so those within a function are found by search
1643 let sorted: Reference[] | undefined
1644 const referencesIn = (fn: Node) => {
1645 sorted ??= [...scopes.references].sort((l, r) => l.id.start - r.id.start)
1646 let low = 0
1647 let high = sorted.length
1648 while (low < high) {
1649 const mid = (low + high) >> 1
1650 if (sorted[mid].id.start < fn.start) low = mid + 1
1651 else high = mid
1652 }
1653 const result: Reference[] = []
1654 for (let i = low; i < sorted.length && sorted[i].id.start < fn.end; i++)
1655 result.push(sorted[i])
1656 return result
1657 }
1658 const readsAlike = (fn: Node) =>
1659 referencesIn(fn).every(
1660 ({ id, binding }) =>
1661 id.end > fn.end ||
1662 (binding?.declaration === fn ? !binding.writes.length
1663 : binding && binding.id.start > fn.start && binding.id.end < fn.end ?
1664 binding.kind !== "var"
1665 : (declared.get(id.name) ?? 0) <= 1)
1666 )
1667 // each inline reads the code as parsed, so no other may touch its span
1668 const edited: [start: number, end: number][] = []
1669 const isEdited = (start: number, end: number) =>
1670 edited.some(span => start < span[1] && span[0] < end)
1671 for (const statement of program.body as Node[]) {
1672 if (statement.type !== "VariableDeclaration") continue
1673 const { declarations } = statement
1674 for (const [i, { id, init: fn }] of declarations.entries()) {
1675 const references = scopes.bindingsById.get(id)?.references ?? []
1676 const call = references[0]?.id.parent
1677 if (
1678 !fn ||
1679 !isFunctionExpression(fn) ||
1680 fn.async ||
1681 references.length !== 1 ||
1682 call?.type !== "CallExpression" ||
1683 call.callee !== references[0].id ||
1684 (call.start > fn.start && call.end < fn.end) ||
1685 !passesParams(call, fn) ||
1686 !readsAlike(fn)
1687 )
1688 continue
1689 const [replaced, text] =
1690 fn.body.type !== "BlockStatement" ?
1691 [call, `(${code.slice(fn.body.start, fn.body.end)})`]
1692 : (
1693 call.parent?.type === "ReturnStatement" &&
1694 fn.body.body[fn.body.body.length - 1]?.type === "ReturnStatement"
1695 ) ?

Callers

nothing calls this directly

Calls 9

isFunctionExpressionFunction · 0.85
passesParamsFunction · 0.85
readsAlikeFunction · 0.85
statementEndInFunction · 0.85
isEditedFunction · 0.85
removeMethod · 0.80
getMethod · 0.65
setMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected