xenon_codegen/
variable_definition.rs1use core::fmt;
2
3use crate::{Visibility, expression::Expression, r#type::Type};
4
5#[derive(Debug, Clone)]
6pub struct VariableDefinition {
7 pub visibility: Visibility,
8 pub name: String,
9 pub ty: Option<Type>,
10 pub value: Option<Expression>,
11}
12impl VariableDefinition {
13 pub fn new(name: String) -> VariableDefinition {
14 VariableDefinition {
15 visibility: Visibility::Private,
16 name,
17 ty: None,
18 value: None,
19 }
20 }
21
22 pub fn is_valid(&self) -> bool {
23 if self.name.is_empty() {
24 return false;
25 }
26 if let Some(t) = self.ty.clone() {
27 if !t.is_valid() {
28 return false;
29 }
30 }
31 if let Some(v) = self.value.clone() {
32 if !v.is_valid() {
33 return false;
34 }
35 }
36
37 true
38 }
39}
40impl fmt::Display for VariableDefinition {
41 fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42 match write!(fmt, "let {}", self.name) {
43 Ok(_) => (),
44 Err(e) => return Err(e),
45 }
46 if let Some(t) = self.ty.clone() {
47 match write!(fmt, ": {}", t) {
48 Ok(_) => (),
49 Err(e) => return Err(e),
50 }
51 }
52 if let Some(v) = self.value.clone() {
53 match write!(fmt, " = {}", v) {
54 Ok(_) => (),
55 Err(e) => return Err(e),
56 }
57 }
58
59 Ok(())
60 }
61}