pliron 0.15.0

Programming Languages Intermediate RepresentatiON
Documentation
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Source location for different IR entities

use std::{fmt::Debug, path::PathBuf};

use combine::{
    Parser, between, optional,
    parser::char::{spaces, string},
    stream::position::SourcePosition,
    token,
};
use rustc_hash::FxHashSet;

use crate::{
    attribute::AttrObj,
    context::Context,
    impl_printable_for_display,
    irfmt::{
        parsers::{delimited_list_parser, quoted_string_parser, spaced},
        printers::list_with_sep,
    },
    parsable::Parsable,
    printable::{self, Printable},
    uniqued_any::{self, UniquedKey},
};

/// Where is the source program?
#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
pub enum Source {
    /// Program being read from a file.
    File(UniquedKey<PathBuf>),
    /// Program is in memory.
    // TODO: Maybe have an `Rc` to the buffer?
    InMemory,
}

impl Source {
    /// Get a [Source] handle to the source specified by `path`.
    pub fn new_from_file(ctx: &mut Context, path: PathBuf) -> Self {
        Self::File(uniqued_any::save(ctx, path))
    }
}

impl Printable for Source {
    fn fmt(
        &self,
        ctx: &Context,
        _state: &printable::State,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Source::File(path_key) => {
                write!(f, "\"{}\"", uniqued_any::get(ctx, *path_key).display())
            }
            Source::InMemory => write!(f, "<in-memory>"),
        }
    }
}

impl Parsable for Source {
    type Arg = ();

    type Parsed = Self;

    fn parse<'a>(
        state_stream: &mut crate::parsable::StateStream<'a>,
        _arg: Self::Arg,
    ) -> crate::parsable::ParseResult<'a, Self::Parsed> {
        enum Source {
            Filename(String),
            InMemory,
        }

        let mut parser = quoted_string_parser()
            .map(Source::Filename)
            .or(string("<in-memory>").map(|_| Source::InMemory));

        parser
            .parse_stream(state_stream)
            .map(|source| match source {
                Source::Filename(s) => {
                    Self::new_from_file(state_stream.state.ctx, PathBuf::from(s))
                }
                Source::InMemory => Self::InMemory,
            })
            .into_result()
    }
}

/// Represents a (combination of) program source locations.
/// This captures more or less the functionality of MLIR's
/// [BuiltinLocationAttributes](https://mlir.llvm.org/docs/Dialects/Builtin/#location-attributes).
/// For simplicity, unlike in MLIR, [Location] is not extensible.
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Location {
    /// A [Source] along with a [position](SourcePosition) within it.
    /// This is same as MLIR's [FileLineColLoc](https://mlir.llvm.org/docs/Dialects/Builtin/#filelinecolloc).
    SrcPos { src: Source, pos: SourcePosition },
    /// A collection of other source locations.
    /// This is same as MLIR's [FusedLoc](https://mlir.llvm.org/docs/Dialects/Builtin/#fusedloc).
    Fused {
        metadata: Option<AttrObj>,
        locations: Vec<Location>,
    },
    /// Location with a name.
    /// See [NameLoc](https://mlir.llvm.org/docs/Dialects/Builtin/#nameloc).
    Named {
        name: String,
        child_loc: Box<Location>,
    },
    /// Connects the location of a callee with the location of the caller.
    /// See [CallSiteLoc](https://mlir.llvm.org/docs/Dialects/Builtin/#callsiteloc).
    CallSite {
        callee: Box<Location>,
        caller: Box<Location>,
    },
    /// Location unknown.
    /// See [UnknownLoc](https://mlir.llvm.org/docs/Dialects/Builtin/#unknownloc).
    Unknown,
}

impl Location {
    /// If the location is from exactly one source, get that source.
    pub fn source(&self) -> Option<Source> {
        let sources = self.sources();
        if sources.len() == 1 {
            sources.first().cloned()
        } else {
            None
        }
    }

