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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Printer and parser for [outlined](OutlinedAttr) attributes.
//! Outlined attributes are printed in a separate section of the
//! IR, after the top level operation is printed.

use std::{borrow::Borrow, hash::Hash};

use combine::{Parser, between, optional, parser::char::spaces, token};
use rustc_hash::FxHashMap;

use crate::{
    attribute::{AttrObj, Attribute, AttributeDict, attr_cast, attr_impls},
    basic_block::BasicBlock,
    builtin::attr_interfaces::{OutlinedAttr, PrintOnceAttr},
    context::{Context, Ptr},
    dict_key,
    identifier::Identifier,
    input_err, input_error,
    location::{Located, Location},
    operation::Operation,
    parsable::{Parsable, StateStream},
    printable::{self, Printable},
    result::Result,
    utils::vec_exns::VecExtns,
};

use super::parsers::{delimited_list_parser, location, spaced, zero_or_more_parser};

/// An item (operation or block) that has something to record in the outlined section.
enum OutlinedItem {
    Op(Ptr<Operation>),
    Block(Ptr<BasicBlock>),
}

// Implement `Hash`, `PartialEq`, `Eq` for `Box<dyn PrintOnceAttr>`
// so that we can use it as a key in `print_once_attrs map`.
struct PrintOnceAttrWrapper(Box<dyn PrintOnceAttr>);

impl std::hash::Hash for PrintOnceAttrWrapper {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash_attr().hash(state);
    }
}

impl PartialEq for PrintOnceAttrWrapper {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_attr(&*other.0)
    }
}

impl Eq for PrintOnceAttrWrapper {}

// To enable looking up `PrintOnceAttrWrapper` in the map using a `&dyn PrintOnceAttr`.
impl Borrow<dyn PrintOnceAttr> for PrintOnceAttrWrapper {
    fn borrow(&self) -> &dyn PrintOnceAttr {
        &*self.0
    }
}

// To enable looking up `PrintOnceAttrWrapper` in the map using a `&dyn PrintOnceAttr`.
impl Hash for dyn PrintOnceAttr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.hash_attr().hash(state);
    }
}

// To enable looking up `PrintOnceAttrWrapper` in the map using a `&dyn PrintOnceAttr`.
impl PartialEq for dyn PrintOnceAttr {
    fn eq(&self, other: &Self) -> bool {
        self.eq_attr(other)
    }
}

impl Eq for dyn PrintOnceAttr {}

#[derive(Default)]
struct OutlinePrintState {
    /// Items (operations or blocks) that have some outline item to be printed.
    outlined_items: Vec<OutlinedItem>,
    /// [PrintOnceAttr]s, mapped to their outindex.
    print_once_attrs: FxHashMap<PrintOnceAttrWrapper, usize>,
}

dict_key!(OUTLINED_STATE, "outlined_state");

/// An [Operation] was just printed, and we now print a future reference to the
/// outlined attributes (if any) or location (if any) that will be printed later.
pub(crate) fn preprint_outline_operation(
    ctx: &Context,
    opr: Ptr<Operation>,
    print_state: printable::State,
    f: &mut core::fmt::Formatter<'_>,
) -> std::fmt::Result {
    let mut aux_print_data = print_state.aux_data_mut();
    let print_state = aux_print_data
        .entry(OUTLINED_STATE.clone())
        .or_insert(Box::new(OutlinePrintState::default()))
        .downcast_mut::<OutlinePrintState>()
        .expect("failed to downcast outline print state");

    let op = opr.deref(ctx);

    // If it has a location, we need to outline the location.
    if !op.loc().is_unknown() {
        let outindex = print_state.outlined_items.push_back(OutlinedItem::Op(opr));
        return write!(f, " !{outindex}");
    }

    // Check if there's any attribute that's outlined.
    if op
        .attributes
        .0
        .iter()
        .any(|(_, attr)| attr_impls::<dyn OutlinedAttr>(&**attr))
    {
        let outindex = print_state.outlined_items.push_back(OutlinedItem::Op(opr));
        return write!(f, " !{outindex}");
    }

    Ok(())
}

