1
0
dust/src/value/function.rs

68 lines
1.8 KiB
Rust
Raw Normal View History

2023-08-22 15:40:50 +00:00
use std::fmt::{self, Display, Formatter};
use serde::{Deserialize, Serialize};
2023-11-27 20:02:08 +00:00
use tree_sitter::Node;
2023-08-22 15:40:50 +00:00
2023-11-30 05:57:15 +00:00
use crate::{AbstractTree, Block, Error, Identifier, Map, Result, TypeDefinition, Value};
2023-08-22 15:40:50 +00:00
2023-09-30 21:52:37 +00:00
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
pub struct Function {
2023-11-30 00:23:42 +00:00
parameters: Vec<Identifier>,
2023-11-27 20:02:08 +00:00
body: Block,
2023-09-30 21:52:37 +00:00
}
2023-08-22 15:40:50 +00:00
impl Function {
2023-11-30 10:40:39 +00:00
pub fn new(parameters: Vec<Identifier>, body: Block) -> Self {
Self { parameters, body }
}
2023-11-30 00:23:42 +00:00
pub fn parameters(&self) -> &Vec<Identifier> {
2023-11-27 20:02:08 +00:00
&self.parameters
2023-08-22 15:40:50 +00:00
}
2023-11-30 00:23:42 +00:00
pub fn body(&self) -> &Block {
&self.body
}
2023-11-27 20:02:08 +00:00
}
2023-10-06 21:11:50 +00:00
2023-11-27 20:02:08 +00:00
impl AbstractTree for Function {
2023-11-30 03:54:46 +00:00
fn from_syntax_node(source: &str, node: Node, context: &Map) -> Result<Self> {
Error::expect_syntax_node(source, "function", node)?;
let child_count = node.child_count();
2023-11-27 20:02:08 +00:00
let mut parameters = Vec::new();
2023-11-30 01:59:58 +00:00
for index in 1..child_count - 2 {
2023-11-30 00:23:42 +00:00
let child = node.child(index).unwrap();
2023-11-27 20:02:08 +00:00
2023-11-30 00:23:42 +00:00
if child.is_named() {
2023-11-30 03:54:46 +00:00
let identifier = Identifier::from_syntax_node(source, child, context)?;
2023-11-30 00:23:42 +00:00
parameters.push(identifier);
}
2023-11-27 20:02:08 +00:00
}
let body_node = node.child(child_count - 1).unwrap();
2023-11-30 03:54:46 +00:00
let body = Block::from_syntax_node(source, body_node, context)?;
2023-11-27 20:02:08 +00:00
2023-11-30 00:23:42 +00:00
Ok(Function { parameters, body })
2023-10-06 21:11:50 +00:00
}
2023-11-30 00:23:42 +00:00
fn run(&self, source: &str, context: &Map) -> Result<Value> {
2023-11-30 10:40:39 +00:00
self.body.run(source, context)
2023-10-06 21:11:50 +00:00
}
2023-11-30 00:23:42 +00:00
2023-11-30 05:57:15 +00:00
fn expected_type(&self, context: &Map) -> Result<TypeDefinition> {
2023-11-30 10:40:39 +00:00
Value::Function(self.clone()).r#type(context)
2023-11-30 00:23:42 +00:00
}
}
2023-08-22 15:40:50 +00:00
impl Display for Function {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
2023-09-30 21:52:37 +00:00
write!(
f,
2023-11-30 00:23:42 +00:00
"Function {{ parameters: {:?}, body: {:?} }}",
self.parameters, self.body
2023-09-30 21:52:37 +00:00
)
2023-08-22 15:40:50 +00:00
}
}