Skip to main content

aozora/
json.rs

1//! Serializes parser projections as versioned JSON envelopes.
2//! Each envelope contains `schemaVersion` and a `data` array.
3//! Check [`SCHEMA_VERSION`] before interpreting an envelope.
4
5use serde::Serialize;
6
7use crate::encoding::gaiji;
8use crate::spec::SLUGS;
9use crate::{DiagnosticSource, Severity, Snapshot};
10
11/// Current JSON wire-format version.
12pub const SCHEMA_VERSION: u32 = 3;
13
14/// Serialize diagnostics as [`Diagnostic`] entries in a versioned envelope.
15#[must_use]
16pub fn diagnostics(diagnostics: &[crate::Diagnostic]) -> String {
17    serialize_envelope(&diagnostic_entries(diagnostics))
18}
19
20/// Return the records serialized by [`diagnostics`].
21#[must_use]
22pub fn diagnostic_entries(diagnostics: &[crate::Diagnostic]) -> Vec<Diagnostic> {
23    diagnostics.iter().map(Diagnostic::from).collect()
24}
25
26/// Serialize snapshot nodes in source order as [`Node`] entries.
27#[must_use]
28pub fn nodes(snapshot: &Snapshot) -> String {
29    serialize_envelope(&node_entries(snapshot))
30}
31
32/// Return the records serialized by [`nodes`].
33#[must_use]
34pub fn node_entries(snapshot: &Snapshot) -> Vec<Node> {
35    snapshot
36        .nodes()
37        .iter()
38        .map(|node| Node {
39            kind: node.kind().as_json_tag(),
40            span: node.span().into(),
41        })
42        .collect()
43}
44
45/// Serialize matched delimiters as [`Pair`] entries.
46///
47/// Excludes unmatched delimiters.
48#[must_use]
49pub fn pairs(snapshot: &Snapshot) -> String {
50    serialize_envelope(&pair_entries(snapshot))
51}
52
53/// Return the records serialized by [`pairs`].
54#[must_use]
55pub fn pair_entries(snapshot: &Snapshot) -> Vec<Pair> {
56    snapshot
57        .pairs()
58        .iter()
59        .map(|link| Pair {
60            kind: link.kind.as_json_tag(),
61            open: link.open.into(),
62            close: link.close.into(),
63        })
64        .collect()
65}
66
67/// Serialize matched container delimiters as [`ContainerPair`] entries.
68#[must_use]
69pub fn container_pairs(snapshot: &Snapshot) -> String {
70    serialize_envelope(&container_pair_entries(snapshot))
71}
72
73/// Return the records serialized by [`container_pairs`].
74#[must_use]
75pub fn container_pair_entries(snapshot: &Snapshot) -> Vec<ContainerPair> {
76    snapshot
77        .container_pairs()
78        .iter()
79        .map(|pair| ContainerPair {
80            kind: pair.kind().as_str(),
81            open: pair.open().into(),
82            close: pair.close().into(),
83        })
84        .collect()
85}
86
87/// Serialize the notation catalogue as [`Slug`] entries.
88#[must_use]
89pub fn slugs() -> String {
90    serialize_envelope(&slug_entries())
91}
92
93/// Return the records serialized by [`slugs`].
94#[must_use]
95pub fn slug_entries() -> Vec<Slug> {
96    SLUGS
97        .iter()
98        .map(|s| Slug {
99            canonical: s.canonical,
100            family: s.family.as_json_tag(),
101            accepts_param: s.accepts_param,
102            doc: s.doc,
103            partner: s.partner,
104        })
105        .collect()
106}
107
108/// Serialize snapshot gaiji references as [`GaijiResolution`] entries.
109#[must_use]
110pub fn gaiji(snapshot: &Snapshot) -> String {
111    serialize_envelope(&gaiji_entries(snapshot))
112}
113
114/// Return the records serialized by [`gaiji`].
115#[must_use]
116pub fn gaiji_entries(snapshot: &Snapshot) -> Vec<GaijiResolution> {
117    snapshot
118        .gaiji_resolutions()
119        .iter()
120        .cloned()
121        .map(Into::into)
122        .collect()
123}
124
125/// Return a gaiji wire record at a source byte offset, or `None` if none covers it.
126#[must_use]
127pub fn gaiji_entry_at(snapshot: &Snapshot, byte_offset: usize) -> Option<GaijiResolution> {
128    snapshot
129        .gaiji_resolution_at(byte_offset)
130        .cloned()
131        .map(Into::into)
132}
133
134#[derive(Serialize)]
135#[serde(rename_all = "camelCase")]
136struct Envelope<'a, T> {
137    schema_version: u32,
138    data: &'a [T],
139}
140
141/// JSON Schema draft 2020-12 for the [`diagnostics`] envelope.
142#[cfg(feature = "schema")]
143#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
144#[must_use]
145pub fn schema_diagnostics() -> serde_json::Value {
146    envelope_schema(
147        "AozoraDiagnosticsEnvelope",
148        "Envelope returned by aozora::json::diagnostics.",
149        schemars::schema_for!(Diagnostic),
150    )
151}
152
153/// JSON Schema for the [`nodes`] envelope output.
154#[cfg(feature = "schema")]
155#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
156#[must_use]
157pub fn schema_nodes() -> serde_json::Value {
158    envelope_schema(
159        "AozoraNodesEnvelope",
160        "Envelope returned by aozora::json::nodes.",
161        schemars::schema_for!(Node),
162    )
163}
164
165/// JSON Schema for the [`pairs`] envelope output.
166#[cfg(feature = "schema")]
167#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
168#[must_use]
169pub fn schema_pairs() -> serde_json::Value {
170    envelope_schema(
171        "AozoraPairsEnvelope",
172        "Envelope returned by aozora::json::pairs.",
173        schemars::schema_for!(Pair),
174    )
175}
176
177/// JSON Schema for the [`container_pairs`] envelope output.
178#[cfg(feature = "schema")]
179#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
180#[must_use]
181pub fn schema_container_pairs() -> serde_json::Value {
182    envelope_schema(
183        "AozoraContainerPairsEnvelope",
184        "Envelope returned by aozora::json::container_pairs.",
185        schemars::schema_for!(ContainerPair),
186    )
187}
188
189/// JSON Schema for the [`gaiji`] envelope output.
190#[cfg(feature = "schema")]
191#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
192#[must_use]
193pub fn schema_gaiji() -> serde_json::Value {
194    envelope_schema(
195        "AozoraGaijiEnvelope",
196        "Envelope returned by aozora::json::gaiji.",
197        schemars::schema_for!(GaijiResolution),
198    )
199}
200
201/// JSON Schema for the [`slugs`] envelope output.
202#[cfg(feature = "schema")]
203#[cfg_attr(docsrs, doc(cfg(feature = "schema")))]
204#[must_use]
205pub fn schema_slugs() -> serde_json::Value {
206    envelope_schema(
207        "AozoraSlugsEnvelope",
208        "Envelope returned by aozora::json::slugs.",
209        schemars::schema_for!(Slug),
210    )
211}
212
213#[cfg(feature = "schema")]
214const JSON_SCHEMA_DIALECT: &str = "https://json-schema.org/draft/2020-12/schema";
215
216#[cfg(feature = "schema")]
217#[expect(
218    clippy::expect_used,
219    reason = "the envelope root is constructed from an object literal"
220)]
221fn envelope_schema(
222    title: &str,
223    description: &str,
224    item_schema: schemars::Schema,
225) -> serde_json::Value {
226    let mut item = item_schema.to_value();
227    let defs = item.as_object_mut().and_then(|obj| {
228        obj.remove("$schema");
229        obj.remove("$defs")
230    });
231    let mut root = serde_json::json!({
232        "$schema": JSON_SCHEMA_DIALECT,
233        "title": title,
234        "description": description,
235        "type": "object",
236        "additionalProperties": false,
237        "required": ["schemaVersion", "data"],
238        "properties": {
239            "schemaVersion": {
240                "description": "Wire schema version. See aozora::json::SCHEMA_VERSION.",
241                "type": "integer",
242                "const": SCHEMA_VERSION,
243            },
244            "data": {
245                "description": "Per-entry payload array; one item per emitted diagnostic / node / pair.",
246                "type": "array",
247                "items": item,
248            },
249        },
250    });
251    if let Some(defs) = defs {
252        root.as_object_mut()
253            .expect("envelope root is a JSON object literal")
254            .insert("$defs".to_owned(), defs);
255    }
256    root
257}
258
259fn serialize_envelope<T: Serialize>(data: &[T]) -> String {
260    let env = Envelope {
261        schema_version: SCHEMA_VERSION,
262        data,
263    };
264    match serde_json::to_string(&env) {
265        Ok(json) => json,
266        Err(error) => unreachable!("wire envelope serialization failed: {error}"),
267    }
268}
269
270/// One half-open `[start, end)` byte span in a wire envelope.
271#[derive(Debug, Clone, Copy, Serialize)]
272#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
273pub struct Span {
274    start: u32,
275    end: u32,
276}
277
278impl From<crate::Span> for Span {
279    fn from(s: crate::Span) -> Self {
280        Self {
281            start: s.start,
282            end: s.end,
283        }
284    }
285}
286
287/// One `diagnostics` envelope entry — a projected [`crate::Diagnostic`].
288#[derive(Debug, Clone, Copy, Serialize)]
289#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
290pub struct Diagnostic {
291    kind: &'static str,
292    severity: &'static str,
293    source: &'static str,
294    span: Span,
295    #[serde(skip_serializing_if = "Option::is_none")]
296    codepoint: Option<u32>,
297}
298
299impl From<&crate::Diagnostic> for Diagnostic {
300    fn from(d: &crate::Diagnostic) -> Self {
301        let codepoint = match d {
302            crate::Diagnostic::SourceContainsPua { codepoint, .. } => Some(u32::from(*codepoint)),
303            _ => None,
304        };
305        let kind = d.code().rsplit("::").next().unwrap_or("unknown");
306        Self {
307            kind,
308            severity: severity_str(d.severity()),
309            source: source_str(d.source()),
310            span: d.span().into(),
311            codepoint,
312        }
313    }
314}
315
316const fn severity_str(s: Severity) -> &'static str {
317    match s {
318        Severity::Warning => "warning",
319        Severity::Note => "note",
320        Severity::Error => "error",
321    }
322}
323
324const fn source_str(s: DiagnosticSource) -> &'static str {
325    match s {
326        DiagnosticSource::Source => "source",
327        DiagnosticSource::Internal => "internal",
328    }
329}
330
331/// One `nodes` envelope entry — a classified node span in source coords.
332#[derive(Debug, Clone, Copy, Serialize)]
333#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
334pub struct Node {
335    kind: &'static str,
336    span: Span,
337}
338
339/// One `pairs` envelope entry — a matched bracket pair.
340#[derive(Debug, Clone, Copy, Serialize)]
341#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
342pub struct Pair {
343    kind: &'static str,
344    open: Span,
345    close: Span,
346}
347
348/// One `container_pairs` envelope entry.
349#[derive(Debug, Clone, Copy, Serialize)]
350#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
351pub struct ContainerPair {
352    kind: &'static str,
353    open: Span,
354    close: Span,
355}
356
357/// One `slugs` envelope entry — a row of the annotation slug catalogue.
358#[derive(Debug, Clone, Copy, Serialize)]
359#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
360pub struct Slug {
361    canonical: &'static str,
362    family: &'static str,
363    accepts_param: bool,
364    doc: &'static str,
365    #[serde(skip_serializing_if = "Option::is_none")]
366    partner: Option<&'static str>,
367}
368
369/// One `gaiji` envelope entry — a resolved `※[#…]` reference.
370#[derive(Debug, Clone, Serialize)]
371#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
372pub struct GaijiResolution {
373    span: Span,
374    description: String,
375    #[serde(skip_serializing_if = "Option::is_none")]
376    mencode: Option<String>,
377    #[serde(skip_serializing_if = "Option::is_none")]
378    codepoint: Option<u32>,
379    #[serde(skip_serializing_if = "Option::is_none")]
380    resolved: Option<String>,
381}
382
383impl From<gaiji::GaijiResolution> for GaijiResolution {
384    fn from(g: gaiji::GaijiResolution) -> Self {
385        Self {
386            span: g.span().into(),
387            description: g.description().to_owned(),
388            mencode: g.mencode().map(str::to_owned),
389            codepoint: g.codepoint(),
390            resolved: g.resolved().map(str::to_owned),
391        }
392    }
393}
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use crate::Document;
399    use serde::ser::Error as _;
400
401    struct RejectSerialization;
402
403    impl Serialize for RejectSerialization {
404        fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
405        where
406            S: serde::Serializer,
407        {
408            Err(S::Error::custom("rejected"))
409        }
410    }
411
412    fn empty_envelope() -> String {
413        format!(r#"{{"schemaVersion":{SCHEMA_VERSION},"data":[]}}"#)
414    }
415
416    fn schema_marker() -> String {
417        format!(r#""schemaVersion":{SCHEMA_VERSION}"#)
418    }
419
420    #[test]
421    fn slugs_envelope_lists_catalogue_with_known_families() {
422        let json = slugs();
423        assert!(json.contains(&schema_marker()));
424        assert!(json.contains(r#""canonical":"#));
425        assert!(json.contains(r#""family":"#));
426        assert!(
427            !json.contains(r#""family":"unknown""#),
428            "shipped catalogue leaked an unknown family: {json}"
429        );
430    }
431
432    #[test]
433    fn gaiji_resolutions_empty_envelope_for_plain_text() {
434        let snapshot = Document::new("no gaiji here").snapshot();
435        assert_eq!(gaiji(&snapshot), empty_envelope());
436    }
437
438    #[test]
439    fn gaiji_resolutions_emits_resolved_entry_in_source_coords() {
440        let snapshot = Document::new("※[#「々」]").snapshot();
441        let json = gaiji(&snapshot);
442        assert!(json.contains(&schema_marker()));
443        assert!(
444            json.contains(r#""span":{"start":0,"end":21}"#),
445            "json: {json}"
446        );
447        assert!(json.contains(r#""description":"々""#), "json: {json}");
448        assert!(json.contains(r#""resolved":"々""#), "json: {json}");
449        assert!(!json.contains(r#""mencode""#), "json: {json}");
450    }
451
452    #[test]
453    fn gaiji_entry_at_resolves_only_inside_span() {
454        let src = "あ※[#「々」]い";
455        let snapshot = Document::new(src).snapshot();
456        let inside = src.find('※').unwrap() + "※".len();
457        let at = gaiji_entry_at(&snapshot, inside).expect("inside gaiji");
458        assert_eq!(at.description, "々");
459        assert_eq!(at.resolved.as_deref(), Some("々"));
460        assert!(gaiji_entry_at(&snapshot, 0).is_none());
461    }
462
463    #[test]
464    fn schema_version_matches_the_wire_authority() {
465        assert_eq!(SCHEMA_VERSION, 3);
466    }
467
468    #[test]
469    fn empty_diagnostics_round_trip_envelope() {
470        let json = diagnostics(&[]);
471        assert_eq!(json, empty_envelope());
472    }
473
474    #[test]
475    #[should_panic(expected = "wire envelope serialization failed: rejected")]
476    fn serialization_failure_is_not_reported_as_an_empty_envelope() {
477        drop(serialize_envelope(&[RejectSerialization]));
478    }
479
480    #[test]
481    fn empty_nodes_round_trip_envelope() {
482        let doc = Document::new("plain");
483        let tree = doc.snapshot();
484        let json = nodes(&tree);
485        assert_eq!(json, empty_envelope());
486    }
487
488    #[test]
489    fn empty_pairs_round_trip_envelope() {
490        let doc = Document::new("plain");
491        let tree = doc.snapshot();
492        let json = pairs(&tree);
493        assert_eq!(json, empty_envelope());
494    }
495
496    #[test]
497    fn pua_collision_serialises_as_warning_kind() {
498        let doc = Document::new("abc\u{E001}def");
499        let tree = doc.snapshot();
500        let json = diagnostics(tree.diagnostics());
501        assert!(json.contains(&schema_marker()));
502        assert!(json.contains(r#""kind":"source_contains_pua""#));
503        assert!(json.contains(&format!(r#""codepoint":{}"#, '\u{E001}' as u32)));
504    }
505
506    #[test]
507    fn ruby_serialises_with_kind_ruby_in_nodes() {
508        let doc = Document::new("|青梅《おうめ》");
509        let tree = doc.snapshot();
510        let json = nodes(&tree);
511        assert!(json.contains(r#""kind":"ruby""#));
512        assert!(json.contains(&schema_marker()));
513    }
514
515    #[test]
516    fn ruby_serialises_in_pairs() {
517        let doc = Document::new("|青梅《おうめ》");
518        let tree = doc.snapshot();
519        let json = pairs(&tree);
520        assert!(json.contains(r#""kind":"ruby""#));
521        assert!(json.contains(r#""open":"#));
522        assert!(json.contains(r#""close":"#));
523    }
524
525    #[test]
526    fn pair_kind_camel_case_covers_all_known_kinds() {
527        use crate::PairKind;
528        assert_eq!(PairKind::Bracket.as_json_tag(), "bracket");
529        assert_eq!(PairKind::Ruby.as_json_tag(), "ruby");
530        assert_eq!(PairKind::AngleQuote.as_json_tag(), "angleQuote");
531        assert_eq!(PairKind::Tortoise.as_json_tag(), "tortoise");
532        assert_eq!(PairKind::Quote.as_json_tag(), "quote");
533    }
534
535    #[test]
536    fn container_pair_entries_projects_indent_open_close_offsets() {
537        let doc = Document::new("[#ここから2字下げ]\n本文\n[#ここで字下げ終わり]\n");
538        let tree = doc.snapshot();
539        let entries = container_pair_entries(&tree);
540        assert_eq!(
541            entries.len(),
542            1,
543            "expected exactly one indent container pair: {entries:?}"
544        );
545        let pair = &entries[0];
546        assert_eq!(pair.kind, "indent", "container kind: {pair:?}");
547        assert!(
548            pair.open.start < pair.close.start,
549            "open must precede close: {pair:?}"
550        );
551    }
552
553    #[cfg(feature = "schema")]
554    #[test]
555    fn schema_fns_return_titled_envelope_not_null() {
556        let cases = [
557            ("AozoraDiagnosticsEnvelope", schema_diagnostics()),
558            ("AozoraNodesEnvelope", schema_nodes()),
559            ("AozoraPairsEnvelope", schema_pairs()),
560            ("AozoraContainerPairsEnvelope", schema_container_pairs()),
561            ("AozoraGaijiEnvelope", schema_gaiji()),
562            ("AozoraSlugsEnvelope", schema_slugs()),
563        ];
564        for (title, value) in cases {
565            assert_eq!(
566                value["title"], title,
567                "schema envelope title mismatch: {value}"
568            );
569            assert_eq!(
570                value["type"], "object",
571                "schema envelope must be an object: {value}"
572            );
573            assert_eq!(
574                value["properties"]["schemaVersion"]["const"],
575                serde_json::json!(SCHEMA_VERSION),
576                "schemaVersion const must pin SCHEMA_VERSION: {value}"
577            );
578            assert_eq!(
579                value["properties"]["data"]["type"], "array",
580                "data property must be an array: {value}"
581            );
582        }
583    }
584
585    #[cfg(feature = "schema")]
586    #[test]
587    fn envelope_schema_wraps_item_in_versioned_envelope() {
588        let value = envelope_schema(
589            "CustomTitle",
590            "Custom description.",
591            schemars::schema_for!(Node),
592        );
593        assert_eq!(value["title"], "CustomTitle", "title: {value}");
594        assert_eq!(
595            value["description"], "Custom description.",
596            "description: {value}"
597        );
598        assert_eq!(
599            value["additionalProperties"], false,
600            "closed shape: {value}"
601        );
602        assert_eq!(
603            value["required"],
604            serde_json::json!(["schemaVersion", "data"]),
605            "required keys: {value}"
606        );
607        assert_eq!(
608            value["properties"]["schemaVersion"]["const"],
609            serde_json::json!(SCHEMA_VERSION),
610            "schemaVersion const: {value}"
611        );
612    }
613
614    #[test]
615    fn container_kind_wire_tags_via_as_json_tag() {
616        use crate::syntax::{BoutenKind, BoutenPosition, RegionFormat};
617        assert_eq!(RegionFormat::Bold { padded: false }.as_json_tag(), "bold");
618        assert_eq!(RegionFormat::Bold { padded: true }.as_json_tag(), "bold");
619        assert_eq!(
620            RegionFormat::Italic { padded: false }.as_json_tag(),
621            "italic"
622        );
623        assert_eq!(
624            RegionFormat::Italic { padded: true }.as_json_tag(),
625            "italic"
626        );
627        assert_eq!(
628            RegionFormat::Bouten {
629                kind: BoutenKind::Goma,
630                position: BoutenPosition::Right,
631            }
632            .as_json_tag(),
633            "boutenRange"
634        );
635    }
636}