Markdown parser fork with extended syntax for personal use.
at hack 103 lines 2.6 kB view raw
1//! abstract syntax trees: [unist][]. 2//! 3//! [unist]: https://github.com/syntax-tree/unist 4 5use alloc::fmt; 6 7/// One place in a source file. 8#[derive(Clone, Eq, PartialEq)] 9#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 10pub struct Point { 11 /// 1-indexed integer representing a line in a source file. 12 pub line: usize, 13 /// 1-indexed integer representing a column in a source file. 14 pub column: usize, 15 /// 0-indexed integer representing a character in a source file. 16 pub offset: usize, 17} 18 19impl Point { 20 #[must_use] 21 pub fn new(line: usize, column: usize, offset: usize) -> Point { 22 Point { 23 line, 24 column, 25 offset, 26 } 27 } 28} 29 30impl fmt::Debug for Point { 31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 32 write!(f, "{}:{} ({})", self.line, self.column, self.offset) 33 } 34} 35 36/// Location of a node in a source file. 37#[derive(Clone, Eq, PartialEq)] 38#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 39pub struct Position { 40 /// Represents the place of the first character of the parsed source region. 41 pub start: Point, 42 /// Represents the place of the first character after the parsed source 43 /// region, whether it exists or not. 44 pub end: Point, 45} 46 47impl Position { 48 #[must_use] 49 pub fn new( 50 start_line: usize, 51 start_column: usize, 52 start_offset: usize, 53 end_line: usize, 54 end_column: usize, 55 end_offset: usize, 56 ) -> Position { 57 Position { 58 start: Point::new(start_line, start_column, start_offset), 59 end: Point::new(end_line, end_column, end_offset), 60 } 61 } 62} 63 64impl fmt::Debug for Position { 65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 66 write!( 67 f, 68 "{}:{}-{}:{} ({}-{})", 69 self.start.line, 70 self.start.column, 71 self.end.line, 72 self.end.column, 73 self.start.offset, 74 self.end.offset 75 ) 76 } 77} 78 79#[cfg(test)] 80mod tests { 81 use super::*; 82 use alloc::format; 83 84 #[test] 85 fn point() { 86 let point = Point::new(1, 1, 0); 87 assert_eq!( 88 format!("{:?}", point), 89 "1:1 (0)", 90 "should support `Debug` on unist points" 91 ); 92 } 93 94 #[test] 95 fn position() { 96 let position = Position::new(1, 1, 0, 1, 3, 2); 97 assert_eq!( 98 format!("{:?}", position), 99 "1:1-1:3 (0-2)", 100 "should support `Debug` on unist positions" 101 ); 102 } 103}