quil_rs/instruction/
control_flow.rs

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
use std::sync::Arc;

use super::MemoryReference;
use crate::quil::{Quil, ToQuilError};

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Label {
    pub target: Target,
}

impl Label {
    pub fn new(target: Target) -> Self {
        Label { target }
    }
}

impl Quil for Label {
    fn write(
        &self,
        writer: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> crate::quil::ToQuilResult<()> {
        write!(writer, "LABEL ")?;
        self.target.write(writer, fall_back_to_debug)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, strum::EnumTryAs)]
pub enum Target {
    Fixed(String),
    Placeholder(TargetPlaceholder),
}

impl Target {
    pub(crate) fn resolve_placeholder<R>(&mut self, resolver: R)
    where
        R: Fn(&TargetPlaceholder) -> Option<String>,
    {
        if let Target::Placeholder(placeholder) = self {
            if let Some(resolved) = resolver(placeholder) {
                *self = Target::Fixed(resolved);
            }
        }
    }
}

impl Quil for Target {
    fn write(
        &self,
        writer: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> crate::quil::ToQuilResult<()> {
        match self {
            Target::Fixed(label) => write!(writer, "@{}", label).map_err(Into::into),
            Target::Placeholder(_) => {
                if fall_back_to_debug {
                    write!(writer, "@{:?}", self).map_err(Into::into)
                } else {
                    Err(ToQuilError::UnresolvedLabelPlaceholder)
                }
            }
        }
    }
}

type TargetPlaceholderInner = Arc<String>;

/// An opaque placeholder for a label whose index may be assigned
/// at a later time.
#[derive(Clone, Debug, Eq)]
pub struct TargetPlaceholder(TargetPlaceholderInner);

impl TargetPlaceholder {
    pub fn new(base_label: String) -> Self {
        Self(Arc::new(base_label))
    }

    pub fn as_inner(&self) -> &str {
        &self.0
    }

    fn address(&self) -> usize {
        &*self.0 as *const _ as usize
    }
}

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

impl PartialOrd for TargetPlaceholder {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for TargetPlaceholder {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.address().cmp(&other.address())
    }
}

impl PartialEq for TargetPlaceholder {
    fn eq(&self, other: &Self) -> bool {
        Arc::<std::string::String>::ptr_eq(&self.0, &other.0)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Jump {
    pub target: Target,
}

impl Quil for Jump {
    fn write(
        &self,
        writer: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> Result<(), crate::quil::ToQuilError> {
        write!(writer, "JUMP ")?;
        self.target.write(writer, fall_back_to_debug)?;
        Ok(())
    }
}

impl Jump {
    pub fn new(target: Target) -> Self {
        Self { target }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JumpWhen {
    pub target: Target,
    pub condition: MemoryReference,
}

impl JumpWhen {
    pub fn new(target: Target, condition: MemoryReference) -> Self {
        Self { target, condition }
    }
}

impl Quil for JumpWhen {
    fn write(
        &self,
        writer: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> Result<(), crate::quil::ToQuilError> {
        write!(writer, "JUMP-WHEN ")?;
        self.target.write(writer, fall_back_to_debug)?;
        write!(writer, " {}", self.condition)?;
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JumpUnless {
    pub target: Target,
    pub condition: MemoryReference,
}

impl JumpUnless {
    pub fn new(target: Target, condition: MemoryReference) -> Self {
        Self { target, condition }
    }
}

impl Quil for JumpUnless {
    fn write(
        &self,
        writer: &mut impl std::fmt::Write,
        fall_back_to_debug: bool,
    ) -> Result<(), crate::quil::ToQuilError> {
        write!(writer, "JUMP-UNLESS ")?;
        self.target.write(writer, fall_back_to_debug)?;
        write!(writer, " {}", self.condition)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rstest::rstest;

    #[test]
    fn resolve_placeholder() {
        let mut label = Target::Placeholder(TargetPlaceholder::new("base".to_string()));
        label.resolve_placeholder(|_| Some("test".to_string()));
        assert_eq!(label, Target::Fixed("test".to_string()))
    }

    #[rstest]
    #[case(Target::Fixed(String::from("test")), Ok("@test"), "@test")]
    #[case(
        Target::Placeholder(TargetPlaceholder::new(String::from("test-placeholder"))),
        Err(ToQuilError::UnresolvedLabelPlaceholder),
        "@Placeholder(TargetPlaceholder(\"test-placeholder\"))"
    )]
    fn quil_format(
        #[case] input: Target,
        #[case] expected_quil: crate::quil::ToQuilResult<&str>,
        #[case] expected_debug: &str,
    ) {
        assert_eq!(input.to_quil(), expected_quil.map(|s| s.to_string()));
        assert_eq!(input.to_quil_or_debug(), expected_debug);
    }
}