use serde::Serialize;
use serde_json::Value as JsonValue;
use crate::ast::Span;
use crate::error::{Error, Result};
use crate::lexer::{Lexer, TokKind};
#[derive(Debug, Clone, Serialize)]
pub struct TokenInfo {
#[serde(rename = "type")]
pub kind: &'static str,
pub value: JsonValue,
pub span: Span,
}
pub fn tokens(source: &str) -> Result<Vec<TokenInfo>> {
let mut lexer = Lexer::new(source);
let mut out = Vec::new();
let mut infix = false;
while let Some(tok) = lexer.next(infix)? {
let (kind, value, operand) = match tok.kind {
TokKind::Name(n) => ("name", n.into(), true),
TokKind::Variable(v) => ("variable", v.into(), true),
TokKind::Str(s) => ("string", s.into(), true),
TokKind::Number(n) => ("number", n.into(), true),
TokKind::Value(lit) => ("value", serde_json::to_value(lit).unwrap_or_default(), true),
TokKind::Regex { pattern, flags } => {
("regex", format!("/{pattern}/{flags}").into(), true)
}
TokKind::Op(op) => ("operator", op.into(), matches!(op, ")" | "]" | "}")),
};
infix = operand;
out.push(TokenInfo {
kind,
value,
span: tok.span,
});
}
Ok(out)
}
pub fn raw_tree(source: &str, recover: bool) -> Result<(JsonValue, Vec<Error>)> {
let (raw, errors, _warnings) = crate::parser::parse(source, recover);
let raw = raw?;
Ok((serde_json::to_value(&raw).unwrap_or_default(), errors))
}