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
use num_traits::NumCast;

use super::{error::AssemblerError, lexer::Token, parser, span::Spanned};
use crate::{isa::InstructionKind, opcode::OperandSize};

pub struct Statement<'ctx> {
    label: Option<Spanned<&'ctx str>>,
    expr: Option<Expression<'ctx>>,
}

impl<'ctx> Statement<'ctx> {
    fn from_parser(
        input: &'ctx str,
        stmt: parser::Statement<'ctx>,
    ) -> Result<Self, AssemblerError> {
        let label = stmt.label.map(|label| {
            Token::try_as_str(label)
                .unwrap_or_else(|e| panic!("Parser anomaly: {:?} at label position", e))
        });
        let expr = match stmt.expr {
            Some(expr) => {
                let parser::Expression { expr, data } = expr;
                Some(match Token::try_as_mnemonic(expr) {
                    Ok(mnemonic) => Expression::Instruction(Instruction {
                        mnemonic,
                        operands: data,
                    }),
                    Err(t) => Expression::Directive(parse_directive(input, t, data.into_iter())?),
                })
            }
            None => None,
        };

        Ok(Self { label, expr })
    }
}

pub enum Expression<'ctx> {
    Directive(Directive<'ctx>),
    Instruction(Instruction<'ctx>),
}

// Representation of the different Falcon security modes.
// TODO: Move this elsewhere?
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SecurityMode {
    // The Falcon No Secure mode. This is the only mode unsigned
    // microcode may execute in directly.
    None,
    // The Falcon Light Secure mode. Must be entered from Heavy
    // Secure context and grants debugging possibilities for
    // secure code.
    Light,
    // The Falcon Heavy Secure mode. Microcode in this mode is
    // granted the highest possible set of privileges while, at
    // the same time, all debugging features are disabled.
    Heavy,
}

// Assembler directives supported in the Falcon assembly language.
#[derive(Clone, Debug, PartialEq)]
pub enum Directive<'ctx> {
    // Specifies alignment of the following code to a given byte boundary.
    Align(u32),
    // Inserts a byte literal at the current position in code.
    Byte(u8),
    // Assigns a numeric constant to a symbol with the chosen name.
    Equ(&'ctx str, u32),
    // Inserts a halfword literal at the current position in code.
    //
    // Uses little endian byte ordering.
    HalfWord(u16),
    // Includes another assembler source file as an additional translation
    // unit into a source file.
    Include(&'ctx str),
    // Inserts a word literal at the current position in code.
    //
    // Uses little endian byte ordering.
    Word(u32),
    // Declares a code section with a name and an optional start address.
    Section(SecurityMode, &'ctx str, Option<u32>),
    // Skips bytes to set the program counter to the supplied value
    // relative to the current section.
    Size(u32),
    // Skips the given amount of bytes in code and optionally fills them
    // with a supplied value.
    Skip(u32, Option<u8>),
    // Inserts a string literal at the current position in code.
    Str(&'ctx str),
}

// Falcon assembly instruction which is lowered into machine code.
//
// This only stores the necessary information for instruction selection to
// enumerate possible forms and find the one that matches the operand list.
#[derive(Clone, Debug, PartialEq)]
pub struct Instruction<'ctx> {
    // The instruction mnemonic.
    pub mnemonic: Spanned<(InstructionKind, OperandSize)>,
    // Various kinds of operands validated during instruction selection.
    pub operands: Vec<Spanned<Token<'ctx>>>,
}

pub fn parse_integer<'ctx, I: Iterator<Item = Spanned<Token<'ctx>>>, U: NumCast>(
    input: &'ctx str,
    iter: &mut I,
) -> Result<Option<U>, AssemblerError> {
    match iter.next() {
        Some(t) => Token::try_as_int(t)
            .map(|u| Some(u.into_node()))
            .map_err(|e| AssemblerError::custom(input, e, "Expected integer operand")),
        None => Ok(None),
    }
}

pub fn parse_string<'ctx, I: Iterator<Item = Spanned<Token<'ctx>>>>(
    input: &'ctx str,
    iter: &mut I,
) -> Result<Option<&'ctx str>, AssemblerError> {
    match iter.next() {
        Some(t) => Token::try_as_str(t)
            .map(|s| Some(s.into_node()))
            .map_err(|e| AssemblerError::custom(input, e, "Expected string literal operand")),
        None => Ok(None),
    }
}

fn parse_directive<'ctx, I: Iterator<Item = Spanned<Token<'ctx>>>>(
    input: &'ctx str,
    dir: Spanned<Token<'ctx>>,
    mut iter: I,
) -> Result<Directive<'ctx>, AssemblerError> {
    match Token::try_as_directive(dir) {
        Ok(dir) => match *dir.node() {
            "align" => {
                let align = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`align` requires integer operand denoting alignment",
                    )
                })?;

                Ok(Directive::Align(align))
            }
            "byte" => {
                let value = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`byte` requires integer operand denoting a value",
                    )
                })?;

                Ok(Directive::Byte(value))
            }
            "equ" => {
                let symbol = parse_string(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir.clone(),
                        "`equ` requires string literal denoting symbol",
                    )
                })?;
                let value = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`equ` requires integer operand denoting constant value after symbol",
                    )
                })?;

                Ok(Directive::Equ(symbol, value))
            }
            "halfword" => {
                let value = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`halfword` requires integer operand denoting a value",
                    )
                })?;

                Ok(Directive::HalfWord(value))
            }
            "include" => {
                let path = parse_string(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir.clone(),
                        "`include` requires string literal denoting file path to include",
                    )
                })?;

                Ok(Directive::Include(path))
            }
            "word" => {
                let value = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`word` requires integer operand denoting a value",
                    )
                })?;

                Ok(Directive::Word(value))
            }
            "nsection" => {
                let name = parse_string(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir.clone(),
                        "`nsection` requires string literal denoting section name",
                    )
                })?;
                let addr = parse_integer(input, &mut iter)?;

                Ok(Directive::Section(SecurityMode::None, name, addr))
            }
            "lsection" => {
                let name = parse_string(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir.clone(),
                        "`lsection` requires string literal denoting section name",
                    )
                })?;
                let addr = parse_integer(input, &mut iter)?;

                Ok(Directive::Section(SecurityMode::Light, name, addr))
            }
            "hsection" => {
                let name = parse_string(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir.clone(),
                        "`hsection` requires string literal denoting section name",
                    )
                })?;
                let addr = parse_integer(input, &mut iter)?;

                Ok(Directive::Section(SecurityMode::Heavy, name, addr))
            }
            "size" => {
                let size = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`size` requires integer operand denoting position to pad to",
                    )
                })?;

                Ok(Directive::Size(size))
            }
            "skip" => {
                let amount = parse_integer(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir,
                        "`skip` requires integer operand denoting bytes to skip",
                    )
                })?;
                let fill = parse_integer(input, &mut iter)?;

                Ok(Directive::Skip(amount, fill))
            }
            "str" => {
                let lit = parse_string(input, &mut iter)?.ok_or_else(|| {
                    AssemblerError::custom(
                        input,
                        dir.clone(),
                        "`str` requires string literal to insert",
                    )
                })?;

                Ok(Directive::Str(lit))
            }

            _ => Err(AssemblerError::custom(input, dir, "Unknown directive")),
        },

        Err(e) => Err(AssemblerError::custom(
            input,
            e,
            "Expected assembler directive at this position",
        )),
    }
}