qbe-parser 0.1.0

A parser for QBE IR
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
use crate::ast::{AstString, Span, StringLiteral};
use crate::lexer::{TokenParser, keyword};
use crate::parse::{Parse, impl_fromstr_via_parse, maybe_newline};
use crate::utils::IterExt;
use arrayvec::ArrayVec;
use chumsky::prelude::*;
use std::fmt::{self, Display, Formatter};

#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct LinkageSection {
    pub span: Span,
    pub name: StringLiteral,
    pub flags: Option<StringLiteral>,
}
impl Display for LinkageSection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "section {}", self.name)?;
        if let Some(ref flags) = self.flags {
            write!(f, " {flags}")?;
        }
        Ok(())
    }
}
impl Parse for LinkageSection {
    const DESC: &'static str = "linkage section";

    fn parser<'a>() -> impl TokenParser<'a, Self> {
        keyword!(section)
            .parser()
            .ignore_then(StringLiteral::parser())
            .then(StringLiteral::parser().or_not())
            .map_with(|(name, flags), extra| LinkageSection {
                name,
                flags,
                span: extra.span(),
            })
    }
}
#[derive(Clone, Debug, Eq, PartialEq, Hash, Default)]
#[non_exhaustive]
pub struct Linkage {
    span: Span,
    // with 3 entries, linear search is fast
    // We want to preserve insertion order,
    // and this avoids needing an IndexMap
    specifiers: ArrayVec<LinkageSpecifier, 3>,
}
impl Parse for Linkage {
    const DESC: &'static str = "linkage";
    fn parser<'a>() -> impl TokenParser<'a, Self> {
        LinkageSpecifier::parser()
            .then_ignore(maybe_newline())
            .repeated()
            .collect::<Vec<LinkageSpecifier>>()
            .try_map(|specifiers, span| {
                Linkage::from_specifiers(span, specifiers).map_err(|e| Rich::custom(span, e))
            })
            .labelled(Self::DESC)
    }
}
impl_fromstr_via_parse!(Linkage);
macro_rules! linkage_extract_item {
    ($this:expr => $variant:ident) => {{
        match $this.get(LinkageSpecifierKind::$variant) {
            Some(LinkageSpecifier::$variant(value)) => Some(value),
            Some(other) => unreachable!("{:?}", other.kind()),
            None => None,
        }
    }};
}
impl Linkage {
    pub fn span(&self) -> Span {
        self.span
    }
    pub fn is_empty(&self) -> bool {
        self.specifiers.is_empty()
    }
    pub fn is_export(&self) -> bool {
        self.has_specifier(LinkageSpecifierKind::Export)
    }
    pub fn is_thread(&self) -> bool {
        self.has_specifier(LinkageSpecifierKind::Thread)
    }
    pub fn export(&self) -> Option<&'_ ExportLinkage> {
        linkage_extract_item!(self => Export)
    }
    pub fn thread(&self) -> Option<&'_ ThreadLinkage> {
        linkage_extract_item!(self => Thread)
    }
    pub fn section(&self) -> Option<&'_ LinkageSection> {
        linkage_extract_item!(self => Section)
    }
    pub fn from_specifiers(
        span: Span,
        specifiers: impl IntoIterator<Item = LinkageSpecifier>,
    ) -> Result<Self, DuplicateSpecifierError> {
        let mut result = Linkage {
            span,
            specifiers: ArrayVec::new(),
        };
        for spec in specifiers {
            let kind = spec.kind();
            if result.has_specifier(kind) {
                return Err(DuplicateSpecifierError { kind });
            } else {
                result.specifiers.push(spec);
            }
        }
        Ok(result)
    }
    #[inline]
    fn get(&self, kind: LinkageSpecifierKind) -> Option<&LinkageSpecifier> {
        // Emulate filter + Itertools::exactly_one
        let mut res = None;
        for entry in &self.specifiers {
            if entry.kind() == kind {
                assert!(res.is_none(), "Internal Error: Duplicate {kind:?} entries");
                res = Some(entry);
            }
        }
        res
    }
    #[inline]
    pub fn has_specifier(&self, kind: LinkageSpecifierKind) -> bool {
        self.get(kind).is_some()
    }
    #[inline]
    pub fn specifier_kinds(&self) -> impl Iterator<Item = LinkageSpecifierKind> + '_ {
        self.specifiers.iter().map(LinkageSpecifier::kind)
    }
    #[inline]
    pub fn specifiers(&self) -> impl Iterator<Item = &'_ LinkageSpecifier> + '_ {
        self.specifiers.iter()
    }
    pub fn builder() -> LinkageBuilder {
        LinkageBuilder::default()
    }
}
impl Display for Linkage {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.specifiers.iter().format(" "))
    }
}
impl From<Linkage> for LinkageBuilder {
    fn from(linkage: Linkage) -> Self {
        LinkageBuilder { linkage }
    }
}
#[derive(Default)]
pub struct LinkageBuilder {
    linkage: Linkage,
}
impl LinkageBuilder {
    /// Add a specifier to the linkage, panicking if already specified.
    ///
    /// # Panics
    /// If the specifier conflicts with an already existing specifier, this will panic.
    /// If this is not desired,
    /// use [`Self::with_specifier_replacing`] or [`Self::try_with_specifier`].
    #[track_caller]
    pub fn with_specifier(&mut self, specifier: impl Into<LinkageSpecifier>) -> &mut Self {
        let specifier = specifier.into();
        if let Some(existing) = self.linkage.get(specifier.kind()) {
            panic!("Specifier `{specifier}` conflicts with existing specifier `{existing}`")
        } else {
            self.linkage.specifiers.push(specifier);
            self
        }
    }
    /// Add a specifier to the linkage.
    /// If a matching specifier already exists, it will replace it.
    ///
    /// Thin wrapper around [`Self::replace_specifier`], which discards the old specifier.
    pub fn with_specifier_replacing(
        &mut self,
        specifier: impl Into<LinkageSpecifier>,
    ) -> &mut Self {
        self.replace_specifier(specifier);
        self
    }
    /// Marks the linkage as [`thread`](ThreadLinkage) if not already marked as such.
    ///
    /// Does nothing if that linkage has already been specified.
    pub fn with_thread(&mut self) -> &mut Self {
        self.with_specifier_replacing(ThreadLinkage {
            span: Span::MISSING,
        })
    }

