substrait-validator 0.1.4

Substrait validator
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
// SPDX-License-Identifier: Apache-2.0

//! This module provides a human-readable export format based on HTML.

use crate::output::comment;
use crate::output::diagnostic;
use crate::output::parse_result;
use crate::output::path;
use crate::output::tree;
use crate::output::type_system::data;
use crate::output::type_system::data::class::ParameterInfo;
use base64::{engine::general_purpose, Engine as _};

const HEADER1: &str = concat!(
    r#"
<!DOCTYPE html>
<!-- Generated by Substrait validator; https://substrait.io/ -->
<html>
<head>
<style>
/*
Copy of license text for icon font
==================================

"#,
    include_str!("fa-solid-900.woff2.LICENSE.txt"),
    r#"
*/
@font-face {
    font-family: 'Font Awesome 6 Free';
    font-style: normal;
    font-weight: 900;
    font-display: block;
    src: url("data:font/woff2;base64,"#
);

const FONT_AWESOME: &[u8] = include_bytes!("fa-solid-900.woff2");

const HEADER2: &str = concat!(
    r#"") format("woff2");
}
"#,
    include_str!("style.css"),
    r#"
</style>
</head>
<body>
"#
);

const FOOTER: &str = r#"
<script>
function open_cards(element) {
    if (element.tagName.toLowerCase() === 'details') {
        element.open = true;
    }
    if (element.parentElement !== null) {
        open_cards(element.parentElement);
    }
}
function select() {
    var hash = location.hash.substring(1);
    if (hash) {
        var details = document.getElementById(hash);
        if (details) {
            open_cards(details);
        }
    }
}
window.addEventListener('hashchange', select);
select();
</script>
</body>
</html>
"#;

/// All the error levels for nodes that we have different formatting for in
/// the context of HTML output.
#[derive(PartialOrd, Ord, PartialEq, Eq)]
enum Level {
    /// Subtree is valid.
    Ok,

    /// There are descendent nodes with warnings.
    ChildWarning,

    /// The current node has warnings.
    Warning,

    /// There are descendent nodes with errors.
    ChildError,

    /// The current node has errors.
    Error,
}

impl From<diagnostic::Level> for Level {
    fn from(level: diagnostic::Level) -> Self {
        match level {
            diagnostic::Level::Info => Level::Ok,
            diagnostic::Level::Warning => Level::Warning,
            diagnostic::Level::Error => Level::Error,
        }
    }
}

impl Level {
    pub fn class(&self) -> &'static str {
        match self {
            Level::Ok => "ok",
            Level::ChildWarning => "warn_child",
            Level::Warning => "warn_here",
            Level::ChildError => "error_child",
            Level::Error => "error_here",
        }
    }
}

/// Escapes HTML text or parameter values using character entities.
fn html_escape<S: AsRef<str>>(text: S) -> String {
    let text = text.as_ref();
    let mut result = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => result += "&amp;",
            '<' => result += "&lt;",
            '>' => result += "&gt;",
            '"' => result += "&quot;",
            '\'' => result += "&apos;",
            c => result.push(c),
        }
    }
    result
}

/// Encodes part of an URL using percent escape sequences.
fn url_encode<S: AsRef<str>>(text: S) -> String {
    use std::fmt::Write;
    let text = text.as_ref();
    let mut result = String::with_capacity(text.len());
    for c in text.chars() {
        if c.is_alphanumeric() || "-._~!$&'()*+,;=:@".contains(c) {
            result.push(c);
        } else {
            let mut buf = [0; 4];
            for b in c.encode_utf8(&mut buf).as_bytes() {
                write!(result, "%{:02x}", *b).unwrap();
            }
        }
    }
    result
}

/// Encodes a node path using () instead of [] and {}. Such paths should be
/// still be unambiguous, and should be more readable than their
/// percent-encoded variants (only round parentheses are unreserved in URLs).
fn path_encode<S: AsRef<str>>(text: S) -> String {
    text.as_ref()
        .chars()
        .map(|c| match c {
            '[' => '(',
            ']' => ')',
            '<' => '(',
            '>' => ')',
            c => c,
        })
        .collect()
}

