calyx_frontend/
source_info.rs

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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use itertools::Itertools;
use std::{collections::HashMap, fmt::Display, num::NonZero, path::PathBuf};
use thiserror::Error;

type Word = u32;

/// An identifier representing a given file path
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FileId(Word);

impl Display for FileId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl FileId {
    pub fn new(id: Word) -> Self {
        Self(id)
    }
}

impl From<Word> for FileId {
    fn from(value: Word) -> Self {
        Self(value)
    }
}

/// An identifier representing a location in the Calyx source code
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PositionId(Word);

impl PositionId {
    pub fn new(id: Word) -> Self {
        Self(id)
    }
}

impl From<Word> for PositionId {
    fn from(value: Word) -> Self {
        Self(value)
    }
}

impl Display for PositionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

/// A newtype wrapping a line number
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LineNum(NonZero<Word>);

impl LineNum {
    pub fn new(line: Word) -> Self {
        Self(NonZero::new(line).expect("Line number must be non-zero"))
    }
    pub fn as_usize(&self) -> usize {
        self.0.get() as usize
    }
}

impl Display for LineNum {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Error)]
#[error("Line number cannot be zero")]
pub struct LineNumCreationError;

impl std::fmt::Debug for LineNumCreationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(self, f)
    }
}

impl TryFrom<Word> for LineNum {
    type Error = LineNumCreationError;

    fn try_from(value: Word) -> Result<Self, Self::Error> {
        if value != 0 {
            Ok(Self(NonZero::new(value).unwrap()))
        } else {
            Err(LineNumCreationError)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceInfoTable {
    /// map file ids to the file path, note that this does not contain file content
    file_map: HashMap<FileId, PathBuf>,
    /// maps position ids to their source locations.
    position_map: HashMap<PositionId, SourceLocation>,
}

impl SourceInfoTable {
    const HEADER: &str = "sourceinfo";

    /// Looks up the path of the file with the given id.
    ///
    /// # Panics
    /// Panics if the file id does not exist in the file map
    pub fn lookup_file_path(&self, file: FileId) -> &PathBuf {
        &self.file_map[&file]
    }

    /// Looks up the source location of the position with the given id.
    ///
    /// # Panics
    /// Panics if the position id does not exist in the position map
    pub fn lookup_position(&self, pos: PositionId) -> &SourceLocation {
        &self.position_map[&pos]
    }

    /// Looks up the source location of the position with the given id. If no
    /// such position exists, returns `None`
    pub fn get_position(&self, pos: PositionId) -> Option<&SourceLocation> {
        self.position_map.get(&pos)
    }

    /// Iterate over the stored file map, returning a tuple of references to the
    /// file id and the path
    pub fn iter_file_map(&self) -> impl Iterator<Item = (&FileId, &PathBuf)> {
        self.file_map.iter()
    }

    /// Iterate over the paths of all files in the file map
    pub fn iter_file_paths(&self) -> impl Iterator<Item = &PathBuf> {
        self.file_map.values()
    }

    /// Iterate over all file ids in the file map
    pub fn iter_file_ids(&self) -> impl Iterator<Item = FileId> + '_ {
        self.file_map.keys().copied()
    }

    /// Iterate over the stored position map, returning a tuple of references to
    /// the position id and the source location
    pub fn iter_position_map(
        &self,
    ) -> impl Iterator<Item = (&PositionId, &SourceLocation)> {
        self.position_map.iter()
    }

    /// Iterate over all position ids in the position map
    pub fn iter_positions(&self) -> impl Iterator<Item = PositionId> + '_ {
        self.position_map.keys().copied()
    }

    /// Iterate over the source locations in the position map
    pub fn iter_source_locations(
        &self,
    ) -> impl Iterator<Item = &SourceLocation> {
        self.position_map.values()
    }

    /// Adds a file to the file map with the given id
    pub fn add_file(&mut self, file: FileId, path: PathBuf) {
        self.file_map.insert(file, path);
    }

    /// Adds a file to the file map and generates a new file id
    /// for it. If you want to add a file with a specific id, use
    /// [`SourceInfoTable::add_file`]
    pub fn push_file(&mut self, path: PathBuf) -> FileId {
        // find the largest file id in the map
        let max = self.iter_file_ids().max().unwrap_or(0.into());
        let new = FileId(max.0 + 1);

        self.add_file(new, path);
        new
    }
    pub fn add_position(
        &mut self,
        pos: PositionId,
        file: FileId,
        line: LineNum,
    ) {
        self.position_map
            .insert(pos, SourceLocation::new(file, line));
    }

    /// Adds a position to the position map and generates a new position id
    /// for it. If you want to add a position with a specific id, use
    /// [`SourceInfoTable::add_position`]
    pub fn push_position(&mut self, file: FileId, line: LineNum) -> PositionId {
        // find the largest position id in the map
        let max = self.iter_positions().max().unwrap_or(0.into());
        let new = PositionId(max.0 + 1);

        self.add_position(new, file, line);
        new
    }

    /// Creates a new empty source info table
    pub fn new_empty() -> Self {
        Self {
            file_map: HashMap::new(),
            position_map: HashMap::new(),
        }
    }

    pub fn new<F, P>(files: F, positions: P) -> SourceInfoResult<Self>
    where
        F: IntoIterator<Item = (FileId, PathBuf)>,
        P: IntoIterator<Item = (PositionId, FileId, LineNum)>,
    {
        let files = files.into_iter();
        let positions = positions.into_iter();

        let mut file_map = HashMap::with_capacity(
            files.size_hint().1.unwrap_or(files.size_hint().0),
        );
        let mut position_map = HashMap::with_capacity(
            positions.size_hint().1.unwrap_or(positions.size_hint().0),
        );

        for (file, path) in files {
            if let Some(first_path) = file_map.insert(file, path) {
                let inserted_path = &file_map[&file];
                if &first_path != inserted_path {
                    return Err(SourceInfoTableError::DuplicateFiles {
                        id1: file,
                        path1: first_path,
                        path2: inserted_path.clone(),
                    });
                }
            }
        }

        for (pos, file, line) in positions {
            let source = SourceLocation::new(file, line);
            if let Some(first_pos) = position_map.insert(pos, source) {
                let inserted_position = &position_map[&pos];
                if inserted_position != &first_pos {
                    return Err(SourceInfoTableError::DuplicatePositions {
                        pos,
                        s1: first_pos,
                        s2: position_map[&pos].clone(),
                    });
                }
            }
        }

        Ok(SourceInfoTable {
            file_map,
            position_map,
        })
    }

    pub fn serialize<W: std::io::Write>(
        &self,
        mut f: W,
    ) -> Result<(), std::io::Error> {
        writeln!(f, "{} #{{", Self::HEADER)?;

        // write file table
        writeln!(f, "FILES")?;
        for (file, path) in self.file_map.iter().sorted_by_key(|(k, _)| **k) {
            writeln!(f, "{file}: {}", path.display())?;
        }

        // write the position table
        writeln!(f, "POSITIONS")?;
        for (position, SourceLocation { line, file }) in
            self.position_map.iter().sorted_by_key(|(k, _)| **k)
        {
            writeln!(f, "{position}: {file} {line}")?;
        }

        writeln!(f, "}}#")
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceLocation {
    pub file: FileId,
    pub line: LineNum,
}

impl SourceLocation {
    pub fn new(file: FileId, line: LineNum) -> Self {
        Self { line, file }
    }
}
#[derive(Error)]
pub enum SourceInfoTableError {
    #[error("Duplicate positions found in the metadata table. Position {pos} is defined multiple times:
    1. file {}, line {}
    2. file {}, line {}\n", s1.file, s1.line, s2.file, s2.line)]
    DuplicatePositions {
        pos: PositionId,
        s1: SourceLocation,
        s2: SourceLocation,
    },

    #[error("Duplicate files found in the metadata table. File id {id1} is defined multiple times:
         1. {path1}
         2. {path2}\n")]
    DuplicateFiles {
        id1: FileId,
        path1: PathBuf,
        path2: PathBuf,
    },
}

impl std::fmt::Debug for SourceInfoTableError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        std::fmt::Display::fmt(&self, f)
    }
}

pub type SourceInfoResult<T> = Result<T, SourceInfoTableError>;

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use crate::{
        parser::CalyxParser,
        source_info::{FileId, LineNum, PositionId, SourceInfoTableError},
    };

