xenon_codegen/
attribute.rs

1use core::fmt;
2use std::fmt::Formatter;
3
4/// An attribute applied to its owner. Usually metadata for the compiler.
5#[derive(Debug, Clone, Default)]
6pub struct Attribute {
7    /// The name of the attribute
8    pub name: String,
9    /// The value, if any
10    pub value: Option<String>,
11}
12impl Attribute {
13    /// Create a new valid attribute
14    pub fn new(name: &str) -> Attribute {
15        Attribute {
16            name: name.to_string(),
17            value: None,
18        }
19    }
20
21    /// Check if the attribute is valid
22    pub fn is_valid(&self) -> bool {
23        // Make sure that all present fields are not empty
24        if self.name.is_empty() {
25            return false;
26        }
27        match self.value.clone() {
28            Some(v) => {
29                if v.is_empty() {
30                    return false;
31                }
32            }
33            None => ()
34        }
35
36        return true;
37    }
38}
39impl std::fmt::Display for Attribute {
40    fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
41        // Print the start of the tag and the name
42        match write!(fmt, "#[{}", self.name) {
43            Ok(_) => (),
44            Err(e) => return Err(e),
45        }
46        // If there's a value, print it in parentheses
47        if self.value.is_some() {
48            match write!(fmt, "({})", self.value.as_ref().unwrap()) {
49                Ok(_) => (),
50                Err(e) => return Err(e),
51            }
52        }
53        // End the tag
54        match writeln!(fmt, "]") {
55            Ok(_) => (),
56            Err(e) => return Err(e),
57        }
58        Ok(())
59    }
60}