revive_solc_json_interface/standard_json/output/error/
source_location.rs

1//! The `solc --standard-json` output error source location.
2
3use std::collections::BTreeMap;
4
5use serde::Deserialize;
6use serde::Serialize;
7
8/// The `solc --standard-json` output error source location.
9#[derive(Debug, Serialize, Deserialize, Clone)]
10#[serde(rename_all = "camelCase")]
11pub struct SourceLocation {
12    /// The source file path.
13    pub file: String,
14    /// The start location.
15    pub start: isize,
16    /// The end location.
17    pub end: isize,
18}
19
20impl SourceLocation {
21    /// A shortcut constructor.
22    pub fn new(file: String) -> Self {
23        Self {
24            file,
25            start: -1,
26            end: -1,
27        }
28    }
29
30    /// A shortcut constructor.
31    ///
32    /// Please note that `start` and `end` are not line and column,
33    /// but absolute char offsets in the source code file.
34    pub fn new_with_offsets(file: String, start: isize, end: isize) -> Self {
35        Self { file, start, end }
36    }
37
38    /// A shortcut constructor from a `solc` AST node.
39    pub fn try_from_ast(source: &str, id_paths: &BTreeMap<usize, &String>) -> Option<Self> {
40        let mut parts = source.split(':');
41        let start = parts
42            .next()
43            .map(|string| string.parse::<isize>())
44            .and_then(Result::ok)
45            .unwrap_or_default();
46        let length = parts
47            .next()
48            .map(|string| string.parse::<isize>())
49            .and_then(Result::ok)
50            .unwrap_or_default();
51        let path = parts
52            .next()
53            .and_then(|string| string.parse::<usize>().ok())
54            .and_then(|file_id| id_paths.get(&file_id))?;
55
56        Some(Self::new_with_offsets(
57            (*path).to_owned(),
58            start,
59            start + length,
60        ))
61    }
62}