use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;
use serde_json::{Map, Value};
use crate::js::num;
pub const TREE_FORMAT: &str = "instruction/1";
pub type Object = Map<String, Value>;
pub type Attrs = Object;
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct KeyOrder(pub(crate) HashMap<String, Vec<String>>);
impl KeyOrder {
pub(crate) fn keys(&self, path: &str, m: &Object) -> Vec<String> {
let mut out: Vec<String> = Vec::with_capacity(m.len());
if let Some(written) = self.0.get(path) {
for k in written {
if m.contains_key(k) && !out.contains(k) {
out.push(k.clone());
}
}
}
for k in m.keys() {
if !out.contains(k) {
out.push(k.clone());
}
}
out
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Document {
pub format: String,
pub uri: String,
pub metadata: Metadata,
pub body: Vec<Node>,
pub(crate) raw: Option<Value>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Metadata {
pub front: Object,
pub back: Object,
pub(crate) front_order: KeyOrder,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NodeType {
Markdown,
Directive,
}
impl NodeType {
pub fn as_str(self) -> &'static str {
match self {
NodeType::Markdown => "markdown",
NodeType::Directive => "directive",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Form {
Container,
Leaf,
Keyword,
Alert,
}
impl Form {
pub fn as_str(self) -> &'static str {
match self {
Form::Container => "container",
Form::Leaf => "leaf",
Form::Keyword => "keyword",
Form::Alert => "alert",
}
}
pub fn parse(s: &str) -> Option<Form> {
Some(match s {
"container" => Form::Container,
"leaf" => Form::Leaf,
"keyword" => Form::Keyword,
"alert" => Form::Alert,
_ => return None,
})
}
}
impl fmt::Display for Form {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Node {
pub node_type: NodeType,
pub kind: String,
pub form: Option<Form>,
pub attrs: Attrs,
pub children: Option<Vec<Node>>,
pub value: Option<StructuredValue>,
pub source: String,
pub range: Option<Range>,
pub instance: String,
pub(crate) prose: bool,
pub(crate) keyword: Option<String>,
pub(crate) reason: Option<Range>,
pub(crate) body: Option<Span>,
}
#[derive(Clone)]
pub(crate) struct Span {
pub(crate) text: Arc<str>,
pub(crate) start: usize,
pub(crate) end: usize,
}
impl Span {
pub(crate) fn as_str(&self) -> &str {
self.text.get(self.start..self.end).unwrap_or("")
}
}
impl fmt::Debug for Span {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
impl PartialEq for Span {
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl Node {
pub fn markdown(source: impl Into<String>) -> Node {
Node {
node_type: NodeType::Markdown,
kind: String::new(),
form: None,
attrs: Attrs::new(),
children: None,
value: None,
source: source.into(),
range: None,
instance: String::new(),
prose: false,
keyword: None,
reason: None,
body: None,
}
}
pub fn directive(kind: impl Into<String>, form: Form, attrs: Attrs) -> Node {
Node { node_type: NodeType::Directive, kind: kind.into(), form: Some(form), attrs, ..Node::markdown("") }
}
pub fn is_markdown(&self) -> bool {
self.node_type == NodeType::Markdown
}
pub fn is_directive(&self) -> bool {
self.node_type == NodeType::Directive
}
pub fn keyword(&self) -> Option<&str> {
self.keyword.as_deref()
}
pub fn reason_range(&self) -> Option<Range> {
self.reason
}
pub fn is_prose(&self) -> bool {
self.prose
}
pub fn body_source(&self) -> Option<&str> {
self.body.as_ref().map(Span::as_str)
}
pub fn children(&self) -> &[Node] {
self.children.as_deref().unwrap_or(&[])
}
pub fn attr_str(&self, key: &str) -> Option<&str> {
self.attrs.get(key).and_then(Value::as_str)
}
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("type".into(), self.node_type.as_str().into());
if self.is_markdown() {
m.insert("source".into(), self.source.clone().into());
} else {
m.insert("kind".into(), self.kind.clone().into());
m.insert("form".into(), self.form.map_or("container", Form::as_str).into());
m.insert("attrs".into(), Value::Object(self.attrs.clone()));
}
if let Some(r) = self.range {
m.insert("range".into(), r.to_json());
}
if self.is_directive() {
if let Some(children) = &self.children {
m.insert("children".into(), Value::Array(children.iter().map(Node::to_json).collect()));
}
if let Some(v) = &self.value {
m.insert("value".into(), v.to_json());
}
if !self.source.is_empty() {
m.insert("source".into(), self.source.clone().into());
}
}
if !self.instance.is_empty() {
m.insert("instance".into(), self.instance.clone().into());
}
Value::Object(m)
}
pub fn from_json(v: &Value) -> Result<Node, String> {
let o = v.as_object().ok_or("a node is an object")?;
let s = |k: &str| o.get(k).and_then(Value::as_str).unwrap_or("").to_string();
let node_type = match o.get("type").and_then(Value::as_str) {
Some("markdown") => NodeType::Markdown,
Some("directive") => NodeType::Directive,
_ => return Err("a node's type is markdown or directive".into()),
};
let form = match o.get("form").and_then(Value::as_str) {
Some(f) => Some(Form::parse(f).ok_or_else(|| format!("unknown form {f}"))?),
None if node_type == NodeType::Directive => Some(Form::Container),
None => None,
};
let children = match o.get("children") {
Some(Value::Array(list)) => Some(list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?),
_ => None,
};
let value = match o.get("value") {
Some(v @ Value::Object(_)) => Some(StructuredValue::from_json(v)),
_ => None,
};
Ok(Node {
node_type,
kind: s("kind"),
form: if node_type == NodeType::Directive { form } else { None },
attrs: o.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(),
children,
value,
source: s("source"),
range: o.get("range").and_then(Range::from_json),
instance: s("instance"),
prose: false,
keyword: None,
reason: None,
body: None,
})
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct StructuredValue {
pub format: String,
pub source: String,
pub data: Option<Value>,
pub(crate) order: KeyOrder,
}
impl StructuredValue {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("format".into(), self.format.clone().into());
m.insert("source".into(), self.source.clone().into());
if let Some(d) = &self.data {
m.insert("data".into(), d.clone());
}
Value::Object(m)
}
pub fn from_json(v: &Value) -> StructuredValue {
let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
StructuredValue { format: s("format"), source: s("source"), data: v.get("data").cloned(), order: KeyOrder::default() }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Range {
pub start: u32,
pub end: u32,
}
impl Range {
pub fn new(start: u32, end: u32) -> Range {
Range { start, end }
}
pub fn line(n: u32) -> Range {
Range { start: n, end: n }
}
pub fn to_json(self) -> Value {
let mut m = Map::new();
m.insert("start".into(), self.start.into());
m.insert("end".into(), self.end.into());
Value::Object(m)
}
fn from_json(v: &Value) -> Option<Range> {
let n = |k: &str| v.get(k).and_then(Value::as_f64).map(|f| f.clamp(0.0, u32::MAX as f64) as u32);
Some(Range { start: n("start")?, end: n("end")? })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Severity {
Error,
Warning,
Info,
}
impl Severity {
pub fn as_str(self) -> &'static str {
match self {
Severity::Error => "error",
Severity::Warning => "warning",
Severity::Info => "info",
}
}
}
impl fmt::Display for Severity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Diagnostic {
pub code: &'static str,
pub severity: Severity,
pub message: String,
pub uri: String,
pub range: Option<Range>,
pub target: String,
pub remedy: String,
}
impl Diagnostic {
pub(crate) fn new(code: &'static str, severity: Severity, message: impl Into<String>, line: u32) -> Diagnostic {
Diagnostic {
code,
severity,
message: message.into(),
uri: String::new(),
range: (line > 0).then(|| Range::line(line)),
target: String::new(),
remedy: String::new(),
}
}
pub fn line(&self) -> Option<u32> {
self.range.map(|r| r.start)
}
pub fn is_error(&self) -> bool {
self.severity == Severity::Error
}
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("code".into(), self.code.into());
m.insert("severity".into(), self.severity.as_str().into());
m.insert("message".into(), self.message.clone().into());
if !self.uri.is_empty() {
m.insert("uri".into(), self.uri.clone().into());
}
if let Some(r) = self.range {
m.insert("range".into(), r.to_json());
}
if !self.target.is_empty() {
m.insert("target".into(), self.target.clone().into());
}
if !self.remedy.is_empty() {
m.insert("remedy".into(), self.remedy.clone().into());
}
Value::Object(m)
}
}
impl fmt::Display for Diagnostic {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.uri.is_empty() {
write!(f, "{}:", self.uri)?;
}
if let Some(r) = self.range {
write!(f, "{}: ", r.start)?;
}
write!(f, "{} {}: {}", self.severity, self.code, self.message)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Identity {
pub id: String,
pub kind: String,
pub line: u32,
}
impl Identity {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("id".into(), self.id.clone().into());
m.insert("kind".into(), self.kind.clone().into());
m.insert("line".into(), self.line.into());
Value::Object(m)
}
}
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Parameter {
pub name: String,
pub param_type: String,
pub required: bool,
pub values: Option<Vec<String>>,
pub default: Option<Value>,
pub example: Option<Value>,
pub description: Option<String>,
pub source: Option<String>,
pub line: u32,
}
impl Parameter {
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("name".into(), self.name.clone().into());
m.insert("type".into(), self.param_type.clone().into());
m.insert("required".into(), self.required.into());
if let Some(v) = &self.values {
m.insert("values".into(), v.clone().into());
}
m.insert("declaredAt".into(), if self.line == 0 { "front-matter".into() } else { self.line.into() });
if let Some(v) = &self.default {
m.insert("default".into(), v.clone());
}
if let Some(v) = &self.example {
m.insert("example".into(), v.clone());
}
if let Some(v) = &self.description {
m.insert("description".into(), v.clone().into());
}
if let Some(v) = &self.source {
m.insert("source".into(), v.clone().into());
}
Value::Object(m)
}
}
impl Document {
pub fn new(body: Vec<Node>) -> Document {
Document { format: TREE_FORMAT.into(), body, ..Document::default() }
}
pub fn to_json(&self) -> Value {
let mut m = Map::new();
m.insert("format".into(), self.format.clone().into());
if !self.uri.is_empty() {
m.insert("uri".into(), self.uri.clone().into());
}
let mut meta = Map::new();
meta.insert("front".into(), Value::Object(self.metadata.front.clone()));
meta.insert("back".into(), Value::Object(self.metadata.back.clone()));
m.insert("metadata".into(), Value::Object(meta));
m.insert("body".into(), Value::Array(self.body.iter().map(Node::to_json).collect()));
Value::Object(m)
}
pub fn from_json(v: &Value) -> Result<Document, String> {
let o = v.as_object().ok_or("a tree is an object")?;
let metadata = o.get("metadata");
let region = |k: &str| metadata.and_then(|m| m.get(k)).and_then(Value::as_object).cloned().unwrap_or_default();
let front = region("front");
let mut order = KeyOrder::default();
order.0.insert(String::new(), front.keys().cloned().collect());
let body = match o.get("body") {
Some(Value::Array(list)) => list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?,
_ => Vec::new(),
};
Ok(Document {
format: o.get("format").and_then(Value::as_str).unwrap_or("").to_string(),
uri: o.get("uri").and_then(Value::as_str).unwrap_or("").to_string(),
metadata: Metadata { front, back: region("back"), front_order: order },
body,
raw: Some(v.clone()),
})
}
pub(crate) fn json_value(&self) -> Value {
self.raw.clone().unwrap_or_else(|| self.to_json())
}
}
pub fn number(f: f64) -> Value {
num(f)
}