use std::fmt::Write;
use std::sync::Arc;
use crate::grammar::ValueBuilder;
use crate::parse::Recovery;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct KindId(pub u32);
impl KindId {
pub const ERROR: KindId = KindId(0);
pub const MISSING: KindId = KindId(1);
pub const SKIPPED: KindId = KindId(2);
pub const RESERVED: u32 = 3;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FieldId(pub u16);
impl FieldId {
pub const NONE: FieldId = FieldId(0);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FieldCount {
One,
Optional,
Many,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Kind {
pub name: String,
pub display: String,
pub fields: Vec<(FieldId, FieldCount)>,
pub builder: Option<ValueBuilder>,
pub token: bool,
pub made: bool,
}
#[derive(Debug, Default)]
pub struct Names {
pub kinds: Vec<String>,
pub fields: Vec<String>,
}
const TOKEN: u8 = 1;
const HIDDEN: u8 = 2;
pub(crate) const ENTRY_BYTES: u64 =
(size_of::<KindId>() + size_of::<u8>() + 3 * size_of::<u32>() + size_of::<FieldId>()) as u64;
#[derive(Clone, Debug)]
pub struct Tree {
kinds: Vec<KindId>,
flags: Vec<u8>,
starts: Vec<u32>,
ends: Vec<u32>,
sizes: Vec<u32>,
fields: Vec<FieldId>,
names: Arc<Names>,
recoveries: Vec<Recovery>,
}
impl Tree {
pub(crate) fn empty(names: Arc<Names>) -> Tree {
Tree {
kinds: Vec::new(),
flags: Vec::new(),
starts: Vec::new(),
ends: Vec::new(),
sizes: Vec::new(),
fields: Vec::new(),
names,
recoveries: Vec::new(),
}
}
pub(crate) fn set_recoveries(&mut self, recoveries: Vec<Recovery>) {
self.recoveries = recoveries;
}
pub fn recoveries(&self) -> &[Recovery] {
&self.recoveries
}
pub(crate) fn reserve(&mut self, entries: usize) {
self.kinds.reserve(entries);
self.flags.reserve(entries);
self.starts.reserve(entries);
self.ends.reserve(entries);
self.sizes.reserve(entries);
self.fields.reserve(entries);
}
pub(crate) fn push_token(
&mut self,
kind: KindId,
hidden: bool,
start: u32,
end: u32,
field: FieldId,
) {
let flags = TOKEN | if hidden { HIDDEN } else { 0 };
self.append(kind, flags, start, end, 1, field);
}
pub(crate) fn push_node(
&mut self,
kind: KindId,
start: u32,
end: u32,
size: u32,
field: FieldId,
) {
self.append(kind, 0, start, end, size, field);
}
fn append(&mut self, kind: KindId, flags: u8, start: u32, end: u32, size: u32, field: FieldId) {
self.kinds.push(kind);
self.flags.push(flags);
self.starts.push(start);
self.ends.push(end);
self.sizes.push(size);
self.fields.push(field);
}
pub fn len(&self) -> usize {
self.kinds.len()
}
pub fn is_empty(&self) -> bool {
self.kinds.is_empty()
}
pub fn node(&self, index: usize) -> Option<NodeRef<'_>> {
(index < self.len()).then_some(NodeRef { tree: self, index })
}
pub fn roots(&self) -> Vec<NodeRef<'_>> {
self.siblings_in(0, self.len())
}
fn siblings_in(&self, first: usize, end: usize) -> Vec<NodeRef<'_>> {
let mut out = Vec::new();
let mut index = end;
while index > first {
let last = index - 1;
out.push(NodeRef {
tree: self,
index: last,
});
index -= self.sizes[last] as usize;
}
out.reverse();
out
}
pub fn names(&self) -> &Names {
&self.names
}
pub fn to_text(&self, input: &str, spans: bool) -> String {
enum Step<'t> {
Item(NodeRef<'t>, bool),
Close,
}
let mut pending: Vec<Step<'_>> = Vec::new();
for (i, root) in self.roots().into_iter().enumerate().rev() {
pending.push(Step::Item(root, i > 0));
}
let mut out = String::new();
while let Some(step) = pending.pop() {
match step {
Step::Close => out.push(')'),
Step::Item(item, space) => {
if space {
out.push(' ');
}
item.write_head(&mut out, input, spans, true);
if !item.is_token() {
pending.push(Step::Close);
for child in item.children().into_iter().rev() {
pending.push(Step::Item(child, true));
}
}
}
}
}
out
}
}
impl Tree {
pub fn to_lines(&self, input: &str, spans: bool) -> String {
let mut out = String::new();
let mut pending: Vec<(NodeRef<'_>, usize)> = self
.roots()
.into_iter()
.rev()
.map(|root| (root, 0))
.collect();
while let Some((item, depth)) = pending.pop() {
for _ in 0..depth {
out.push_str(" ");
}
item.write_head(&mut out, input, spans, false);
for child in item.children().into_iter().rev() {
pending.push((child, depth + 1));
}
out.push('\n');
}
out
}
}
#[derive(Clone, Copy, Debug)]
pub struct NodeRef<'t> {
tree: &'t Tree,
index: usize,
}
impl<'t> NodeRef<'t> {
pub fn index(&self) -> usize {
self.index
}
pub fn size(&self) -> usize {
self.tree.sizes[self.index] as usize
}
pub fn kind(&self) -> KindId {
self.tree.kinds[self.index]
}
pub fn kind_name(&self) -> &'t str {
self.tree
.names
.kinds
.get(self.kind().0 as usize)
.map_or("", String::as_str)
}
pub fn is_token(&self) -> bool {
self.tree.flags[self.index] & TOKEN != 0
}
pub fn is_hidden(&self) -> bool {
self.tree.flags[self.index] & HIDDEN != 0
}
pub fn span(&self) -> (u32, u32) {
(self.tree.starts[self.index], self.tree.ends[self.index])
}
pub fn field(&self) -> FieldId {
self.tree.fields[self.index]
}
pub fn field_name(&self) -> Option<&'t str> {
match self.field() {
FieldId::NONE => None,
FieldId(id) => self
.tree
.names
.fields
.get(usize::from(id))
.map(String::as_str),
}
}
pub fn children(&self) -> Vec<NodeRef<'t>> {
let size = self.tree.sizes[self.index] as usize;
self.tree.siblings_in(self.index + 1 - size, self.index)
}
pub fn text<'i>(&self, input: &'i str) -> &'i str {
let (start, end) = self.span();
input.get(start as usize..end as usize).unwrap_or("")
}
fn write_head(&self, out: &mut String, input: &str, spans: bool, bracket: bool) {
if let Some(field) = self.field_name() {
out.push_str(field);
out.push('=');
}
if self.is_hidden() {
out.push('~');
}
let (start, end) = self.span();
if self.is_token() {
let name = self.kind_name();
if !name.starts_with(['"', '[', '.', '\\', '%']) {
out.push_str(name);
}
let _ = write!(out, "{:?}", self.text(input));
} else {
if bracket {
out.push('(');
}
out.push_str(self.kind_name());
}
if spans {
let _ = write!(out, "@{start}..{end}");
}
}
}