adoctra-core 0.0.1

Core parser and document model for the adoctra AsciiDoc toolchain
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Shared a-stage for ordinary inline text, definitions and selected pass
//! substitutions. Ordinary references retain their original source ownership.
use crate::attributes::{parts_text, push_value};
use crate::substitution_context::Evaluation;
use crate::substitution_text::Text;
use crate::{AttributePart as P, Diagnostic, Inline, Severity, Span};

#[derive(Clone)]
pub(crate) struct Reference {
    pub span: Span,
    pub name: String,
    pub missing: bool,
    /// A missing reference removed by the `drop-line` policy (its line is
    /// dropped).
    pub drops_line: bool,
}

/// Match only ordinary references. Stateful set/counter expressions have a
/// separate lifecycle and are deliberately left literal here.
pub(crate) fn reference(src: &str, at: usize) -> Option<(usize, &str, bool)> {
    let leading = src[at..].starts_with("\\{");
    let open = at + usize::from(leading);
    if src.as_bytes().get(open) != Some(&b'{') {
        return None;
    }
    let mut end = open + 1;
    for (i, ch) in src[end..].char_indices() {
        if crate::unicode_word::is_word(ch) || (i > 0 && ch == '-') {
            continue;
        }
        end += i;
        let trailing = src.as_bytes().get(end) == Some(&b'\\');
        let close = end + usize::from(trailing);
        return (end > open + 1 && src.as_bytes().get(close) == Some(&b'}')).then_some((
            close + 1,
            &src[open + 1..end],
            leading || trailing,
        ));
    }
    None
}

pub(crate) fn apply(
    text: Text,
    attrs: &mut Evaluation<'_>,
    diagnostics: &mut Vec<Diagnostic>,
) -> (Text, Vec<Reference>) {
    let policy = attrs.get("attribute-missing").unwrap_or("skip").to_owned();
    apply_with_policy(text, attrs, &policy, false, diagnostics)
}

