diagprint 0.8.1

A Rust diagnostics lifecycle framework for structured diagnostics, rendering, remediation, CI, editors, and telemetry.
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
use super::Renderer;
use crate::{Diagnostic, ExportPolicy, Label, LabelKind, Severity};
use serde_json::{Map, Value, json};
use std::{collections::BTreeMap, fs, io, path::Path};

/// Renders diagnostics as SARIF 2.1.0.
///
/// A single [`struct@Diagnostic`] becomes one SARIF result.
///
/// For source locations:
///
/// - the first primary label becomes the result's main location;
/// - if there is no primary label, the first available label is used;
/// - all remaining labels become `relatedLocations`.
///
/// SARIF regions use exclusive `endColumn` semantics.
///
/// Existing [`Renderer`] behavior preserves source paths exactly as supplied.
/// Use [`SarifRenderer::render_many_with_policy`] when an explicit external
/// privacy policy is required.
#[derive(Debug, Default, Clone, Copy)]
pub struct SarifRenderer;

impl SarifRenderer {
    const SCHEMA: &'static str = "https://json.schemastore.org/sarif-2.1.0.json";

    fn serialization_fallback() -> String {
        r#"{
  "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
  "version": "2.1.0",
  "runs": [
    {
      "tool": {
        "driver": {
          "name": "diagprint"
        }
      },
      "results": [
        {
          "level": "error",
          "message": {
            "text": "diagprint SARIF serialization failed"
          }
        }
      ]
    }
  ]
}"#
        .to_owned()
    }

    /// Attempts to render multiple diagnostics into one complete SARIF
    /// document.
    ///
    /// This preserves the historical path and text behavior.
    pub fn try_render_many<'a>(
        &self,
        diagnostics: impl IntoIterator<Item = &'a Diagnostic>,
    ) -> serde_json::Result<String> {
        self.try_render_many_internal(diagnostics, None)
    }

    /// Renders multiple diagnostics into one complete SARIF document.
    ///
    /// Serialization failures produce a minimal valid SARIF error document
    /// rather than panicking. Use [`SarifRenderer::try_render_many`] when the
    /// caller needs the serialization error itself.
    pub fn render_many<'a>(&self, diagnostics: impl IntoIterator<Item = &'a Diagnostic>) -> String {
        self.try_render_many(diagnostics)
            .unwrap_or_else(|_| Self::serialization_fallback())
    }

    /// Attempts to render multiple diagnostics into one complete SARIF
    /// document using an explicit external-export policy.
    pub fn try_render_many_with_policy<'a>(
        &self,
        diagnostics: impl IntoIterator<Item = &'a Diagnostic>,
        policy: &ExportPolicy,
    ) -> serde_json::Result<String> {
        self.try_render_many_internal(diagnostics, Some(policy))
    }

    /// Renders multiple diagnostics into one complete SARIF document using an
    /// explicit external-export policy.
    ///
    /// Serialization failures produce a minimal valid SARIF error document
    /// rather than panicking. Use
    /// [`SarifRenderer::try_render_many_with_policy`] when the caller needs the
    /// serialization error itself.
    pub fn render_many_with_policy<'a>(
        &self,
        diagnostics: impl IntoIterator<Item = &'a Diagnostic>,
        policy: &ExportPolicy,
    ) -> String {
        self.try_render_many_with_policy(diagnostics, policy)
            .unwrap_or_else(|_| Self::serialization_fallback())
    }

    fn try_render_many_internal<'a>(
        &self,
        diagnostics: impl IntoIterator<Item = &'a Diagnostic>,
        policy: Option<&ExportPolicy>,
    ) -> serde_json::Result<String> {
        let diagnostics: Vec<&Diagnostic> = diagnostics.into_iter().collect();

        let mut rule_sources: BTreeMap<String, &Diagnostic> = BTreeMap::new();

        for &diagnostic in &diagnostics {
            let rule_id = Self::rule_id(diagnostic);

            rule_sources.entry(rule_id).or_insert(diagnostic);
        }

        let rule_indices: BTreeMap<String, usize> = rule_sources
            .keys()
            .enumerate()
            .map(|(index, rule_id)| (rule_id.clone(), index))
            .collect();

        let rules: Vec<Value> = rule_sources
            .iter()
            .map(|(rule_id, diagnostic)| Self::rule_descriptor(rule_id, diagnostic, policy))
            .collect();

        let results: Vec<Value> = diagnostics
            .iter()
            .map(|diagnostic| Self::result(diagnostic, &rule_indices, policy))
            .collect();

        let log = json!({
            "$schema": Self::SCHEMA,
            "version": "2.1.0",
            "runs": [
                {
                    "tool": {
                        "driver": {
                            "name": "diagprint",
                            "semanticVersion": env!(
                                "CARGO_PKG_VERSION"
                            ),
                            "informationUri": env!(
                                "CARGO_PKG_REPOSITORY"
                            ),
                            "rules": rules
                        }
                    },
                    "results": results
                }
            ]
        });

        serde_json::to_string_pretty(&log)
    }

    /// Writes one complete SARIF document.
    ///
    /// Unlike `Reporter`'s normal file output, this overwrites the destination
    /// instead of appending independent rendered documents.
    pub fn write_many<'a>(
        &self,
        path: impl AsRef<Path>,
        diagnostics: impl IntoIterator<Item = &'a Diagnostic>,
    ) -> io::Result<()> {
        let rendered = self
            .try_render_many(diagnostics)
            .map_err(io::Error::other)?;

        fs::write(path, rendered)
    }

    /// Writes one complete policy-controlled SARIF document.
    pub fn write_many_with_policy<'a>(
        &self,
        path: impl AsRef<Path>,
        diagnostics: impl IntoIterator<Item = &'a Diagnostic>,
        policy: &ExportPolicy,
    ) -> io::Result<()> {
        let rendered = self
            .try_render_many_with_policy(diagnostics, policy)
            .map_err(io::Error::other)?;

        fs::write(path, rendered)
    }

    fn rule_id(diagnostic: &Diagnostic) -> String {
        if let Some(code) = diagnostic.code.as_deref().filter(|code| !code.is_empty()) {
            return code.to_owned();
        }

        format!(
            "diagprint/uncoded/{}",
            Self::severity_slug(diagnostic.severity)
        )
    }

    fn severity_slug(severity: Severity) -> &'static str {
        match severity {
            Severity::Trace => "trace",
            Severity::Debug => "debug",
            Severity::Info => "info",
            Severity::Warning => "warning",
            Severity::Error => "error",
            Severity::Fatal => "fatal",
        }
    }

    fn level(severity: Severity) -> &'static str {
        match severity {
            Severity::Trace | Severity::Debug => "none",

            Severity::Info => "note",

            Severity::Warning => "warning",

            Severity::Error | Severity::Fatal => "error",
        }
    }

    fn apply_text(value: &str, policy: Option<&ExportPolicy>) -> String {
        match policy {
            Some(policy) => policy.apply_text(value),

            None => value.to_owned(),
        }
    }

    fn rule_descriptor(
        rule_id: &str,
        diagnostic: &Diagnostic,
        policy: Option<&ExportPolicy>,
    ) -> Value {
        let mut rule = Map::new();

        rule.insert("id".into(), json!(rule_id));

        rule.insert(
            "shortDescription".into(),
            json!({
                "text":
                    Self::apply_text(
                        &diagnostic.message,
                        policy,
                    )
            }),
        );

        rule.insert(
            "defaultConfiguration".into(),
            json!({
                "level":
                    Self::level(
                        diagnostic.severity
                    )
            }),
        );

        if let Some(help) = diagnostic.help.as_deref().filter(|help| !help.is_empty()) {
            rule.insert(
                "help".into(),
                json!({
                    "text":
                        Self::apply_text(
                            help,
                            policy,
                        )
                }),
            );
        }

        Value::Object(rule)
    }

    fn result(
        diagnostic: &Diagnostic,
        rule_indices: &BTreeMap<String, usize>,
        policy: Option<&ExportPolicy>,
    ) -> Value {
        let rule_id = Self::rule_id(diagnostic);

        let rule_index = rule_indices.get(&rule_id).copied();

        let mut result = Map::new();

        result.insert("ruleId".into(), json!(rule_id));

        if let Some(rule_index) = rule_index {
            result.insert("ruleIndex".into(), json!(rule_index));
        }

        result.insert("level".into(), json!(Self::level(diagnostic.severity)));

        result.insert(
            "message".into(),
            json!({
                "text":
                    Self::result_message(
                        diagnostic,
                        policy,
                    )
            }),
        );

        if let Some(primary_index) = Self::primary_label_index(diagnostic) {
            let primary = &diagnostic.labels[primary_index];

            result.insert(
                "locations".into(),
                Value::Array(vec![Self::location(primary, None, policy)]),
            );

            let mut related = Vec::new();

            for (index, label) in diagnostic.labels.iter().enumerate() {
                if index == primary_index {
                    continue;
                }

                let id = related.len() + 1;

                related.push(Self::location(label, Some(id), policy));
            }

            if !related.is_empty() {
                result.insert("relatedLocations".into(), Value::Array(related));
            }
        }

        Value::Object(result)
    }

    fn primary_label_index(diagnostic: &Diagnostic) -> Option<usize> {
        diagnostic
            .labels
            .iter()
            .position(|label| label.kind == LabelKind::Primary)
            .or((!diagnostic.labels.is_empty()).then_some(0))
    }

    fn location(label: &Label, id: Option<usize>, policy: Option<&ExportPolicy>) -> Value {
        let mut region = Map::new();

        region.insert("startLine".into(), json!(label.location.line.max(1)));

        if let Some(column) = label.location.column {
            let column = column.max(1);

            region.insert("startColumn".into(), json!(column));

            if let Some(length) = label.length {
                let length = u32::try_from(length).unwrap_or(u32::MAX);

                let end_column = column.saturating_add(length);

                region.insert("endColumn".into(), json!(end_column));
            }
        }

        let mut physical_location = Map::new();

        let exported_path = match policy {
            Some(policy) => policy.apply_path(&label.location.file),

            None => Some(label.location.file.clone()),
        };

        if let Some(file) = exported_path {
            physical_location.insert(
                "artifactLocation".into(),
                json!({
                    "uri": file
                }),
            );
        }

        physical_location.insert("region".into(), Value::Object(region));

        let mut location = Map::new();

        if let Some(id) = id {
            location.insert("id".into(), json!(id));
        }

        location.insert("physicalLocation".into(), Value::Object(physical_location));

        if let Some(message) = label
            .message
            .as_deref()
            .filter(|message| !message.is_empty())
        {
            location.insert(
                "message".into(),
                json!({
                    "text":
                        Self::apply_text(
                            message,
                            policy,
                        )
                }),
            );
        }

        if let Some(revision) = label.location.revision {
            location.insert(
                "properties".into(),
                json!({
                    "diagprintSourceRevision":
                        revision.get()
                }),
            );
        }

        Value::Object(location)
    }

    fn result_message(diagnostic: &Diagnostic, policy: Option<&ExportPolicy>) -> String {
        let mut message = diagnostic.message.clone();

        for note in &diagnostic.notes {
            message.push_str("\n\nNote: ");

            message.push_str(note);
        }

        if let Some(help) = &diagnostic.help {
            message.push_str("\n\nHelp: ");

            message.push_str(help);
        }

        if let Some(cause) = &diagnostic.cause {
            for cause in cause.iter() {
                message.push_str("\n\nCaused by: ");

                message.push_str(&cause.message);
            }
        }

        Self::apply_text(&message, policy)
    }
}

impl Renderer for SarifRenderer {
    fn render(&self, diagnostic: &Diagnostic) -> String {
        self.render_many([diagnostic])
    }
}