use alloc::borrow::ToOwned;
use alloc::string::String;
use crate::syntax::SyntaxNode;
use crate::syntax::{SyntaxGraphArgs, SyntaxGraphError};
use crate::NodeId;
pub fn build_string_literal_node(
args: &mut SyntaxGraphArgs<'_>,
n_id: NodeId,
value: String,
c_ids: &[NodeId],
) -> Result<NodeId, SyntaxGraphError> {
args.syntax_graph.add_node(
n_id,
SyntaxNode::Literal {
value: strip_surrounding_quotes(value),
value_type: "string".to_owned(),
},
);
for c_id in c_ids {
let built = args.generic(*c_id)?;
args.syntax_graph.add_ast_edge(n_id, built);
}
Ok(n_id)
}
fn strip_surrounding_quotes(value: String) -> String {
if value.starts_with(['\'', '"', '`']) {
let mut chars = value.chars();
chars.next();
chars.next_back();
String::from(chars.as_str())
} else {
value
}
}
#[cfg(test)]
mod tests {
use super::strip_surrounding_quotes;
use alloc::borrow::ToOwned;
#[test]
fn strips_first_and_last_char_only_when_quoted() {
assert_eq!(strip_surrounding_quotes("\"doe\"".to_owned()), "doe");
assert_eq!(strip_surrounding_quotes("'doe'".to_owned()), "doe");
assert_eq!(strip_surrounding_quotes("`doe`".to_owned()), "doe");
assert_eq!(strip_surrounding_quotes("doe".to_owned()), "doe");
assert_eq!(strip_surrounding_quotes("\"doe".to_owned()), "do");
}
}