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