Debian Codegraph @

third_party/rust/uniffi_pipeline/src/pipeline.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use std::{any::type_name, io::Write, marker::PhantomData, process::Command};
6
7 use anyhow::{anyhow, Context, Result};
8 use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
9
10 use super::Node;
11
12 /// Bindgen pipeline
13 ///
14 /// Input and Output are root nodes of the input/output IR. This pipeline converts from `Input` to
15 /// `Output` using a series of passes.
16 ///
17 /// See https://mozilla.github.io/uniffi-rs/latest/internals/bindings_ir_pipeline.html for details on
18 /// how this works.
19 pub struct Pipeline<Input, Output> {
20 passes: Vec<Pass>,
21 input: PhantomData<Input>,
22 output: PhantomData<Output>,
23 }
24
25 /// A pipeline pass is a function that converts the root node of an IR into another root node
26 pub struct Pass {
27 name: String,
28 func: PassFn,
29 }
30
31 type PassFn = Box<dyn FnMut(Box<dyn Node>) -> Result<Box<dyn Node>>>;
32
33 pub fn new_pipeline<Input: Node>() -> Pipeline<Input, Input> {
34 Pipeline {
35 passes: vec![],
36 input: PhantomData,
37 output: PhantomData,
38 }
39 }
40
41 impl<Input: Node, Output: Node> Pipeline<Input, Output> {
42 /// Add a pass that converts the current root node into NewOutput
43 ///
44 /// Under the hood, this uses [Node::into_value] and [Node::try_from_value].
45 pub fn convert_ir_pass<NewOutput: Node>(mut self) -> Pipeline<Input, NewOutput> {
46 self.passes.push(Pass {
47 name: format!("Convert root to {}", type_name::<NewOutput>()),
48 func: Box::new(|mut root| {
49 let root = NewOutput::try_from_value(root.take_into_value())
50 .map_err(|e| e.into_anyhow())?;
51 Ok(Box::new(root))
52 }),
53 });
54 Pipeline {
55 passes: self.passes,
56 input: self.input,
57 output: PhantomData,
58 }
59 }
60
61 /// Add a pass that mutates nodes in the current IR
62 ///
63 /// This uses [Node::visit_mut] to find all nodes of a given type, then passes those nodes to
64 /// the provided closure to mutate them.
65 pub fn pass<F, N>(mut self, mut pass_func: F) -> Self
66 where
67 F: FnMut(&mut N) -> Result<()> + 'static,
68 N: Node,
69 {
70 self.passes.push(Pass {
71 name: type_name::<F>().to_string(),
72 func: Box::new(move |mut root| {
73 root.try_visit_descendents_recurse_mut(&mut pass_func)?;
74 Ok(root)
75 }),
76 });
77 self
78 }
79
80 /// Execute the pipeline
81 pub fn execute(&mut self, root: Input) -> Result<Output> {
82 self.execute_all_passes(root, &mut NullPipelineRecorder)
83 }
84
85 /// Execute the pipeline, printing out debugging information for each pass
86 ///
87 /// This is used to implement the `pipeline` CLI subcommand
88 pub fn print_passes(&mut self, root: Input, opts: PrintOptions) -> Result<()> {
89 let mut last_output: Option<(tempfile::TempPath, String)> = None;
90 let mut recorder = PipelineCliRecorder::new(opts.clone());
91 let execute_result = self.execute_all_passes(root, &mut recorder);
92
93 let count = recorder.passes.len();
94
95 for (i, (title, content)) in recorder.passes.into_iter().enumerate() {
96 // Save output for diffing
97 let mut output = tempfile::NamedTempFile::new()?;
98 write!(output, "{content}")?;
99 let output_path = output.into_temp_path();
100
101 if opts.matches_pass(&title, i + 1 == count) {
102 match (last_output, opts.no_diff) {
103 (None, _) | (Some(_), true) => {
104 // First pass, print out the content
105 let title = format!(" {title} ");
106 println!("{title:=^78}");
107 println!("{content}");
108 }
109 (Some((last_output, last_title)), _) => {
110 // Middle pass, print out the diff from the last run
111 Command::new("diff")
112 .args(["-du", "--color=auto"])
113 .arg(&last_output)
114 .arg(&output_path)
115 .arg("--label")
116 .arg(&last_title)
117 .arg("--label")
118 .arg(&title)
119 .spawn()?
120 .wait()?;
121 }
122 }
123 println!();
124 }
125 last_output = Some((output_path, title));
126 }
127 // Check the result after printing all passes. This gives the user more context when things
128 // go wrong.
129 execute_result?;
130 if matches!(opts.pass.as_deref(), None | Some("final")) {
131 if let Some((output_path, _)) = last_output {
132 println!("{:=^78}", " final ");
133 println!("{}", std::fs::read_to_string(output_path)?);
134 }
135 }
136 Ok(())
137 }
138
139 /// Execute each pass in the pipeline and convert `Self::Input` to `Self::Output`
140 ///
141 /// After each pass, call `recorder.report_pass`, passing it the name of the pass and the root node
142 /// after the pass.
143 fn execute_all_passes(
144 &mut self,
145 root: Input,
146 recorder: &mut dyn PipelineRecorder,
147 ) -> Result<Output> {
148 recorder.record_pass("initial", &root);
149 let mut root: Box<dyn Node> = Box::new(root);
150 for pass in self.passes.iter_mut() {
151 root = (pass.func)(root).with_context(|| format!("pass: {}", pass.name))?;
152 recorder.record_pass(&pass.name, root.as_ref());
153 }
154 let root = root
155 .to_box_any()
156 .downcast::<Output>()
157 .map_err(|_| anyhow!("Output type mismatch"))?;
158 Ok(*root)
159 }
160 }
161
162 /// Records passes taken in a IR pipeline
163 pub trait PipelineRecorder {
164 /// Record the result of a pass for the pipeline CLI
165 fn record_pass(&mut self, name: &str, node: &dyn Node);
166 }
167
168 /// Implements PipelineRecorder by doing nothing. This is what's used when we want to just
169 /// generate bindings, not print out the passes for the pipeline CLI
170 struct NullPipelineRecorder;
171
172 impl PipelineRecorder for NullPipelineRecorder {
173 fn record_pass(&mut self, _name: &str, _node: &dyn Node) {}
174 }
175
176 /// Implements PipelineRecorder for the pipeline CLI
177 struct PipelineCliRecorder {
178 opts: PrintOptions,
179 passes: Vec<(String, String)>,
180 }
181
182 impl PipelineCliRecorder {
183 fn new(opts: PrintOptions) -> Self {
184 Self {
185 opts,
186 passes: vec![],
187 }
188 }
189 }
190
191 impl PipelineRecorder for PipelineCliRecorder {
192 fn record_pass(&mut self, name: &str, node: &dyn Node) {
193 self.passes
194 .push((name.to_string(), pass_content(node, &self.opts)));
195 }
196 }
197
198 #[derive(Clone)]
199 pub struct PrintOptions {
200 pub pass: Option<String>,
201 pub no_diff: bool,
202 pub filter_type: Option<String>,
203 pub filter_name: Option<String>,
204 }
205
206 impl PrintOptions {
207 fn matches_pass(&self, title: &str, last: bool) -> bool {
208 match self.pass.as_deref() {
209 None => true,
210 Some("last") => last,
211 Some(p) => title.contains(p),
212 }
213 }
214
215 fn has_filter(&self) -> bool {
216 self.filter_type.is_some() || self.filter_name.is_some()
217 }
218
219 fn matches_node(&self, node: &dyn Node, child: &dyn Node) -> bool {
220 if let Some(filter_type) = &self.filter_type {
221 if node.type_name() != Some(filter_type) {
222 return false;
223 }
224 }
225 if let Some(filter_name) = &self.filter_name {
226 let Some(string_value) = child.as_any().downcast_ref::<String>() else {
227 return false;
228 };
229 if !(string_value.contains(filter_name)
230 || string_value.to_snake_case().contains(filter_name)
231 || string_value.to_shouty_snake_case().contains(filter_name)
232 || string_value.to_lower_camel_case().contains(filter_name)
233 || string_value.to_upper_camel_case().contains(filter_name))
234 {
235 return false;
236 }
237 }
238 true
239 }
240 }
241
242 fn pass_content(node: &dyn Node, opts: &PrintOptions) -> String {
243 if !opts.has_filter() {
244 return format!("{node:#?}");
245 }
246 let mut search = NodeFilterSearch::new(opts);
247 search.search(node);
248 if search.results.is_empty() {
249 return "Empty".to_string();
250 }
251 let mut content = String::new();
252 for (path, node_content) in search.results {
253 let path = format!(" {path} ");
254 content.push_str(&format!("{path:-^78}\n{node_content}\n"));
255 }
256 content
257 }
258
259 // Implements the depth-first-search to handle `pass_content` with a filter
260 struct NodeFilterSearch<'a> {
261 opts: &'a PrintOptions,
262 current_path: Vec<String>,
263 results: Vec<(String, String)>,
264 }
265
266 impl<'a> NodeFilterSearch<'a> {
267 fn new(opts: &'a PrintOptions) -> Self {
268 Self {
269 opts,
270 current_path: vec!["root".to_string()],
271 results: vec![],
272 }
273 }
274
275 fn search(&mut self, node: &dyn Node) {
276 // If any child nodes match, then add this node to the results
277 let mut child_match = false;
278 node.visit_children(&mut |_, child| {
279 child_match = child_match || self.opts.matches_node(node, child);
280 Ok(())
281 })
282 .unwrap();
283 if child_match {
284 self.results
285 .push((self.current_path.join(""), format!("{node:#?}")));
286 } else {
287 // Otherwise, continue recursing
288 node.visit_children(&mut |field_name, child| {
289 self.current_path.push(field_name.to_string());
290 self.search(child);
291 self.current_path.pop();
292 Ok(())
293 })
294 .unwrap();
295 }
296 }
297 }