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