/// Definitions and selected stages carry an enclosing physical origin: their
/// text may already have been joined, unescaped or rewritten by another stage.
pub(crate) fn parts(
    parts: &[P],
    attrs: &mut Evaluation<'_>,
    span: Span,
    policy: &str,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<P> {
    let mut text = Text::default();
    for part in parts {
        text.append_part(part, 0, span);
    }
    apply_with_policy(text, attrs, policy, false, diagnostics)
        .0
        .into_parts()
}

/// The implicit doctitle uses an explicit skip policy even if an expression
/// changes attribute-missing while this early a-stage is running.
pub(crate) fn implicit_title(
    value: &str,
    attrs: &mut Evaluation<'_>,
    span: Span,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<P> {
    let mut text = Text::default();
    text.append_part(&P::Text(value.into()), 0, span);
    apply_with_policy(text, attrs, "skip", true, diagnostics)
        .0
        .into_parts()
}

/// Ruby's `apply_header_subs` on an implicit header value (author and
/// revision metadata): attribute references with the document's
/// attribute-missing policy, set/counter expressions executing.
pub(crate) fn header_value(
    value: &str,
    attrs: &mut Evaluation<'_>,
    span: Span,
    diagnostics: &mut Vec<Diagnostic>,
) -> Vec<P> {
    let mut text = Text::default();
    text.append_part(&P::Text(value.into()), 0, span);
    let policy = attrs.get("attribute-missing").unwrap_or("skip").to_owned();
    apply_with_policy(text, attrs, &policy, false, diagnostics)
        .0
        .into_parts()
}

/// Ruby's `Document#sub_attributes` on a preprocessor string (`ifeval`
/// operands, include targets and parameter lists). The source is raw text;
/// substituted values keep the spelling Ruby stores, and set/counter
/// expressions execute. `Some(policy)` fixes attribute-missing (Ruby's
/// `attribute_missing:` option), `None` reads it when first needed.
pub(crate) fn preprocessor(
    value: &str,
    attrs: &mut Evaluation<'_>,
    span: Span,
    policy: Option<&str>,
    diagnostics: &mut Vec<Diagnostic>,
) -> String {
    let mut text = Text::default();
    text.append_part(&P::Raw(value.into()), 0, span);
    let (fixed, policy) = match policy {
        Some(policy) => (true, policy.to_owned()),
        None => (
            false,
            attrs.get("attribute-missing").unwrap_or("skip").to_owned(),
        ),
    };
    let parts = apply_with_policy(text, attrs, &policy, fixed, diagnostics)
        .0
        .into_parts();
    crate::attributes::reference_text(&parts)
}

fn apply_with_policy(
    text: Text,
    attrs: &mut Evaluation<'_>,
    policy: &str,
    fixed_policy: bool,
    diagnostics: &mut Vec<Diagnostic>,
) -> (Text, Vec<Reference>) {
    // Both ordinary references and stateful expressions need a brace pair in
    // the assembled lexical stream, possibly supplied by different fragments.
    if !text.text.contains('{') || !text.text.contains('}') {
        return (text, Vec::new());
    }
    let mut output = Text::default();
    let mut refs = Vec::new();
    let mut dropped = Vec::new();
    let mut dropped_lines = Vec::new();
    let closes: Vec<_> = text.text.match_indices('}').map(|(i, _)| i).collect();
    let mut at = 0;
    let mut copied = 0;
    let mut missing_policy = None;
    let mut undefined_policy = None;
    while at < text.text.len() {
        let stateful = attrs
            .stateful()
            .then(|| crate::substitution_context::expression(&text.text, at, &closes))
            .flatten();
        let Some((end, name, escaped)) = stateful.or_else(|| reference(&text.text, at)) else {
            at += text.text[at..].chars().next().unwrap().len_utf8();
            continue;
        };
        text.copy(copied..at, &mut output);
        if escaped {
            let literal = format!("{{{name}}}");
            text.replacement(at..end, &literal, Some(&literal), &mut output);
        } else if stateful.is_some() {
            let span = text.match_span(at..end);
            let effect = attrs.execute(name, span, &mut undefined_policy, diagnostics);
            if effect.remove_empty {
                dropped.push(output.text.len());
            }
            if effect.remove_line {
                dropped_lines.push(output.text.len());
            }
            let metadata = text.fragments[text.fragments.partition_point(|(r, _)| r.end <= at)]
                .1
                .part
                .as_ref()
                .is_some_and(P::is_boundary);
            if metadata {
                text.replacement(
                    at..end,
                    &crate::attributes::reference_text(&effect.parts),
                    None,
                    &mut output,
                );
            } else {
                refs.push(Reference {
                    span,
                    name: name.into(),
                    missing: false,
                    drops_line: false,
                });
                for part in &effect.parts {
                    output.append_part(part, refs.len(), span);
                }
            }
        } else {
            let span = text.match_span(at..end);
            let metadata = text.fragments[text.fragments.partition_point(|(r, _)| r.end <= at)]
                .1
                .part
                .as_ref()
                .is_some_and(P::is_boundary);
            let parts = attrs.value_parts(name).or_else(|| {
                crate::context::intrinsic(&name.to_lowercase())
                    .map(|value| vec![P::Raw(value.into())])
            });
            let missing = parts.is_none();
            let policy = if missing && attrs.stateful() && !fixed_policy {
                missing_policy
                    .get_or_insert_with(|| {
                        attrs.get("attribute-missing").unwrap_or("skip").to_owned()
                    })
                    .as_str()
            } else {
                policy
            };
            let removed = missing && matches!(policy, "drop" | "drop-line");
            if !metadata {
                refs.push(Reference {
                    span,
                    name: name.into(),
                    missing: missing && !removed,
                    drops_line: removed && policy == "drop-line",
                });
            }
            if removed {
                dropped.push(output.text.len());
                if policy == "drop-line" {
                    dropped_lines.push(output.text.len());
                }
            }
            if missing && matches!(policy, "warn" | "drop-line") {
                diagnostics.push(Diagnostic {
                    omitted_span: None,
                    report: crate::DiagnosticReport {
                        location: crate::DiagnosticLocation::Unlocated,
                        ..Default::default()
                    },
                    span,
                    severity: if policy == "warn" {
                        Severity::Warning
                    } else {
                        Severity::Info
                    },
                    message: format!(
                        "{} reference to missing attribute: {}",
                        if policy == "warn" {
                            "skipping"
                        } else {
                            "dropping line containing"
                        },
                        name.to_lowercase()
                    ),
                });
            }
            let parts = parts.unwrap_or_else(|| {
                if removed {
                    Vec::new()
                } else {
                    vec![P::Text(text.text[at..end].into())]
                }
            });
            if metadata {
                text.replacement(
                    at..end,
                    &crate::attributes::reference_text(&parts),
                    None,
                    &mut output,
                );
            } else {
                for part in &parts {
                    output.append_part(part, refs.len(), span);
                }
            }
        }
        copied = end;
        at = end;
    }
    if copied == 0 {
        return (text, refs);
    }
    text.copy(copied..text.text.len(), &mut output);
    if !dropped.is_empty() {
        let mut retained = Text::default();
        let mut positions = dropped.into_iter().peekable();
        let mut line_positions = dropped_lines.into_iter().peekable();
        let mut start = 0;
        let mut previous_end = None;
        for line in output.text.split('\n') {
            let end = start + line.len();
            let mut missing = false;
            while positions.peek().is_some_and(|&pos| pos <= end) {
                positions.next();
                missing = true;
            }
            let mut drop_line = false;
            while line_positions.peek().is_some_and(|&pos| pos <= end) {
                line_positions.next();
                drop_line = true;
            }
            if !drop_line && (!missing || !line.is_empty()) {
                if let Some(end) = previous_end {
                    output.copy(end..end + 1, &mut retained);
                }
                output.copy(start..end, &mut retained);
                previous_end = Some(end);
            }
            start = end + 1;
        }
        output = retained;
    }
    (output, refs)
}

/// Turn the lexical a-stage result into source edits. Empty references remain
/// addressable by editors; a deleted unresolved reference becomes Some("").
pub(crate) fn nodes(text: Text, refs: Vec<Reference>) -> Vec<Inline> {
    let mut parts = vec![Vec::new(); refs.len()];
    let mut nodes = Vec::new();
    for f in text.into_fragments() {
        let (owner, span) = (f.owner, f.span);
        let part = f.into_part();
        if owner > 0 {
            push_value(&mut parts[owner - 1], part);
        } else {
            nodes.push(match part {
                P::Text(value) => Inline::Text { value, span },
                P::Raw(value) => Inline::Raw { value, span },
                part => Inline::Substituted {
                    value: String::new(),
                    parts: vec![part],
                    span,
                },
            });
        }
    }
    for (r, mut parts) in refs.into_iter().zip(parts) {
        let value = if r.missing && !parts.is_empty() {
            None
        } else {
            Some(parts_text(&parts))
        };
        if value.is_none() || !parts.iter().any(P::is_special) {
            parts.clear();
        }
        nodes.push(Inline::AttributeRef {
            name: r.name,
            value,
            parts,
            span: r.span,
        });
    }
    nodes.sort_by_key(|n| n.span().start);
    nodes
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unmatched_attribute_stage_reuses_buffers_without_effects_or_diagnostics() {
        use crate::substitution_text::tests::{assert_reused, marked_text};
        for source in [
            "Ж🙂 & text\r\n",
            "{unfinished",
            "stray}",
            "{} {bad name}",
            "{counter:n",
        ] {
            for policy in ["skip", "warn", "drop", "drop-line"] {
                for stateful in [false, true] {
                    let attrs = crate::Attributes::new();
                    let locked = std::collections::BTreeSet::new();
                    let mut counters = std::collections::BTreeMap::new();
                    let mut evaluation = if stateful {
                        Evaluation::definition(&attrs, &locked, &mut counters, false)
                    } else {
                        Evaluation::read_only(&attrs)
                    };
                    let mut diagnostics = Vec::new();
                    assert_reused(marked_text(source), |text| {
                        let (result, refs) = apply_with_policy(
                            text,
                            &mut evaluation,
                            policy,
                            false,
                            &mut diagnostics,
                        );
                        assert!(refs.is_empty());
                        result
                    });
                    assert!(evaluation.changed_attributes().is_none());
                    assert!(counters.is_empty());
                    assert!(diagnostics.is_empty());
                }
            }
        }
    }

    #[test]
    fn matched_attributes_keep_reports_and_effects_even_without_visible_changes() {
        let attrs = crate::Attributes::new();
        let locked = std::collections::BTreeSet::new();
        let mut counters = std::collections::BTreeMap::new();
        let mut evaluation = Evaluation::definition(&attrs, &locked, &mut counters, false);
        let span = Span::in_source(crate::SourceId(7), 10, 22);
        let mut diagnostics = Vec::new();
        let mut text = Text::default();
        text.append_part(&P::Text("{counter2:".into()), 0, span);
        text.append_part(&P::Text("n}".into()), 1, span);
        let (result, refs) =
            apply_with_policy(text, &mut evaluation, "skip", false, &mut diagnostics);
        assert!(result.text.is_empty());
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].span, span);
        assert_eq!(evaluation.get("n"), Some("1"));

        let text = Text::from_parts_at(&[P::Text("{missing}".into())], span);
        let (result, refs) =
            apply_with_policy(text, &mut evaluation, "warn", true, &mut diagnostics);
        assert_eq!(result.text, "{missing}");
        assert_eq!(refs.len(), 1);
        assert!(refs[0].missing);
        assert_eq!(refs[0].span, span);
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span, span);

        let text = Text::from_parts_at(&[P::Text("\\{n}".into())], span);
        let (result, refs) =
            apply_with_policy(text, &mut evaluation, "skip", false, &mut diagnostics);
        assert_eq!(result.text, "{n}");
        assert!(refs.is_empty());
        assert_eq!(evaluation.get("n"), Some("1"));
    }
    use crate::Attributes;

    #[test]
    fn shared_stage_matches_across_parts_and_drops_the_transformed_line() {
        let mut attrs = Attributes::new();
        attrs.set_parts("name", vec![P::Raw("first\nsecond".into())]);
        let span = Span::new(12, 42);
        let mut diagnostics = Vec::new();
        let output = parts(
            &[
                P::Text("before {na".into()),
                P::Raw("me} {missing}\nafter".into()),
            ],
            &mut Evaluation::read_only(&attrs),
            span,
            "drop-line",
            &mut diagnostics,
        );
        assert_eq!(
            output,
            vec![P::Text("before ".into()), P::Raw("first\nafter".into())]
        );
        assert_eq!(diagnostics.len(), 1);
        assert_eq!(diagnostics[0].span, span);
        assert_eq!(diagnostics[0].severity, Severity::Info);
    }
}