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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use crate::ast::data::Constant;
use crate::ast::linkage::Linkage;
use crate::ast::types::{AbiType, BaseType};
use crate::ast::{BlockName, FloatLiteral, GlobalName, Ident, Span, Spanned, TemporaryName};
use crate::lexer::Keyword;
use crate::print::{IndentedPrinter, impl_display_via_print};
use crate::utils::{IterExt, delegate_enum_getters, impl_enum_display};
use std::fmt;
use std::fmt::{Display, Formatter, Write};
use std::str::FromStr;

mod parse;
#[cfg(test)]
mod test;

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct FunctionDef {
    pub span: Span,
    pub linkage: Linkage,
    pub return_type: Option<AbiType>,
    pub name: GlobalName,
    pub params: Vec<ParamDef>,
    pub body: FunctionBody,
}
impl FunctionDef {
    // dummy method for enum getter
    pub(crate) fn span(&self) -> Span {
        self.span
    }
    pub fn validate(&self) -> Result<(), Vec<InvalidFunctionReason>> {
        let mut res = Vec::new();
        for (index, param) in self.params.iter().enumerate() {
            match param {
                ParamDef::Regular(_) => {}
                ParamDef::Environment(_) => {
                    if index > 0 {
                        res.push(InvalidFunctionReason::EnvironmentParamMustComeFirst {
                            span: param.span(),
                        });
                    }
                }
                ParamDef::Variadic(_) => {
                    if index < self.params.len() - 1 {
                        res.push(InvalidFunctionReason::VariadicParamMustComeLast {
                            span: param.span(),
                        });
                    }
                }
            }
        }
        if res.is_empty() { Ok(()) } else { Err(res) }
    }
    fn print(&self, out: &mut IndentedPrinter<'_>) -> fmt::Result {
        if !self.linkage.is_empty() {
            write!(out, "{} ", self.linkage)?;
        }
        out.write_str("function ")?;
        if let Some(ref return_type) = self.return_type {
            write!(out, "{return_type} ")?;
        }
        write!(out, "{}({}) ", self.name, self.params.iter().format(", "))?;
        self.body.print(out)?;
        Ok(())
    }
}
impl_display_via_print!(FunctionDef);

/// An error that occurs calling [`FunctionDef::validate`].
#[derive(Debug, Clone, Eq, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum InvalidFunctionReason {
    #[error("Variadic parameter must come last")]
    VariadicParamMustComeLast { span: Span },
    #[error("Environment parameter must come first")]
    EnvironmentParamMustComeFirst { span: Span },
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ParamDef {
    Regular(RegularParamDef),
    Environment(EnvironmentParamDef),
    Variadic(VariadicParamDef),
}
impl ParamDef {
    pub fn span(&self) -> Span {
        match self {
            ParamDef::Regular(param) => param.span,
            ParamDef::Environment(param) => param.span,
            ParamDef::Variadic(param) => param.span,
        }
    }
    pub fn name(&self) -> Result<&'_ TemporaryName, UnnamedParamError> {
        Ok(match self {
            ParamDef::Regular(param) => &param.name,
            ParamDef::Environment(param) => &param.name,
            ParamDef::Variadic(param) => {
                return Err(UnnamedParamError::Variadic { span: param.span });
            }
        })
    }
}
impl Display for ParamDef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ParamDef::Regular(param) => write!(f, "{param}"),
            ParamDef::Environment(param) => write!(f, "{param}"),
            ParamDef::Variadic(param) => write!(f, "{param}"),
        }
    }
}
#[derive(thiserror::Error, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum UnnamedParamError {
    #[error("Variadic parameter has no name")]
    Variadic { span: Span },
}
impl UnnamedParamError {
    pub fn span(&self) -> Span {
        match self {
            UnnamedParamError::Variadic { span } => *span,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct RegularParamDef {
    pub span: Span,
    pub name: TemporaryName,
    pub ty: AbiType,
}
impl Display for RegularParamDef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.ty, self.name)
    }
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct EnvironmentParamDef {
    pub span: Span,
    pub name: TemporaryName,
}
impl Display for EnvironmentParamDef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "env {}", self.name)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct VariadicParamDef {
    pub span: Span,
}
impl Display for VariadicParamDef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("...")
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct FunctionBody {
    pub span: Span,
    pub blocks: Vec<FunctionBlock>,
}
impl FunctionBody {
    fn print(&self, out: &mut IndentedPrinter<'_>) -> fmt::Result {
        out.write_str("{\n")?;
        for block in &self.blocks {
            block.print(out)?;
        }
        out.maybe_writeln()?;
        out.write_char('}')
    }
}
impl_display_via_print!(FunctionBody);
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct FunctionBlock {
    pub span: Span,
    pub label: BlockName,
    pub phis: Vec<PhiInstruction>,
    pub instructions: Vec<RegularInstruction>,
    pub terminator: Option<JumpInstruction>,
}
impl FunctionBlock {
    fn print(&self, out: &mut IndentedPrinter<'_>) -> fmt::Result {
        writeln!(out, "{}", self.label)?;
        out.indented(|out| {
            for phi in &self.phis {
                writeln!(out, "{phi}")?;
            }
            for insn in &self.instructions {
                writeln!(out, "{insn}")?;
            }
            if let Some(ref term) = self.terminator {
                writeln!(out, "{term}")?;
            }
            Ok(())
        })
    }
}
impl_display_via_print!(FunctionBlock);
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct PhiInstruction {
    pub span: Span,
    pub dest_info: InsnDestInfo,
    pub args: Vec<PhiArg>,
}
impl PhiInstruction {
    #[inline]
    pub fn dest(&self) -> &'_ TemporaryName {
        &self.dest_info.dest
    }
    #[inline]
    pub fn dest_type(&self) -> &'_ BaseType {
        &self.dest_info.ty
    }
}
impl Display for PhiInstruction {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} phi ", self.dest_info)?;
        write!(f, "{}", self.args.iter().format(", "))?;
        Ok(())
    }
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct PhiArg {
    pub span: Span,
    pub block: BlockName,
    pub value: Value,
}
impl Display for PhiArg {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.block, self.value)
    }
}