/// A [BasicBlock] was just printed (label + args), and we now print a future reference to the
/// outlined attributes (if any) or location (if any) that will be printed later.
pub(crate) fn preprint_outline_block(
    ctx: &Context,
    block: Ptr<BasicBlock>,
    print_state: printable::State,
    f: &mut core::fmt::Formatter<'_>,
) -> std::fmt::Result {
    let mut aux_print_data = print_state.aux_data_mut();
    let print_state = aux_print_data
        .entry(OUTLINED_STATE.clone())
        .or_insert(Box::new(OutlinePrintState::default()))
        .downcast_mut::<OutlinePrintState>()
        .expect("failed to downcast outline print state");

    let bl = block.deref(ctx);

    // If it has a location, we need to outline the location.
    if !bl.loc().is_unknown() {
        let outindex = print_state
            .outlined_items
            .push_back(OutlinedItem::Block(block));
        return write!(f, " !{outindex}");
    }

    // Check if there's any attribute that's outlined.
    if bl
        .attributes
        .0
        .iter()
        .any(|(_, attr)| attr_impls::<dyn OutlinedAttr>(&**attr))
    {
        let outindex = print_state
            .outlined_items
            .push_back(OutlinedItem::Block(block));
        return write!(f, " !{outindex}");
    }

    Ok(())
}

/// Print the outlined attributes and locations.
/// This is called after all operations have been printed.
pub(crate) fn print_outlines(
    ctx: &Context,
    print_state: printable::State,
    f: &mut core::fmt::Formatter<'_>,
) -> std::fmt::Result {
    let Some(print_state) = print_state.aux_data_mut().remove(&*OUTLINED_STATE) else {
        return Ok(());
    };

    let mut print_state = *print_state
        .downcast::<OutlinePrintState>()
        .expect("failed to downcast outline print state");

    if print_state.outlined_items.is_empty() {
        return Ok(());
    }

    writeln!(f, "\n\noutlined_attributes:")?;
    let mut print_once_attr_indices = print_state.outlined_items.len();

    // A helper function so we don't duplicate the per-attribute printing logic.
    fn print_outlined_attrs_for(
        ctx: &Context,
        f: &mut core::fmt::Formatter<'_>,
        print_once_attrs: &mut FxHashMap<PrintOnceAttrWrapper, usize>,
        print_once_attr_indices: &mut usize,
        attributes: &AttributeDict,
        loc: Location,
    ) -> std::fmt::Result {
        if !loc.is_unknown() {
            write!(f, "@[{}], ", loc.disp(ctx))?;
        }
        write!(f, "[")?;
        let mut first = true;
        for (attr_name, attr) in attributes.0.iter() {
            if attr_impls::<dyn OutlinedAttr>(&**attr) {
                if !first {
                    write!(f, ", ")?;
                }
                first = false;
                if let Some(print_once_attr) = attr_cast::<dyn PrintOnceAttr>(&**attr) {
                    if let Some(outindex) = print_once_attrs.get(print_once_attr) {
                        write!(f, "{attr_name} = !{outindex}")?;
                    } else {
                        // If this is the first time we see this PrintOnceAttr,
                        // we need to store it for later.
                        print_once_attrs.insert(
                            PrintOnceAttrWrapper(dyn_clone::clone_box(print_once_attr)),
                            *print_once_attr_indices,
                        );
                        write!(f, "{attr_name} = !{print_once_attr_indices}")?;
                        *print_once_attr_indices += 1;
                    }
                } else {
                    write!(f, "{} = {}", attr_name, attr.disp(ctx))?;
                }
            }
        }
        Ok(())
    }

    for (outidx, item) in print_state.outlined_items.iter().enumerate() {
        write!(f, "!{outidx} = ")?;
        match item {
            OutlinedItem::Op(op) => {
                let opr = op.deref(ctx);
                print_outlined_attrs_for(
                    ctx,
                    f,
                    &mut print_state.print_once_attrs,
                    &mut print_once_attr_indices,
                    &opr.attributes,
                    opr.loc(),
                )?;
            }
            OutlinedItem::Block(block) => {
                let bl = block.deref(ctx);
                print_outlined_attrs_for(
                    ctx,
                    f,
                    &mut print_state.print_once_attrs,
                    &mut print_once_attr_indices,
                    &bl.attributes,
                    bl.loc(),
                )?;
            }
        }
        writeln!(f, "]")?;
    }

    // Now print the PrintOnceAttrs, if any.
    if !print_state.print_once_attrs.is_empty() {
        for (attr, outindex) in print_state.print_once_attrs {
            let attr = attr.0 as Box<dyn Attribute>;
            writeln!(f, "!{} = {}", outindex, attr.disp(ctx))?;
        }
    }

    Ok(())
}