    /// Get all sources that this location is associated with.
    pub fn sources(&self) -> Vec<Source> {
        let mut res = FxHashSet::default();
        fn sources(loc: &Location, res: &mut FxHashSet<Source>) {
            match loc {
                Location::SrcPos { src, pos: _ } => {
                    res.insert(*src);
                }
                Location::Fused {
                    metadata: _,
                    locations,
                } => {
                    for loc in locations {
                        sources(loc, res);
                    }
                }
                Location::Named { name: _, child_loc } => {
                    sources(child_loc, res);
                }
                Location::CallSite { callee, caller } => {
                    sources(callee, res);
                    sources(caller, res);
                }
                Location::Unknown => (),
            }
        }
        sources(self, &mut res);
        res.into_iter().collect()
    }

    /// Is this unknown?
    pub fn is_unknown(&self) -> bool {
        matches!(self, Self::Unknown)
    }
}

impl Printable for Location {
    fn fmt(
        &self,
        ctx: &Context,
        _state: &printable::State,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::fmt::Result {
        match self {
            Self::SrcPos { src, pos } => {
                write!(f, "{}: {}", src.disp(ctx), pos)
            }
            Self::Fused {
                metadata,
                locations,
            } => {
                write!(f, "fused")?;
                if let Some(metadata) = metadata {
                    write!(f, "<{}>", metadata.disp(ctx))?;
                }
                write!(
                    f,
                    "[{}]",
                    list_with_sep(locations, printable::ListSeparator::CharSpace(',')).disp(ctx),
                )
            }
            Self::Named { name, child_loc } => {
                write!(f, "name: \"{}\", loc: ({})", name, child_loc.disp(ctx))
            }
            Self::CallSite { callee, caller } => {
                write!(f, "callsite({} at {})", callee.disp(ctx), caller.disp(ctx))
            }
            Self::Unknown => write!(f, "?"),
        }
    }
}

impl Parsable for SourcePosition {
    type Arg = ();

    type Parsed = Self;

    fn parse<'a>(
        state_stream: &mut crate::parsable::StateStream<'a>,
        _arg: Self::Arg,
    ) -> crate::parsable::ParseResult<'a, Self::Parsed> {
        (
            string("line").skip(spaced(token(':'))),
            i32::parser(()).skip(spaced(token(','))),
            string("column").skip(spaced(token(':'))),
            i32::parser(()),
        )
            .parse_stream(state_stream)
            .map(|(_, line, _, column)| SourcePosition { line, column })
            .into_result()
    }
}

impl_printable_for_display!(SourcePosition);

impl Parsable for Location {
    type Arg = ();

    type Parsed = Self;

    fn parse<'a>(
        state_stream: &mut crate::parsable::StateStream<'a>,
        _arg: Self::Arg,
    ) -> crate::parsable::ParseResult<'a, Self::Parsed> {
        let src_pos_parser = (
            Source::parser(()).skip(spaced(token(':'))),
            SourcePosition::parser(()),
        )
            .map(|(src, pos)| Location::SrcPos { src, pos });

        let fused_parser = string("fused").skip(spaces()).with(
            (
                optional(between(token('<'), token('>'), spaced(AttrObj::parser(())))),
                delimited_list_parser('[', ']', ',', Location::parser(())),
            )
                .map(|(metadata, locations)| Location::Fused {
                    metadata,
                    locations,
                }),
        );

        let named_parser = (
            string("name").skip(spaced(token(':'))),
            quoted_string_parser().skip(spaced(token(','))),
            string("loc").skip(spaced(token(':'))),
            between(token('('), token(')'), Location::parser(())),
        )
            .map(|(_, name, _, child_loc)| Location::Named {
                name,
                child_loc: Box::new(child_loc),
            });

        let callsite_parser = string("callsite")
            .with(between(
                spaced(token('(')),
                spaced(token(')')),
                (
                    Location::parser(()).skip(spaced(string("at"))),
                    Location::parser(()),
                ),
            ))
            .map(|(callee, caller)| Location::CallSite {
                callee: Box::new(callee),
                caller: Box::new(caller),
            });

        let unknown_parser = token('?').map(|_| Location::Unknown);

        let mut parser = src_pos_parser
            .or(fused_parser)
            .or(named_parser)
            .or(callsite_parser)
            .or(unknown_parser);

        parser.parse_stream(state_stream).into_result()
    }
}

