Skip to main content

ironwork_rt/lir/
markup.rs

1//! JSON GENERATE, JSON PARSE, XML GENERATE and XML PARSE (lir.md ยง9.13): each statement's
2//! phrases, and the tree of items its walk reaches with every choice the walker makes by name or
3//! kind made once. Trees nest by index: a node's members come after it in its node table.
4
5use super::{AbendId, CondId, ConstId, Count, IntExpr, MovePlan, Odo, Operand, PlaceId, RangeId, StorePlan, SymId};
6use crate::storage::Kind;
7use crate::vocab::Figurative;
8use crate::{codec_enum, codec_struct};
9use zarch::hfp::Precision;
10
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub enum Markup {
13    JsonGenerate(JsonGenerate),
14    XmlGenerate(XmlGenerate),
15    XmlParse(XmlParse),
16    JsonParse(JsonParse),
17}
18
19impl Markup {
20    /// ON EXCEPTION and NOT ON EXCEPTION as written: with either, the op returns Arm(1) for an
21    /// exception and Arm(0) otherwise, for a `Select` of two blocks.
22    pub fn phrases(&self) -> (bool, bool) {
23        match self {
24            Markup::JsonGenerate(g) => (g.on_exception, g.not_on_exception),
25            Markup::XmlGenerate(g) => (g.on_exception, g.not_on_exception),
26            Markup::XmlParse(p) => (p.on_exception, p.not_on_exception),
27            Markup::JsonParse(p) => (p.on_exception, p.not_on_exception),
28        }
29    }
30}
31
32/// The CCSID a statement's document is in: none written, the program's CODEPAGE (JSON's ENCODING
33/// FROM CODEPAGE), or an operand read as the statement starts.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub enum Ccsid {
36    Unnamed,
37    CodePage,
38    Operand(Operand),
39}
40
41/// An elementary item's value as JSON and XML GENERATE write it.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum Convert {
44    /// Alphanumeric and edited items, and a group with no members: its bytes decoded in the
45    /// program's code page, trimmed of trailing spaces, or of leading ones when `justified`.
46    Chars { justified: bool },
47    /// UTF-16 units, trimmed of trailing spaces.
48    National,
49    /// COMP-1 (8 decimals) or COMP-2 (17).
50    Float(Precision),
51    /// Zoned, packed, binary and index items: the value, read as its kind reads it, with at least
52    /// `integers` integer positions before the leading zeros are trimmed.
53    Fixed { integers: u32 },
54    /// A pointer, procedure-pointer or object reference: this IRONWORK abend when it is reached.
55    Refused(AbendId),
56}
57
58/// A USING value that stands for true or null.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum Marker {
61    /// The first byte equals this literal's first, in the program's code page; never when the
62    /// literal has none.
63    Byte(Option<u8>),
64    /// A condition-name, its conditional variable located with the walk's subscripts.
65    Condition(CondId),
66    /// The IRONWORK abend the walker gives when it tests the marker.
67    Refused(AbendId),
68}
69
70/// JSON GENERATE. In order: FROM is located, its subscripts evaluated, which begin the walk's
71/// subscripts (`IntExpr::Walk`), and the tree walked from `nodes[0]`; then the receiver is located,
72/// the encoding read, the document written, COUNT IN and JSON-CODE stored.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct JsonGenerate {
75    /// FROM, or its table's first element when it names the whole table.
76    pub from: PlaceId,
77    pub subscripts: Vec<IntExpr>,
78    /// `nodes[0]` is FROM, with `occurs` when FROM names a whole table.
79    pub nodes: Vec<JsonNode>,
80    /// The name the document wraps FROM's value in, as a JSON string; None for NAME ... OMITTED.
81    pub name: Option<SymId>,
82    pub receiver: PlaceId,
83    pub encoding: Ccsid,
84    pub count: Option<(PlaceId, StorePlan)>,
85    pub code: (PlaceId, StorePlan),
86    pub on_exception: bool,
87    pub not_on_exception: bool,
88}
89
90/// An item of the tree, `offset` bytes into the occurrence of the node that holds it, less the
91/// unused occurrences of the `moved` tables, which lie ahead of it in its record and not ahead of
92/// that node and are counted as the walk reaches it (C161), before `occurs`; `len` its size; a
93/// table's elements are `len` apart, `occurs` of them. `name` is a member's JSON string. Each
94/// occurrence, of a group or an elementary item, is null when `indicator`'s marker holds or it
95/// equals `null`, tested in that order before its value.
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct JsonNode {
98    pub offset: u32,
99    pub moved: Vec<Odo>,
100    pub len: u32,
101    pub kind: Kind,
102    pub name: SymId,
103    pub occurs: Option<Count>,
104    /// INDICATING: the indicator, located with the walk's subscripts, whose first byte `Marker`
105    /// tests; or the abend of locating it with too few.
106    pub indicator: Option<(Result<PlaceId, AbendId>, Marker)>,
107    /// CONVERTING ... TO JSON NULL: null when the item equals this figurative constant.
108    pub null: Option<Figurative>,
109    pub value: JsonValue,
110}
111
112#[derive(Clone, Debug, PartialEq, Eq)]
113pub enum JsonValue {
114    /// A group's members, in order, an unnamed group's among them. With `eligible` (some member
115    /// is not ignored), a group whose members are all left out is left out; a table whose
116    /// elements all are is left out.
117    Object { members: Vec<u32>, eligible: bool },
118    Leaf(JsonLeaf),
119}
120
121/// Tested in this order, after the node's null tests: `suppress` (left out), `boolean`, `convert`.
122#[derive(Clone, Debug, PartialEq, Eq)]
123pub struct JsonLeaf {
124    /// SUPPRESS: the item's own WHEN constants, then each EVERY phrase's that selects its kind.
125    pub suppress: Vec<Figurative>,
126    /// CONVERTING ... TO BOOLEAN: true when the marker holds of the item's first byte.
127    pub boolean: Option<Marker>,
128    pub convert: Convert,
129}
130
131/// XML GENERATE. In order: the receiver is located and the encoding read, which may end the
132/// statement with XML-CODE 411, 414 or 415; NAMESPACE is read (416), then NAMESPACE-PREFIX for a
133/// namespace that is not empty (419); FROM is located, its subscripts evaluated, and the tree walked from `nodes[0]`; a national
134/// value in a single-byte document ends it with 420; then the document is written and COUNT IN and
135/// XML-CODE stored.
136#[derive(Clone, Debug, PartialEq, Eq)]
137pub struct XmlGenerate {
138    pub receiver: PlaceId,
139    /// `Unnamed` is UTF-16 for a national receiver and the program's CODEPAGE otherwise.
140    pub encoding: Ccsid,
141    pub namespace: Option<Operand>,
142    pub prefix: Option<Operand>,
143    pub declaration: bool,
144    pub from: PlaceId,
145    pub subscripts: Vec<IntExpr>,
146    /// `nodes[0]` is FROM: its element, which SUPPRESS never leaves out and which takes the
147    /// namespace declaration, or an elementary item's element whatever its form.
148    pub nodes: Vec<XmlNode>,
149    /// SUPPRESS is written, so an element left with no attributes and no content is left out.
150    pub suppressing: bool,
151    pub count: Option<(PlaceId, StorePlan)>,
152    pub code: (PlaceId, StorePlan),
153    pub on_exception: bool,
154    pub not_on_exception: bool,
155}
156
157/// As `JsonNode`; `name` is the element or attribute name as the document writes it.
158#[derive(Clone, Debug, PartialEq, Eq)]
159pub struct XmlNode {
160    pub offset: u32,
161    pub moved: Vec<Odo>,
162    pub len: u32,
163    pub kind: Kind,
164    pub name: SymId,
165    pub occurs: Option<Count>,
166    pub value: XmlValue,
167}
168
169#[derive(Clone, Debug, PartialEq, Eq)]
170pub enum XmlValue {
171    /// A named group's element: each occurrence of each member, in order.
172    Element { members: Vec<u32> },
173    /// An unnamed group, each occurrence's members joining the element that holds it.
174    Members { members: Vec<u32> },
175    /// `suppress`: the item's own WHEN constants, or when it has none each EVERY phrase's that
176    /// selects its kind and form. A value that is not legal XML goes in hexadecimal, as an element
177    /// named "hex." and the name, and XML-CODE is 417.
178    Leaf { form: XmlForm, suppress: Vec<Figurative>, convert: Convert },
179}
180
181#[derive(Clone, Copy, Debug, PartialEq, Eq)]
182pub enum XmlForm {
183    Attribute,
184    Element,
185    Content,
186}
187
188/// XML PARSE. The document is located, the encoding read (a CCSID ironwork has no page for abends
189/// IRONWORK), and the document located again and decoded; then each event the scanner reports
190/// sets XML-EVENT, XML-CODE and XML-INFORMATION and the fragment registers (`Base::Xml`), and runs
191/// `procedure` through `Procedures::run` with the arrival PERFORM LOOP, at the statement's depth.
192/// A procedure that leaves ends the statement with its step. After it completes, XML-CODE is read:
193/// a warning the scanner reports as an EXCEPTION event (an undeclared prefix) goes on when it is 0,
194/// and that or any other EXCEPTION otherwise ends the parse with the scanner's code;
195/// END-OF-DOCUMENT ends it with 0; at END-OF-INPUT 1 locates the document again for the next
196/// segment and any other value ends the input; after any other event -1 ends the parse with -1.
197/// XML-CODE then takes the result.
198#[derive(Clone, Debug, PartialEq, Eq)]
199pub struct XmlParse {
200    pub document: PlaceId,
201    pub encoding: Option<Operand>,
202    /// RETURNING NATIONAL.
203    pub national: bool,
204    pub procedure: RangeId,
205    pub event: PlaceId,
206    pub code: (PlaceId, StorePlan),
207    pub information: (PlaceId, StorePlan),
208    /// XML-CODE as read after each event.
209    pub code_value: IntExpr,
210    pub on_exception: bool,
211    pub not_on_exception: bool,
212}
213
214/// JSON PARSE. In order: the source is located, the encoding read (ENCODING FROM CODEPAGE of a
215/// national source is JSON-CODE 109 before it is), the text decoded and parsed; then, for a
216/// document that parses, INTO is located and its subscripts evaluated, which begin the walk's, and
217/// each value goes into the item whose name matches it, by MOVE's rules; JSON-CODE and then
218/// JSON-STATUS are stored.
219#[derive(Clone, Debug, PartialEq, Eq)]
220pub struct JsonParse {
221    pub source: PlaceId,
222    pub encoding: Ccsid,
223    /// INTO, or its table's first element when it names the whole table.
224    pub into: PlaceId,
225    pub subscripts: Vec<IntExpr>,
226    /// `nodes[0]` is INTO, with `occurs` when INTO names a whole table. Its name `Omitted` makes
227    /// the document INTO's value; otherwise the document is an object whose members INTO's name
228    /// matches.
229    pub nodes: Vec<ParseNode>,
230    /// IGNORING JSON NULL FOR ALL.
231    pub ignore_all: bool,
232    pub code: (PlaceId, StorePlan),
233    pub status: (PlaceId, StorePlan),
234    pub on_exception: bool,
235    pub not_on_exception: bool,
236}
237
238/// As `JsonNode`, a member's `moved` counted as its pair is reached, unless SUPPRESS names it. Each
239/// item takes a value in this order: a second value at the same item and offset is a duplicate;
240/// `indicator`; then a null goes to `null`'s MOVE, or is ignored, or is a status; an object fills a
241/// group's members; any other value goes to a leaf.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct ParseNode {
244    pub offset: u32,
245    pub moved: Vec<Odo>,
246    pub len: u32,
247    pub kind: Kind,
248    pub name: Named,
249    pub occurs: Option<Count>,
250    /// IGNORING JSON NULL FOR the item.
251    pub ignored: bool,
252    pub indicator: Option<Indicator>,
253    /// CONVERTING ... FROM JSON NULL: the figurative constant and its MOVE into the item.
254    pub null: Option<(Figurative, MovePlan)>,
255    pub value: ParseValue,
256}
257
258/// How a JSON name matches an item: a NAME literal exactly, a data-name whatever the case of its
259/// letters, or never (NAME ... OMITTED).
260#[derive(Clone, Copy, Debug, PartialEq, Eq)]
261pub enum Named {
262    Exactly(SymId),
263    Folded(SymId),
264    Omitted,
265}
266
267#[derive(Clone, Debug, PartialEq, Eq)]
268pub enum ParseValue {
269    /// A group's members a name can reach, an unnamed group's among them, unnamed tables not.
270    Object { members: Vec<u32> },
271    Leaf(ParseLeaf),
272    /// SUPPRESS: a name reaches it, and it takes nothing.
273    Suppressed,
274}
275
276#[derive(Clone, Debug, PartialEq, Eq)]
277pub struct ParseLeaf {
278    /// CONVERTING ... FROM BOOLEAN: true sets the first value, false the second.
279    pub boolean: Option<Flag>,
280    /// A string's characters into an alphanumeric, alphanumeric-edited or national item: bytes in
281    /// the program's code page, X'3F' for any it lacks, or UTF-16, by this MOVE. None for any
282    /// other item, which takes the number a string of digits spells.
283    pub text: Option<MovePlan>,
284    pub number: NumberInto,
285}
286
287/// How a number goes into a leaf.
288#[derive(Clone, Copy, Debug, PartialEq, Eq)]
289pub enum NumberInto {
290    Float(MovePlan),
291    /// Zoned, packed or binary: stored with a size error a status, not an exception.
292    Store(StorePlan),
293    /// Numeric-edited, by MOVE.
294    Edited(MovePlan),
295    /// An integer only: an alphanumeric or alphanumeric-edited item takes it as MOVE takes an
296    /// unsigned integer of as many digits, a national item its digits as UTF-16.
297    Digits,
298    /// An alphabetic item, or any other no number moves to.
299    Incompatible,
300}
301
302/// INDICATING: the indicator IN names, located with the walk's subscripts whatever the flag,
303/// then the flag, on for a null.
304#[derive(Clone, Debug, PartialEq, Eq)]
305pub struct Indicator {
306    pub place: Option<Result<PlaceId, AbendId>>,
307    pub flag: Flag,
308}
309
310/// A USING phrase: what a true or null value sets, then what a false or other value sets.
311#[derive(Clone, Copy, Debug, PartialEq, Eq)]
312pub enum Flag {
313    /// SET condition-name TO TRUE, or TO FALSE.
314    Set { on: SetTo, off: SetTo },
315    /// One of two literals moved into the indicator, or the item.
316    Literals { on: (ConstId, MovePlan), off: (ConstId, MovePlan) },
317}
318
319/// SET of a condition-name, its conditional variable located with the walk's subscripts.
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
321pub enum SetTo {
322    /// It has no such value.
323    Nothing,
324    Move { place: PlaceId, value: ConstId, plan: MovePlan },
325    /// It is not a condition-name, or the walk has too few subscripts for it.
326    Refused(AbendId),
327}
328
329/// The XML special registers whose length is the current event's fragment's: empty outside a
330/// processing procedure.
331#[derive(Clone, Copy, Debug, PartialEq, Eq)]
332pub enum XmlRegister {
333    Text,
334    NText,
335    Namespace,
336    NNamespace,
337    Prefix,
338    NPrefix,
339}
340
341impl XmlRegister {
342    pub fn national(self) -> bool {
343        matches!(self, XmlRegister::NText | XmlRegister::NNamespace | XmlRegister::NPrefix)
344    }
345}
346
347codec_enum!(Markup { JsonGenerate(g) = 0, XmlGenerate(g) = 1, XmlParse(p) = 2, JsonParse(p) = 3 });
348codec_enum!(Ccsid { Unnamed = 0, CodePage = 1, Operand(o) = 2 });
349codec_enum!(Convert { Chars { justified } = 0, National = 1, Float(precision) = 2, Fixed { integers } = 3, Refused(abend) = 4 });
350codec_enum!(Marker { Byte(b) = 0, Condition(c) = 1, Refused(abend) = 2 });
351codec_struct!(JsonGenerate { from, subscripts, nodes, name, receiver, encoding, count, code, on_exception, not_on_exception } check json_valid);
352codec_struct!(JsonNode { offset, moved, len, kind, name, occurs, indicator, null, value });
353codec_enum!(JsonValue { Object { members, eligible } = 0, Leaf(leaf) = 1 });
354codec_struct!(JsonLeaf { suppress, boolean, convert });
355codec_struct!(XmlGenerate {
356    receiver, encoding, namespace, prefix, declaration, from, subscripts, nodes, suppressing, count, code, on_exception, not_on_exception,
357} check xml_valid);
358codec_struct!(XmlNode { offset, moved, len, kind, name, occurs, value });
359codec_enum!(XmlValue { Element { members } = 0, Members { members } = 1, Leaf { form, suppress, convert } = 2 });
360codec_enum!(XmlForm { Attribute = 0, Element = 1, Content = 2 });
361codec_struct!(XmlParse { document, encoding, national, procedure, event, code, information, code_value, on_exception, not_on_exception });
362codec_struct!(JsonParse { source, encoding, into, subscripts, nodes, ignore_all, code, status, on_exception, not_on_exception } check parse_valid);
363codec_struct!(ParseNode { offset, moved, len, kind, name, occurs, ignored, indicator, null, value });
364codec_enum!(Named { Exactly(name) = 0, Folded(name) = 1, Omitted = 2 });
365codec_enum!(ParseValue { Object { members } = 0, Leaf(leaf) = 1, Suppressed = 2 });
366codec_struct!(ParseLeaf { boolean, text, number });
367codec_enum!(NumberInto { Float(plan) = 0, Store(store) = 1, Edited(plan) = 2, Digits = 3, Incompatible = 4 });
368codec_struct!(Indicator { place, flag });
369codec_enum!(Flag { Set { on, off } = 0, Literals { on, off } = 1 });
370codec_enum!(SetTo { Nothing = 0, Move { place, value, plan } = 1, Refused(abend) = 2 });
371codec_enum!(XmlRegister { Text = 0, NText = 1, Namespace = 2, NNamespace = 3, Prefix = 4, NPrefix = 5 });
372
373/// A tree with a root, whose every member comes after the node that holds it, so no walk loops.
374fn tree_valid<'n>(nodes: usize, members: impl Iterator<Item = (usize, &'n [u32])>) -> Result<(), String> {
375    if nodes == 0 {
376        return Err("a markup tree with no root".into());
377    }
378    for (k, list) in members {
379        if let Some(&m) = list.iter().find(|&&m| m as usize <= k || m as usize >= nodes) {
380            return Err(format!("markup node {k} holds node {m} of {nodes}"));
381        }
382    }
383    Ok(())
384}
385
386fn json_valid(g: &JsonGenerate) -> Result<(), String> {
387    tree_valid(g.nodes.len(), g.nodes.iter().enumerate().filter_map(|(k, n)| match &n.value {
388        JsonValue::Object { members, .. } => Some((k, &members[..])),
389        JsonValue::Leaf(_) => None,
390    }))
391}
392
393fn xml_valid(g: &XmlGenerate) -> Result<(), String> {
394    tree_valid(g.nodes.len(), g.nodes.iter().enumerate().filter_map(|(k, n)| match &n.value {
395        XmlValue::Element { members } | XmlValue::Members { members } => Some((k, &members[..])),
396        XmlValue::Leaf { .. } => None,
397    }))
398}
399
400fn parse_valid(p: &JsonParse) -> Result<(), String> {
401    tree_valid(p.nodes.len(), p.nodes.iter().enumerate().filter_map(|(k, n)| match &n.value {
402        ParseValue::Object { members } => Some((k, &members[..])),
403        _ => None,
404    }))
405}