/// Formats a path to a node or diagnostic.
fn format_path(path: &path::PathBuf, index: Option<usize>) -> String {
    if let Some(index) = index {
        format!("{path}:{index}")
    } else {
        path.to_string()
    }
}

/// Formats the parameters of an <a> tag to a node or diagnostic.
fn format_reference_parameters(path: &path::PathBuf, index: Option<usize>) -> String {
    let path = format_path(path, index);
    format!(
        "href=\"#{}\" title=\"{}\"",
        html_escape(url_encode(path_encode(&path))),
        html_escape(&path)
    )
}

/// Formats a link to a node (index = None)
/// or diagnostic (index = Some(index of NodeData entry)).
fn format_reference<S: std::fmt::Display>(
    text: S,
    path: &path::PathBuf,
    index: Option<usize>,
) -> String {
    format!("<a {}>{text}</a>", format_reference_parameters(path, index))
}

/// Formats an anchor/permalink tag for a node (index = None)
/// or diagnostic (index = Some(index of NodeData entry)).
fn format_anchor(path: &path::PathBuf, index: Option<usize>) -> String {
    format!(
        "<a {} class=\"anchor\"></a>",
        format_reference_parameters(path, index)
    )
}

/// Formats the id parameter for a div/details tag for a node (index = None)
/// or diagnostic (index = Some(index of NodeData entry)).
fn format_id(path: &path::PathBuf, index: Option<usize>) -> String {
    format!(
        "id=\"{}\"",
        html_escape(url_encode(path_encode(format_path(path, index))))
    )
}

/// Creates a span with the given class name. The text is HTML-escaped.
fn format_span<S: std::fmt::Display>(class: &'static str, text: S) -> String {
    format!(
        "<span class=\"{class}\">{}</span>",
        html_escape(text.to_string())
    )
}

/// Creates a span with the given class name.
fn format_span_html<S: std::fmt::Display>(class: &'static str, html: S) -> String {
    format!("<span class=\"{class}\">{}</span>", html)
}

/// Formats a diagnostic message box. path should be the node that the
/// diagnostic is defined in, and index should be its index within Node::data.
/// with_id specifies whether the HTML id parameter should be included.
fn format_diagnostic(
    diag: &diagnostic::Diagnostic,
    path: &path::PathBuf,
    index: usize,
    with_id: bool,
    with_path: bool,
) -> String {
    let cause = format_span(
        "cause",
        if with_path {
            diag.to_string()
        } else {
            format!("{:#}", diag)
        },
    );
    let cause = if &diag.path == path {
        cause
    } else {
        format_reference(cause, &diag.path, None)
    };
    let id = if with_id {
        let mut id = format_id(path, Some(index));
        id.push(' ');
        id
    } else {
        String::new()
    };
    let anchor = format_anchor(path, Some(index));

    let class = match diag.adjusted_level {
        diagnostic::Level::Info => "diag_info",
        diagnostic::Level::Warning => "diag_warn",
        diagnostic::Level::Error => "diag_error",
    };

    format!("<div {id}class=\"card {class}\">\n{cause}\n{anchor}\n</div>")
}

/// Format a flattened list of diagnostic cards.
fn format_diagnostics(path: &path::Path, node: &tree::Node) -> (Vec<String>, diagnostic::Level) {
    let mut html = vec![];
    let mut level = diagnostic::Level::Info;
    for (index, data) in node.data.iter().enumerate() {
        match data {
            tree::NodeData::Child(child) => {
                let (sub_html, sub_level) =
                    format_diagnostics(&path.with(child.path_element.clone()), &child.node);
                html.extend(sub_html);
                level = std::cmp::max(level, sub_level);
            }
            tree::NodeData::Diagnostic(diag) => {
                html.push(format_diagnostic(
                    diag,
                    &path.to_path_buf(),
                    index,
                    false,
                    true,
                ));
                level = std::cmp::max(level, diag.adjusted_level);
            }
            _ => {}
        }
    }
    (html, level)
}

