use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use techy::core::node::{BodySlotExt, NodeId, NodeKind, NodeRef, NodeTree};
use techy::latexlike::MathGroupForm;
use techy::serialize::SerialValue;
use techy::source::LineIndexCache;
use crate::model::addr::{NodeAddr, TreeId};
use crate::model::doc::DocContent;
use crate::core::run::Run;
use crate::core::data::table::{ProjectCx, Table};
use crate::lang::ext::{PresPayload, TextSourceMap};
use crate::lang::flm::{Flm, FlmCallableType, FlmGroupType};
use crate::lang::origin::{FlmDiagnostic, FlmOrigin, FlmSpan};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProjectOptions {
pub spans: bool,
pub payloads: bool,
pub source_maps: bool,
}
impl Default for ProjectOptions {
fn default() -> ProjectOptions {
ProjectOptions { spans: false, payloads: true, source_maps: false }
}
}
impl ProjectOptions {
pub fn new() -> ProjectOptions {
ProjectOptions::default()
}
pub fn with_spans(mut self) -> ProjectOptions {
self.spans = true;
self
}
pub fn without_payloads(mut self) -> ProjectOptions {
self.payloads = false;
self
}
pub fn with_source_maps(mut self) -> ProjectOptions {
self.source_maps = true;
self
}
}
fn text(value: impl Into<String>) -> SerialValue {
SerialValue::Str(value.into())
}
fn has_source_name(form: FlmCallableType) -> bool {
match form {
FlmCallableType::Macro | FlmCallableType::Environment => true,
FlmCallableType::Specials
| FlmCallableType::Placeholder
| FlmCallableType::Presentation => false,
}
}
fn map(entries: Vec<(&str, SerialValue)>) -> SerialValue {
SerialValue::Map(entries.into_iter().map(|(key, value)| (String::from(key), value)).collect())
}
pub struct Projector {
options: ProjectOptions,
lines: Mutex<LineIndexCache<FlmOrigin>>,
}
impl Projector {
pub fn new(options: ProjectOptions) -> Projector {
Projector { options, lines: Mutex::new(LineIndexCache::new()) }
}
pub fn options(&self) -> &ProjectOptions {
&self.options
}
pub fn tree(&self, tree: &NodeTree<Flm>) -> SerialValue {
let root = tree.root();
if root.is_list() {
self.nodes(root.children().iter())
} else {
SerialValue::List(vec![self.node(&root)])
}
}
pub fn nodes<'t>(&self, nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>) -> SerialValue {
SerialValue::List(nodes.into_iter().map(|node| self.node(&node)).collect())
}
pub fn node(&self, node: &NodeRef<'_, Flm>) -> SerialValue {
let mut entries: Vec<(&str, SerialValue)> = Vec::new();
match node.kind() {
NodeKind::Chars { content } => {
entries.push(("chars", text(content.resolve(node.span().source()))));
if self.options.source_maps {
if let Some(source_map) = &node.ext().source_map {
entries.push(("map", self.source_map(source_map)));
}
}
}
NodeKind::Comment(comment) => {
entries.push(("kind", text("comment")));
entries.push(("text", text(comment.content.resolve(node.span().source()))));
}
NodeKind::List => {
entries.push(("kind", text("list")));
entries.push(("children", self.nodes(node.children().iter())));
}
NodeKind::Group(group) => {
entries.push(("elem", text(node.ext().element.name.as_str())));
if let Some(FlmGroupType::Math(form)) = group.group_type {
let form = match form {
MathGroupForm::Inline => "inline",
MathGroupForm::Display => "display",
};
entries.push(("form", text(form)));
}
entries.push(("children", self.nodes(node.children().iter())));
}
NodeKind::Callable(data) => {
entries.push(("elem", text(node.ext().element.name.as_str())));
if has_source_name(data.callable_type) {
entries.push(("name", text(&*data.name)));
}
let mut args: Vec<(String, SerialValue)> = Vec::new();
for (index, argument) in data.arguments.iter().enumerate() {
if let Some(content) = node.argument_content_nodes(index) {
let key = argument.name().map_or_else(|| index.to_string(), String::from);
args.push((key, self.nodes(content.iter())));
}
}
if !args.is_empty() {
entries.push(("args", SerialValue::Map(args)));
}
let mut body: Option<SerialValue> = None;
let mut slots: Vec<(String, SerialValue)> = Vec::new();
for (index, slot) in data.slots.iter().enumerate() {
let Some(content) = node.slot_content_nodes(index) else {
continue;
};
let projection = self.nodes(content.iter());
if body.is_none() && slot.ext.is_body() {
body = Some(projection);
} else {
let key = slot.name().map_or_else(|| index.to_string(), String::from);
slots.push((key, projection));
}
}
if let Some(body) = body {
entries.push(("body", body));
}
if !slots.is_empty() {
entries.push(("slots", SerialValue::Map(slots)));
}
if self.options.payloads {
if let Some(payload) = &node.ext().payload {
entries.push(("payload", payload.project()));
}
}
}
}
if self.options.spans {
entries.push(("span", text(self.span(node.span()))));
}
map(entries)
}
pub fn source_map(&self, source_map: &TextSourceMap) -> SerialValue {
SerialValue::List(
source_map
.pieces()
.iter()
.map(|piece| {
map(vec![
("len", SerialValue::Int(i64::from(piece.out_len))),
("span", text(self.span(&piece.span))),
])
})
.collect(),
)
}
pub fn node_ref(&self, tree: &NodeTree<Flm>, node: NodeId) -> SerialValue {
match tree.get(node) {
Some(node) => {
text(format!("{}@{}", node.ext().element.name.as_str(), self.position(node.span())))
}
None => text(format!("?@{}", node.index())),
}
}
pub fn tree_ref(&self, tree: TreeId) -> SerialValue {
text(tree.to_string())
}
pub fn diagnostic(&self, diagnostic: &FlmDiagnostic) -> SerialValue {
let mut entries: Vec<(&str, SerialValue)> = vec![
("id", text(diagnostic.identifier())),
("severity", text(diagnostic.severity().to_string())),
("span", text(self.span(diagnostic.span()))),
];
if let Some(path) = diagnostic.span().source().origin().canonical_path() {
entries.push(("file", text(path)));
}
entries.push(("data", SerialValue::from(diagnostic.data().serializable_data())));
map(entries)
}
pub fn diagnostics<'a>(
&self,
diagnostics: impl IntoIterator<Item = &'a FlmDiagnostic>,
) -> SerialValue {
SerialValue::List(
diagnostics.into_iter().map(|diagnostic| self.diagnostic(diagnostic)).collect(),
)
}
pub fn span(&self, span: &FlmSpan) -> String {
let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
match lines.line_col_span(span.source(), span.range()) {
Some(((line, col), (end_line, end_col))) => {
if span.is_empty() {
format!("{line}:{col}")
} else {
format!("{line}:{col}-{end_line}:{end_col}")
}
}
None if span.is_empty() => format!("@{}", span.start()),
None => format!("@{}-{}", span.start(), span.end()),
}
}
pub fn position(&self, span: &FlmSpan) -> String {
let mut lines = self.lines.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
match lines.line_col(span.source(), span.start()) {
Some((line, col)) => format!("{line}:{col}"),
None => format!("b{}", span.start()),
}
}
}
impl std::fmt::Debug for Projector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Projector").field("options", &self.options).finish_non_exhaustive()
}
}
pub fn project_tree(tree: &NodeTree<Flm>, options: &ProjectOptions) -> SerialValue {
Projector::new(*options).tree(tree)
}
pub fn project_node(node: &NodeRef<'_, Flm>, options: &ProjectOptions) -> SerialValue {
Projector::new(*options).node(node)
}
pub fn project_nodes<'t>(
nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>,
options: &ProjectOptions,
) -> SerialValue {
Projector::new(*options).nodes(nodes)
}
pub fn project_diagnostic(diagnostic: &FlmDiagnostic, options: &ProjectOptions) -> SerialValue {
Projector::new(*options).diagnostic(diagnostic)
}
pub fn project_diagnostics<'a>(
diagnostics: impl IntoIterator<Item = &'a FlmDiagnostic>,
options: &ProjectOptions,
) -> SerialValue {
Projector::new(*options).diagnostics(diagnostics)
}
pub trait TreeSource {
fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>>;
}
impl TreeSource for DocContent {
fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>> {
self.tree(id).map(|tree| &**tree)
}
}
impl TreeSource for Run {
fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>> {
self.frozen_tree(id).map(|tree| &**tree)
}
}
impl TreeSource for BTreeMap<TreeId, Arc<NodeTree<Flm>>> {
fn tree_of(&self, id: TreeId) -> Option<&NodeTree<Flm>> {
self.get(&id).map(|tree| &**tree)
}
}
pub struct TableProjection<'a> {
projector: &'a Projector,
trees: &'a dyn TreeSource,
}
impl ProjectCx for TableProjection<'_> {
fn node_ref(&self, addr: NodeAddr) -> SerialValue {
match self.trees.tree_of(addr.tree) {
Some(tree) => self.projector.node_ref(tree, addr.node),
None => text(format!("?@{}/{}", addr.tree, addr.node.index())),
}
}
fn tree_ref(&self, id: TreeId) -> SerialValue {
self.projector.tree_ref(id)
}
fn tree(&self, tree: &NodeTree<Flm>) -> SerialValue {
self.projector.tree(tree)
}
}
impl Projector {
pub fn table_projection<'a>(&'a self, trees: &'a dyn TreeSource) -> TableProjection<'a> {
TableProjection { projector: self, trees }
}
pub fn table<T: Table>(&self, name: &str, table: &T, trees: &dyn TreeSource) -> SerialValue {
project_table(name, table.project(&self.table_projection(trees)))
}
}
pub fn project_table(name: &str, projection: SerialValue) -> SerialValue {
map(vec![(name, projection)])
}
pub fn node_ref_value(tree: &NodeTree<Flm>, node: NodeId, options: &ProjectOptions) -> SerialValue {
Projector::new(*options).node_ref(tree, node)
}
pub fn tree_ref_value(tree: TreeId) -> SerialValue {
text(tree.to_string())
}
pub fn project_payload(payload: &dyn PresPayload) -> SerialValue {
payload.project()
}