1use core::fmt;
2
3use super::{Block, Instruction};
4use crate::{SourceSpan, Span, Spanned};
5
6#[derive(Clone)]
11#[repr(u8)]
12pub enum Op {
13 If {
17 span: SourceSpan,
18 then_blk: Block,
20 else_blk: Block,
22 } = 0,
23 While { span: SourceSpan, body: Block } = 1,
25 Repeat {
30 span: SourceSpan,
31 count: u32,
32 body: Block,
33 } = 2,
34 Inst(Span<Instruction>) = 3,
36}
37
38impl crate::prettier::PrettyPrint for Op {
39 fn render(&self) -> crate::prettier::Document {
40 use crate::prettier::*;
41
42 match self {
43 Self::If { then_blk, else_blk, .. } => {
44 text("if.true") + then_blk.render() + text("else") + else_blk.render() + text("end")
45 },
46 Self::While { body, .. } => text("while.true") + body.render() + text("end"),
47 Self::Repeat { count, body, .. } => {
48 display(format!("repeat.{count}")) + body.render() + text("end")
49 },
50 Self::Inst(inst) => inst.render(),
51 }
52 }
53}
54
55impl fmt::Debug for Op {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 match self {
58 Self::If { then_blk, else_blk, .. } => {
59 f.debug_struct("If").field("then", then_blk).field("else", else_blk).finish()
60 },
61 Self::While { body, .. } => f.debug_tuple("While").field(body).finish(),
62 Self::Repeat { count, body, .. } => {
63 f.debug_struct("Repeat").field("count", count).field("body", body).finish()
64 },
65 Self::Inst(inst) => fmt::Debug::fmt(&**inst, f),
66 }
67 }
68}
69
70impl Eq for Op {}
71
72impl PartialEq for Op {
73 fn eq(&self, other: &Self) -> bool {
74 match (self, other) {
75 (
76 Self::If { then_blk: lt, else_blk: le, .. },
77 Self::If { then_blk: rt, else_blk: re, .. },
78 ) => lt == rt && le == re,
79 (Self::While { body: lbody, .. }, Self::While { body: rbody, .. }) => lbody == rbody,
80 (
81 Self::Repeat { count: lcount, body: lbody, .. },
82 Self::Repeat { count: rcount, body: rbody, .. },
83 ) => lcount == rcount && lbody == rbody,
84 (Self::Inst(l), Self::Inst(r)) => l == r,
85 _ => false,
86 }
87 }
88}
89
90impl Spanned for Op {
91 fn span(&self) -> SourceSpan {
92 match self {
93 Self::If { span, .. } | Self::While { span, .. } | Self::Repeat { span, .. } => *span,
94 Self::Inst(spanned) => spanned.span(),
95 }
96 }
97}