-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.rs
More file actions
508 lines (434 loc) · 15.3 KB
/
compiler.rs
File metadata and controls
508 lines (434 loc) · 15.3 KB
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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! The compiler and associated types
use crate::{
ast::{Expr, ExprS, IdentifierKind, add_type_to_expr},
builtins::BuiltinFn,
errors::{
CompileError::{self, WrongNumberOfArgs},
ExprError, ExprErrorS, ExprResult,
},
prelude::lookup::TYPE,
types::Type,
value::Value,
};
pub mod opcode {
iota::iota! {
pub const
CALL: u8 = iota;,
GET,
CONSTANT,
TRUE,
FALSE
}
}
/// Types of lookups for the GET op code
///
/// Used at compile time to encode lookup indexes
///
/// Used at runtime to use lookup indexes to reference runtime values
pub mod lookup {
iota::iota! {
pub const
BUILTIN: u8 = iota;,
VAR,
PROMPT,
SECRET,
USER_BUILTIN,
CLIENT_CTX,
TYPE
}
}
/// Try to get a string from a list
fn get(list: &[String], identifier: &str) -> Option<u8> {
list.iter().position(|x| x == identifier).map(|i| i as u8)
}
#[derive(Debug)]
pub struct CompileTimeEnv {
builtins: Vec<BuiltinFn<'static>>,
user_builtins: Vec<BuiltinFn<'static>>,
vars: Vec<String>,
prompts: Vec<String>,
secrets: Vec<String>,
client_context: Vec<String>,
}
impl Default for CompileTimeEnv {
fn default() -> Self {
Self {
builtins: BuiltinFn::DEFAULT_BUILTINS.to_vec(),
user_builtins: vec![],
vars: vec![],
prompts: vec![],
secrets: vec![],
client_context: vec![],
}
}
}
impl CompileTimeEnv {
pub fn new(
vars: Vec<String>,
prompts: Vec<String>,
secrets: Vec<String>,
client_context: Vec<String>,
) -> Self {
Self {
vars,
prompts,
secrets,
client_context,
..Default::default()
}
}
pub fn get_builtin_index(&self, name: &str) -> Option<(&BuiltinFn<'_>, u8)> {
let index = self.builtins.iter().position(|x| x.name == name);
index.map(|i| (self.builtins.get(i).unwrap(), i as u8))
}
pub fn get_user_builtin_index(&self, name: &str) -> Option<(&BuiltinFn<'_>, u8)> {
let index = self.user_builtins.iter().position(|x| x.name == name);
index.map(|i| (self.user_builtins.get(i).unwrap(), i as u8))
}
pub fn add_user_builtins(&mut self, builtins: Vec<BuiltinFn<'static>>) {
for builtin in builtins {
self.add_user_builtin(builtin);
}
}
pub fn add_user_builtin(&mut self, builtin: BuiltinFn<'static>) {
self.user_builtins.push(builtin);
}
pub fn get_builtin(&self, index: usize) -> Option<&BuiltinFn<'static>> {
self.builtins.get(index)
}
pub fn get_user_builtin(&self, index: usize) -> Option<&BuiltinFn<'static>> {
self.user_builtins.get(index)
}
pub fn get_var(&self, index: usize) -> Option<&String> {
self.vars.get(index)
}
pub fn get_var_index(&self, name: &str) -> Option<usize> {
self.vars
.iter()
.position(|context_name| context_name == name)
}
pub fn get_prompt(&self, index: usize) -> Option<&String> {
self.prompts.get(index)
}
pub fn get_prompt_index(&self, name: &str) -> Option<usize> {
self.prompts
.iter()
.position(|context_name| context_name == name)
}
pub fn get_secret(&self, index: usize) -> Option<&String> {
self.secrets.get(index)
}
pub fn get_secret_index(&self, name: &str) -> Option<usize> {
self.secrets
.iter()
.position(|context_name| context_name == name)
}
pub fn get_client_context(&self, index: usize) -> Option<&String> {
self.client_context.get(index)
}
pub fn add_to_client_context(&mut self, key: &str) -> usize {
match self.client_context.iter().position(|x| x == key) {
Some(i) => i,
None => {
self.client_context.push(key.to_string());
self.client_context.len() - 1
}
}
}
pub fn get_client_context_index(&self, name: &str) -> Option<(&String, u8)> {
let index = self
.client_context
.iter()
.position(|context_name| context_name == name);
index.map(|i| (self.client_context.get(i).unwrap(), i as u8))
}
}
/// The compiled bytecode for an expression
#[derive(Debug, Clone, PartialEq)]
pub struct ExprByteCode {
version: [u8; 4],
codes: Vec<u8>,
constants: Vec<Value>,
types: Vec<Type>,
}
impl ExprByteCode {
pub fn new(codes: Vec<u8>, constants: Vec<Value>, types: Vec<Type>) -> Self {
let version_bytes = get_version_bytes();
let version_bytes_from_codes = &codes[0..4];
assert_eq!(
version_bytes, version_bytes_from_codes,
"Version bytes do not match"
);
let codes = codes[4..].to_vec();
Self {
version: version_bytes,
codes,
constants,
types,
}
}
pub fn version(&self) -> &[u8; 4] {
&self.version
}
pub fn codes(&self) -> &[u8] {
&self.codes
}
pub fn constants(&self) -> &[Value] {
&self.constants
}
pub fn types(&self) -> &[Type] {
&self.types
}
}
pub fn get_version_bytes() -> [u8; 4] {
[
env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(),
env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(),
env!("CARGO_PKG_VERSION_PATCH").parse().unwrap(),
0,
]
}
/// Compile an [`ast::Expr`] into [`ExprByteCode`]
pub fn compile(expr: &mut ExprS, env: &CompileTimeEnv) -> ExprResult<ExprByteCode> {
let mut constants: Vec<Value> = vec![];
let mut types: Vec<Type> = vec![];
let mut codes = vec![];
codes.extend(get_version_bytes());
codes.extend(compile_expr(expr, env, &mut constants, &mut types)?);
Ok(ExprByteCode::new(codes, constants, types))
}
fn compile_expr(
(expr, span): &mut ExprS,
env: &CompileTimeEnv,
constants: &mut Vec<Value>,
types: &mut Vec<Type>,
) -> ExprResult<Vec<u8>> {
use opcode::*;
let mut codes = vec![];
let mut errs: Vec<ExprErrorS> = vec![];
add_type_to_expr(expr, env);
match expr {
Expr::String(string) => {
if let Some(index) = constants.iter().position(|x| {
if let Value::String(string_constant) = x {
string_constant == &string.0
} else {
false
}
}) {
codes.push(CONSTANT);
codes.push(index as u8);
} else {
constants.push(Value::String(string.0.clone()));
let index = constants.len() - 1;
codes.push(CONSTANT);
codes.push(index as u8);
}
}
Expr::Number(number) => {
if let Some(index) = constants.iter().position(|x| {
if let Value::Number(value) = x {
value == &number.0
} else {
false
}
}) {
codes.push(CONSTANT);
codes.push(index as u8);
} else {
constants.push(Value::Number(number.0));
let index = constants.len() - 1;
codes.push(CONSTANT);
codes.push(index as u8);
}
}
Expr::Identifier(identifier) => {
let identifier_lookup_name = identifier.lookup_name();
let identifier_name = identifier.full_name().to_string();
let identifier_undefined_err = (
CompileError::Undefined(identifier_name.clone()).into(),
span.clone(),
);
let result = match identifier.identifier_kind() {
IdentifierKind::Var => get(&env.vars, identifier_lookup_name).map(|index| {
codes.push(GET);
codes.push(lookup::VAR);
codes.push(index);
}),
IdentifierKind::Prompt => get(&env.prompts, identifier_lookup_name).map(|index| {
codes.push(GET);
codes.push(lookup::PROMPT);
codes.push(index);
}),
IdentifierKind::Secret => get(&env.secrets, identifier_lookup_name).map(|index| {
codes.push(GET);
codes.push(lookup::SECRET);
codes.push(index);
}),
IdentifierKind::Client => {
get(&env.client_context, identifier_lookup_name).map(|index| {
codes.push(GET);
codes.push(lookup::CLIENT_CTX);
codes.push(index);
})
}
IdentifierKind::Builtin => {
if let Some((_, index)) = env.get_builtin_index(identifier_lookup_name) {
codes.push(GET);
codes.push(lookup::BUILTIN);
codes.push(index);
Some(())
} else if let Some((_, index)) =
env.get_user_builtin_index(identifier_lookup_name)
{
codes.push(GET);
codes.push(lookup::USER_BUILTIN);
codes.push(index);
Some(())
} else {
None
}
}
IdentifierKind::Type => {
let ty = Type::from(&identifier_name);
if let Some(index) = types.iter().position(|x| x == &ty) {
codes.push(GET);
codes.push(TYPE);
codes.push(index as u8);
} else {
types.push(ty);
let index = types.len() - 1;
codes.push(GET);
codes.push(TYPE);
codes.push(index as u8);
}
Some(())
}
};
if result.is_none() {
errs.push(identifier_undefined_err);
}
}
Expr::Call(expr_call) => {
let callee_bytecode = compile_expr(&mut expr_call.callee, env, constants, types)?;
if let Some(_op) = callee_bytecode.first()
&& let Some(lookup) = callee_bytecode.get(1)
&& let Some(index) = callee_bytecode.get(2)
{
match *lookup {
lookup::BUILTIN => {
let builtin = env.get_builtin((*index).into()).unwrap();
let call_arity: usize = expr_call.args.len();
if !builtin.arity_matches(call_arity.try_into().unwrap()) {
errs.push((
ExprError::CompileError(WrongNumberOfArgs {
expected: builtin.arity() as usize,
actual: call_arity,
}),
span.clone(),
));
}
let args: Vec<_> = expr_call.args.iter().take(call_arity).collect();
for (i, fnarg) in builtin.args.iter().enumerate() {
if let Some((a, a_span)) = args.get(i) {
let a_type = a.get_type();
let types_match = fnarg.ty == a_type
|| fnarg.ty == Type::Value
|| a_type == Type::Unknown;
if !types_match {
errs.push((
CompileError::TypeMismatch {
expected: fnarg.ty.clone(),
actual: a_type.clone(),
}
.into(),
a_span.clone(),
));
}
}
}
}
lookup::USER_BUILTIN => {
let builtin = env.get_user_builtin((*index).into()).unwrap();
let call_arity: usize = expr_call.args.len();
if !builtin.arity_matches(call_arity.try_into().unwrap()) {
errs.push((
ExprError::CompileError(WrongNumberOfArgs {
expected: builtin.arity() as usize,
actual: call_arity,
}),
span.clone(),
));
}
}
lookup::CLIENT_CTX => {
// No validation needs to be ran at this point
// This won't happen until runtime when the client
// a value.
}
_ => {
errs.push((
CompileError::InvalidLookupType(*lookup).into(),
span.clone(),
));
}
}
}
codes.extend(callee_bytecode);
for arg in expr_call.args.iter_mut() {
match compile_expr(arg, env, constants, types) {
Ok(arg_bytecode) => {
codes.extend(arg_bytecode);
}
Err(err) => {
errs.extend(err);
}
}
}
codes.push(opcode::CALL);
codes.push(expr_call.args.len() as u8);
}
Expr::Bool(value) => match value.0 {
true => {
codes.push(opcode::TRUE);
}
false => {
codes.push(opcode::FALSE);
}
},
Expr::Error => panic!("tried to compile despite parser errors"),
}
if !errs.is_empty() {
return Err(errs);
}
Ok(codes)
}
#[cfg(test)]
mod compiler_tests {
use super::*;
#[test]
pub fn current_version_bytes() {
let version_bytes = get_version_bytes();
assert_eq!(version_bytes, [0, 8, 0, 0]);
}
#[test]
pub fn valid_bytecode_version_bytes() {
let mut codes = get_version_bytes().to_vec();
codes.push(opcode::TRUE);
ExprByteCode::new(codes.to_vec(), vec![], vec![]);
}
#[test]
#[should_panic(expected = "Version bytes do not match")]
pub fn invalid_bytecode_version_bytes() {
let mut codes: Vec<u8> = [0, 0, 0, 0].to_vec();
codes.push(opcode::TRUE);
ExprByteCode::new(codes.to_vec(), vec![], vec![]);
}
#[test]
pub fn get_version_bytes_from_bytecode() {
let mut codes = get_version_bytes().to_vec();
codes.push(opcode::TRUE);
let bytecode = ExprByteCode::new(codes.to_vec(), vec![], vec![]);
assert_eq!(bytecode.version(), &get_version_bytes());
}
}