| 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::Any, fmt, hash::Hash}; |
| 6 |
|
| 7 |
use anyhow::{anyhow, Result}; |
| 8 |
use indexmap::{IndexMap, IndexSet}; |
| 9 |
|
| 10 |
use super::Value; |
| 11 |
|
| 12 |
/// Node trait, this is implemented on all nodes in the Ir (structs, enums and their fields) |
| 13 |
/// |
| 14 |
/// Note: All node types must implement `Clone`, `Default`, and `PartialEq`, and the derive macro ensures that. |
| 15 |
/// However, these are not bounds on the node trait, since they're not `dyn-compatible`. |
| 16 |
pub trait Node: fmt::Debug + Any { |
| 17 |
/// Call a visitor function for all child nodes |
| 18 |
/// |
| 19 |
/// Calls the visitor with a path string that represents the field name, vec index, etc. along |
| 20 |
/// with the child node. |
| 21 |
/// |
| 22 |
/// If the visitor returns an error, then the error is returned from `visit_children` without |
| 23 |
/// any more visits. |
| 24 |
fn visit_children( |
| 25 |
&self, |
| 26 |
_visitor: &mut dyn FnMut(&str, &dyn Node) -> Result<()>, |
| 27 |
) -> Result<()> { |
| 28 |
Ok(()) |
| 29 |
} |
| 30 |
|
| 31 |
/// Like visit_children, but use &mut. |
| 32 |
/// |
| 33 |
/// Note: this will not visit `IndexMap` keys, since they can't be mutated. |
| 34 |
fn visit_children_mut( |
| 35 |
&mut self, |
| 36 |
_visitor: &mut dyn FnMut(&str, &mut dyn Node) -> Result<()>, |
| 37 |
) -> Result<()> { |
| 38 |
Ok(()) |
| 39 |
} |
| 40 |
|
| 41 |
/// Type name for structs / enums |
| 42 |
/// |
| 43 |
/// This is used to implement the type name filter in the CLI |
| 44 |
fn type_name(&self) -> Option<&'static str> { |
| 45 |
None |
| 46 |
} |
| 47 |
|
| 48 |
/// Create a value from this node's data |
| 49 |
/// |
| 50 |
/// Logically, this consumes `self`. However, in inputs `&mut self` because it works better |
| 51 |
/// with dyn traits. It leaves behind an empty node. |
| 52 |
fn take_into_value(&mut self) -> Value; |
| 53 |
|
| 54 |
/// Convert a value into this node. |
| 55 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> |
| 56 |
where |
| 57 |
Self: Sized; |
| 58 |
|
| 59 |
/// Convert `&Node` into `&dyn Any`. |
| 60 |
/// |
| 61 |
/// This is used to implement `visit_children`. |
| 62 |
fn as_any(&self) -> &dyn Any; |
| 63 |
|
| 64 |
/// Convert `&Node` into `&mut dyn Any`. |
| 65 |
fn as_any_mut(&mut self) -> &mut dyn Any; |
| 66 |
|
| 67 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any>; |
| 68 |
|
| 69 |
fn visit<T: Node>(&self, mut visitor: impl FnMut(&T)) |
| 70 |
where |
| 71 |
Self: Sized, |
| 72 |
{ |
| 73 |
// unwrap() should never panic, since the visitor doesn't return an error |
| 74 |
(self as &dyn Node) |
| 75 |
.try_visit_descendents_recurse(&mut |node| { |
| 76 |
visitor(node); |
| 77 |
Ok(()) |
| 78 |
}) |
| 79 |
.unwrap() |
| 80 |
} |
| 81 |
|
| 82 |
fn visit_mut<T: Node>(&mut self, mut visitor: impl FnMut(&mut T)) |
| 83 |
where |
| 84 |
Self: Sized, |
| 85 |
{ |
| 86 |
// unwrap() should never panic, since the visitor doesn't return an error |
| 87 |
(self as &mut dyn Node) |
| 88 |
.try_visit_descendents_recurse_mut(&mut |node| { |
| 89 |
visitor(node); |
| 90 |
Ok(()) |
| 91 |
}) |
| 92 |
.unwrap() |
| 93 |
} |
| 94 |
|
| 95 |
fn try_visit<T: Node>(&self, mut visitor: impl FnMut(&T) -> Result<()>) -> Result<()> |
| 96 |
where |
| 97 |
Self: Sized, |
| 98 |
{ |
| 99 |
(self as &dyn Node).try_visit_descendents_recurse(&mut visitor) |
| 100 |
} |
| 101 |
|
| 102 |
fn try_visit_mut<T: Node>( |
| 103 |
&mut self, |
| 104 |
mut visitor: impl FnMut(&mut T) -> Result<()>, |
| 105 |
) -> Result<()> |
| 106 |
where |
| 107 |
Self: Sized, |
| 108 |
{ |
| 109 |
(self as &mut dyn Node).try_visit_descendents_recurse_mut(&mut visitor) |
| 110 |
} |
| 111 |
|
| 112 |
/// Take the current value from `self` leaving behind an empty value |
| 113 |
fn take(&mut self) -> Self |
| 114 |
where |
| 115 |
Self: Default, |
| 116 |
{ |
| 117 |
std::mem::take(self) |
| 118 |
} |
| 119 |
|
| 120 |
/// Convert from one node to another |
| 121 |
fn try_from_node(mut other: impl Node) -> Result<Self> |
| 122 |
where |
| 123 |
Self: Sized, |
| 124 |
{ |
| 125 |
Self::try_from_value(other.take_into_value()).map_err(|mut e| { |
| 126 |
e.path.reverse(); |
| 127 |
let path = e.path.join(""); |
| 128 |
anyhow!("Node conversion error: {} (path: <root>{path})", e.message) |
| 129 |
}) |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
impl dyn Node { |
| 134 |
pub(crate) fn try_visit_descendents_recurse<T: Node>( |
| 135 |
&self, |
| 136 |
visitor: &mut dyn FnMut(&T) -> Result<()>, |
| 137 |
) -> Result<()> { |
| 138 |
if let Some(node) = self.as_any().downcast_ref::<T>() { |
| 139 |
visitor(node)?; |
| 140 |
} |
| 141 |
self.visit_children(&mut |_, child| { |
| 142 |
child.try_visit_descendents_recurse(visitor)?; |
| 143 |
Ok(()) |
| 144 |
}) |
| 145 |
} |
| 146 |
|
| 147 |
pub(crate) fn try_visit_descendents_recurse_mut<T: Node>( |
| 148 |
&mut self, |
| 149 |
visitor: &mut dyn FnMut(&mut T) -> Result<()>, |
| 150 |
) -> Result<()> { |
| 151 |
if let Some(node) = self.as_any_mut().downcast_mut::<T>() { |
| 152 |
visitor(node)?; |
| 153 |
} |
| 154 |
self.visit_children_mut(&mut |_, child| { |
| 155 |
child.try_visit_descendents_recurse_mut(visitor)?; |
| 156 |
Ok(()) |
| 157 |
}) |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
/// Error struct for `Node::try_from_value` |
| 162 |
pub struct FromValueError { |
| 163 |
/// Field path to the node that couldn't be converted. |
| 164 |
/// |
| 165 |
/// To make the generated code simpler, this is in reverse order, the first items in the vec |
| 166 |
/// are the deepest items in the node tree. |
| 167 |
path: Vec<String>, |
| 168 |
message: String, |
| 169 |
} |
| 170 |
|
| 171 |
impl FromValueError { |
| 172 |
pub fn new(message: String) -> Self { |
| 173 |
Self { |
| 174 |
message, |
| 175 |
path: vec![], |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
pub fn add_field_to_path(mut self, field: impl Into<String>) -> Self { |
| 180 |
self.path.push(field.into()); |
| 181 |
self |
| 182 |
} |
| 183 |
|
| 184 |
pub fn into_anyhow(mut self) -> anyhow::Error { |
| 185 |
self.path.reverse(); |
| 186 |
let path = self.path.join(""); |
| 187 |
anyhow!( |
| 188 |
"Node conversion error: {} (path: <root>{path})", |
| 189 |
self.message |
| 190 |
) |
| 191 |
} |
| 192 |
} |
| 193 |
|
| 194 |
macro_rules! simple_nodes { |
| 195 |
($($value_variant:ident($ty:ty)),* $(,)?) => { |
| 196 |
$( |
| 197 |
impl Node for $ty { |
| 198 |
fn as_any(&self) -> &dyn Any { |
| 199 |
self |
| 200 |
} |
| 201 |
|
| 202 |
fn as_any_mut(&mut self) -> &mut dyn Any { |
| 203 |
self |
| 204 |
} |
| 205 |
|
| 206 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any>{ |
| 207 |
self |
| 208 |
} |
| 209 |
|
| 210 |
fn take_into_value(&mut self) -> Value { |
| 211 |
Value::$value_variant(self.take()) |
| 212 |
} |
| 213 |
|
| 214 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> { |
| 215 |
match value { |
| 216 |
Value::$value_variant(v) => Ok(v), |
| 217 |
v => Err(FromValueError::new(format!( |
| 218 |
"Node type error (expected {}, actual {v:?})", |
| 219 |
std::stringify!($value_variant) |
| 220 |
))), |
| 221 |
} |
| 222 |
} |
| 223 |
} |
| 224 |
)* |
| 225 |
}; |
| 226 |
} |
| 227 |
|
| 228 |
simple_nodes!( |
| 229 |
UInt8(u8), |
| 230 |
Int8(i8), |
| 231 |
UInt16(u16), |
| 232 |
Int16(i16), |
| 233 |
UInt32(u32), |
| 234 |
Int32(i32), |
| 235 |
UInt64(u64), |
| 236 |
Int64(i64), |
| 237 |
Float32(f32), |
| 238 |
Float64(f64), |
| 239 |
String(String), |
| 240 |
Bool(bool), |
| 241 |
); |
| 242 |
|
| 243 |
impl<T: Node> Node for Box<T> { |
| 244 |
fn visit_children(&self, visitor: &mut dyn FnMut(&str, &dyn Node) -> Result<()>) -> Result<()> { |
| 245 |
visitor("", &**self) |
| 246 |
} |
| 247 |
|
| 248 |
fn visit_children_mut( |
| 249 |
&mut self, |
| 250 |
visitor: &mut dyn FnMut(&str, &mut dyn Node) -> Result<()>, |
| 251 |
) -> Result<()> { |
| 252 |
visitor("", &mut **self) |
| 253 |
} |
| 254 |
|
| 255 |
fn as_any(&self) -> &dyn Any { |
| 256 |
self |
| 257 |
} |
| 258 |
|
| 259 |
fn as_any_mut(&mut self) -> &mut dyn Any { |
| 260 |
self |
| 261 |
} |
| 262 |
|
| 263 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any> { |
| 264 |
self |
| 265 |
} |
| 266 |
|
| 267 |
fn take_into_value(&mut self) -> Value { |
| 268 |
(**self).take_into_value() |
| 269 |
} |
| 270 |
|
| 271 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> { |
| 272 |
T::try_from_value(value).map(Box::new) |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
impl<T: Node> Node for Option<T> { |
| 277 |
fn visit_children(&self, visitor: &mut dyn FnMut(&str, &dyn Node) -> Result<()>) -> Result<()> { |
| 278 |
if let Some(node) = self { |
| 279 |
visitor("", node)?; |
| 280 |
} |
| 281 |
Ok(()) |
| 282 |
} |
| 283 |
|
| 284 |
fn visit_children_mut( |
| 285 |
&mut self, |
| 286 |
visitor: &mut dyn FnMut(&str, &mut dyn Node) -> Result<()>, |
| 287 |
) -> Result<()> { |
| 288 |
if let Some(node) = self { |
| 289 |
visitor("", node)?; |
| 290 |
} |
| 291 |
Ok(()) |
| 292 |
} |
| 293 |
|
| 294 |
fn as_any(&self) -> &dyn Any { |
| 295 |
self |
| 296 |
} |
| 297 |
|
| 298 |
fn as_any_mut(&mut self) -> &mut dyn Any { |
| 299 |
self |
| 300 |
} |
| 301 |
|
| 302 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any> { |
| 303 |
self |
| 304 |
} |
| 305 |
|
| 306 |
fn take_into_value(&mut self) -> Value { |
| 307 |
Value::Option( |
| 308 |
self.take() |
| 309 |
.map(|mut node| node.take_into_value()) |
| 310 |
.map(Box::new), |
| 311 |
) |
| 312 |
} |
| 313 |
|
| 314 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> { |
| 315 |
match value { |
| 316 |
Value::Option(v) => v.map(|v| v.try_into_node()).transpose(), |
| 317 |
v => Err(FromValueError::new(format!( |
| 318 |
"Node type error (expected Option, actual {v:?})" |
| 319 |
))), |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
|
| 324 |
impl<T: Node> Node for Vec<T> { |
| 325 |
fn visit_children(&self, visitor: &mut dyn FnMut(&str, &dyn Node) -> Result<()>) -> Result<()> { |
| 326 |
for (i, child) in self.iter().enumerate() { |
| 327 |
visitor(&format!(".{i}"), child)?; |
| 328 |
} |
| 329 |
Ok(()) |
| 330 |
} |
| 331 |
|
| 332 |
fn visit_children_mut( |
| 333 |
&mut self, |
| 334 |
visitor: &mut dyn FnMut(&str, &mut dyn Node) -> Result<()>, |
| 335 |
) -> Result<()> { |
| 336 |
for (i, child) in self.iter_mut().enumerate() { |
| 337 |
visitor(&format!(".{i}"), child)?; |
| 338 |
} |
| 339 |
Ok(()) |
| 340 |
} |
| 341 |
|
| 342 |
fn as_any(&self) -> &dyn Any { |
| 343 |
self |
| 344 |
} |
| 345 |
|
| 346 |
fn as_any_mut(&mut self) -> &mut dyn Any { |
| 347 |
self |
| 348 |
} |
| 349 |
|
| 350 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any> { |
| 351 |
self |
| 352 |
} |
| 353 |
|
| 354 |
fn take_into_value(&mut self) -> Value { |
| 355 |
Value::Vec( |
| 356 |
self.take() |
| 357 |
.into_iter() |
| 358 |
.map(|mut node| node.take_into_value()) |
| 359 |
.collect(), |
| 360 |
) |
| 361 |
} |
| 362 |
|
| 363 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> { |
| 364 |
match value { |
| 365 |
Value::Vec(values) => values |
| 366 |
.into_iter() |
| 367 |
.enumerate() |
| 368 |
.map(|(i, v)| { |
| 369 |
v.try_into_node() |
| 370 |
.map_err(|e| e.add_field_to_path(format!("[{i}]"))) |
| 371 |
}) |
| 372 |
.collect(), |
| 373 |
v => Err(FromValueError::new(format!( |
| 374 |
"Node type error (expected Vec, actual {v:?})", |
| 375 |
))), |
| 376 |
} |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
impl<T> Node for IndexSet<T> |
| 381 |
where |
| 382 |
T: Node + Hash + Eq, |
| 383 |
{ |
| 384 |
fn visit_children(&self, visitor: &mut dyn FnMut(&str, &dyn Node) -> Result<()>) -> Result<()> { |
| 385 |
for v in self.iter() { |
| 386 |
visitor(&format!("{{{v:?}}}"), v)?; |
| 387 |
} |
| 388 |
Ok(()) |
| 389 |
} |
| 390 |
|
| 391 |
fn visit_children_mut( |
| 392 |
&mut self, |
| 393 |
visitor: &mut dyn FnMut(&str, &mut dyn Node) -> Result<()>, |
| 394 |
) -> Result<()> { |
| 395 |
// We can't directly mutate IndexSet items, since that would change their hash value. |
| 396 |
// Instead, use deconstruct the set using into_iter() and collect everything at the end. |
| 397 |
*self = Node::take(self) |
| 398 |
.into_iter() |
| 399 |
.map(|mut v| { |
| 400 |
visitor(&format!("{{{v:?}}}"), &mut v)?; |
| 401 |
Ok(v) |
| 402 |
}) |
| 403 |
.collect::<Result<IndexSet<_>>>()?; |
| 404 |
Ok(()) |
| 405 |
} |
| 406 |
|
| 407 |
fn as_any(&self) -> &dyn Any { |
| 408 |
self |
| 409 |
} |
| 410 |
|
| 411 |
fn as_any_mut(&mut self) -> &mut dyn Any { |
| 412 |
self |
| 413 |
} |
| 414 |
|
| 415 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any> { |
| 416 |
self |
| 417 |
} |
| 418 |
|
| 419 |
fn take_into_value(&mut self) -> Value { |
| 420 |
Value::Set( |
| 421 |
Node::take(self) |
| 422 |
.into_iter() |
| 423 |
.map(|mut node| node.take_into_value()) |
| 424 |
.collect(), |
| 425 |
) |
| 426 |
} |
| 427 |
|
| 428 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> { |
| 429 |
match value { |
| 430 |
Value::Set(values) => values |
| 431 |
.into_iter() |
| 432 |
.map(|k| { |
| 433 |
let key_name = format!("{k:?}"); |
| 434 |
k.try_into_node() |
| 435 |
.map_err(|e| e.add_field_to_path(format!("{{{key_name:?}}}"))) |
| 436 |
}) |
| 437 |
.collect(), |
| 438 |
v => Err(FromValueError::new(format!( |
| 439 |
"Node type error (expected Map, actual {v:?})", |
| 440 |
))), |
| 441 |
} |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
impl<K, V> Node for IndexMap<K, V> |
| 446 |
where |
| 447 |
K: Node + Hash + Eq, |
| 448 |
V: Node, |
| 449 |
{ |
| 450 |
fn visit_children(&self, visitor: &mut dyn FnMut(&str, &dyn Node) -> Result<()>) -> Result<()> { |
| 451 |
for (k, v) in self.iter() { |
| 452 |
visitor(&format!("[{k:?}]"), v)?; |
| 453 |
visitor(&format!(".key[{k:?}]"), k)?; |
| 454 |
} |
| 455 |
Ok(()) |
| 456 |
} |
| 457 |
|
| 458 |
fn visit_children_mut( |
| 459 |
&mut self, |
| 460 |
visitor: &mut dyn FnMut(&str, &mut dyn Node) -> Result<()>, |
| 461 |
) -> Result<()> { |
| 462 |
// We can't directly mutate Map key, since that would change their hash value. |
| 463 |
// Instead, use deconstruct the set using into_iter() and collect everything at the end. |
| 464 |
*self = self |
| 465 |
.take() |
| 466 |
.into_iter() |
| 467 |
.map(|(mut k, mut v)| { |
| 468 |
let key_name = format!("{k:?}"); |
| 469 |
visitor(&format!("{{{key_name:?}}}"), &mut k)?; |
| 470 |
visitor(&format!("[{key_name:?}]"), &mut v)?; |
| 471 |
Ok((k, v)) |
| 472 |
}) |
| 473 |
.collect::<Result<IndexMap<_, _>>>()?; |
| 474 |
Ok(()) |
| 475 |
} |
| 476 |
|
| 477 |
fn as_any(&self) -> &dyn Any { |
| 478 |
self |
| 479 |
} |
| 480 |
|
| 481 |
fn as_any_mut(&mut self) -> &mut dyn Any { |
| 482 |
self |
| 483 |
} |
| 484 |
|
| 485 |
fn to_box_any(self: Box<Self>) -> Box<dyn Any> { |
| 486 |
self |
| 487 |
} |
| 488 |
|
| 489 |
fn take_into_value(&mut self) -> Value { |
| 490 |
Value::Map( |
| 491 |
self.take() |
| 492 |
.into_iter() |
| 493 |
.map(|(mut k, mut v)| (k.take_into_value(), v.take_into_value())) |
| 494 |
.collect(), |
| 495 |
) |
| 496 |
} |
| 497 |
|
| 498 |
fn try_from_value(value: Value) -> Result<Self, FromValueError> { |
| 499 |
match value { |
| 500 |
Value::Map(values) => values |
| 501 |
.into_iter() |
| 502 |
.map(|(k, v)| { |
| 503 |
let v = v |
| 504 |
.try_into_node() |
| 505 |
.map_err(|e| e.add_field_to_path(format!("[{k:?}]")))?; |
| 506 |
let k = k |
| 507 |
.try_into_node() |
| 508 |
.map_err(|e| e.add_field_to_path("[<key>]".to_string()))?; |
| 509 |
Ok((k, v)) |
| 510 |
}) |
| 511 |
.collect(), |
| 512 |
v => Err(FromValueError::new(format!( |
| 513 |
"Node type error (expected Map, actual {v:?})", |
| 514 |
))), |
| 515 |
} |
| 516 |
} |
| 517 |
} |