/// The destination where the result of an instruction is stored.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct InsnDestInfo {
    pub span: Span,
    pub dest: TemporaryName,
    pub ty: BaseType,
}
impl Display for InsnDestInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} ={}", self.dest, self.ty)
    }
}
/// An instruction that is not a [`JumpInstruction`].
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum RegularInstruction {
    Simple(SimpleInstruction),
    Call(CallInstruction),
}
delegate_enum_getters! {
    enum RegularInstruction {
        Simple,
        Call
    } get {
        pub fn dest_info(&self) -> Option<&'_ InsnDestInfo>;
        pub fn dest(&self) -> Option<&'_ TemporaryName>;
        pub fn dest_type(&self) -> Option<&'_ BaseType>;
        pub fn name(&self) -> Ident;
        pub fn span(&self) -> Span;
    }
}
impl From<SimpleInstruction> for RegularInstruction {
    fn from(value: SimpleInstruction) -> Self {
        RegularInstruction::Simple(value)
    }
}
impl From<CallInstruction> for RegularInstruction {
    fn from(value: CallInstruction) -> Self {
        RegularInstruction::Call(value)
    }
}
impl_enum_display!(
    enum RegularInstruction {
        Simple,
        Call,
    }
);
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct SimpleInstruction {
    pub span: Span,
    pub dest_info: Option<InsnDestInfo>,
    pub args: Vec<Value>,
    pub name: Ident,
}
impl SimpleInstruction {
    fn name(&self) -> Ident {
        self.name.clone()
    }
}
macro_rules! regular_insn_common {
    ($target:ident) => {
        impl $target {
            // this is an internal method, only needed for the macro
            fn dest_info(&self) -> Option<&'_ InsnDestInfo> {
                self.dest_info.as_ref()
            }
            #[inline]
            fn span(&self) -> Span {
                self.span
            }
            pub fn dest(&self) -> Option<&'_ TemporaryName> {
                self.dest_info.as_ref().map(|info| &info.dest)
            }
            pub fn dest_type(&self) -> Option<&'_ BaseType> {
                self.dest_info.as_ref().map(|info| &info.ty)
            }
        }
    };
}
regular_insn_common!(SimpleInstruction);
impl Display for SimpleInstruction {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Some(ref info) = self.dest_info {
            write!(f, "{info} ")?;
        }
        write!(f, "{}", self.name)?;
        if !self.args.is_empty() {
            f.write_char(' ')?;
        }
        write!(f, "{}", self.args.iter().format(", "))?;
        Ok(())
    }
}
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct CallInstruction {
    pub span: Span,
    /// Span of the "call" keyword, used for [`Self::name`].
    pub call_kw_span: Span,
    pub dest_info: Option<InsnDestInfo>,
    pub target: Value,
    pub args: Vec<CallArgument>,
}
impl Display for CallInstruction {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        if let Some(ref info) = self.dest_info {
            write!(f, "{info} ")?;
        }
        write!(f, "call {}({})", self.target, self.args.iter().format(", "))
    }
}
impl CallInstruction {
    pub fn name(&self) -> Ident {
        Spanned {
            span: self.call_kw_span,
            value: Keyword::Call,
        }
        .into()
    }
}
regular_insn_common!(CallInstruction);

