mini_builder_rs/parser/
node.rs

1use crate::tokenizer::token::{Token, TokenType};
2
3use super::expression::Expression;
4
5pub type Nodes<'a> = Vec<Box<Node<'a>>>;
6
7/// The data that the [Node] holds. Different Nodes hold different types of data.
8#[derive(Debug)]
9pub enum NodeContent<'a> {
10	Source(&'a str),
11	Expression(Expression<'a>),
12	Assignment(&'a str, TokenType, Expression<'a>),
13	If(Expression<'a>),
14	For(&'a str, Expression<'a>),
15	Elif(Expression<'a>),
16	Else,
17	End,
18}
19
20/// [Node] contains some data, and the location (in the tokenized text) of the
21/// first token it used.
22#[derive(Debug)]
23pub struct Node<'a> {
24	pub location: usize,
25	pub content: NodeContent<'a>,
26}
27
28impl<'a> Node<'a> {
29	pub fn new(location: usize, content: NodeContent<'a>) -> Self {
30		Self { location, content }
31	}
32
33	pub fn _source(location: usize, source: &'a str) -> Self {
34		Self::new(location, NodeContent::Source(source))
35	}
36
37	pub fn source_from_token(token: &Token<'a>) -> Self {
38		Self::new(token.location, NodeContent::Source(token.content))
39	}
40
41	pub fn expression(location: usize, expression: Expression<'a>) -> Self {
42		Self::new(location, NodeContent::Expression(expression))
43	}
44
45	pub fn assignment(location: usize, name: &'a str, expression: Expression<'a>) -> Self {
46		Self::new(
47			location,
48			NodeContent::Assignment(name, TokenType::Assign, expression),
49		)
50	}
51
52	pub fn if_node(location: usize, expression: Expression<'a>) -> Self {
53		Self::new(location, NodeContent::If(expression))
54	}
55
56	pub fn for_node(location: usize, var_name: &'a str, expression: Expression<'a>) -> Self {
57		Self::new(location, NodeContent::For(var_name, expression))
58	}
59
60	pub fn elif(location: usize, expression: Expression<'a>) -> Self {
61		Self::new(location, NodeContent::Elif(expression))
62	}
63
64	pub fn else_node(location: usize) -> Self {
65		Self::new(location, NodeContent::Else)
66	}
67
68	pub fn end(location: usize) -> Self {
69		Self::new(location, NodeContent::End)
70	}
71}