    use super::SourceInfoTable;

    #[test]
    fn test_parse_metadata() {
        let input_str = r#"sourceinfo #{
    FILES
        0: test.calyx
        1: test2.calyx
        2: test3.calyx
    POSITIONS
        0: 0 5
        1: 0 1
        2: 0 2
}#"#;

        let metadata = CalyxParser::parse_source_info_table(input_str)
            .unwrap()
            .unwrap();
        let file = metadata.lookup_file_path(1.into());
        assert_eq!(file, &PathBuf::from("test2.calyx"));

        let pos = metadata.lookup_position(1.into());
        assert_eq!(pos.file, 0.into());
        assert_eq!(pos.line, LineNum::new(1));
    }

    #[test]
    fn test_duplicate_file_parse() {
        let input_str = r#"sourceinfo #{
            FILES
                0: test.calyx
                0: test2.calyx
                2: test3.calyx
            POSITIONS
                0: 0 5
                1: 0 1
                2: 0 2
        }#"#;
        let metadata = CalyxParser::parse_source_info_table(input_str).unwrap();

        assert!(metadata.is_err());
        let err = metadata.unwrap_err();
        assert!(matches!(&err, SourceInfoTableError::DuplicateFiles { .. }));
        if let SourceInfoTableError::DuplicateFiles { id1, .. } = &err {
            assert_eq!(id1, &FileId::new(0))
        } else {
            unreachable!()
        }
    }

    #[test]
    fn test_duplicate_position_parse() {
        let input_str = r#"sourceinfo #{
            FILES
                0: test.calyx
                1: test2.calyx
                2: test3.calyx
            POSITIONS
                0: 0 5
                0: 0 1
                2: 0 2
        }#"#;
        let metadata = CalyxParser::parse_source_info_table(input_str).unwrap();

        assert!(metadata.is_err());
        let err = metadata.unwrap_err();
        assert!(matches!(
            &err,
            SourceInfoTableError::DuplicatePositions { .. }
        ));
        if let SourceInfoTableError::DuplicatePositions { pos, .. } = err {
            assert_eq!(pos, PositionId::new(0))
        } else {
            unreachable!()
        }
    }

    #[test]
    fn test_serialize() {
        let mut metadata = SourceInfoTable::new_empty();
        metadata.add_file(0.into(), "test.calyx".into());
        metadata.add_file(1.into(), "test2.calyx".into());
        metadata.add_file(2.into(), "test3.calyx".into());

        metadata.add_position(0.into(), 0.into(), LineNum::new(1));
        metadata.add_position(1.into(), 1.into(), LineNum::new(2));
        metadata.add_position(150.into(), 2.into(), LineNum::new(148));

        let mut serialized_str = vec![];
        metadata.serialize(&mut serialized_str).unwrap();
        let serialized_str = String::from_utf8(serialized_str).unwrap();

        let parsed_metadata =
            CalyxParser::parse_source_info_table(&serialized_str)
                .unwrap()
                .unwrap();

        assert_eq!(metadata, parsed_metadata)
    }
}