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
use std::str::Chars;
use std::iter::Peekable;


pub struct ParserError(pub String);

impl ParserError {
    pub fn new(msg: String) -> Self {
        Self(msg)
    }
}

#[derive(Debug)]
pub enum AssemblyLine {
    Directive(String, Vec<String>),
    Label(String),
    Instruction(String, Vec<AssemblyOperand>),
}

#[derive(Debug)]
pub enum AssemblyOperand {
    Register(String),
    Indirect(Vec<AssemblyOperand>),
    IndirectPre(String, Vec<AssemblyOperand>),
    IndirectPost(Vec<AssemblyOperand>, String),
    Immediate(usize),
    Label(String),
}


pub struct AssemblyParser<'input> {
    lexer: AssemblyLexer<'input>,
}

impl<'input> AssemblyParser<'input> {
    pub fn new(input: &'input str) -> Self {
        Self {
            lexer: AssemblyLexer::new(input),
        }
    }

    pub fn parse(&mut self) -> Result<Vec<(usize, AssemblyLine)>, ParserError> {
        let mut output = vec![];
        loop {
            let lineno = self.lexer.get_next_lineno();
            if let Some(line) = self.parse_line()? {
                output.push((lineno, line));
            } else {
                break;
            }
        }
        Ok(output)
    }

    fn parse_line(&mut self) -> Result<Option<AssemblyLine>, ParserError> {
        let token = loop {
            match self.lexer.get_next() {
                Some(token) if token == "\n" => {},
                Some(token) => {
                    break token;
                },
                None => {
                    return Ok(None);
                },
            }
        };

        let result = match token.as_str() {
            "." => {
                let name = self.lexer.expect_next()?;
                let list = self.parse_list_of_words()?;
                AssemblyLine::Directive(name, list)
            },
            word if word.chars().next().map(is_word).unwrap_or(false) => {
                let next = self.lexer.peek();
                if next.is_some() && next.as_ref().unwrap() == ":" {
                    self.lexer.expect_next()?;
                    AssemblyLine::Label(token)
                } else {
                    let list = self.parse_list_of_operands()?;
                    AssemblyLine::Instruction(token, list)
                }
            },
            _ => {
                return Err(ParserError::new(format!(
                    "parse error at line {}: expected word, found {:?}",
                    self.lexer.lineno(),
                    token
                )));
            },
        };

        self.lexer.expect_end()?;
        Ok(Some(result))
    }

    fn parse_list_of_words(&mut self) -> Result<Vec<String>, ParserError> {
        let mut list = vec![];

        // If we're already at the end of the line, then it's an empty list, so return
        let next = self.lexer.peek();
        if next.is_none() || next.as_ref().unwrap() == "\n" {
            return Ok(list);
        }

        loop {
            list.push(self.lexer.expect_next()?);

            let next = self.lexer.peek();
            if next.is_none() || next.as_ref().unwrap() != "," {
                return Ok(list);
            }
            self.lexer.expect_next()?;
        }
    }

    fn parse_list_of_operands(&mut self) -> Result<Vec<AssemblyOperand>, ParserError> {
        let mut list = vec![];

        // If we're already at the end of the line, then it's an empty list, so return
        let next = self.lexer.peek();
        if next.is_none() || next.as_ref().unwrap() == "\n" {
            return Ok(list);
        }

        loop {
            list.push(self.parse_operand()?);

            let next = self.lexer.peek();
            if next.is_none() || next.unwrap() != "," {
                return Ok(list);
            }
            self.lexer.expect_next()?;
        }
    }

    fn parse_operand(&mut self) -> Result<AssemblyOperand, ParserError> {
        let token = self.lexer.expect_next()?;
        match token.as_str() {
            "%" => {
                // TODO check for movem type ranges
                Ok(AssemblyOperand::Register(self.lexer.expect_next()?))
            },
            "(" => {
                let list = self.parse_list_of_operands()?;
                self.lexer.expect_token(")")?;

                if let Some(next) = self.lexer.peek() {
                    if next == "+" || next == "-" {
                        self.lexer.expect_next()?;
                        return Ok(AssemblyOperand::IndirectPost(list, next));
                    }
                }
                Ok(AssemblyOperand::Indirect(list))
            },
            "+" | "-" => {
                self.lexer.expect_token("(")?;
                let list = self.parse_list_of_operands()?;
                self.lexer.expect_token(")")?;
                Ok(AssemblyOperand::IndirectPre(token, list))
            },
            "#" => {
                let string = self.lexer.expect_next()?;
                let number = parse_any_number(self.lexer.lineno(), &string)?;
                Ok(AssemblyOperand::Immediate(number))
            },
            _ => {
                if is_digit(token.chars().next().unwrap()) {
                    let number = parse_any_number(self.lexer.lineno(), &token)?;
                    Ok(AssemblyOperand::Immediate(number))
                } else {
                    Ok(AssemblyOperand::Label(token))
                }
            },
        }
    }
}

