shared/span.rs
1//! Contains the `Span` struct, which represents a span of characters in the source code.
2use serde::ser::SerializeStruct;
3use serde::{Serialize, Serializer};
4
5/// Constant to control whether to use shorthand serialisation for spans.
6///
7/// If `true`, spans will be serialised into: `"span": "157..160"`, instead of
8/// `"span": {"start": 157, "end": 160}`.
9const SHORTHAND_SPAN_SERIALISATION: bool = true;
10
11/// Represents a span of characters in the source code.
12///
13/// A `Span` contains the starting and ending indices of a span of characters in the
14/// source code. The `start` field represents the index of the first character in the
15/// span, while the `end` field represents the index of the last character in the span.
16#[derive(PartialEq, Debug, Clone)]
17pub struct Span {
18 pub start: usize,
19 pub end: usize,
20}
21
22impl Span {
23 /// Creates a new `Span` with the specified start and end positions.
24 ///
25 /// # Arguments
26 ///
27 /// * `start` - The starting position of the span.
28 /// * `end` - The ending position of the span.
29 pub fn new(start: usize, end: usize) -> Span {
30 Span { start, end }
31 }
32}
33
34/// Implements the `Serialize` trait for the `Span` struct.
35///
36/// This allows the `Span` struct to be serialized into a JSON object.
37impl Serialize for Span {
38 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
39 where
40 S: Serializer,
41 {
42 if SHORTHAND_SPAN_SERIALISATION {
43 serializer.serialize_str(&format!("{}..{}", self.start, self.end))
44 } else {
45 let mut state = serializer.serialize_struct("Span", 2)?;
46 state.serialize_field("start", &self.start)?;
47 state.serialize_field("end", &self.end)?;
48 state.end()
49 }
50 }
51}
52
53/// Trait for getting the span of a node. For enums, this is useful for getting the span
54/// of the current variant, without having to match on each variant.
55pub trait GetSpan {
56 fn span(&self) -> &Span;
57}