/// The state used to parse outlined attributes and locations.
#[derive(Default)]
struct OutlineParseState {
    /// Map an outline item number to the [Operation] it refers to.
    outindex_op_map: FxHashMap<usize, Ptr<Operation>>,
    /// Map an outline item number to the [BasicBlock] it refers to.
    outindex_block_map: FxHashMap<usize, Ptr<BasicBlock>>,
}

/// Each [Operation] is associated with an optional [Location] and
/// a number of outlined attributes or references to them.
enum AttrOrOutlineEntryRef {
    Attr(AttrObj),
    /// The location here is where the entry ref (`!<outindex>`) is,
    /// mainly for reporting errors.
    OutlineEntryRef((Location, usize)),
}

enum OutlineEntry {
    /// A [PrintOnceAttr] is an entry by itself.
    PrintOnceAttr(AttrObj),
    /// The outline entry for an [Operation] or [BasicBlock]:
    /// A location and a list of attributes or references to attributes.
    LocAndOutlinedAttrs(Option<Location>, Vec<(Identifier, AttrOrOutlineEntryRef)>),
}

/// An [Operation] was just parsed, see if it has any outlined item number and note that down.
pub(crate) fn postparse_outline(state_stream: &mut StateStream, op: Ptr<Operation>) -> Result<()> {
    let mut outindex_parser = spaces().with(optional(combine::token('!').with(usize::parser(()))));

    let loc = state_stream.loc();
    let outindex = match outindex_parser.parse_stream(state_stream).into_result() {
        Ok((Some(outindex), _)) => outindex,
        Ok((None, _)) => {
            // No outline index, nothing to do.
            return Ok(());
        }
        Err(e) => {
            return input_err!(
                loc,
                "Error parsing outline index for operation: {}",
                e.into_inner().error
            );
        }
    };

    let parse_state = state_stream
        .state
        .aux_data
        .entry(OUTLINED_STATE.clone())
        .or_insert(Box::new(OutlineParseState::default()))
        .downcast_mut::<OutlineParseState>()
        .expect("failed to downcast outline parse state");

    if parse_state.outindex_op_map.insert(outindex, op).is_some() {
        return input_err!(loc, "Duplicate outline index: {}", outindex);
    }

    Ok(())
}

/// Register a [BasicBlock] with a given outline index in the parse state.
/// Called from [BasicBlock](crate::basic_block::BasicBlock) parsing after the block is
/// created, with the outline index that was already parsed from the stream.
pub(crate) fn register_block_for_outline(
    state_stream: &mut StateStream,
    outindex: usize,
    block: Ptr<BasicBlock>,
    loc: crate::location::Location,
) -> Result<()> {
    let parse_state = state_stream
        .state
        .aux_data
        .entry(OUTLINED_STATE.clone())
        .or_insert(Box::new(OutlineParseState::default()))
        .downcast_mut::<OutlineParseState>()
        .expect("failed to downcast outline parse state");

    if parse_state
        .outindex_block_map
        .insert(outindex, block)
        .is_some()
    {
        return input_err!(loc, "Duplicate outline index: {}", outindex);
    }

    Ok(())
}

