| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import {visitReactiveFunction} from '.'; |
| 9 | import {InstructionId, Place, ReactiveFunction, ReactiveValue} from '../HIR'; |
| 10 | import {ReactiveFunctionVisitor} from './visitors'; |
| 11 | |
| 12 | /** |
| 13 | * Returns a set of unique globals (by name) that are referenced transitively within the function. |
| 14 | */ |
| 15 | export function collectReferencedGlobals(fn: ReactiveFunction): Set<string> { |
| 16 | const identifiers = new Set<string>(); |
| 17 | visitReactiveFunction(fn, new Visitor(), identifiers); |
| 18 | return identifiers; |
| 19 | } |
| 20 | |
| 21 | class Visitor extends ReactiveFunctionVisitor<Set<string>> { |
| 22 | override visitValue( |
| 23 | id: InstructionId, |
| 24 | value: ReactiveValue, |
| 25 | state: Set<string>, |
| 26 | ): void { |
| 27 | this.traverseValue(id, value, state); |
| 28 | if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') { |
| 29 | this.visitHirFunction(value.loweredFunc.func, state); |
| 30 | } else if (value.kind === 'LoadGlobal') { |
| 31 | state.add(value.binding.name); |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | override visitReactiveFunctionValue( |
| 36 | _id: InstructionId, |
| 37 | _dependencies: Array<Place>, |
| 38 | fn: ReactiveFunction, |
| 39 | state: Set<string>, |
| 40 | ): void { |
| 41 | visitReactiveFunction(fn, this, state); |
| 42 | } |
| 43 | } |