diff --git a/rust/yarp/build.rs b/rust/yarp/build.rs index 06b80af1dc2..88f2faee104 100644 --- a/rust/yarp/build.rs +++ b/rust/yarp/build.rs @@ -156,6 +156,12 @@ fn write_node(file: &mut File, node: &Node) -> Result<(), Box {}<'pr> {{", node.name)?; + writeln!(file, " /// Converts this node to a generic node.")?; + writeln!(file, " #[must_use]")?; + writeln!(file, " pub fn as_node(&self) -> Node<'pr> {{")?; + writeln!(file, " Node::{} {{ pointer: self.pointer, marker: PhantomData }}", node.name)?; + writeln!(file, " }}")?; + writeln!(file)?; writeln!(file, " /// Returns the location of this node.")?; writeln!(file, " #[must_use]")?; writeln!(file, " pub fn location(&self) -> Location<'pr> {{")?; diff --git a/rust/yarp/src/lib.rs b/rust/yarp/src/lib.rs index becb8d163ac..23930793382 100644 --- a/rust/yarp/src/lib.rs +++ b/rust/yarp/src/lib.rs @@ -312,4 +312,20 @@ mod tests { assert_eq!(visitor.count, 2); } + + #[test] + fn node_upcast_test() { + use super::Node; + + let source = "module Foo; end"; + let result = parse(source.as_ref()); + + let node = result.node(); + let upcast_node = node.as_program_node().unwrap().as_node(); + assert!(matches!(upcast_node, Node::ProgramNode { .. })); + + let node = node.as_program_node().unwrap().statements().body().iter().next().unwrap(); + let upcast_node = node.as_module_node().unwrap().as_node(); + assert!(matches!(upcast_node, Node::ModuleNode { .. })); + } }