Skip to main content

fallow_types/
extract_components.rs

1//! Dependency injection keys, component props, emits, events, inputs and
2//! outputs, custom elements, load return keys, component functions, hooks,
3//! render edges, and forwarded attributes.
4
5/// Which side of a dependency-injection link a call site represents.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
7pub enum DiRole {
8    /// `provide(KEY, value)` / `app.provide(KEY, value)` / `setContext(KEY, value)`.
9    Provide,
10    /// `inject(KEY)` / `getContext(KEY)`.
11    Inject,
12}
13
14/// Which framework's DI API a call site came from (drives the finding message).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
16pub enum DiFramework {
17    /// Vue `provide` / `inject` (from `vue` / `@vue/runtime-core`).
18    Vue,
19    /// Svelte `setContext` / `getContext` (from `svelte`).
20    Svelte,
21    /// Angular `inject(TOKEN)` / `@Inject(TOKEN)` (from `@angular/core`),
22    /// matched against `{ provide: TOKEN, ... }` provider objects.
23    Angular,
24}
25
26/// A Vue `provide`/`inject` or Svelte `setContext`/`getContext` call site keyed
27/// by an identifier symbol. The `key_local` is resolved at analyze time through
28/// the consuming module's import/export tables to a canonical defining-site
29/// export key, so a provide and an inject of the same shared symbol unify even
30/// across barrel re-exports. Consumed by the `unprovided-inject` detector.
31#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
32pub struct DiKeySite {
33    /// The key identifier as written at the call site.
34    pub key_local: String,
35    /// Whether this is a provide or an inject.
36    pub role: DiRole,
37    /// Which framework's API this came from.
38    pub framework: DiFramework,
39    /// Start byte offset of the call expression (anchors the finding).
40    pub span_start: u32,
41}
42
43/// A component prop declared by Vue `<script setup>` `defineProps` or Svelte 5
44/// `$props()`. `used_in_script` / `used_in_template` are set during extraction;
45/// the `unused-component-prop` detector flags a prop where neither is true. See
46/// `harvest_define_props` and `harvest_svelte_props` in `sfc_props.rs`.
47#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
48pub struct ComponentProp {
49    /// The declared prop name.
50    pub name: String,
51    /// The template/script-visible local binding name: the destructure alias for
52    /// `const { name: alias } = defineProps()` or
53    /// `let { name: alias } = $props()`, otherwise the prop name itself. A
54    /// renamed prop is read through this local, so usage must be checked against
55    /// it, not the declared name.
56    pub local: String,
57    /// Start byte offset of the prop declaration (anchors the finding).
58    pub span_start: u32,
59    /// Whether this prop is referenced in the component's `<script>` (a
60    /// destructured local binding with a resolved reference, or a `props.<name>`
61    /// member access). For React, this is set-in-body: a resolved reference to the
62    /// destructured local anywhere in the component function body.
63    pub used_in_script: bool,
64    /// Whether this prop name is referenced in the component's `<template>`.
65    /// Set by `apply_template_usage` when the template scanner credits the name.
66    /// Always false for React (no template; React uses `used_in_script`).
67    pub used_in_template: bool,
68    /// The enclosing component name. Empty for Vue SFCs (one component per file,
69    /// the file stem is the component, set by the detector). For React this is the
70    /// component function/arrow name a prop was declared on, so the detector can
71    /// emit the right `component_name` and apply the per-component abstain ladder
72    /// (a file can declare several React components).
73    pub component: String,
74    /// React-only: `true` when the destructured prop local is referenced at least
75    /// once OUTSIDE a child-JSX attribute value expression (a substantive
76    /// consumption: a hook arg, a host-element child, a non-JSX-attr read). When
77    /// `used_in_script` is true but this is false, the prop is referenced ONLY as
78    /// the root of forwarded child attribute values, i.e. a pure pass-through.
79    /// Always `false` for Vue (no forward-vs-consume distinction is computed).
80    pub used_outside_forward: bool,
81}
82
83/// A Vue `<script setup>` `defineEmits` declared event, harvested from the type
84/// tuple-call form (`defineEmits<{ (e: 'foo'): void }>()`), the type object form
85/// (`defineEmits<{ foo: [x: string] }>()`), or the runtime array form
86/// (`defineEmits(['foo'])`). `used` is set during extraction when the bound emit
87/// name is called as `emit('<name>')`. The `unused-component-emit` detector flags
88/// an event where `used` is false. See `harvest_define_emits` in `sfc_props.rs`.
89#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
90pub struct ComponentEmit {
91    /// The declared emit event name.
92    pub name: String,
93    /// Start byte offset of the emit declaration (anchors the finding).
94    pub span_start: u32,
95    /// Whether this event is emitted via `emit('<name>')` somewhere in the
96    /// component's `<script>`.
97    pub used: bool,
98}
99
100/// A Svelte custom event dispatched via `dispatch('<name>')`, where `dispatch`
101/// is the binding from a `const dispatch = createEventDispatcher()` call. Only
102/// literal-first-arg dispatches are recorded; a `dispatch(<nonLiteral>)` sets
103/// `ModuleInfo::has_dynamic_dispatch` instead. Consumed by the
104/// `unused-svelte-event` detector, which flags an event dispatched here but
105/// listened to nowhere project-wide (the cross-file dead-output direction). The
106/// span is a byte offset (not an `oxc_span::Span`) so the type round-trips
107/// through the bitcode cache directly, mirroring `ComponentEmit::span_start`.
108#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
109pub struct DispatchedEvent {
110    /// The dispatched event name (the literal first argument).
111    pub name: String,
112    /// Start byte offset of the `dispatch(...)` call (anchors the finding).
113    pub span_start: u32,
114}
115
116/// A declared Angular component/directive input, harvested from an `@Input()`
117/// decorator or a signal `input()` / `input.required()` / `model()` initializer
118/// on an Angular-decorated class. Consumed by the `unused-component-input`
119/// detector, which flags an input read nowhere in its own component (neither the
120/// template nor the class body). The span is stored as a byte offset (not an
121/// `oxc_span::Span`) so the type is cheap to mirror onto the cache, matching
122/// `ComponentEmit::span_start`. `ModuleInfo` is not serialized, so no serde
123/// attrs are derived here. `bitcode` derives let the type be mirrored directly
124/// onto `CachedModule` (the same pattern as `ComponentEmit`).
125#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
126pub struct AngularInputMember {
127    /// The declared input name (the property key).
128    pub name: String,
129    /// Start byte offset of the property key (anchors the finding).
130    pub span_start: u32,
131}
132
133/// A declared Angular component/directive output, harvested from an `@Output()`
134/// decorator or a signal `output()` / `outputFromObservable()` initializer on an
135/// Angular-decorated class. Consumed by the `unused-component-output` detector,
136/// which flags an output emitted nowhere in its own component. A `model()` is an
137/// input and a framework-driven output, so it is recorded ONLY as an input and
138/// never appears here (the implicit `update:` emit is framework-managed). The
139/// span is a byte offset for the same reason as `AngularInputMember`.
140#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
141pub struct AngularOutputMember {
142    /// The declared output name (the property key).
143    pub name: String,
144    /// Start byte offset of the property key (anchors the finding).
145    pub span_start: u32,
146}
147
148/// A declared Angular `@Component` and its `selector` value(s), harvested from a
149/// `@Component({ selector: '...' })` decorator. Consumed by the Angular arm of
150/// the `unrendered-component` detector, which flags a component whose every
151/// element selector is used in NO template project-wide (and that is not
152/// referenced by class name anywhere, e.g. routed / bootstrapped / dynamically
153/// rendered). A multi-selector string (`'app-foo, [appBar]'`) is split into the
154/// `selectors` list. The span is stored as a byte offset (not an
155/// `oxc_span::Span`) so the type round-trips through the bitcode cache directly,
156/// mirroring `AngularInputMember::span_start`. `@Directive` is intentionally NOT
157/// harvested here (directives have no template render). `ModuleInfo` is not
158/// serialized, so no serde attrs are derived.
159#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
160pub struct AngularComponentSelector {
161    /// The declared selector strings for this component, split on `,`. A purely
162    /// element-selector component has only `app-foo`-shaped entries; attribute
163    /// (`[appFoo]`) and class (`.foo`) selectors are retained verbatim so the
164    /// detector can abstain when ANY non-element selector is present.
165    pub selectors: Vec<String>,
166    /// Start byte offset of the component class declaration (anchors the
167    /// finding).
168    pub span_start: u32,
169    /// The component class name (used to credit routed / bootstrapped / dynamic
170    /// class-name references project-wide).
171    pub class_name: String,
172}
173
174/// A Lit / web-component custom element registered in a module via
175/// `@customElement('x-foo')` or `customElements.define('x-foo', C)`. Consumed by
176/// the Lit arm of the `unrendered-component` detector. The span is stored as a
177/// byte offset (not an `oxc_span::Span`) so the type round-trips through the
178/// bitcode cache directly, mirroring `AngularComponentSelector::span_start`.
179#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
180pub struct RegisteredCustomElement {
181    /// The registered custom-element tag name (`x-foo`).
182    pub tag: String,
183    /// The registering class's local name, used for the public-API / export
184    /// abstain (an exported / published element is rendered by a downstream
185    /// consumer the scan cannot see). Empty for an anonymous
186    /// `export default @customElement('x-foo') class extends LitElement {}`.
187    pub class_local_name: String,
188    /// Start byte offset of the registering class declaration (anchors the
189    /// finding at the element, NOT line 1, since a `.ts` file can register
190    /// several custom elements).
191    pub span_start: u32,
192}
193
194/// A key returned from a SvelteKit route `load()` function's terminal return
195/// object literal. Harvested from `+page.{ts,server.ts,js,server.js}` files
196/// exporting a `load` function. Consumed by the `unused-load-data-key` detector,
197/// which flags a key read by no consumer. The span is stored as byte offsets
198/// (not an `oxc_span::Span`) so the type round-trips through the bitcode cache
199/// directly, mirroring `DiKeySite::span_start` / `ComponentEmit::span_start`.
200#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode, PartialEq, Eq)]
201pub struct LoadReturnKey {
202    /// The returned-object property key name.
203    pub name: String,
204    /// Start byte offset of the key (anchors the finding).
205    pub span_start: u32,
206    /// End byte offset of the key.
207    pub span_end: u32,
208}
209
210/// The syntactic shape of an identified React component definition. Drives the
211/// abstain ladder later phases apply: a `forwardRef` / `memo` wrapper whose
212/// props come from an imported interface fallow cannot resolve must abstain
213/// (ADR-001), not guess.
214#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
215pub enum ComponentFunctionKind {
216    /// A `function Foo() { return <.../> }` declaration.
217    FnDecl,
218    /// A `const Foo = () => <.../>` arrow (or function-expression) binding.
219    Arrow,
220    /// A `const Foo = forwardRef((props, ref) => <.../>)` wrapper.
221    ForwardRefWrapper,
222    /// A `const Foo = memo((props) => <.../>)` wrapper.
223    MemoWrapper,
224}
225
226/// An identified React component: a function/arrow whose body returns JSX.
227/// Captured by `visit_jsx_element`'s enclosing-component tracking. The
228/// `unused-component-prop` (React arm) and complexity-fold phases consume this;
229/// the abstain flags keep zero-FP on the cases ADR-001 cannot resolve.
230#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
231pub struct ComponentFunction {
232    /// The component name (the binding or declaration identifier).
233    pub name: String,
234    /// Start byte offset of the component definition (anchors findings).
235    pub span_start: u32,
236    /// The syntactic shape of the definition.
237    pub kind: ComponentFunctionKind,
238    /// Whether the component is exported from its module (a named export, a
239    /// `export default`, or re-exported in the same module). Public-API
240    /// components abstain in the prop phase.
241    pub is_exported: bool,
242    /// `true` when the component's props are not statically harvestable: a
243    /// rest/spread in the signature (`{ ...rest }`), props passed wholesale to a
244    /// hook/helper, or a `forwardRef` / `memo` wrapper whose props come from an
245    /// imported interface generic fallow cannot resolve (ADR-001). The prop
246    /// phase abstains on the whole component when set.
247    pub has_unharvestable_props: bool,
248    /// `true` when the component body calls `cloneElement` / `React.cloneElement`.
249    /// `cloneElement` injects props by reflection, so the static forward-set is
250    /// incomplete; the prop-drilling phase abstains on any chain through this
251    /// component (ADR-001, zero-FP).
252    pub uses_clone_element: bool,
253    /// `true` when the component renders a `*.Provider` member-expression tag
254    /// (`<FooContext.Provider>`). A context provider in the subtree means the
255    /// drilling may be a deliberate non-context choice (or the prop is about to
256    /// be provided); the prop-drilling phase downgrades/abstains.
257    pub renders_provider: bool,
258    /// `true` when the component passes a function as a child render value
259    /// (render-props / children-as-function: `<Foo>{() => ...}</Foo>` or
260    /// `<Foo render={() => ...}/>`). The forwarded shape is dynamic; the
261    /// prop-drilling phase abstains on chains through this component.
262    pub has_children_as_function: bool,
263    /// `true` when the component body is pure structural indirection: a single
264    /// statement returning exactly one capitalized/member-expression JSX element
265    /// (no host wrapper, no extra children, optionally a fragment wrapping a
266    /// single element) that forwards props via a bare spread of the component's
267    /// own props binding / rest local (`<Child {...props}/>`), with NO named
268    /// attributes alongside the spread and NO self-render. The cross-component
269    /// `thin-wrapper` phase joins this with hook-density / cyclomatic checks and
270    /// the resolved single render edge to flag a component that is a candidate
271    /// for inlining. Computed from the component's own AST only, so it caches
272    /// byte-identity-safe (ADR-001).
273    pub is_pure_passthrough: bool,
274}
275
276/// The kind of a React hook call. `Custom` covers any `use*`-named call that is
277/// not one of the built-in hooks.
278#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
279pub enum HookUseKind {
280    /// `useState(...)`.
281    UseState,
282    /// `useEffect(...)`.
283    UseEffect,
284    /// `useMemo(...)`.
285    UseMemo,
286    /// `useCallback(...)`.
287    UseCallback,
288    /// Any other `use*`-named call (a custom hook).
289    Custom,
290}
291
292/// A React hook call site inside a component. Consumed by the complexity-fold
293/// phase (hook density) and surfaced as descriptive hotspot context.
294#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
295pub struct HookUse {
296    /// The hook kind.
297    pub kind: HookUseKind,
298    /// The dependency-array arity, recorded ONLY when a literal array is present
299    /// at the dependency-array position (`[a, b]` -> `Some(2)`, `[]` ->
300    /// `Some(0)`). `None` when the call has no dependency array argument or the
301    /// argument is not a literal array (ADR-001: do not guess).
302    pub dep_array_arity: Option<u32>,
303    /// Start byte offset of the hook call (anchors findings).
304    pub span_start: u32,
305    /// The enclosing component name (the top of the visitor's component stack
306    /// when the hook call was recorded). Lets the descriptive per-component hook
307    /// summary attribute hooks exactly even when a file declares several
308    /// components. A hook recorded outside any component carries an empty string
309    /// (the visitor only records hooks inside a component, so this is the
310    /// rare top-level / unattributed case).
311    pub component: String,
312}
313
314/// A render edge: one component rendering another (a capitalized or
315/// member-expression JSX tag). Captured at extraction time with the child's
316/// written name; resolution of `child_component_name` to a `FileId`/export is
317/// deferred to graph build via the existing import map.
318#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
319pub struct RenderEdge {
320    /// The name of the component that renders the child (the enclosing
321    /// component). Empty when the JSX is not inside an identified component (a
322    /// top-level render expression).
323    pub parent_component: String,
324    /// The rendered child component name as written (`Foo` or the full
325    /// member-expression path `Foo.Bar`).
326    pub child_component_name: String,
327    /// The attribute (prop) names passed at the render site, in source order.
328    pub attr_names: Vec<String>,
329    /// `true` when the render site contains a JSX spread (`{...x}`), so the
330    /// passed-prop set is not statically complete.
331    pub has_spread: bool,
332    /// The forwarded attributes at this render site: each pairs the child
333    /// attribute NAME with the identifier ROOT of its value expression
334    /// (`userName={user.name}` -> `{ attr: "userName", root: "user" }`;
335    /// `value={x}` -> `{ attr: "value", root: "x" }`). ONLY plain identifier or
336    /// member-root access values are recorded (`{x}`, `{x.y}`, `{x.y.z}`); a value
337    /// that is a call, an arrow/function, a conditional, a JSX element, or any
338    /// other complex expression is NOT recorded here (its root would not be a pure
339    /// forward) and sets `has_complex_forward` instead. The prop-drilling chain
340    /// walk uses this pairing to map "this component forwards prop P" to "the
341    /// child receives it as attribute A".
342    pub forward_attrs: Vec<ForwardAttr>,
343    /// `true` when at least one attribute value at this render site is a complex
344    /// expression (a call, an arrow/function render-prop, a conditional, a JSX
345    /// element-as-prop, a template literal, etc.) whose identifier root was NOT
346    /// recorded in `forward_attrs`. The prop-drilling phase abstains on a chain
347    /// whose forwarded prop flows through such a value (ADR-001, zero-FP).
348    pub has_complex_forward: bool,
349}
350
351/// One forwarded JSX attribute: the child attribute name plus the identifier
352/// root of its value expression. See [`RenderEdge::forward_attrs`].
353#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
354pub struct ForwardAttr {
355    /// The child attribute (prop) name as written (`userName`).
356    pub attr: String,
357    /// The identifier root of the attribute value expression (`user` for
358    /// `userName={user.name}`).
359    pub root: String,
360}