summaryrefslogtreecommitdiff
path: root/src/stages/semantic_tokens.rs
blob: 69c6c98d0f90473b5ff7b28ef81e99578bb05345 (plain) (blame)
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
use crate::*;


pub enum SemanticToken {
    MacroDefinition(MacroDefinition),
    BlockToken(BlockToken),
}

#[derive(Clone)]
pub struct MacroDefinition {
    pub name: Tracked<String>,
    pub arguments: Vec<Tracked<ArgumentDefinition>>,
    pub body: MacroDefinitionBody,
}

#[derive(Clone)]
pub struct ArgumentDefinition {
    pub name: String,
    pub variant: ArgumentType,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ArgumentType {
    Integer,
    Block,
    List,
}

impl std::fmt::Display for ArgumentType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        match self {
            ArgumentType::Integer => write!(f, "an integer"),
            ArgumentType::Block => write!(f, "a block"),
            ArgumentType::List => write!(f, "a list"),
        }
    }
}

#[derive(Clone)]
pub enum MacroDefinitionBody {
    Integer(Tracked<IntegerToken>),
    Block(Vec<Tracked<BlockToken>>),
    List(Tracked<ListToken>),
    Invocation(Tracked<Invocation>),
}

#[derive(Clone)]
pub struct ConditionalBlock {
    pub predicate: Tracked<IntegerToken>,
    pub body: Tracked<BlockToken>,
}

#[derive(Clone)]
pub enum IntegerToken {
    IntegerLiteral(isize),
    Expression(Expression),
    Invocation(Invocation),
}

#[derive(Clone)]
pub struct Expression {
    pub tokens: Vec<Tracked<ExpressionToken>>,
}

#[derive(Clone)]
pub enum ExpressionToken {
    IntegerToken(Box<IntegerToken>),
    ListToken(ListToken),
    Invocation(Invocation),
    Operator(Operator),
}

#[derive(Clone)]
pub enum BlockToken {
    LabelDefinition(String),
    PinnedAddress(Tracked<IntegerToken>),
    ConditionalBlock(Box<ConditionalBlock>),
    WordTemplate(WordTemplate),
    Block(Vec<Tracked<BlockToken>>),
    Invocation(Invocation),
}

#[derive(Clone)]
pub enum ListToken {
    StringLiteral(StringLiteral),
    ListLiteral(Vec<Tracked<IntegerToken>>),
    Invocation(Invocation),
}

#[derive(Clone)]
pub struct Invocation {
    pub name: String,
    pub arguments: Vec<Tracked<InvocationArgument>>,
}

#[derive(Clone)]
pub enum InvocationArgument {
    IntegerToken(IntegerToken),
    BlockToken(BlockToken),
    ListToken(ListToken),
    Invocation(Invocation),
}


impl Expression {
    pub fn is_list(&self) -> bool {
        self.tokens.iter().all(|t| {
            match t.value {
                ExpressionToken::IntegerToken(_) => true,
                ExpressionToken::Invocation(_) => true,
                ExpressionToken::ListToken(_) => false,
                ExpressionToken::Operator(_) => false,
            }
        })
    }

    pub fn to_list(self) -> Vec<Tracked<IntegerToken>> {
        let mut list = Vec::new();
        for token in self.tokens {
            let source = token.source;
            match token.value {
                ExpressionToken::IntegerToken(token) => {
                    let tracked = Tracked::from(*token, source);
                    list.push(tracked);
                }
                ExpressionToken::Invocation(invocation) => {
                    let token = IntegerToken::Invocation(invocation);
                    list.push(Tracked::from(token, source));
                }
                ExpressionToken::ListToken(_) => unreachable!(
                    "Could not convert expression containing a list token to a list"),
                ExpressionToken::Operator(_) => unreachable!(
                    "Could not convert expression containing an operator to a list"),
            };
        }
        return list;
    }
}


pub enum SemanticError {
    MisplacedSeparator,
    MisplacedMacroDefinition,

    ExpectedInteger(SemanticLocation),
    ExpectedBlock(SemanticLocation),
    ExpectedString(SemanticLocation),

    InvalidArgumentDefinition,
    InvalidInvocationArgument,
    InvalidBlockInExpression,

    GlobalLabelInMacroDefinition,
    LocalLabelWithoutNamespace,
    LocalSymbolWithoutNamespace,
}

#[derive(Clone, Copy)]
pub enum SemanticLocation {
    MacroDefinitionBody,
    Expression,
    ConditionPredicate,
    ConditionBody,
    Program,
    BlockLiteral,
    PinAddress,
}

impl std::fmt::Display for SemanticLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        let string = match self {
            SemanticLocation::Expression =>
                "inside this expression",
            SemanticLocation::ConditionPredicate =>
                "as the predicate of this conditional block",
            SemanticLocation::ConditionBody =>
                "as the body of this conditional block",
            SemanticLocation::Program =>
                "at the outermost level of the program",
            SemanticLocation::BlockLiteral =>
                "inside this block literal",
            SemanticLocation::MacroDefinitionBody =>
                "inside the body of this macro definition",
            SemanticLocation::PinAddress =>
                "as the address of this pin",
        };
        write!(f, "{string}")
    }
}


pub fn report_semantic_errors(errors: &[Tracked<SemanticError>], source_code: &str) {
    for error in errors {
        report_semantic_error(error, source_code);
    }
}

