Skip to main content

datafusion_common/
spans.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::cmp::{self, Ordering};
6use std::fmt;
7use std::hash::{Hash, Hasher};
8
9/// Represents a location, determined by a line and a column number, in the
10/// original SQL query.
11#[derive(Eq, PartialEq, Hash, Clone, Copy, Ord, PartialOrd)]
12pub struct Location {
13    /// Line number, starting from 1.
14    ///
15    /// Note: Line 0 is used for empty spans
16    pub line: u64,
17    /// Line column, starting from 1.
18    ///
19    /// Note: Column 0 is used for empty spans
20    pub column: u64,
21}
22
23impl fmt::Debug for Location {
24    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
25        write!(f, "Location({},{})", self.line, self.column)
26    }
27}
28
29#[cfg(feature = "sql")]
30impl From<sqlparser::tokenizer::Location> for Location {
31    fn from(value: sqlparser::tokenizer::Location) -> Self {
32        Self {
33            line: value.line,
34            column: value.column,
35        }
36    }
37}
38
39/// Represents an interval of characters in the original SQL query.
40#[derive(Eq, PartialEq, Hash, Clone, PartialOrd, Ord, Copy)]
41pub struct Span {
42    pub start: Location,
43    pub end: Location,
44}
45
46impl fmt::Debug for Span {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        write!(f, "Span({:?}..{:?})", self.start, self.end)
49    }
50}
51
52impl Span {
53    /// Creates a new [`Span`] from a start and an end [`Location`].
54    pub fn new(start: Location, end: Location) -> Self {
55        Self { start, end }
56    }
57
58    /// Convert a [`Span`](sqlparser::tokenizer::Span) from the parser, into a
59    /// DataFusion [`Span`]. If the input span is empty (line 0 column 0, to
60    /// line 0 column 0), then [`None`] is returned.
61    #[cfg(feature = "sql")]
62    pub fn try_from_sqlparser_span(span: sqlparser::tokenizer::Span) -> Option<Span> {
63        if span == sqlparser::tokenizer::Span::empty() {
64            None
65        } else {
66            Some(Span {
67                start: span.start.into(),
68                end: span.end.into(),
69            })
70        }
71    }
72
73    /// Returns the smallest Span that contains both `self` and `other`
74    ///
75    /// # Examples
76    /// ```
77    /// # use sqlparser::tokenizer::{Span, Location};
78    /// // line 1, column1 -> line 2, column 5
79    /// let span1 = Span::new(Location::new(1, 1), Location::new(2, 5));
80    /// // line 2, column 3 -> line 3, column 7
81    /// let span2 = Span::new(Location::new(2, 3), Location::new(3, 7));
82    /// // Union of the two is the min/max of the two spans
83    /// // line 1, column 1 -> line 3, column 7
84    /// let union = span1.union(&span2);
85    /// assert_eq!(union, Span::new(Location::new(1, 1), Location::new(3, 7)));
86    /// ```
87    pub fn union(&self, other: &Span) -> Span {
88        Span {
89            start: cmp::min(self.start, other.start),
90            end: cmp::max(self.end, other.end),
91        }
92    }
93
94    /// Same as [Span::union] for `Option<Span>`.
95    ///
96    /// If `other` is `None`, `self` is returned.
97    pub fn union_opt(&self, other: &Option<Span>) -> Span {
98        match other {
99            Some(other) => self.union(other),
100            None => *self,
101        }
102    }
103
104    /// Return the [Span::union] of all spans in the iterator.
105    ///
106    /// If the iterator is empty, [`None`] is returned.
107    ///
108    /// # Example
109    /// ```
110    /// # use sqlparser::tokenizer::{Span, Location};
111    /// let spans = vec![
112    ///     Span::new(Location::new(1, 1), Location::new(2, 5)),
113    ///     Span::new(Location::new(2, 3), Location::new(3, 7)),
114    ///     Span::new(Location::new(3, 1), Location::new(4, 2)),
115    /// ];
116    /// // line 1, column 1 -> line 4, column 2
117    /// assert_eq!(
118    ///   Span::union_iter(spans),
119    ///   Span::new(Location::new(1, 1), Location::new(4, 2))
120    /// );
121    pub fn union_iter<I: IntoIterator<Item = Span>>(iter: I) -> Option<Span> {
122        iter.into_iter().reduce(|acc, item| acc.union(&item))
123    }
124}
125
126/// A collection of [`Span`], meant to be used as a field of entities whose
127/// location in the original SQL query is desired to be tracked. Sometimes an
128/// entity can have multiple spans. e.g. if you want to track the position of
129/// the column a that comes from SELECT 1 AS a UNION ALL SELECT 2 AS a you'll
130/// need two spans.
131#[derive(Debug, Clone)]
132// Store the first [`Span`] on the stack because that is by far the most common
133// case. More will spill onto the heap.
134pub struct Spans(pub Vec<Span>);
135
136impl Spans {
137    /// Creates a new empty [`Spans`] with no [`Span`].
138    pub fn new() -> Self {
139        Spans(Vec::new())
140    }
141
142    /// Returns the first [`Span`], if any. This is useful when you know that
143    /// there's gonna be only one [`Span`] at most.
144    pub fn first(&self) -> Option<Span> {
145        self.0.first().copied()
146    }
147
148    /// Returns a slice of the [`Span`]s.
149    pub fn get_spans(&self) -> &[Span] {
150        &self.0
151    }
152
153    /// Adds a [`Span`] to the collection.
154    pub fn add_span(&mut self, span: Span) {
155        self.0.push(span);
156    }
157
158    /// Iterates over the [`Span`]s.
159    pub fn iter(&self) -> impl Iterator<Item = &Span> {
160        self.0.iter()
161    }
162}
163
164impl Default for Spans {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170// Since [`Spans`] will be used as a field in other structs, we don't want it to
171// interfere with the equality and ordering of the entities themselves, since
172// this is just diagnostics information for the end user.
173impl PartialEq for Spans {
174    fn eq(&self, _other: &Self) -> bool {
175        true
176    }
177}
178
179// Since [`Spans`] will be used as a field in other structs, we don't want it to
180// interfere with the equality and ordering of the entities themselves, since
181// this is just diagnostics information for the end user.
182impl Eq for Spans {}
183
184// Since [`Spans`] will be used as a field in other structs, we don't want it to
185// interfere with the equality and ordering of the entities themselves, since
186// this is just diagnostics information for the end user.
187impl PartialOrd for Spans {
188    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
189        Some(self.cmp(other))
190    }
191}
192
193// Since [`Spans`] will be used as a field in other structs, we don't want it to
194// interfere with the equality and ordering of the entities themselves, since
195// this is just diagnostics information for the end user.
196impl Ord for Spans {
197    fn cmp(&self, _other: &Self) -> Ordering {
198        Ordering::Equal
199    }
200}
201
202// Since [`Spans`] will be used as a field in other structs, we don't want it to
203// interfere with the equality and ordering of the entities themselves, since
204// this is just diagnostics information for the end user.
205impl Hash for Spans {
206    fn hash<H: Hasher>(&self, _state: &mut H) {}
207}