/// Formats a comment span.
fn format_comment_span(span: &comment::Span) -> String {
    match &span.link {
        None => html_escape(&span.text),
        Some(comment::Link::Path(path)) => format_reference(html_escape(&span.text), path, None),
        Some(comment::Link::Url(url)) => format!(
            "<a href=\"{}\">{}</a>",
            html_escape(url),
            html_escape(&span.text)
        ),
    }
}

/// Formats a comment using HTML markup.
fn format_comment(comment: &comment::Comment) -> String {
    let mut result = String::new();
    let mut p_open = false;
    for element in comment.elements().iter() {
        match element {
            comment::Element::Span(span) => {
                if !p_open {
                    result += "<p>";
                    p_open = true;
                }
                result += &format_comment_span(span);
            }
            comment::Element::NewLine => {
                if p_open {
                    result += "</p>";
                    p_open = false;
                }
            }
            comment::Element::ListOpen => {
                if p_open {
                    result += "</p>";
                    p_open = false;
                }
                result += "<ul><li>";
            }
            comment::Element::ListNext => {
                if p_open {
                    result += "</p>";
                    p_open = false;
                }
                result += "</li><li>";
            }
            comment::Element::ListClose => {
                if p_open {
                    result += "</p>";
                    p_open = false;
                }
                result += "</li></ul>";
            }
        }
    }
    if p_open {
        result += "</p>";
    }
    result
}

/// Formats a brief comment using HTML markup.
fn format_brief(brief: &comment::Brief) -> String {
    let mut result = String::new();
    for span in brief.spans().iter() {
        result += &format_comment_span(span);
    }
    result
}

// Format the relation trees.
fn format_relation_tree(
    path: &path::Path,
    node: &tree::Node,
    index: &mut usize,
    is_root: bool,
    in_expression: bool,
) -> Vec<String> {
    let mut html = vec![];

    let text = node
        .brief
        .as_ref()
        .map(format_brief)
        .unwrap_or_else(|| String::from("unknown"));
    let is_relation = matches!(node.class, tree::Class::Relation);
    let is_expression = matches!(node.class, tree::Class::Expression);

    if is_relation {
        if is_root {
            html.push("<details class=\"relation_tree\">".to_string());
            html.push(format!(
                "<summary>Query/relation graph #{}</summary>",
                *index
            ));
            html.push("<ul class=\"tree\"><li><span class=\"root\">Sink</span><ul>".to_string());
        };
        html.push(format!(
            "<li><span class=\"{}\">{text} ({})</span>",
            if in_expression {
                "subquery"
            } else {
                "data_source"
            },
            format_reference("link", &path.to_path_buf(), None)
        ));
    }

    let mut has_children = false;
    for data in node.data.iter() {
        if let tree::NodeData::Child(child) = data {
            let sub_html = format_relation_tree(
                &path.with(child.path_element.clone()),
                &child.node,
                index,
                is_root && !is_relation,
                (in_expression && !is_relation) || is_expression,
            );
            if !sub_html.is_empty() {
                if is_relation && !has_children {
                    html.push("<ul>".to_string());
                }
                has_children = true;
                html.extend(sub_html);
            }
        }
    }

    if is_relation {
        if has_children {
            html.push("</ul>".to_string());
        }
        html.push("</li>".to_string());
        if is_root {
            html.push("</ul></li></ul>".to_string());
            html.push("</details>".to_string());
            *index += 1;
        }
    }

    html
}

// Format a data type parameter card.
fn format_data_type_card(content: &str) -> String {
    format!(
        "<div class=\"card data_type\">\n{}\n</div>",
        html_escape(content),
    )
}