fn parse_any_number(lineno: usize, string: &str) -> Result<usize, ParserError> {
    let (radix, numeric) = if let Some(s) = string.strip_prefix("0x") {
        (16, s)
    } else if let Some(s) = string.strip_prefix("0b") {
        (2, s)
    } else if let Some(s) = string.strip_prefix("0o") {
        (8, s)
    } else {
        (10, string)
    };
    usize::from_str_radix(numeric, radix)
        .map_err(|_| ParserError::new(format!("parse error at line {}: expected number after #, but found {:?}", lineno, string)))
}


pub struct AssemblyLexer<'input> {
    lineno: usize,
    chars: Peekable<Chars<'input>>,
    peeked: Option<String>,
}

impl<'input> AssemblyLexer<'input> {
    pub fn new(input: &'input str) -> Self {
        Self {
            lineno: 1,
            chars: input.chars().peekable(),
            peeked: None,
        }
    }

    pub fn lineno(&self) -> usize {
        self.lineno
    }

    pub fn get_next_lineno(&mut self) -> usize {
        self.eat_whitespace();
        self.lineno
    }

    pub fn get_next(&mut self) -> Option<String> {
        if self.peeked.is_some() {
            let result = self.peeked.take();
            return result;
        }

        self.eat_whitespace();

        let ch = self.chars.next()?;
        let mut string = ch.to_string();

        if is_word(ch) {
            while let Some(ch) = self.chars.next_if(|ch| is_word(*ch) || *ch == '.') {
                // Ignore periods in words
                if ch != '.' {
                    string.push(ch);
                }
            }
        }

        Some(string)
    }

    pub fn peek(&mut self) -> Option<String> {
        self.peeked = self.get_next();
        self.peeked.clone()
    }

    pub fn expect_next(&mut self) -> Result<String, ParserError> {
        self.get_next()
            .ok_or_else(|| ParserError::new(format!("unexpected end of input at line {}", self.lineno)))
    }

    pub fn expect_token(&mut self, expected: &str) -> Result<(), ParserError> {
        let token = self.expect_next()?;
        if token == expected {
            Ok(())
        } else {
            Err(ParserError::new(format!(
                "parse error at line {}: expected {:?}, found {:?}",
                self.lineno, expected, token
            )))
        }
    }

    pub fn expect_end(&mut self) -> Result<(), ParserError> {
        let token = self.get_next();
        if token.is_none() || token.as_ref().unwrap() == "\n" {
            Ok(())
        } else {
            Err(ParserError::new(format!("expected end of line at {}: found {:?}", self.lineno, token)))
        }
    }

    fn eat_whitespace(&mut self) {
        while let Some(ch) = self.chars.peek() {
            if *ch == '|' {
                self.read_until('\n')
            } else if *ch == '/' {
                self.chars.next();
                if self.chars.next_if(|ch| *ch == '*').is_some() {
                    loop {
                        self.read_until('*');
                        self.chars.next();
                        if self.chars.next_if(|ch| *ch == '/').is_some() {
                            break;
                        }
                    }
                }
            } else if *ch == ' ' || *ch == '\t' || *ch == '\r' {
                self.chars.next();
            } else {
                if *ch == '\n' {
                    self.lineno += 1;
                }
                break;
            }
        }
    }

    fn read_until(&mut self, test: char) {
        while let Some(ch) = self.chars.peek() {
            if *ch == test {
                return;
            }
            if *ch == '\n' {
                self.lineno += 1;
            }
            self.chars.next();
        }
    }
}

fn is_word(ch: char) -> bool {
    ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch.is_ascii_digit() || (ch == '_')
}

fn is_digit(ch: char) -> bool {
    ch.is_ascii_digit()
}

pub fn expect_args(lineno: usize, args: &[AssemblyOperand], expected: usize) -> Result<(), ParserError> {
    if args.len() == expected {
        Ok(())
    } else {
        Err(ParserError::new(format!(
            "error at line {}: expected {} args, but found {}",
            lineno,
            expected,
            args.len()
        )))
    }
}

pub fn expect_label(lineno: usize, args: &[AssemblyOperand]) -> Result<String, ParserError> {
    expect_args(lineno, args, 1)?;
    if let AssemblyOperand::Label(name) = &args[0] {
        Ok(name.clone())
    } else {
        Err(ParserError::new(format!("error at line {}: expected a label, but found {:?}", lineno, args)))
    }
}

pub fn expect_immediate(lineno: usize, operand: &AssemblyOperand) -> Result<usize, ParserError> {
    if let AssemblyOperand::Immediate(value) = operand {
        Ok(*value)
    } else {
        Err(ParserError::new(format!(
            "error at line {}: expected an immediate value, but found {:?}",
            lineno, operand
        )))
    }
}