/// Parse the outlined attributes and locations.
pub(crate) fn parse_outlines(state_stream: &mut StateStream) -> Result<()> {
    let Some(parse_state) = state_stream.state.aux_data.remove(&*OUTLINED_STATE) else {
        return Ok(());
    };

    let mut parse_state = *parse_state
        .downcast::<OutlineParseState>()
        .expect("failed to downcast outline parse state");

    if parse_state.outindex_op_map.is_empty() && parse_state.outindex_block_map.is_empty() {
        return Ok(());
    }

    let outindex_parser = || (location(), token('!').with(usize::parser(())));

    // We'll first try to parse `OutlineEntry::LocAndOutlinedAttrs` entries.
    let optional_loc_parser = optional(
        token('@')
            .with(between(
                token('['),
                token(']'),
                spaced(Location::parser(())),
            ))
            .skip(spaced(token(','))),
    );
    let name_attr_parser = (
        Identifier::parser(()).skip(spaced(token('='))),
        AttrObj::parser(())
            .map(AttrOrOutlineEntryRef::Attr)
            .or(outindex_parser().map(AttrOrOutlineEntryRef::OutlineEntryRef)),
    );
    let name_attrs_parser = delimited_list_parser('[', ']', ',', name_attr_parser);
    let loc_and_outlined_attrs_parser = (optional_loc_parser, spaces().with(name_attrs_parser))
        .map(|(loc, name_attrs)| OutlineEntry::LocAndOutlinedAttrs(loc, name_attrs));

    let print_once_attr_parser = AttrObj::parser(()).map(OutlineEntry::PrintOnceAttr);

    let outline_entry_parser = (
        outindex_parser().skip(spaced(token('='))),
        loc_and_outlined_attrs_parser.or(print_once_attr_parser),
    );

    let start_loc = state_stream.loc();
    let (mut entries, _): (Vec<((Location, usize), OutlineEntry)>, _) =
        spaced(combine::parser::char::string("outlined_attributes:"))
            .with(zero_or_more_parser(outline_entry_parser))
            .parse_stream(state_stream)
            .into_result()
            .map_err(|e| {
                let e = e.into_inner().error;
                let loc = if let Some(src) = start_loc.source() {
                    // There's a source, use it to create a more precise location.
                    Location::SrcPos {
                        src,
                        pos: e.position,
                    }
                } else {
                    // No source, use the start location.
                    start_loc
                };
                input_error!(loc, "Error parsing outline entries: {}", e)
            })?;

    // Separate the two kinds of entries we have.
    let print_once_entries: FxHashMap<_, _> = entries
        .extract_if(0..entries.len(), |e| {
            matches!(e.1, OutlineEntry::PrintOnceAttr(_))
        })
        .map(|(outindex, entry)| {
            if let OutlineEntry::PrintOnceAttr(attr) = entry {
                (outindex.1, attr)
            } else {
                unreachable!("print_once_entries should only contain PrintOnceAttr entries")
            }
        })
        .collect();

    let loc_and_outline_entries = entries
        .into_iter()
        .map(|(outindex, entry)| {
            let OutlineEntry::LocAndOutlinedAttrs(loc, attrs) = entry else {
                unreachable!(
                    "loc_and_outline_entries should only contain LocAndOutlinedAttrs entries"
                );
            };
            (outindex, (loc, attrs))
        })
        .collect::<Vec<_>>();

    for ((outindex_loc, outindex), (loc_opt, named_attrs)) in loc_and_outline_entries {
        // Check if this index refers to an operation or a block.
        if let Some(opr) = parse_state.outindex_op_map.remove(&outindex) {
            if let Some(loc) = loc_opt {
                opr.deref_mut(state_stream.state.ctx).set_loc(loc);
            }
            for (name, attr_or_ref) in named_attrs {
                match attr_or_ref {
                    AttrOrOutlineEntryRef::Attr(attr) => {
                        opr.deref_mut(state_stream.state.ctx)
                            .attributes
                            .0
                            .insert(name, attr);
                    }
                    AttrOrOutlineEntryRef::OutlineEntryRef((ref_outindex_loc, ref_outindex)) => {
                        if let Some(attr) = print_once_entries.get(&ref_outindex) {
                            opr.deref_mut(state_stream.state.ctx)
                                .attributes
                                .0
                                .insert(name, attr.clone());
                        } else {
                            return input_err!(
                                ref_outindex_loc,
                                "No PrintOnceAttr found for outline index: {}",
                                ref_outindex
                            );
                        }
                    }
                }
            }
        } else if let Some(block) = parse_state.outindex_block_map.remove(&outindex) {
            if let Some(loc) = loc_opt {
                block.deref_mut(state_stream.state.ctx).set_loc(loc);
            }
            for (name, attr_or_ref) in named_attrs {
                match attr_or_ref {
                    AttrOrOutlineEntryRef::Attr(attr) => {
                        block
                            .deref_mut(state_stream.state.ctx)
                            .attributes
                            .0
                            .insert(name, attr);
                    }
                    AttrOrOutlineEntryRef::OutlineEntryRef((ref_outindex_loc, ref_outindex)) => {
                        if let Some(attr) = print_once_entries.get(&ref_outindex) {
                            block
                                .deref_mut(state_stream.state.ctx)
                                .attributes
                                .0
                                .insert(name, attr.clone());
                        } else {
                            return input_err!(
                                ref_outindex_loc,
                                "No PrintOnceAttr found for outline index: {}",
                                ref_outindex
                            );
                        }
                    }
                }
            }
        } else {
            return input_err!(
                outindex_loc,
                "No operation or block found for outline index: {}",
                outindex
            );
        }
    }

    Ok(())
}