Skip to main content

with_location/
with_location.rs

1//! Source location example.
2//!
3//! This example shows how to attach source location information to diagnostic messages
4//! for integration with ariadne and source context rendering.
5
6use quarto_error_reporting::DiagnosticMessageBuilder;
7use quarto_source_map::{SourceContext, SourceInfo};
8
9fn main() {
10    println!("=== Example 1: Error with source location ===\n");
11
12    // Create a source context
13    let mut ctx = SourceContext::new();
14    let file_id = ctx.add_file(
15        "example.qmd".to_string(),
16        Some("title: My Document\nauthor: John Doe\ndate: 2024-01-01\n".to_string()),
17    );
18
19    // Create a location (let's say there's an error in "My Document" - offsets 7 to 18)
20    let location = SourceInfo::original(file_id, 7, 18);
21
22    let error = DiagnosticMessageBuilder::error("Invalid title format")
23        .with_code("Q-1-10")
24        .with_location(location)
25        .problem("Title must be a string, not a complex object")
26        .add_detail("Title value starts at this location")
27        .add_hint("Ensure the title is a simple quoted string")
28        .build();
29
30    // Render WITHOUT context - shows offset
31    println!("Without context:");
32    println!("{}", error.to_text(None));
33
34    println!("\n---\n");
35
36    // Render WITH context - shows file path and line:column
37    println!("With context:");
38    println!("{}", error.to_text(Some(&ctx)));
39
40    println!("\n=== Example 2: Multiple locations ===\n");
41
42    let another_ctx = SourceContext::new();
43
44    // Note: This example shows the API, but without actual file content,
45    // the rendering will still show offsets. In real usage with proper
46    // SourceContext, this would show rich source snippets via ariadne.
47
48    let location2 = SourceInfo::original(quarto_source_map::FileId(0), 100, 110);
49
50    let error2 = DiagnosticMessageBuilder::error("Unclosed code block")
51        .with_code("Q-2-301")
52        .with_location(location2)
53        .problem("Code block started but never closed")
54        .add_detail("The opening ``` was found but no closing ``` before end of block")
55        .add_hint("Add a closing ``` on a new line")
56        .build();
57
58    println!("{}", error2.to_text(Some(&another_ctx)));
59
60    println!("\n=== Example 3: JSON output with location ===\n");
61
62    let json = error.to_json();
63    println!("{}", serde_json::to_string_pretty(&json).unwrap());
64}