2023-10-06 17:32:58 +00:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use tree_sitter::Node;
|
|
|
|
|
2023-12-05 22:08:22 +00:00
|
|
|
use crate::{AbstractTree, Error, Map, Result, Type, Value, BUILT_IN_FUNCTIONS};
|
2023-10-06 17:32:58 +00:00
|
|
|
|
2023-12-06 18:48:38 +00:00
|
|
|
/// A string by which a variable is known to a context.
|
|
|
|
///
|
|
|
|
/// Every variable is a key-value pair. An identifier holds the key part of that
|
|
|
|
/// pair. Its inner value can be used to retrieve a Value instance from a Map.
|
2023-10-06 17:32:58 +00:00
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, PartialOrd, Ord)]
|
|
|
|
pub struct Identifier(String);
|
|
|
|
|
|
|
|
impl Identifier {
|
|
|
|
pub fn new(inner: String) -> Self {
|
|
|
|
Identifier(inner)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn take_inner(self) -> String {
|
|
|
|
self.0
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn inner(&self) -> &String {
|
|
|
|
&self.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AbstractTree for Identifier {
|
2023-11-30 03:54:46 +00:00
|
|
|
fn from_syntax_node(source: &str, node: Node, _context: &Map) -> Result<Self> {
|
2023-11-15 02:24:47 +00:00
|
|
|
Error::expect_syntax_node(source, "identifier", node)?;
|
2023-10-22 18:33:08 +00:00
|
|
|
|
2023-11-30 03:54:46 +00:00
|
|
|
let text = &source[node.byte_range()];
|
2023-10-06 17:32:58 +00:00
|
|
|
|
2023-11-30 03:54:46 +00:00
|
|
|
Ok(Identifier(text.to_string()))
|
2023-10-06 17:32:58 +00:00
|
|
|
}
|
|
|
|
|
2023-11-30 00:23:42 +00:00
|
|
|
fn run(&self, _source: &str, context: &Map) -> Result<Value> {
|
2023-12-09 22:15:41 +00:00
|
|
|
if let Some((value, _)) = context.variables()?.get(&self.0) {
|
2023-10-29 23:31:06 +00:00
|
|
|
Ok(value.clone())
|
2023-10-10 21:12:38 +00:00
|
|
|
} else {
|
2023-10-29 23:31:06 +00:00
|
|
|
Err(Error::VariableIdentifierNotFound(self.inner().clone()))
|
|
|
|
}
|
2023-10-06 17:32:58 +00:00
|
|
|
}
|
2023-11-30 00:23:42 +00:00
|
|
|
|
2023-12-05 22:08:22 +00:00
|
|
|
fn expected_type(&self, context: &Map) -> Result<Type> {
|
2023-12-12 23:21:16 +00:00
|
|
|
if let Some((_value, r#type)) = context.variables()?.get(&self.0) {
|
|
|
|
Ok(r#type.clone())
|
2023-11-30 00:23:42 +00:00
|
|
|
} else {
|
2023-12-02 03:16:50 +00:00
|
|
|
for built_in_function in BUILT_IN_FUNCTIONS {
|
|
|
|
if self.0 == built_in_function.name() {
|
2023-12-15 22:54:11 +00:00
|
|
|
return Ok(built_in_function.r#type());
|
2023-12-02 03:16:50 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-12 23:21:16 +00:00
|
|
|
Ok(Type::Empty)
|
2023-11-30 00:23:42 +00:00
|
|
|
}
|
|
|
|
}
|
2023-10-06 17:32:58 +00:00
|
|
|
}
|