1use std::collections::HashMap;
5use std::fmt;
6use std::sync::Arc;
7
8use serde_json::{Map, Value};
9
10use crate::js::num;
11
12pub const TREE_FORMAT: &str = "instruction/1";
14
15pub type Object = Map<String, Value>;
17
18pub type Attrs = Object;
20
21#[derive(Clone, Debug, Default, PartialEq)]
24pub(crate) struct KeyOrder(pub(crate) HashMap<String, Vec<String>>);
25
26impl KeyOrder {
27 pub(crate) fn path(key: &str, rest: &[&str]) -> String {
29 let mut p = key.to_string();
30 for k in rest {
31 p.push('\u{1f}');
32 p.push_str(k);
33 }
34 p
35 }
36
37 pub(crate) fn keys(&self, path: &str, m: &Object) -> Vec<String> {
39 let mut out: Vec<String> = Vec::with_capacity(m.len());
40 if let Some(written) = self.0.get(path) {
41 for k in written {
42 if m.contains_key(k) && !out.contains(k) {
43 out.push(k.clone());
44 }
45 }
46 }
47 for k in m.keys() {
48 if !out.contains(k) {
49 out.push(k.clone());
50 }
51 }
52 out
53 }
54}
55
56#[derive(Clone, Debug, Default, PartialEq)]
58pub struct Document {
59 pub format: String,
60 pub uri: String,
62 pub metadata: Metadata,
63 pub body: Vec<Node>,
64 pub(crate) raw: Option<Value>,
66}
67
68#[derive(Clone, Debug, Default, PartialEq)]
70pub struct Metadata {
71 pub front: Object,
72 pub back: Object,
73 pub(crate) front_order: KeyOrder,
74}
75
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
78pub enum NodeType {
79 Markdown,
80 Directive,
81}
82
83impl NodeType {
84 pub fn as_str(self) -> &'static str {
85 match self {
86 NodeType::Markdown => "markdown",
87 NodeType::Directive => "directive",
88 }
89 }
90}
91
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
94pub enum Form {
95 Container,
96 Leaf,
97 Keyword,
98 Alert,
99}
100
101impl Form {
102 pub fn as_str(self) -> &'static str {
103 match self {
104 Form::Container => "container",
105 Form::Leaf => "leaf",
106 Form::Keyword => "keyword",
107 Form::Alert => "alert",
108 }
109 }
110
111 pub fn parse(s: &str) -> Option<Form> {
112 Some(match s {
113 "container" => Form::Container,
114 "leaf" => Form::Leaf,
115 "keyword" => Form::Keyword,
116 "alert" => Form::Alert,
117 _ => return None,
118 })
119 }
120}
121
122impl fmt::Display for Form {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.write_str(self.as_str())
125 }
126}
127
128#[derive(Clone, Debug, PartialEq)]
130pub struct Node {
131 pub node_type: NodeType,
132 pub kind: String,
134 pub form: Option<Form>,
136 pub attrs: Attrs,
137 pub children: Option<Vec<Node>>,
140 pub value: Option<StructuredValue>,
142 pub source: String,
144 pub range: Option<Range>,
145 pub instance: String,
147
148 pub(crate) prose: bool,
149 pub(crate) keyword: Option<String>,
150 pub(crate) reason: Option<Range>,
151 pub(crate) body: Option<Span>,
153}
154
155#[derive(Clone)]
157pub(crate) struct Span {
158 pub(crate) text: Arc<str>,
159 pub(crate) start: usize,
160 pub(crate) end: usize,
161}
162
163impl Span {
164 pub(crate) fn as_str(&self) -> &str {
165 self.text.get(self.start..self.end).unwrap_or("")
166 }
167}
168
169impl fmt::Debug for Span {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 fmt::Debug::fmt(self.as_str(), f)
172 }
173}
174
175impl PartialEq for Span {
176 fn eq(&self, other: &Self) -> bool {
177 self.as_str() == other.as_str()
178 }
179}
180
181impl Node {
182 pub fn markdown(source: impl Into<String>) -> Node {
184 Node {
185 node_type: NodeType::Markdown,
186 kind: String::new(),
187 form: None,
188 attrs: Attrs::new(),
189 children: None,
190 value: None,
191 source: source.into(),
192 range: None,
193 instance: String::new(),
194 prose: false,
195 keyword: None,
196 reason: None,
197 body: None,
198 }
199 }
200
201 pub fn directive(kind: impl Into<String>, form: Form, attrs: Attrs) -> Node {
203 Node { node_type: NodeType::Directive, kind: kind.into(), form: Some(form), attrs, ..Node::markdown("") }
204 }
205
206 pub fn is_markdown(&self) -> bool {
207 self.node_type == NodeType::Markdown
208 }
209
210 pub fn is_directive(&self) -> bool {
211 self.node_type == NodeType::Directive
212 }
213
214 pub fn keyword(&self) -> Option<&str> {
217 self.keyword.as_deref()
218 }
219
220 pub fn reason_range(&self) -> Option<Range> {
222 self.reason
223 }
224
225 pub fn is_prose(&self) -> bool {
227 self.prose
228 }
229
230 pub fn body_source(&self) -> Option<&str> {
242 self.body.as_ref().map(Span::as_str)
243 }
244
245 pub fn children(&self) -> &[Node] {
247 self.children.as_deref().unwrap_or(&[])
248 }
249
250 pub fn attr_str(&self, key: &str) -> Option<&str> {
252 self.attrs.get(key).and_then(Value::as_str)
253 }
254
255 pub fn to_json(&self) -> Value {
257 let mut m = Map::new();
258 m.insert("type".into(), self.node_type.as_str().into());
259 if self.is_markdown() {
260 m.insert("source".into(), self.source.clone().into());
261 } else {
262 m.insert("kind".into(), self.kind.clone().into());
263 m.insert("form".into(), self.form.map_or("container", Form::as_str).into());
264 m.insert("attrs".into(), Value::Object(self.attrs.clone()));
265 }
266 if let Some(r) = self.range {
267 m.insert("range".into(), r.to_json());
268 }
269 if self.is_directive() {
270 if let Some(children) = &self.children {
271 m.insert("children".into(), Value::Array(children.iter().map(Node::to_json).collect()));
272 }
273 if let Some(v) = &self.value {
274 m.insert("value".into(), v.to_json());
275 }
276 if !self.source.is_empty() {
277 m.insert("source".into(), self.source.clone().into());
278 }
279 }
280 if !self.instance.is_empty() {
281 m.insert("instance".into(), self.instance.clone().into());
282 }
283 Value::Object(m)
284 }
285
286 pub fn from_json(v: &Value) -> Result<Node, String> {
288 let o = v.as_object().ok_or("a node is an object")?;
289 let s = |k: &str| o.get(k).and_then(Value::as_str).unwrap_or("").to_string();
290 let node_type = match o.get("type").and_then(Value::as_str) {
291 Some("markdown") => NodeType::Markdown,
292 Some("directive") => NodeType::Directive,
293 _ => return Err("a node's type is markdown or directive".into()),
294 };
295 let form = match o.get("form").and_then(Value::as_str) {
296 Some(f) => Some(Form::parse(f).ok_or_else(|| format!("unknown form {f}"))?),
297 None if node_type == NodeType::Directive => Some(Form::Container),
298 None => None,
299 };
300 let children = match o.get("children") {
301 Some(Value::Array(list)) => Some(list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?),
302 _ => None,
303 };
304 let value = match o.get("value") {
305 Some(v @ Value::Object(_)) => Some(StructuredValue::from_json(v)),
306 _ => None,
307 };
308 Ok(Node {
309 node_type,
310 kind: s("kind"),
311 form: if node_type == NodeType::Directive { form } else { None },
312 attrs: o.get("attrs").and_then(Value::as_object).cloned().unwrap_or_default(),
313 children,
314 value,
315 source: s("source"),
316 range: o.get("range").and_then(Range::from_json),
317 instance: s("instance"),
318 prose: false,
319 keyword: None,
320 reason: None,
321 body: None,
322 })
323 }
324}
325
326#[derive(Clone, Debug, PartialEq)]
328pub struct StructuredValue {
329 pub format: String,
330 pub source: String,
331 pub data: Option<Value>,
333 pub(crate) order: KeyOrder,
334}
335
336impl StructuredValue {
337 pub fn to_json(&self) -> Value {
338 let mut m = Map::new();
339 m.insert("format".into(), self.format.clone().into());
340 m.insert("source".into(), self.source.clone().into());
341 if let Some(d) = &self.data {
342 m.insert("data".into(), d.clone());
343 }
344 Value::Object(m)
345 }
346
347 pub fn from_json(v: &Value) -> StructuredValue {
348 let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
349 StructuredValue { format: s("format"), source: s("source"), data: v.get("data").cloned(), order: KeyOrder::default() }
350 }
351}
352
353#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
355pub struct Range {
356 pub start: u32,
357 pub end: u32,
358}
359
360impl Range {
361 pub fn new(start: u32, end: u32) -> Range {
362 Range { start, end }
363 }
364
365 pub fn line(n: u32) -> Range {
366 Range { start: n, end: n }
367 }
368
369 pub fn to_json(self) -> Value {
370 let mut m = Map::new();
371 m.insert("start".into(), self.start.into());
372 m.insert("end".into(), self.end.into());
373 Value::Object(m)
374 }
375
376 fn from_json(v: &Value) -> Option<Range> {
377 let n = |k: &str| v.get(k).and_then(Value::as_f64).map(|f| f.clamp(0.0, u32::MAX as f64) as u32);
378 Some(Range { start: n("start")?, end: n("end")? })
379 }
380}
381
382#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
384pub enum Severity {
385 Error,
386 Warning,
387 Info,
388}
389
390impl Severity {
391 pub fn as_str(self) -> &'static str {
392 match self {
393 Severity::Error => "error",
394 Severity::Warning => "warning",
395 Severity::Info => "info",
396 }
397 }
398}
399
400impl fmt::Display for Severity {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 f.write_str(self.as_str())
403 }
404}
405
406#[derive(Clone, Debug, PartialEq)]
409pub struct Diagnostic {
410 pub code: &'static str,
411 pub severity: Severity,
412 pub message: String,
413 pub uri: String,
415 pub range: Option<Range>,
416 pub target: String,
417 pub remedy: String,
418}
419
420impl Diagnostic {
421 pub(crate) fn new(code: &'static str, severity: Severity, message: impl Into<String>, line: u32) -> Diagnostic {
422 Diagnostic {
423 code,
424 severity,
425 message: message.into(),
426 uri: String::new(),
427 range: (line > 0).then(|| Range::line(line)),
428 target: String::new(),
429 remedy: String::new(),
430 }
431 }
432
433 pub fn line(&self) -> Option<u32> {
435 self.range.map(|r| r.start)
436 }
437
438 pub fn is_error(&self) -> bool {
439 self.severity == Severity::Error
440 }
441
442 pub fn to_json(&self) -> Value {
444 let mut m = Map::new();
445 m.insert("code".into(), self.code.into());
446 m.insert("severity".into(), self.severity.as_str().into());
447 m.insert("message".into(), self.message.clone().into());
448 if !self.uri.is_empty() {
449 m.insert("uri".into(), self.uri.clone().into());
450 }
451 if let Some(r) = self.range {
452 m.insert("range".into(), r.to_json());
453 }
454 if !self.target.is_empty() {
455 m.insert("target".into(), self.target.clone().into());
456 }
457 if !self.remedy.is_empty() {
458 m.insert("remedy".into(), self.remedy.clone().into());
459 }
460 Value::Object(m)
461 }
462}
463
464impl fmt::Display for Diagnostic {
465 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
466 if !self.uri.is_empty() {
467 write!(f, "{}:", self.uri)?;
468 }
469 if let Some(r) = self.range {
470 write!(f, "{}: ", r.start)?;
471 }
472 write!(f, "{} {}: {}", self.severity, self.code, self.message)
473 }
474}
475
476#[derive(Clone, Debug, PartialEq, Eq)]
478pub struct Identity {
479 pub id: String,
480 pub kind: String,
481 pub line: u32,
482}
483
484impl Identity {
485 pub fn to_json(&self) -> Value {
486 let mut m = Map::new();
487 m.insert("id".into(), self.id.clone().into());
488 m.insert("kind".into(), self.kind.clone().into());
489 m.insert("line".into(), self.line.into());
490 Value::Object(m)
491 }
492}
493
494#[derive(Clone, Debug, PartialEq, Default)]
496pub struct Parameter {
497 pub name: String,
498 pub param_type: String,
499 pub required: bool,
500 pub values: Option<Vec<String>>,
501 pub default: Option<Value>,
503 pub example: Option<Value>,
504 pub description: Option<String>,
505 pub source: Option<String>,
506 pub line: u32,
508}
509
510impl Parameter {
511 pub fn to_json(&self) -> Value {
513 let mut m = Map::new();
514 m.insert("name".into(), self.name.clone().into());
515 m.insert("type".into(), self.param_type.clone().into());
516 m.insert("required".into(), self.required.into());
517 if let Some(v) = &self.values {
518 m.insert("values".into(), v.clone().into());
519 }
520 m.insert("declaredAt".into(), if self.line == 0 { "front-matter".into() } else { self.line.into() });
521 if let Some(v) = &self.default {
522 m.insert("default".into(), v.clone());
523 }
524 if let Some(v) = &self.example {
525 m.insert("example".into(), v.clone());
526 }
527 if let Some(v) = &self.description {
528 m.insert("description".into(), v.clone().into());
529 }
530 if let Some(v) = &self.source {
531 m.insert("source".into(), v.clone().into());
532 }
533 Value::Object(m)
534 }
535}
536
537impl Document {
538 pub fn new(body: Vec<Node>) -> Document {
540 Document { format: TREE_FORMAT.into(), body, ..Document::default() }
541 }
542
543 pub fn to_json(&self) -> Value {
545 let mut m = Map::new();
546 m.insert("format".into(), self.format.clone().into());
547 if !self.uri.is_empty() {
548 m.insert("uri".into(), self.uri.clone().into());
549 }
550 let mut meta = Map::new();
551 meta.insert("front".into(), Value::Object(self.metadata.front.clone()));
552 meta.insert("back".into(), Value::Object(self.metadata.back.clone()));
553 m.insert("metadata".into(), Value::Object(meta));
554 m.insert("body".into(), Value::Array(self.body.iter().map(Node::to_json).collect()));
555 Value::Object(m)
556 }
557
558 pub fn from_json(v: &Value) -> Result<Document, String> {
560 let o = v.as_object().ok_or("a tree is an object")?;
561 let metadata = o.get("metadata");
562 let region = |k: &str| metadata.and_then(|m| m.get(k)).and_then(Value::as_object).cloned().unwrap_or_default();
563 let front = region("front");
564 let mut order = KeyOrder::default();
565 order.0.insert(String::new(), front.keys().cloned().collect());
567 let body = match o.get("body") {
568 Some(Value::Array(list)) => list.iter().map(Node::from_json).collect::<Result<Vec<_>, _>>()?,
569 _ => Vec::new(),
570 };
571 Ok(Document {
572 format: o.get("format").and_then(Value::as_str).unwrap_or("").to_string(),
573 uri: o.get("uri").and_then(Value::as_str).unwrap_or("").to_string(),
574 metadata: Metadata { front, back: region("back"), front_order: order },
575 body,
576 raw: Some(v.clone()),
577 })
578 }
579
580 pub(crate) fn json_value(&self) -> Value {
582 self.raw.clone().unwrap_or_else(|| self.to_json())
583 }
584}
585
586pub fn number(f: f64) -> Value {
588 num(f)
589}