pipeline_script/ast/expr/
mod.rs

1mod function_call;
2
3use crate::ast::data::Data;
4use crate::ast::declaration::VariableDeclaration;
5pub use crate::ast::expr::function_call::FunctionCall;
6use crate::ast::r#type::Type;
7use crate::ast::stmt::StmtNode;
8use crate::ast::NodeTrait;
9use crate::lexer::position::Position;
10use std::any::Any;
11use std::collections::HashMap;
12use std::fmt::{Display, Formatter};
13
14#[derive(Debug, Clone)]
15pub struct ExprNode {
16    pub(crate) expr: Expr,
17    pos: Position,
18    ty: Option<Type>,
19}
20
21impl NodeTrait for ExprNode {
22    fn get_id(&self) -> &str {
23        match self.expr {
24            Expr::String(_) => "Expr:String",
25            Expr::Int(_) => "Expr:Int",
26            Expr::Float(_) => "Expr:Float",
27            Expr::Boolean(_) => "Expr:Boolean",
28            Expr::Brace(_) => "Expr:Brace",
29            Expr::FnCall(_) => "Expr:FnCall",
30            Expr::Variable(_) => "Expr:Variable",
31            Expr::Binary(_, _, _) => "Expr:Binary",
32            Expr::Unary(_, _) => "Expr:Unary",
33            Expr::Array(_) => "Expr:Array",
34            Expr::Map(_) => "Expr:Map",
35            Expr::Index(_, _) => "Expr:Index",
36            Expr::Address(_) => "Expr:Address",
37            Expr::Closure { .. } => "Expr:Closure",
38            Expr::Struct(_) => "Expr:Struct",
39            Expr::Member(_, _) => "Expr:Member",
40            Expr::EnumVariant(_, _, _) => "Expr:EnumVariant",
41            Expr::None => "Expr:None",
42        }
43    }
44
45    fn get_data(&self, key: &str) -> Option<Data> {
46        match &self.expr {
47            Expr::Variable(name) => {
48                if key == "name" {
49                    return Some(Data::String(name.clone()));
50                }
51            }
52            Expr::FnCall(call) => {
53                if key == "name" {
54                    return Some(Data::String(call.name.clone()));
55                }
56            }
57            _ => todo!(),
58        }
59        None
60    }
61
62    fn set_data(&mut self, key: &str, value: Data) {
63        match &mut self.expr {
64            Expr::Variable(name) => {
65                if key == "name" {
66                    *name = value.as_str().unwrap().to_string()
67                }
68            }
69            Expr::FnCall(call) => {
70                if key == "name" {
71                    call.name = value.as_str().unwrap().to_string()
72                }
73            }
74            _ => todo!(),
75        }
76    }
77
78    fn get_children(&self) -> Vec<&dyn NodeTrait> {
79        todo!()
80    }
81
82    fn get_mut_children(&mut self) -> Vec<&mut dyn NodeTrait> {
83        match &mut self.expr {
84            Expr::String(_) => vec![],
85            Expr::Int(_) => vec![],
86            Expr::Float(_) => vec![],
87            Expr::Boolean(_) => vec![],
88            Expr::Brace(expr) => vec![&mut **expr],
89            Expr::FnCall(call) => {
90                let mut children: Vec<&mut dyn NodeTrait> = vec![];
91                for arg in call.args.iter_mut() {
92                    children.push(&mut arg.value)
93                }
94                children
95            }
96            Expr::Variable(_) => vec![],
97            Expr::Binary(_, left, right) => vec![&mut **left, &mut **right],
98            Expr::Unary(_, expr) => vec![&mut **expr],
99            Expr::Array(exprs) => {
100                let mut children: Vec<&mut dyn NodeTrait> = vec![];
101                for expr in exprs.iter_mut() {
102                    children.push(expr)
103                }
104                children
105            }
106            Expr::Map(exprs) => {
107                let mut children = vec![];
108                for (k, v) in exprs.iter_mut() {
109                    children.push(k as &mut dyn NodeTrait);
110                    children.push(v)
111                }
112                children
113            }
114            Expr::Index(left, right) => vec![&mut **left, &mut **right],
115            Expr::Address(expr) => vec![&mut **expr as &mut dyn NodeTrait],
116            Expr::Closure { args, body, .. } => {
117                let mut children: Vec<&mut dyn NodeTrait> = vec![];
118                for arg in args.iter_mut() {
119                    if let Some(expr) = &mut arg.default {
120                        children.push(expr as &mut dyn NodeTrait);
121                    }
122                }
123                for stmt in body.iter_mut() {
124                    children.push(stmt as &mut dyn NodeTrait)
125                }
126                children
127            }
128            Expr::Struct(_) => vec![],
129            Expr::Member(_, _) => vec![],
130            Expr::EnumVariant(_, _, value) => {
131                if let Some(expr) = value {
132                    vec![&mut **expr]
133                } else {
134                    vec![]
135                }
136            }
137            Expr::None => vec![],
138        }
139    }
140
141    fn get_extra(&self) -> &HashMap<String, Box<dyn Any>> {
142        todo!()
143    }
144}
145impl ExprNode {
146    #[allow(unused)]
147    pub(crate) fn get_closure_body(&self) -> Vec<StmtNode> {
148        match &self.expr {
149            Expr::Closure { body, .. } => body.clone(),
150            _ => panic!("not closure expr"),
151        }
152    }
153    pub fn is_fn_call(&self) -> bool {
154        matches!(&self.expr, Expr::FnCall(_))
155    }
156    pub fn get_closure_params(&self) -> Vec<VariableDeclaration> {
157        match &self.expr {
158            Expr::Closure { args, .. } => args.clone(),
159            _ => panic!("not closure expr"),
160        }
161    }
162    pub fn get_variable_name(&self) -> Option<String> {
163        match &self.expr {
164            Expr::Variable(name) => Some(name.clone()),
165            _ => None,
166        }
167    }
168    pub fn get_closure_captures(&self) -> Vec<(String, Type)> {
169        match &self.expr {
170            Expr::Closure { captures, .. } => captures.clone(),
171            _ => panic!("not closure expr"),
172        }
173    }
174    pub fn get_expr_mut(&mut self) -> &mut Expr {
175        &mut self.expr
176    }
177    pub fn get_member_root(&self) -> ExprNode {
178        match &self.expr {
179            Expr::Member(expr, _) => expr.as_ref().clone(),
180            _ => panic!("Not a member expression"),
181        }
182    }
183    pub fn is_member(&self) -> bool {
184        matches!(&self.expr, Expr::Member(_, _))
185    }
186}
187
188#[derive(Debug, Clone)]
189pub enum Expr {
190    String(String),
191    Int(i64),
192    Float(f32),
193    Boolean(bool),
194    Brace(Box<ExprNode>),
195    FnCall(FunctionCall),
196    Variable(String),
197    Binary(Op, Box<ExprNode>, Box<ExprNode>),
198    Unary(Op, Box<ExprNode>),
199    Array(Vec<ExprNode>),
200    Map(Vec<(ExprNode, ExprNode)>),
201    Index(Box<ExprNode>, Box<ExprNode>),
202    Address(Box<ExprNode>),
203    Closure {
204        args: Vec<VariableDeclaration>,
205        body: Vec<StmtNode>,
206        captures: Vec<(String, Type)>,
207        return_type: Option<Type>,
208    },
209    Struct(StructExpr),
210    Member(Box<ExprNode>, String),
211    EnumVariant(String, String, Option<Box<ExprNode>>),
212    None,
213}
214#[derive(Debug, Clone)]
215pub struct StructExpr {
216    pub(crate) name: String,
217    pub(crate) props: HashMap<String, ExprNode>,
218    generics: Vec<Type>,
219}
220
221impl StructExpr {
222    pub fn new(name: String, props: HashMap<String, ExprNode>) -> Self {
223        Self {
224            name,
225            props,
226            generics: vec![],
227        }
228    }
229    pub fn get_name(&self) -> &str {
230        &self.name
231    }
232    pub fn get_props(&self) -> &HashMap<String, ExprNode> {
233        &self.props
234    }
235    pub fn has_generic(&self) -> bool {
236        !self.generics.is_empty()
237    }
238    pub fn get_generics(&self) -> &Vec<Type> {
239        &self.generics
240    }
241    pub fn with_generics(mut self, generics: Vec<Type>) -> Self {
242        self.generics = generics;
243        self
244    }
245}
246#[derive(Debug, Clone)]
247pub enum Op {
248    Plus,
249    Minus,
250    Mul,
251    Div,
252    Mod,
253    Greater,
254    Less,
255    GreaterEqual,
256    LessEqual,
257    Equal,
258    NotEqual,
259    Negate,
260    // 取反
261    Not,
262    And,
263    Or,
264}
265impl Display for Op {
266    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
267        match self {
268            Op::Plus => write!(f, "+"),
269            Op::Minus => write!(f, "-"),
270            Op::Mul => write!(f, "*"),
271            Op::Div => write!(f, "/"),
272            Op::Mod => write!(f, "%"),
273            Op::Greater => write!(f, ">"),
274            Op::Less => write!(f, "<"),
275            Op::Equal => write!(f, "=="),
276            Op::NotEqual => write!(f, "!="),
277            Op::Negate => write!(f, "!"),
278            Op::And => write!(f, "&&"),
279            Op::Or => write!(f, "||"),
280            Op::GreaterEqual => write!(f, ">="),
281            Op::LessEqual => write!(f, "<="),
282            Op::Not => write!(f, "!"),
283        }
284    }
285}
286
287#[derive(Debug, Clone)]
288pub struct Argument {
289    name: Option<String>,
290    pub value: ExprNode,
291}
292impl Argument {
293    pub fn new(expr: ExprNode) -> Self {
294        Self {
295            name: None,
296            value: expr,
297        }
298    }
299    pub fn with_name(name: impl Into<String>, expr: ExprNode) -> Self {
300        Self {
301            name: Some(name.into()),
302            value: expr,
303        }
304    }
305    pub fn has_name(&self) -> bool {
306        self.name.is_some()
307    }
308    pub fn get_name(&self) -> Option<&str> {
309        match &self.name {
310            None => None,
311            Some(s) => Some(s),
312        }
313    }
314}
315impl ExprNode {
316    pub fn new(expr: Expr) -> Self {
317        Self {
318            expr,
319            pos: Position::none(),
320            ty: None,
321        }
322    }
323    pub fn is_closure(&self) -> bool {
324        matches!(&self.expr, Expr::Closure { .. })
325    }
326    pub fn with_position(mut self, pos: Position) -> Self {
327        self.pos = pos;
328        self
329    }
330    pub fn with_type(mut self, ty: Type) -> Self {
331        self.ty = Some(ty);
332        self
333    }
334    pub fn position(&self) -> Position {
335        self.pos.clone()
336    }
337    pub fn get_expr(&self) -> &Expr {
338        &self.expr
339    }
340    pub fn get_type(&self) -> Option<Type> {
341        self.ty.clone()
342    }
343    pub fn get_deep_type(&self) -> Option<Type> {
344        if let Some(Type::Ref(ty)) = &self.ty {
345            return Some(*ty.clone());
346        }
347        if let Some(Type::GenericInstance { instance, .. }) = &self.ty {
348            return Some(*instance.clone());
349        }
350        self.ty.clone()
351    }
352    pub fn get_member_name(&self) -> String {
353        match &self.expr {
354            Expr::Member(_, name) => name.clone(),
355            _ => panic!("not member expr"),
356        }
357    }
358}
359
360impl From<Expr> for ExprNode {
361    fn from(value: Expr) -> Self {
362        ExprNode {
363            expr: value,
364            pos: Position::none(),
365            ty: None,
366        }
367    }
368}