    /// Marks the linkage as [`export`](ExportLinkage) if not already marked as such.
    ///
    /// Does nothing if that linkage has already been specified.
    pub fn with_export(&mut self) -> &mut Self {
        self.with_specifier_replacing(ExportLinkage {
            span: Span::MISSING,
        })
    }
    /// Add a [`LinkageSection`] with just a name (no flags).
    ///
    /// # Panics
    /// Will panic if a section has already been specified.
    #[track_caller]
    pub fn with_simple_section(&mut self, name: impl Into<AstString>) -> &mut Self {
        self.with_specifier(LinkageSection {
            span: Span::MISSING,
            name: StringLiteral::unspanned(name),
            flags: None,
        })
    }
    /// Add a [`LinkageSection`] with both a name and flags.
    ///
    /// # Panics
    /// If a section has already been specified, this will panic
    #[track_caller]
    pub fn with_section_and_flags(
        &mut self,
        name: impl Into<AstString>,
        flags: impl Into<AstString>,
    ) -> &mut Self {
        self.with_specifier(LinkageSection {
            span: Span::MISSING,
            name: StringLiteral::unspanned(name),
            flags: Some(StringLiteral::unspanned(flags)),
        })
    }
    /// Try to add a specifier to the linkage,
    /// returning an error if it conflicts with an existing specifier.
    pub fn try_with_specifier(
        &mut self,
        specifier: impl Into<LinkageSpecifier>,
    ) -> Result<&mut Self, DuplicateSpecifierError> {
        let specifier = specifier.into();
        if self.linkage.has_specifier(specifier.kind()) {
            Err(DuplicateSpecifierError {
                kind: specifier.kind(),
            })
        } else {
            self.linkage.specifiers.push(specifier);
            Ok(self)
        }
    }
    /// Add a specifier to the linkage,
    /// overriding any conflicting specifier.
    ///
    /// Returns the old specifier if present
    pub fn replace_specifier(
        &mut self,
        specifier: impl Into<LinkageSpecifier>,
    ) -> Option<LinkageSpecifier> {
        let specifier = specifier.into();
        let index = self
            .linkage
            .specifiers
            .iter()
            .position(|item| item.kind() == specifier.kind());
        match index {
            Some(index) => Some(std::mem::replace(
                &mut self.linkage.specifiers[index],
                specifier,
            )),
            None => {
                self.linkage.specifiers.push(specifier);
                None
            }
        }
    }
    #[inline]
    pub fn with_span(&mut self, span: Span) -> &mut Self {
        self.linkage.span = span;
        self
    }
    pub fn build(&mut self) -> Linkage {
        self.linkage.clone()
    }
}

