1 use std::fmt; 2 3 use crate::gen::rust::component::RustPathComponent; 4 use crate::gen::rust::ident::RustIdent; 5 use crate::gen::rust::ident_with_path::RustIdentWithPath; 6 use crate::gen::rust::rel_path::RustRelativePath; 7 8 #[derive(Default, Eq, PartialEq, Debug, Clone)] 9 pub(crate) struct RustPath { 10 pub(crate) absolute: bool, 11 pub(crate) path: RustRelativePath, 12 } 13 14 impl RustPath { super_path() -> RustPath15 pub fn super_path() -> RustPath { 16 RustPath::from("super") 17 } 18 is_absolute(&self) -> bool19 pub fn is_absolute(&self) -> bool { 20 self.absolute 21 } 22 with_ident(self, ident: RustIdent) -> RustIdentWithPath23 pub fn with_ident(self, ident: RustIdent) -> RustIdentWithPath { 24 RustIdentWithPath { path: self, ident } 25 } 26 first(&self) -> Option<RustPathComponent>27 pub fn first(&self) -> Option<RustPathComponent> { 28 assert!(!self.absolute); 29 self.path.first() 30 } 31 remove_first(&mut self) -> Option<RustPathComponent>32 pub fn remove_first(&mut self) -> Option<RustPathComponent> { 33 assert!(!self.absolute); 34 self.path.remove_first() 35 } 36 prepend_ident(&mut self, ident: RustIdent)37 pub fn prepend_ident(&mut self, ident: RustIdent) { 38 assert!(!self.absolute); 39 self.path.prepend_ident(ident); 40 } 41 append(self, path: RustPath) -> RustPath42 pub fn append(self, path: RustPath) -> RustPath { 43 if path.absolute { 44 path 45 } else { 46 RustPath { 47 absolute: self.absolute, 48 path: self.path.append(path.path), 49 } 50 } 51 } 52 append_component(mut self, component: RustPathComponent) -> RustPath53 pub(crate) fn append_component(mut self, component: RustPathComponent) -> RustPath { 54 self.path.path.push(component); 55 self 56 } 57 append_ident(self, ident: RustIdent) -> RustPath58 pub fn append_ident(self, ident: RustIdent) -> RustPath { 59 self.append_component(RustPathComponent::Ident(ident)) 60 } 61 append_with_ident(self, path: RustIdentWithPath) -> RustIdentWithPath62 pub fn append_with_ident(self, path: RustIdentWithPath) -> RustIdentWithPath { 63 self.append(path.path).with_ident(path.ident) 64 } 65 into_relative_or_panic(self) -> RustRelativePath66 pub fn into_relative_or_panic(self) -> RustRelativePath { 67 assert!(!self.absolute); 68 self.path 69 } 70 } 71 72 impl From<&'_ str> for RustPath { from(s: &str) -> Self73 fn from(s: &str) -> Self { 74 let (s, absolute) = if s.starts_with("::") { 75 (&s[2..], true) 76 } else { 77 (s, false) 78 }; 79 RustPath { 80 absolute, 81 path: RustRelativePath::from(s), 82 } 83 } 84 } 85 86 impl From<String> for RustPath { from(s: String) -> Self87 fn from(s: String) -> Self { 88 RustPath::from(&s[..]) 89 } 90 } 91 92 impl fmt::Display for RustPath { fmt(&self, f: &mut fmt::Formatter) -> fmt::Result93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 94 if self.absolute { 95 write!(f, "::")?; 96 } 97 write!(f, "{}", self.path) 98 } 99 } 100