fn report_semantic_error(error: &Tracked<SemanticError>, source_code: &str) {
    let context = Context { source_code: &source_code, source: &error.source };
    let message = match &error.value {
        SemanticError::MisplacedSeparator =>
            "Separators can only be used for constructing an argument list",
        SemanticError::MisplacedMacroDefinition =>
            "Macro definition must be placed at the outermost level of a program",

        SemanticError::ExpectedInteger(location) =>
            &format!("An integer value was expected {location}"),
        SemanticError::ExpectedBlock(location) =>
            &format!("A block value was expected {location}"),
        SemanticError::ExpectedString(location) =>
            &format!("A string value was expected {location}"),

        SemanticError::InvalidArgumentDefinition =>
            "Argument definition must take one of the following forms: name, {name}, or [name]",
        SemanticError::InvalidInvocationArgument =>
            "This token cannot be used in an invocation argument",
        SemanticError::InvalidBlockInExpression =>
            "Expression cannot contain a block token",

        SemanticError::GlobalLabelInMacroDefinition =>
            &format!("Macro definition cannot contain a global label"),
        SemanticError::LocalLabelWithoutNamespace =>
            &format!("Local label must be placed inside a macro definition or after a global label"),
        SemanticError::LocalSymbolWithoutNamespace =>
            &format!("Local symbol must be placed inside a macro definition or after a global label"),
    };

    report_source_issue(LogLevel::Error, &context, message);
}


pub fn print_semantic_token(i: usize, token: &SemanticToken) {
    match token {
        SemanticToken::MacroDefinition(definition) => {
            indent!(i, "MacroDefinition({})", definition.name);
            for argument in &definition.arguments {
                print_argument_definition(i+1, argument);
            }
            match &definition.body {
                MacroDefinitionBody::Integer(integer) => {
                    print_integer_token(i+1, integer)
                }
                MacroDefinitionBody::Block(tokens) => {
                    print_block(i+1, tokens);
                }
                MacroDefinitionBody::List(list) => {
                    print_list_token(i+1, list);
                }
                MacroDefinitionBody::Invocation(invocation) => {
                    print_invocation(i+1, invocation);
                }
            }
        }
        SemanticToken::BlockToken(block) => print_block_token(i, block),
    }
}

fn print_argument_definition(i: usize, argument: &ArgumentDefinition) {
    match argument.variant {
        ArgumentType::Integer => {
            indent!(i, "Argument({}, integer)", argument.name)
        }
        ArgumentType::Block => {
            indent!(i, "Argument({}, block)", argument.name)
        }
        ArgumentType::List => {
            indent!(i, "Argument({}, list)", argument.name)
        }
    }
}

fn print_block_token(i: usize, block: &BlockToken) {
    match block {
        BlockToken::Invocation(invocation) => {
            print_invocation(i, invocation)
        }
        BlockToken::LabelDefinition(name) => {
            indent!(i, "LabelDefinition({name})")
        }
        BlockToken::Block(block) => {
            print_block(i, block);
        }
        BlockToken::PinnedAddress(integer) => {
            indent!(i, "PinnedAddress");
            print_integer_token(i+1, integer);
        }
        BlockToken::ConditionalBlock(condition) => {
            indent!(i, "ConditionalBlock");
            indent!(i+1, "Predicate");
            print_integer_token(i+2, &condition.predicate);
            indent!(i+1, "Body");
            print_block_token(i+2, &condition.body);
        }
        BlockToken::WordTemplate(word_template) => {
            indent!(i, "WordTemplate({word_template})")
        }
    }
}

fn print_block(i: usize, tokens: &[Tracked<BlockToken>]) {
    indent!(i, "Block");
    for token in tokens {
        print_block_token(i+1, token);
    }
}

fn print_invocation(i: usize, invocation: &Invocation) {
    indent!(i, "Invocation({})", invocation.name);
    for argument in &invocation.arguments {
        print_invocation_argument(i+1, argument);
    }
}

fn print_invocation_argument(i: usize, argument: &InvocationArgument) {
    match &argument {
        InvocationArgument::ListToken(list) => {
            print_list_token(i, list)
        }
        InvocationArgument::IntegerToken(integer) => {
            print_integer_token(i, integer)
        }
        InvocationArgument::BlockToken(block) => {
            print_block_token(i, block)
        }
        InvocationArgument::Invocation(invocation) => {
            print_invocation(i, invocation)
        }
    }
}

fn print_integer_token(i: usize, integer: &IntegerToken) {
    match integer {
        IntegerToken::IntegerLiteral(value) => {
            indent!(i, "IntegerValue({value})")
        }
        IntegerToken::Expression(expression) => {
            print_expression(i, expression)
        }
        IntegerToken::Invocation(invocation) => {
            print_invocation(i, invocation)
        }
    }
}

fn print_list_token(i: usize, string: &ListToken) {
    match string {
        ListToken::StringLiteral(string_literal) => {
            indent!(i, "StringLiteral({string_literal})")
        }
        ListToken::ListLiteral(integers) => {
            indent!(i, "ListLiteral");
            for integer in integers {
                print_integer_token(i+1, integer);
            }
        }
        ListToken::Invocation(invocation) => {
            print_invocation(i, invocation)
        }
    }
}

fn print_expression(i: usize, expression: &Expression) {
    indent!(i, "Expression");
    for token in &expression.tokens {
        match &token.value {
            ExpressionToken::IntegerToken(integer) => {
                print_integer_token(i+1, &integer)
            }
            ExpressionToken::ListToken(list) => {
                print_list_token(i+1, &list)
            }
            ExpressionToken::Invocation(invocation) => {
                print_invocation(i+1, &invocation);
            }
            ExpressionToken::Operator(operator) => {
                indent!(i+1, "Operator({operator})")
            }
        }
    }
}