1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
use crate::Path;
use log::debug;
use std::collections::BTreeMap;
use yaml_rust::{
    parser::{Event as YamlEvent, MarkedEventReceiver},
    scanner::{Marker, TScalarStyle, TokenType},
};

/// Line and column position of content in a file
#[derive(Debug, PartialEq)]
pub struct Position {
    pub line: usize,
    pub col: usize,
}

impl Into<Position> for Marker {
    fn into(self) -> Position {
        let (line, col) = (self.line(), self.col());
        Position { line, col }
    }
}

#[derive(Debug, PartialEq, Clone)]
enum Event {
    Scalar(String, TScalarStyle, Option<TokenType>),
    SequenceStart,
    SequenceEnd,
    MappingStart,
    MappingEnd,
}

#[doc(hidden)]
impl Default for Positions {
    fn default() -> Self {
        Self {
            pos: 0,
            events: Vec::new(),
            index: BTreeMap::new(),
        }
    }
}

/// A table of [`Position`](struct.Position.html) information
pub struct Positions {
    pos: usize,
    events: Vec<(Event, Marker)>,
    index: BTreeMap<String, Position>,
}

impl Positions {
    /// Gets a yaml field's position within a document given its JSON Pointer path
    ///
    /// JSON Pointer defines a string syntax for identifying a specific value
    /// within a JavaScript Object Notation (JSON) document.
    ///
    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
    pub fn get<P>(
        &self,
        ptr: P,
    ) -> Option<&Position>
    where
        P: AsRef<str>,
    {
        self.index.get(ptr.as_ref())
    }

    fn next(&mut self) -> Option<(Event, Position)> {
        self.events.clone().get(self.pos).map(|event| {
            self.pos += 1;
            (event.clone().0, event.1.into())
        })
    }

    /// Returns an iterator over positions
    pub fn iter(&self) -> impl IntoIterator<Item = (&String, &Position)> {
        self.index.iter()
    }

    pub(crate) fn collect(
        &mut self,
        path: &Path,
    ) {
        if let Some((ev, _)) = self.next() {
            match ev {
                Event::SequenceStart => {
                    self.collect_seq(0, path);
                    self.collect(path);
                }
                Event::MappingStart => {
                    self.collect_map(path);
                    self.collect(path);
                }
                other => debug!("unhandled {:?} in collect", other),
            }
        }
    }

    fn collect_seq(
        &mut self,
        index: usize,
        path: &Path,
    ) {
        if let Some((ev, pos)) = self.next() {
            match ev {
                Event::SequenceEnd => (),
                Event::Scalar(_, _, _) => {
                    self.index.insert(
                        format!(
                            "{}",
                            Path::Seq {
                                parent: &path,
                                index: index
                            }
                        ),
                        pos,
                    );
                    self.collect_seq(index + 1, &path);
                }
                Event::MappingStart => {
                    self.collect_map(&Path::Seq {
                        parent: &path,
                        index,
                    });
                    self.collect_seq(index + 1, &path);
                }
                other => debug!("unhandled {:?} in collect_seq", other),
            }
        }
    }

    fn collect_map(
        &mut self,
        path: &Path,
    ) {
        if let Some((ev, pos)) = self.next() {
            match ev {
                Event::MappingEnd => (),
                Event::Scalar(key, _, _) => {
                    let this_path = Path::Map {
                        parent: &path,
                        key: &key,
                    };
                    self.index.insert(format!("{}", this_path), pos);
                    match self.next() {
                        Some((Event::MappingStart, _)) => {
                            self.collect_map(&this_path);
                        }
                        Some((Event::SequenceStart, _)) => {
                            self.collect_seq(0, &this_path);
                        }
                        _ => (),
                    }
                    self.collect_map(&path);
                }
                other => debug!("unhandled {:?} in collect_map", other),
            }
        }
    }
}

#[doc(hidden)]
impl MarkedEventReceiver for Positions {
    fn on_event(
        &mut self,
        event: YamlEvent,
        marker: Marker,
    ) {
        let event = match event {
            YamlEvent::Nothing
            | YamlEvent::StreamStart
            | YamlEvent::StreamEnd
            | YamlEvent::DocumentStart
            | YamlEvent::DocumentEnd
            | YamlEvent::Alias(_) /*come back to Alias later*/=> return,
            YamlEvent::Scalar(value, style, _, tag) => {
                Event::Scalar(value, style, tag)
            }
            YamlEvent::SequenceStart(_) => {
                Event::SequenceStart
            }
            YamlEvent::SequenceEnd => Event::SequenceEnd,
            YamlEvent::MappingStart(_) => {
                Event::MappingStart
            }
            YamlEvent::MappingEnd => Event::MappingEnd,
        };
        self.events.push((event, marker));
    }
}