/// An argument to a [`CallInstruction`].
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum CallArgument {
    Regular(RegularCallArgument),
    Environment(Value),
    VariadicMarker(Span),
}
impl Display for CallArgument {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            CallArgument::Regular(inner) => Display::fmt(inner, f),
            CallArgument::Environment(value) => write!(f, "env {value}"),
            CallArgument::VariadicMarker(_) => f.write_str("..."),
        }
    }
}
/// A regular [`CallArgument`], including both a value and its type.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct RegularCallArgument {
    pub span: Span,
    pub ty: AbiType,
    pub value: Value,
}
impl Display for RegularCallArgument {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}", self.ty, self.value)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub struct ThreadLocalRef {
    pub span: Span,
    pub name: GlobalName,
}
impl Display for ThreadLocalRef {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "thread {}", self.name)
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum Value {
    Constant(Constant),
    ThreadLocalRef(ThreadLocalRef),
    Temporary(TemporaryName),
}
impl_enum_display!(
    enum Value {
        Constant,
        ThreadLocalRef,
        Temporary,
    }
);
macro_rules! impl_from_constant {
    ($($target:ty),+) => {
        $(impl From<$target> for Value {
            fn from(value: $target) -> Self {
                Value::Constant(value.into())
            }
        })*
    };
}
impl_from_constant!(Constant, i128, i64, i32, u64, FloatLiteral);
impl From<TemporaryName> for Value {
    fn from(name: TemporaryName) -> Self {
        Value::Temporary(name)
    }
}

macro_rules! insn_kind_names {
    ($target:ident {
        const KIND_DESC = $kind_desc:literal;
        $($variant:ident => $name:literal),+ $(,)?
    }) => {
        impl $target {
            pub fn name(&self) -> &'static str {
                match self {
                    $(Self::$variant => $name,)*
                }
            }
            pub fn from_name(name: &str) -> Option<Self> {
                match name {
                    $($name => Some(Self::$variant),)*
                    _ => None,
                }
            }
        }
        impl FromStr for $target {
            type Err = UnknownInstructionNameError;
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Self::from_name(s).ok_or_else(|| UnknownInstructionNameError {
                    kind_desc: Some($kind_desc),
                    name: s.into()
                })
            }
        }
    };
}
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum JumpInstructionKind {
    Jump,
    JumpNonZero,
    Return,
    Halt,
}
insn_kind_names!(JumpInstructionKind {
    const KIND_DESC = "jump";
    Jump => "jmp",
    JumpNonZero => "jnz",
    Return => "ret",
    Halt => "hlt",
});
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum JumpInstruction {
    Jump {
        span: Span,
        target: BlockName,
    },
    JumpNonZero {
        span: Span,
        op: Value,
        target: BlockName,
        fallthrough: BlockName,
    },
    Return {
        span: Span,
        value: Option<Value>,
    },
    Halt {
        span: Span,
    },
}
impl JumpInstruction {
    #[inline]
    pub fn dest_info(&self) -> Option<&InsnDestInfo> {
        None
    }
    pub fn span(&self) -> Span {
        match *self {
            JumpInstruction::Jump { span, .. }
            | JumpInstruction::JumpNonZero { span, .. }
            | JumpInstruction::Return { span, .. }
            | JumpInstruction::Halt { span, .. } => span,
        }
    }
    pub fn kind(self) -> JumpInstructionKind {
        match self {
            JumpInstruction::Jump { .. } => JumpInstructionKind::Jump,
            JumpInstruction::JumpNonZero { .. } => JumpInstructionKind::JumpNonZero,
            JumpInstruction::Return { .. } => JumpInstructionKind::Return,
            JumpInstruction::Halt { .. } => JumpInstructionKind::Halt,
        }
    }
}
impl Display for JumpInstruction {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            JumpInstruction::Jump { span: _, target } => {
                write!(f, "jmp {target}")
            }
            JumpInstruction::JumpNonZero {
                span: _,
                op,
                fallthrough,
                target,
            } => {
                write!(f, "jnz {op}, {target}, {fallthrough}")
            }
            JumpInstruction::Return { span: _, value } => {
                f.write_str("ret")?;
                if let Some(value) = value {
                    write!(f, " {value}")?;
                }
                Ok(())
            }
            JumpInstruction::Halt { span: _ } => f.write_str("hlt"),
        }
    }
}

#[derive(thiserror::Error, Debug, Clone, Eq, PartialEq)]
pub struct UnknownInstructionNameError {
    kind_desc: Option<&'static str>,
    name: String,
}
impl UnknownInstructionNameError {
    pub fn name(&self) -> &'_ str {
        &self.name
    }
}
impl Display for UnknownInstructionNameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Unknown")?;
        if let Some(kind) = self.kind_desc {
            write!(f, " {kind}")?;
        }
        write!(f, " instruction name: {:?}", self.name)
    }
}