// Format a data type.
fn format_data_type(prefix: &str, data_type: &data::Type) -> Vec<String> {
    let mut html = vec![];

    if data_type.parameters().is_empty() {
        html.push(format_data_type_card(&format!("{prefix}: {:#}", data_type)));
    } else {
        html.push("<details class=\"data_type\">\n<summary>".to_string());
        html.push(format!("{prefix}: {}", html_escape(data_type.to_string())));
        html.push("</summary>".to_string());
        for (index, parameter) in data_type.parameters().iter().enumerate() {
            let name = data_type
                .class()
                .parameter_name(index)
                .unwrap_or_else(|| "?".to_string());
            html.push(format_data_type_card(&format!(
                ".{}: {}",
                parameter.name.as_ref().unwrap_or(&name),
                parameter
                    .value
                    .as_ref()
                    .map(ToString::to_string)
                    .unwrap_or_else(|| String::from("null"))
            )));
        }
        html.push("</details>".to_string());
    }

    html
}

// Format the node tree.
fn format_node_tree(
    path: &path::Path,
    unknown_subtree: bool,
    node: &tree::Node,
) -> (Vec<String>, Level) {
    // Get the HTML ID for this card.
    let pathbuf = path.to_path_buf();
    let id = format_id(&pathbuf, None);

    // Format the card header.
    let brief = if let Some(brief) = &node.brief {
        format_span_html("brief", format_brief(brief))
    } else {
        String::from("")
    };
    let value = match &node.node_type {
        tree::NodeType::ProtoMessage(proto_type) => {
            format!("{brief} {}", format_span("type", proto_type))
        }
        tree::NodeType::ProtoPrimitive(proto_type, data) => {
            format!(
                "= {} {brief} {}",
                format_span("value", data),
                format_span("type", proto_type)
            )
        }
        tree::NodeType::ProtoMissingOneOf => "?".to_string(),
        tree::NodeType::NodeReference(num, target) => format_reference(
            format!(
                "= {} {brief} {}",
                format_span("value", num),
                format_span("type", "uint32, reference")
            ),
            &target.path,
            None,
        ),
        tree::NodeType::ResolvedUri(uri) => {
            format!(
                "= {} {brief} {}",
                format_span("value", uri),
                format_span("type", "string, resolved as URI")
            )
        }
        tree::NodeType::YamlMap => format!("{brief} {}", format_span("type", "YAML map")),
        tree::NodeType::YamlArray => format!("{brief} {}", format_span("type", "YAML array")),
        tree::NodeType::YamlPrimitive(data) => format!("= {}{brief}", format_span("value", data)),
        tree::NodeType::AstNode => format!("{brief} {}", format_span("type", "AST node")),
    };
    let header = format!(
        "{} {value} {}",
        format_span("field", path.end_to_string()),
        format_anchor(&pathbuf, None)
    );

    // If the node doesn't have any additional data associated with it, output
    // a normal <div> rather than a <details> card.
    if node.data.is_empty() && node.summary.is_none() {
        let class = if unknown_subtree { "unknown" } else { "ok" };
        return (
            vec![format!("<div {id} class=\"card {class}\">{header}</div>")],
            Level::Ok,
        );
    }

    // Gather child nodes here. The first entry of the html Vec is reserved for
    // the open tags, which we don't have all the information for just yet.
    let mut html = vec![String::new()];
    let mut level = Level::Ok;

    // Add the summary.
    if let Some(ref summary) = node.summary {
        html.push(format_comment(summary));
    }

    // Iterate over node data here, recursively entering children.
    for (index, data) in node.data.iter().enumerate() {
        match data {
            tree::NodeData::Child(child) => {
                let (sub_html, sub_level) = format_node_tree(
                    &path.with(child.path_element.clone()),
                    !child.recognized,
                    &child.node,
                );
                html.extend(sub_html);
                level = std::cmp::max(level, sub_level);
            }
            tree::NodeData::Diagnostic(diag) => {
                html.push(format_diagnostic(
                    diag,
                    &pathbuf,
                    index,
                    true,
                    diag.path != pathbuf,
                ));
                level = std::cmp::max(level, diag.adjusted_level.into());
            }
            tree::NodeData::DataType(data_type) => {
                html.extend(format_data_type(
                    if matches!(node.class, tree::Class::Relation) {
                        "Schema"
                    } else {
                        "Data type"
                    },
                    data_type,
                ));
            }
            tree::NodeData::Comment(comment) => {
                html.push("<div class=\"card comment\">\n".to_string());
                html.push(format_comment(comment));
                html.push("\n</div>".to_string());
            }
        }
    }

    // Add the surrounding <details> tags now that we have the error level
    // information we needed.
    let class = if unknown_subtree {
        "unknown"
    } else {
        level.class()
    };
    html[0] = format!("<details {id} class=\"{class}\">\n<summary>\n{header}\n</summary>");
    html.push("</details>".to_string());

    // Determine the minimum error level for the parent.
    let level = match level {
        Level::Error => Level::ChildError,
        Level::Warning => Level::ChildWarning,
        x => x,
    };

    (html, level)
}

