shape/
location.rs

1use apollo_compiler::parser::FileId;
2use std::fmt::Display;
3use std::ops::Range;
4use std::sync::Arc;
5
6/// Some identifier of the source text that a [`Location`] refers to.
7/// The content only matters to the caller, who will need to be able to use this to give
8/// diagnostics to users.
9///
10/// This might be a file name, reference to an editor panel, or a unique identifier for a
11/// sub-slice of a larger text. It could also be the string content itself.
12#[derive(Clone, Debug, Hash, PartialEq, Eq)]
13pub enum SourceId {
14    /// A key into [`apollo_compiler::Schema`] sources.
15    GraphQL(FileId),
16    /// An arbitrary source identifier from a consumer.
17    Other(Arc<str>),
18}
19
20impl SourceId {
21    pub fn new(id: impl Into<Arc<str>>) -> Self {
22        Self::Other(id.into())
23    }
24
25    /// Create a new [`Location`] within this source text.
26    #[must_use]
27    pub fn location(&self, span: Range<usize>) -> Location {
28        Location {
29            source_id: self.clone(),
30            span,
31        }
32    }
33}
34
35/// The location of a [`crate::Shape`] within the source text that produced it.
36#[derive(Clone, Debug, Hash, PartialEq, Eq)]
37pub struct Location {
38    /// Some identifier correlating `span` to a string the caller controls
39    pub source_id: SourceId,
40    /// The character offset within the source text. 0-indexed, end is exclusive.
41    pub span: Range<usize>,
42}
43
44/// Used to track the location of a thing.
45#[derive(Clone, Debug, Hash, PartialEq, Eq)]
46pub struct Located<T> {
47    pub value: T,
48    pub locations: Vec<Location>,
49}
50
51impl<T> Located<T> {
52    pub fn new(value: T, locations: impl IntoIterator<Item = Location>) -> Self {
53        Self {
54            value,
55            locations: locations.into_iter().collect(),
56        }
57    }
58}
59
60impl<T: Display> Display for Located<T> {
61    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62        write!(f, "{}", self.value)
63    }
64}