/// Any object that has an associated location.
pub trait Located {
    fn loc(&self) -> Location;
    fn set_loc(&mut self, loc: Location);
}

#[cfg(test)]
mod tests {

    use combine::ParseError;

    use expect_test::expect;

    use crate::builtin::attributes::StringAttr;

    use crate::input_err;
    use crate::{
        location::Source,
        parsable::{self, state_stream_from_iterator},
    };

    use super::*;

    fn parse_location(input: &str, ctx: &mut Context) -> Location {
        let state_stream =
            state_stream_from_iterator(input.chars(), parsable::State::new(ctx, Source::InMemory));

        let res = match Location::parser(()).parse(state_stream) {
            Ok(loc) => Ok(loc.0),
            Err(err) => {
                let loc = Location::SrcPos {
                    src: Source::InMemory,
                    pos: err.position(),
                };
                input_err!(loc, "Failed to parse location: {}", err)
            }
        };

        match res {
            Ok(loc) => loc,
            Err(e) => {
                panic!("{}", e.disp(ctx))
            }
        }
    }

    fn print_location(loc: &Location, ctx: &Context) -> String {
        format!("{}", loc.disp(ctx))
    }

    #[test]
    fn test_print_and_parse_srcpos_location() {
        let mut ctx = Context::default();
        let path = PathBuf::from("foo.mlir");
        let src = Source::new_from_file(&mut ctx, path.clone());
        let pos = SourcePosition {
            line: 42,
            column: 7,
        };
        let loc = Location::SrcPos { src, pos };

        let printed = print_location(&loc, &ctx);
        expect![[r#""foo.mlir": line: 42, column: 7"#]].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, loc);
    }

    #[test]
    fn test_print_and_parse_inmemory_srcpos_location() {
        let mut ctx = Context::default();
        let src = Source::InMemory;
        let pos = SourcePosition { line: 1, column: 2 };
        let loc = Location::SrcPos { src, pos };

        let printed = print_location(&loc, &ctx);
        expect![[r#"<in-memory>: line: 1, column: 2"#]].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, loc);
    }

    #[test]
    fn test_print_and_parse_fused_location() {
        let mut ctx = Context::default();
        let src = Source::InMemory;
        let pos = SourcePosition { line: 3, column: 4 };
        let loc1 = Location::SrcPos { src, pos };
        let loc2 = Location::Unknown;
        let fused = Location::Fused {
            metadata: None,
            locations: vec![loc1.clone(), loc2.clone()],
        };

        let printed = print_location(&fused, &ctx);
        expect![[r#"fused[<in-memory>: line: 3, column: 4, ?]"#]].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, fused);
    }

    #[test]
    fn test_print_and_parse_named_location() {
        let mut ctx = Context::default();
        let child = Location::Unknown;
        let named = Location::Named {
            name: "foo".to_string(),
            child_loc: Box::new(child.clone()),
        };

        let printed = print_location(&named, &ctx);
        expect![[r#"name: "foo", loc: (?)"#]].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, named);
    }

    #[test]
    fn test_print_and_parse_callsite_location() {
        let mut ctx = Context::default();
        let callee = Location::Unknown;
        let caller = Location::Unknown;
        let callsite = Location::CallSite {
            callee: Box::new(callee.clone()),
            caller: Box::new(caller.clone()),
        };

        let printed = print_location(&callsite, &ctx);
        expect![r#"callsite(? at ?)"#].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, callsite);
    }

    #[test]
    fn test_print_and_parse_unknown_location() {
        let mut ctx = Context::default();
        let loc = Location::Unknown;

        let printed = print_location(&loc, &ctx);
        expect![r#"?"#].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, loc);
    }

    #[test]
    fn test_fused_with_metadata_print_and_parse() {
        let mut ctx = Context::default();

        let attr = StringAttr::new("testattr".to_string());
        let loc = Location::Fused {
            metadata: Some(Box::new(attr)),
            locations: vec![Location::Unknown],
        };

        let printed = print_location(&loc, &ctx);
        expect![[r#"fused<builtin.string "testattr">[?]"#]].assert_eq(&printed);

        let parsed = parse_location(&printed, &mut ctx);
        assert_eq!(parsed, loc);
    }
}