Skip to main content

fallow_types/
extract_flags.rs

1//! Feature flag uses, flag site facts, flag patterns, and the flag key
2//! registry.
3
4/// The kind of feature flag pattern detected.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
6pub enum FlagUseKind {
7    /// `process.env.FEATURE_X` pattern.
8    EnvVar,
9    /// SDK function call like `useFlag('name')`.
10    SdkCall,
11    /// Config object access like `config.features.x`.
12    ConfigObject,
13}
14
15/// A feature flag use site.
16#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
17pub struct FlagUse {
18    /// Flag identifier.
19    pub flag_name: String,
20    /// Detection kind.
21    pub kind: FlagUseKind,
22    /// 1-based line number.
23    pub line: u32,
24    /// 0-based byte column offset.
25    pub col: u32,
26    /// Start byte offset of the guarded block.
27    pub guard_span_start: Option<u32>,
28    /// End byte offset of the guarded block.
29    pub guard_span_end: Option<u32>,
30    /// SDK/provider name.
31    pub sdk_name: Option<String>,
32    /// Facts about the site, for the retirement report and the confidence
33    /// mapping.
34    pub facts: FlagSiteFacts,
35}
36
37const _: () = assert!(std::mem::size_of::<FlagUse>() <= 96);
38
39/// Facts about a flag site that the flag retirement report and the
40/// confidence mapping read.
41///
42/// The branch facts describe the `if`, ternary or JSX `&&` that the site
43/// guards. A site without a guard has no branch facts.
44#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
45pub struct FlagSiteFacts(u8);
46
47impl FlagSiteFacts {
48    const IDENTICAL_BRANCHES: u8 = 1;
49    const EMPTY_BRANCH: u8 = 1 << 1;
50    const DEFINITION: u8 = 1 << 2;
51    const UNCONFIRMED_SDK: u8 = 1 << 3;
52
53    /// Both branches of the guard are the same code, ignoring whitespace
54    /// and comments.
55    #[must_use]
56    pub const fn identical_branches(self) -> bool {
57        self.0 & Self::IDENTICAL_BRANCHES != 0
58    }
59
60    /// No branch of the guard holds code, so the flag does nothing. An
61    /// empty branch is `{}`, `;`, `null`, `undefined`, `void 0`, `<></>`, or
62    /// `false` next to JSX. A missing `else` is an empty branch. Code in one
63    /// branch, for the on case or for the off case, clears this fact.
64    #[must_use]
65    pub const fn empty_branch(self) -> bool {
66        self.0 & Self::EMPTY_BRANCH != 0
67    }
68
69    /// The site defines the flag, as in `export const x = flag({ key })`,
70    /// and does not read it.
71    #[must_use]
72    pub const fn definition(self) -> bool {
73        self.0 & Self::DEFINITION != 0
74    }
75
76    /// The site calls a generic SDK name, such as `isEnabled` or
77    /// `getValue`, and its file imports no flag SDK or flag module. Other
78    /// libraries use the same names, so the site is less certain.
79    #[must_use]
80    pub const fn unconfirmed_sdk(self) -> bool {
81        self.0 & Self::UNCONFIRMED_SDK != 0
82    }
83
84    /// These facts with `unconfirmed_sdk` set to `value`.
85    #[must_use]
86    pub const fn with_unconfirmed_sdk(self, value: bool) -> Self {
87        Self::set(self, Self::UNCONFIRMED_SDK, value)
88    }
89
90    /// These facts with `definition` set to `value`.
91    #[must_use]
92    pub const fn with_definition(self, value: bool) -> Self {
93        Self::set(self, Self::DEFINITION, value)
94    }
95
96    /// These facts with `identical_branches` set to `value`.
97    #[must_use]
98    pub const fn with_identical_branches(self, value: bool) -> Self {
99        Self::set(self, Self::IDENTICAL_BRANCHES, value)
100    }
101
102    /// These facts with `empty_branch` set to `value`.
103    #[must_use]
104    pub const fn with_empty_branch(self, value: bool) -> Self {
105        Self::set(self, Self::EMPTY_BRANCH, value)
106    }
107
108    const fn set(self, bit: u8, value: bool) -> Self {
109        if value {
110            Self(self.0 | bit)
111        } else {
112            Self(self.0 & !bit)
113        }
114    }
115}
116
117/// User flag patterns from the `flags` config section that detection
118/// applies during the parse. The default holds the built-in patterns only.
119///
120/// The parse cache keys on these patterns, so every parse that writes the
121/// cache must use the patterns of the resolved config.
122#[derive(Debug, Clone, Default, PartialEq, Eq)]
123pub struct FlagPatterns {
124    /// Extra SDK calls: function name, zero-based name argument, provider label.
125    pub sdk_patterns: Vec<(String, usize, String)>,
126    /// Extra environment variable prefixes.
127    pub env_prefixes: Vec<String>,
128    /// Whether an access on a config object with a flag-like name is a flag.
129    pub config_object_heuristics: bool,
130}
131
132impl FlagPatterns {
133    /// Whether no user pattern is present.
134    #[must_use]
135    pub fn is_builtin_only(&self) -> bool {
136        self.sdk_patterns.is_empty()
137            && self.env_prefixes.is_empty()
138            && !self.config_object_heuristics
139    }
140}
141
142/// A flag-key registry that a module exports: a module-level `as const`
143/// object or a TypeScript enum whose members hold string flag keys.
144#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
145pub struct FlagKeyRegistry {
146    /// Name the module exports the registry under.
147    pub export_name: String,
148    /// Member name and flag key of each string member, in declaration order.
149    pub members: Vec<(String, String)>,
150}
151
152/// A flag read whose key is a member of an imported registry, as in
153/// `useFlag(FLAGS.X)` where `FLAGS` is imported.
154///
155/// Extraction sees one file only, so project analysis resolves the key
156/// through the import of `registry`.
157#[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
158pub struct FlagRegistryRead {
159    /// Local name of the imported registry binding.
160    pub registry: String,
161    /// Registry member that holds the flag key.
162    pub member: String,
163    /// The read site. `flag_name` stays empty until analysis resolves the key.
164    pub flag_use: FlagUse,
165}
166
167/// A module-level `const` with a flag-style name and a literal value, such
168/// as `const FEATURE_NEW_UI = true`, that a guard in the same module tests.
169///
170/// The flag retirement report reads these. They are not in the per-site
171/// flag findings.
172#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
173pub struct FlagConstant {
174    /// Binding name.
175    pub name: String,
176    /// The literal value as source code: `true`, `0` or `'on'`.
177    pub value: String,
178    /// 1-based line of the binding.
179    pub line: u32,
180    /// 0-based byte column of the binding.
181    pub col: u32,
182    /// Guard tests that read the binding, in source order.
183    pub reads: Vec<FlagConstantRead>,
184}
185
186/// A guard test that reads a [`FlagConstant`].
187#[derive(Debug, Clone, Copy, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
188pub struct FlagConstantRead {
189    /// 1-based line.
190    pub line: u32,
191    /// 0-based byte column.
192    pub col: u32,
193    /// Facts about the guard.
194    pub facts: FlagSiteFacts,
195}
196
197/// A flag definition bound to a `const`, as in
198/// `export const showBanner = flag({ key: 'show-banner' })`.
199#[derive(Debug, Clone, PartialEq, Eq, bitcode::Encode, bitcode::Decode)]
200pub struct FlagDefinition {
201    /// The binding that holds the definition.
202    pub binding: String,
203    /// 1-based line of the definition call, as on its [`FlagUse`].
204    pub line: u32,
205    /// 0-based byte column of the definition call, as on its [`FlagUse`].
206    pub col: u32,
207}
208
209/// Registry facts, and other flag facts outside the per-site findings, that
210/// a module gives to feature flag analysis.
211#[derive(Debug, Clone, Default, bitcode::Encode, bitcode::Decode)]
212pub struct FlagRegistryFacts {
213    /// Registries this module exports.
214    pub registries: Vec<FlagKeyRegistry>,
215    /// Flag reads that name a member of an imported registry.
216    pub reads: Vec<FlagRegistryRead>,
217    /// Literal `const` flags that a guard in the module tests.
218    pub constants: Vec<FlagConstant>,
219    /// Flag definitions bound to a `const`.
220    pub definitions: Vec<FlagDefinition>,
221}
222
223impl FlagRegistryFacts {
224    /// Whether the module contributes no fact.
225    #[must_use]
226    pub fn is_empty(&self) -> bool {
227        self.registries.is_empty()
228            && self.reads.is_empty()
229            && self.constants.is_empty()
230            && self.definitions.is_empty()
231    }
232}