#[derive(thiserror::Error, Debug, Clone, Eq, PartialEq)]
#[error("Linkage contains duplicate `{kind}` specifiers")]
pub struct DuplicateSpecifierError {
    kind: LinkageSpecifierKind,
}
macro_rules! declare_specifiers {
    (enum LinkageSpecifier {
        $($variant:ident($inner:ty)),+ $(,)?
    }) => {
        /// The kind of [`LinkageSpecifier`].
        #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
        #[non_exhaustive]
        #[repr(usize)]
        pub enum LinkageSpecifierKind {
            $($variant,)*
        }
        impl LinkageSpecifierKind {
            /// The number of different kinds.
            pub const COUNT: usize = declare_specifiers!(@count $($variant),*);
            #[inline]
            pub fn as_str(self) -> &'static str {
                match self {
                    $(LinkageSpecifierKind::$variant => paste3::paste!(stringify!([<$variant:lower>])),)*
                }
            }
            #[inline]
            pub fn index(self) -> usize {
                self as usize
            }
            #[inline]
            pub fn from_index(idx: usize) -> Option<LinkageSpecifierKind> {
                if idx < Self::COUNT {
                    // SAFETY: Performed the appropriate bounds check
                    Some(unsafe { std::mem::transmute::<usize, Self>(idx) })
                } else {
                    None
                }
            }
        }
        impl Display for LinkageSpecifierKind {
            fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
                f.write_str(self.as_str())
            }
        }
        #[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
        #[non_exhaustive]
        pub enum LinkageSpecifier {
            $($variant($inner),)*
        }
        impl LinkageSpecifier {
            #[inline]
            pub fn kind(&self) -> LinkageSpecifierKind {
                match self {
                    $(Self::$variant(_) => LinkageSpecifierKind::$variant,)*
                }
            }
            #[inline]
            pub fn span(&self) -> Span {
                match self {
                    $(Self::$variant(inner) => inner.span,)*
                }
            }
        }
        impl Display for LinkageSpecifier {
            fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
                match self {
                    $(Self::$variant(inner) => write!(f, "{inner}"),)*
                }
            }
        }
        impl Parse for LinkageSpecifier {
            const DESC: &'static str = "linkage specifier";
            fn parser<'a>() -> impl TokenParser<'a, Self> {
                choice((
                    $(<$inner as Parse>::parser().map(LinkageSpecifier::$variant)),*
                )).labelled(Self::DESC)
            }
        }
        $(impl From<$inner> for LinkageSpecifier {
            #[inline]
            fn from(v: $inner) -> Self {
                Self::$variant(v)
            }
        })*
    };
    (@count) => (0);
    (@count $first:ident $(, $item:ident)* $(,)?) => {
        1 + declare_specifiers!(@count $($item),*)
    }
}
declare_specifiers!(
    enum LinkageSpecifier {
        Export(ExportLinkage),
        Thread(ThreadLinkage),
        Section(LinkageSection),
    }
);

/// Specifies `export` [linkage](Linkage).
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct ExportLinkage {
    pub span: Span,
}
impl Display for ExportLinkage {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("export")
    }
}
impl Parse for ExportLinkage {
    const DESC: &'static str = "export linkage spec";
    fn parser<'a>() -> impl TokenParser<'a, Self> {
        keyword!(export).parser().map(|span| ExportLinkage { span })
    }
}
/// Specifies `thread` [linkage](Linkage).
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct ThreadLinkage {
    pub span: Span,
}
impl Display for ThreadLinkage {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("thread")
    }
}
impl Parse for ThreadLinkage {
    const DESC: &'static str = "thread linkage spec";
    fn parser<'a>() -> impl TokenParser<'a, Self> {
        keyword!(thread).parser().map(|span| ThreadLinkage { span })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use similar_asserts::assert_eq;

    fn export() -> LinkageSpecifier {
        ExportLinkage {
            span: Span::MISSING,
        }
        .into()
    }

    fn thread() -> LinkageSpecifier {
        ThreadLinkage {
            span: Span::MISSING,
        }
        .into()
    }

    fn builder() -> LinkageBuilder {
        LinkageBuilder::default()
    }

    fn linkage<const N: usize>(sections: [LinkageSpecifier; N]) -> Linkage {
        assert!(sections.len() <= LinkageSpecifierKind::COUNT);
        Linkage::from_specifiers(Span::MISSING, sections).unwrap()
    }

    #[test]
    fn parse_linkage() {
        assert_eq!("".parse::<Linkage>().unwrap(), linkage([]));
        assert_eq!("export".parse::<Linkage>().unwrap(), linkage([export()]),);
        assert_eq!(
            "export thread".parse::<Linkage>().unwrap(),
            linkage([export(), thread()]),
        );
        assert_eq!(
            "thread\nexport".parse::<Linkage>().unwrap(),
            linkage([thread(), export()]),
        );
        assert_eq!(
            "export thread section \"foo\"".parse::<Linkage>().unwrap(),
            builder()
                .with_export()
                .with_thread()
                .with_simple_section("foo")
                .build()
        );
        assert_eq!(
            "export thread section \"foo\" \"flags\""
                .parse::<Linkage>()
                .unwrap(),
            builder()
                .with_export()
                .with_thread()
                .with_section_and_flags("foo", "flags")
                .build(),
        );
    }

    #[test]
    fn print_linkage() {
        assert_eq!("", Linkage::default().to_string());
        assert_eq!("export", linkage([export()]).to_string());
        assert_eq!("export thread", linkage([export(), thread()]).to_string());
        assert_eq!("thread export", linkage([thread(), export()]).to_string());
        assert_eq!(
            "export thread section \"foo\"",
            builder()
                .with_export()
                .with_thread()
                .with_simple_section("foo")
                .build()
                .to_string()
        );
        assert_eq!(
            "export thread section \"foo\" \"flags\"",
            builder()
                .with_export()
                .with_thread()
                .with_section_and_flags("foo", "flags")
                .build()
                .to_string()
        );
    }
}