use std::cell::RefCell;
use std::collections::HashMap;
use indexmap::IndexMap;
use tabnas::{Token, Value};
use crate::state::{handle_node, handle_token, node_handle, token_handle, with_state};
pub const NODE_KEY: &str = "$cnode";
pub const TOKEN_KEY: &str = "$ctoken";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
pub start: usize,
pub end: usize,
pub line: usize,
pub col: usize,
}
impl Span {
pub fn zero() -> Self {
Span {
start: 0,
end: 0,
line: 1,
col: 1,
}
}
pub fn to_value(self) -> Value {
let mut entries = IndexMap::new();
entries.insert("start".to_string(), Value::Number(self.start as f64));
entries.insert("end".to_string(), Value::Number(self.end as f64));
entries.insert("line".to_string(), Value::Number(self.line as f64));
entries.insert("col".to_string(), Value::Number(self.col as f64));
Value::object(entries)
}
}
#[derive(Debug, Clone)]
pub enum Item {
Node(usize),
Token(usize),
Val(Value),
List(Vec<Item>),
}
impl Item {
pub fn str(text: impl Into<String>) -> Self {
Item::Val(Value::String(text.into()))
}
pub fn bool(flag: bool) -> Self {
Item::Val(Value::Bool(flag))
}
pub fn as_node(&self) -> Option<usize> {
match self {
Item::Node(id) => Some(*id),
Item::Val(value) => handle_node(value),
_ => None,
}
}
pub fn as_token(&self) -> Option<usize> {
match self {
Item::Token(id) => Some(*id),
Item::Val(value) => handle_token(value),
_ => None,
}
}
pub fn to_handle(&self) -> Value {
match self {
Item::Node(id) => node_handle(*id),
Item::Token(id) => token_handle(*id),
Item::Val(value) => value.clone(),
Item::List(items) => {
Value::array(items.iter().map(Item::to_handle).collect::<Vec<_>>())
}
}
}
pub fn from_value(value: &Value) -> Self {
if let Some(id) = handle_node(value) {
return Item::Node(id);
}
if let Some(id) = handle_token(value) {
return Item::Token(id);
}
Item::Val(value.clone())
}
}
#[derive(Debug, Clone)]
pub struct NodeData {
pub kind: String,
pub span: Span,
pub children: Vec<Item>,
pub leading: Vec<Item>,
pub trailing: Vec<Item>,
pub extras: IndexMap<String, Item>,
}
#[derive(Debug, Clone)]
pub struct TokenData {
pub name: String,
pub src: String,
pub span: Span,
pub leading: Vec<usize>,
}
pub fn token_span(token: &Token) -> Span {
Span {
start: token.site.pos,
end: token.site.pos + token.src.as_str().chars().count(),
line: token.site.ri,
col: token.site.ci,
}
}
pub fn no_token() -> usize {
with_state(|state| {
if let Some(id) = state.no_token {
return id;
}
state.tokens.push(TokenData {
name: String::new(),
src: String::new(),
span: Span {
start: 0,
end: 0,
line: 1,
col: 1,
},
leading: Vec::new(),
});
let id = state.tokens.len() - 1;
state.no_token = Some(id);
id
})
}
pub fn intern_token(token: &Token) -> usize {
let leading = leading_ids(token);
with_state(|state| {
state.tokens.push(TokenData {
name: token.name.as_str().to_string(),
src: token.src.as_str().to_string(),
span: token_span(token),
leading,
});
state.tokens.len() - 1
})
}
fn leading_ids(token: &Token) -> Vec<usize> {
let Some(use_data) = token.use_data.as_ref() else {
return Vec::new();
};
let Some(Value::Array(items)) = use_data.get("leading") else {
return Vec::new();
};
items.iter().filter_map(handle_token).collect()
}
pub fn new_node(kind: &str, span: Option<Span>) -> usize {
with_state(|state| {
state.nodes.push(NodeData {
kind: kind.to_string(),
span: span.unwrap_or_else(Span::zero),
children: Vec::new(),
leading: Vec::new(),
trailing: Vec::new(),
extras: IndexMap::new(),
});
state.nodes.len() - 1
})
}
pub fn kind_of(node: usize) -> String {
with_state(|state| {
state
.nodes
.get(node)
.map(|data| data.kind.clone())
.unwrap_or_default()
})
}
pub fn set_kind(node: usize, kind: &str) {
with_state(|state| {
if let Some(data) = state.nodes.get_mut(node) {
data.kind = kind.to_string();
}
});
}
pub fn span_of(node: usize) -> Span {
with_state(|state| {
state
.nodes
.get(node)
.map(|data| data.span)
.unwrap_or_else(Span::zero)
})
}
pub fn set_span(node: usize, span: Span) {
with_state(|state| {
if let Some(data) = state.nodes.get_mut(node) {
data.span = span;
}
});
}
pub fn push_child(node: usize, item: Item) {
with_state(|state| {
if let Some(data) = state.nodes.get_mut(node) {
data.children.push(item);
}
});
}
pub fn set_children(node: usize, items: Vec<Item>) {
with_state(|state| {
if let Some(data) = state.nodes.get_mut(node) {
data.children = items;
}
});
}
pub fn children_of(node: usize) -> Vec<Item> {
with_state(|state| {
state
.nodes
.get(node)
.map(|data| data.children.clone())
.unwrap_or_default()
})
}
pub fn child_count(node: usize) -> usize {
with_state(|state| {
state
.nodes
.get(node)
.map(|data| data.children.len())
.unwrap_or_default()
})
}
pub fn set_extra(node: usize, key: &str, item: Item) {
with_state(|state| {
if let Some(data) = state.nodes.get_mut(node) {
data.extras.insert(key.to_string(), item);
}
});
}
pub fn extra_of(node: usize, key: &str) -> Option<Item> {
with_state(|state| {
state
.nodes
.get(node)
.and_then(|data| data.extras.get(key).cloned())
})
}
pub fn has_extra(node: usize, key: &str) -> bool {
with_state(|state| {
state
.nodes
.get(node)
.is_some_and(|data| data.extras.contains_key(key))
})
}
pub fn token_src(token: usize) -> String {
with_state(|state| {
state
.tokens
.get(token)
.map(|data| data.src.clone())
.unwrap_or_default()
})
}
pub fn token_name(token: usize) -> String {
with_state(|state| {
state
.tokens
.get(token)
.map(|data| data.name.clone())
.unwrap_or_default()
})
}
pub fn token_data(token: usize) -> Option<TokenData> {
with_state(|state| state.tokens.get(token).cloned())
}
pub fn leading_trivia_items(token: usize) -> Vec<Item> {
with_state(|state| {
state
.tokens
.get(token)
.map(|data| data.leading.iter().map(|id| Item::Token(*id)).collect())
.unwrap_or_default()
})
}
pub fn push_token_with_trivia(node: usize, token: usize) {
for item in leading_trivia_items(token) {
push_child(node, item);
}
push_child(node, Item::Token(token));
}
pub const REALIZE_DEPTH_CAP: usize = 256;
thread_local! {
static REALIZE_TRUNCATED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static REALIZED: RefCell<HashMap<usize, Value>> = RefCell::new(HashMap::new());
}
pub fn realize_truncated() -> bool {
REALIZE_TRUNCATED.with(|cell| cell.get())
}
pub fn realize(value: &Value) -> Value {
REALIZE_TRUNCATED.with(|cell| cell.set(false));
REALIZED.with(|memo| memo.borrow_mut().clear());
let out = realize_at(value, 0);
REALIZED.with(|memo| memo.borrow_mut().clear());
out
}
fn past_the_cap(depth: usize) -> bool {
REALIZE_TRUNCATED.with(|cell| {
if !cell.get() && depth >= REALIZE_DEPTH_CAP {
cell.set(true);
}
cell.get()
})
}
fn realize_at(value: &Value, depth: usize) -> Value {
if past_the_cap(depth) {
return Value::Null;
}
if let Some(node) = handle_node(value) {
return realize_node(node, depth);
}
if let Some(token) = handle_token(value) {
return realize_token(token);
}
match value {
Value::Array(items) => Value::array(
items
.iter()
.map(|item| realize_at(item, depth + 1))
.collect::<Vec<_>>(),
),
Value::ListRef(list) => Value::array(
list.value
.iter()
.map(|item| realize_at(item, depth + 1))
.collect::<Vec<_>>(),
),
Value::Object(entries) => Value::object(
entries
.iter()
.map(|(key, entry)| (key.clone(), realize_at(entry, depth + 1)))
.collect::<IndexMap<_, _>>(),
),
Value::MapRef(map) => Value::object(
map.value
.iter()
.map(|(key, entry)| (key.clone(), realize_at(entry, depth + 1)))
.collect::<IndexMap<_, _>>(),
),
other => other.clone(),
}
}
fn realize_item(item: &Item, depth: usize) -> Value {
if past_the_cap(depth) {
return Value::Null;
}
match item {
Item::Node(id) => realize_node(*id, depth),
Item::Token(id) => realize_token(*id),
Item::Val(value) => realize_at(value, depth),
Item::List(items) => Value::array(
items
.iter()
.map(|item| realize_item(item, depth + 1))
.collect::<Vec<_>>(),
),
}
}
fn realize_token(token: usize) -> Value {
let Some(data) = token_data(token) else {
return Value::Null;
};
let mut entries = IndexMap::new();
entries.insert("kind".to_string(), Value::String("token".to_string()));
entries.insert("tname".to_string(), Value::String(data.name));
entries.insert("src".to_string(), Value::String(data.src));
entries.insert("span".to_string(), data.span.to_value());
Value::object(entries)
}
fn realize_node(node: usize, depth: usize) -> Value {
if past_the_cap(depth) {
return Value::Null;
}
if let Some(done) = REALIZED.with(|memo| memo.borrow().get(&node).cloned()) {
return done;
}
let Some(data) = with_state(|state| state.nodes.get(node).cloned()) else {
return Value::Null;
};
let mut entries = IndexMap::new();
entries.insert("kind".to_string(), Value::String(data.kind));
entries.insert("span".to_string(), data.span.to_value());
entries.insert(
"children".to_string(),
Value::array(
data.children
.iter()
.map(|item| realize_item(item, depth + 1))
.collect::<Vec<_>>(),
),
);
let mut trivia = IndexMap::new();
trivia.insert(
"leading".to_string(),
Value::array(
data.leading
.iter()
.map(|item| realize_item(item, depth + 1))
.collect::<Vec<_>>(),
),
);
trivia.insert(
"trailing".to_string(),
Value::array(
data.trailing
.iter()
.map(|item| realize_item(item, depth + 1))
.collect::<Vec<_>>(),
),
);
entries.insert("trivia".to_string(), Value::object(trivia));
for (key, item) in data.extras.iter() {
entries.insert(key.clone(), realize_item(item, depth + 1));
}
let out = Value::object(entries);
if !REALIZE_TRUNCATED.with(|cell| cell.get()) {
REALIZED.with(|memo| memo.borrow_mut().insert(node, out.clone()));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn first_cycle() -> Option<(usize, Vec<usize>)> {
fn children_of(node: usize) -> Vec<usize> {
with_state(|state| {
let Some(data) = state.nodes.get(node) else {
return Vec::new();
};
let mut out = Vec::new();
let mut push = |item: &Item| {
let mut stack = vec![item.clone()];
while let Some(item) = stack.pop() {
match item {
Item::Node(id) => out.push(id),
Item::List(items) => stack.extend(items),
_ => {}
}
}
};
for item in data
.children
.iter()
.chain(data.leading.iter())
.chain(data.trailing.iter())
.chain(data.extras.values())
{
push(item);
}
out
})
}
let count = with_state(|state| state.nodes.len());
for root in 0..count {
let mut stack = vec![(root, vec![root])];
let mut seen = std::collections::HashSet::new();
while let Some((node, path)) = stack.pop() {
for child in children_of(node) {
if path.contains(&child) {
let mut loop_path = path.clone();
loop_path.push(child);
return Some((child, loop_path));
}
if seen.insert(child) {
let mut next = path.clone();
next.push(child);
stack.push((child, next));
}
}
}
}
None
}
#[test]
fn no_ordinary_source_builds_a_node_that_holds_itself() {
let parser = crate::make_with(&crate::COptions::new().with_extended(true));
for source in [
"int g = (int)0;",
"int *p = (int[2]){1,2};",
"int g = (int)0 + 1;",
"void f(void) { int y = (int)x + 1; }",
"int g = sizeof(int);",
"int g[2] = {1,2};",
"int g[2][2] = {{1,2},{3,4}};",
"struct S { int x; }; struct S s = { .x = 1 };",
"int g = _Generic(x, int: 1, default: 0);",
"int g = ({ 1; });",
"const char *s = \"a\" \"b\";",
"void f(void) { for (int i = 0; i < 2; i++) { g(i); } }",
"typedef int T; T f(T a) { return a; }",
"#define M(a) (a)\nint g = M(1);",
"void f(void) { switch (x) { case 1: break; default: break; } }",
"int f(int (*p)(void)) { return p(); }",
"enum E { A = 1, B };",
"union U { int a; char b; };",
"static const volatile int *const p = 0;",
"void f(void) { while (x) { y = a ? b : c; } }",
] {
let _ = crate::parse_with(&parser, source);
assert_eq!(
first_cycle(),
None,
"{source:?} built a node that is its own descendant"
);
}
}
}