cairo_lang_syntax/node/
ast_ext.rsuse cairo_lang_utils::require;
use num_bigint::{BigInt, Sign};
use num_traits::Num;
use smol_str::SmolStr;
use unescaper::unescape;
use super::{
TerminalFalse, TerminalLiteralNumber, TerminalShortString, TerminalString, TerminalTrue,
};
use crate::node::db::SyntaxGroup;
use crate::node::Terminal;
impl TerminalTrue {
#[inline(always)]
pub fn boolean_value(&self) -> bool {
true
}
}
impl TerminalFalse {
#[inline(always)]
pub fn boolean_value(&self) -> bool {
false
}
}
impl TerminalLiteralNumber {
pub fn numeric_value(&self, db: &dyn SyntaxGroup) -> Option<BigInt> {
self.numeric_value_and_suffix(db).map(|(value, _suffix)| value)
}
pub fn numeric_value_and_suffix(
&self,
db: &dyn SyntaxGroup,
) -> Option<(BigInt, Option<SmolStr>)> {
let text = self.text(db);
let (text, radix) = if let Some(num_no_prefix) = text.strip_prefix("0x") {
(num_no_prefix, 16)
} else if let Some(num_no_prefix) = text.strip_prefix("0o") {
(num_no_prefix, 8)
} else if let Some(num_no_prefix) = text.strip_prefix("0b") {
(num_no_prefix, 2)
} else {
(text.as_str(), 10)
};
if let Ok(value) = BigInt::from_str_radix(text, radix) {
Some((value, None))
} else {
let (text, suffix) = match text.rsplit_once('_') {
Some((text, suffix)) => {
let suffix = if suffix.is_empty() { None } else { Some(suffix) };
(text, suffix)
}
None => (text, None),
};
Some((BigInt::from_str_radix(text, radix).ok()?, suffix.map(SmolStr::new)))
}
}
}
impl TerminalShortString {
pub fn string_value(&self, db: &dyn SyntaxGroup) -> Option<String> {
let text = self.text(db);
let (text, _suffix) = string_value(&text, '\'')?;
Some(text)
}
pub fn numeric_value(&self, db: &dyn SyntaxGroup) -> Option<BigInt> {
self.string_value(db).map(|string| BigInt::from_bytes_be(Sign::Plus, string.as_bytes()))
}
pub fn suffix(&self, db: &dyn SyntaxGroup) -> Option<SmolStr> {
let text = self.text(db);
let (_literal, mut suffix) = text[1..].rsplit_once('\'')?;
require(!suffix.is_empty())?;
if suffix.starts_with('_') {
suffix = &suffix[1..];
}
Some(suffix.into())
}
}
impl TerminalString {
pub fn string_value(&self, db: &dyn SyntaxGroup) -> Option<String> {
let text = self.text(db);
let (text, suffix) = string_value(&text, '"')?;
if !suffix.is_empty() {
unreachable!();
}
Some(text)
}
}
fn string_value(text: &str, delimiter: char) -> Option<(String, &str)> {
let (prefix, text) = text.split_once(delimiter)?;
if !prefix.is_empty() {
unreachable!();
}
let (text, suffix) = text.rsplit_once(delimiter)?;
let text = unescape(text).ok()?;
require(text.is_ascii())?;
Some((text, suffix))
}