/// Export the tree in HTML format, with as many details as possible, and as
/// human-readable as possible. Purely intended for debugging.
pub fn export<T: std::io::Write>(
    out: &mut T,
    root_name: &'static str,
    result: &parse_result::ParseResult,
) -> std::io::Result<()> {
    let path = path::Path::Root(root_name);

    // Generate and write header.
    let font_awesome_b64 = general_purpose::STANDARD.encode(FONT_AWESOME);
    write!(out, "{HEADER1}{}{HEADER2}", font_awesome_b64)?;

    // Emit metadata.
    writeln!(out, "<details class=\"relation_tree\" open=\"true\">")?;
    writeln!(out, "<summary>Metadata</summary>")?;
    writeln!(
        out,
        "<p>Checked using validator version {}</p>",
        crate::version()
    )?;
    writeln!(
        out,
        "<p>Checked against Substrait version {}</p>",
        crate::substrait_version()
    )?;
    writeln!(out, "</details>")?;

    // Emit the node graph.
    writeln!(out, "<details class=\"relation_tree\" open=\"true\">")?;
    writeln!(out, "<summary>Relation graphs</summary>")?;
    writeln!(
        out,
        "<div class=\"note\">Note: data flows upwards in these graphs.</div>"
    )?;
    let mut index = 0;
    for s in format_relation_tree(&path, &result.root, &mut index, true, false) {
        writeln!(out, "{s}")?;
    }
    writeln!(out, "</details>")?;

    // Emit diagnostics summary.
    let (diag_html, level) = format_diagnostics(&path, &result.root);
    let validity_class = match level {
        diagnostic::Level::Info => "valid",
        diagnostic::Level::Warning => "maybe_valid",
        diagnostic::Level::Error => "invalid",
    };
    let validity_summary = match level {
        diagnostic::Level::Info => "This plan is <span class=\"valid\">VALID</span>",
        diagnostic::Level::Warning => "The validator was unable to determine validity",
        diagnostic::Level::Error => "This plan is <span class=\"invalid\">INVALID</span>",
    };
    writeln!(
        out,
        "<details class=\"{}\" open=\"true\">",
        Level::from(level).class()
    )?;
    writeln!(
        out,
        "<summary class=\"{validity_class}\">{validity_summary}</summary>"
    )?;
    if diag_html.is_empty() {
        writeln!(
            out,
            "<div class=\"note\">No diagnostics were reported.</div>"
        )?;
    } else {
        for s in diag_html {
            writeln!(out, "{s}")?;
        }
    }
    writeln!(out, "</details>")?;

    // Emit protobuf-level raw node tree.
    for s in format_node_tree(&path, false, &result.root).0 {
        writeln!(out, "{s}")?;
    }

    write!(out, "{FOOTER}")
}