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
use crate::*;
#[derive(EnumSetType, Debug)]
#[cfg_attr(feature = "io", derive(Serialize, Deserialize))]
pub enum FunctionAttribute {
Export,
Job,
}
impl<'a> std::fmt::Display for FunctionAttribute {
fn fmt(
&self,
writer: &mut std::fmt::Formatter<'_>,
) -> std::result::Result<(), std::fmt::Error> {
match self {
FunctionAttribute::Export => write!(writer, "export"),
FunctionAttribute::Job => write!(writer, "job"),
}
}
}
pub type FunctionAttributes = EnumSet<FunctionAttribute>;
#[cfg_attr(feature = "io", derive(Serialize, Deserialize))]
pub(crate) struct FunctionPayload {
pub(crate) name: Name,
pub(crate) function_type: Type,
pub(crate) arguments: Vec<Value>,
pub(crate) blocks: Vec<Block>,
pub(crate) attributes: FunctionAttributes,
pub(crate) location: Option<Location>,
}
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "io", derive(Serialize, Deserialize))]
pub struct Function(pub(crate) generational_arena::Index);
pub struct FunctionDisplayer<'a> {
pub(crate) function: Function,
pub(crate) library: &'a Library,
}
impl<'a> std::fmt::Display for FunctionDisplayer<'a> {
fn fmt(
&self,
writer: &mut std::fmt::Formatter<'_>,
) -> std::result::Result<(), std::fmt::Error> {
write!(writer, "fn ")?;
let attributes = self.function.get_attributes(self.library);
if !attributes.is_empty() {
write!(writer, "[")?;
let mut first = true;
for attribute in attributes.iter() {
if first {
first = false;
} else {
write!(writer, ", ")?;
}
write!(writer, "{}", attribute)?;
}
write!(writer, "] ")?;
}
write!(
writer,
"{}(",
self.function
.get_name(self.library)
.get_displayer(self.library)
)?;
for i in 0..self.function.get_num_args(self.library) {
if i > 0 {
writer.write_fmt(format_args!(", "))?;
}
let arg = self.function.get_arg(self.library, i);
let arg_name = arg.get_name(self.library).get_displayer(self.library);
let ty_name = arg.get_type(self.library).get_displayer(self.library);
writer.write_fmt(format_args!("{} : {}", arg_name, ty_name))?;
}
let ret_ty_name = self
.function
.get_return_type(self.library)
.get_displayer(self.library);
let location = self.function.get_location(self.library);
writer.write_fmt(format_args!(") : {}", ret_ty_name))?;
if let Some(location) = location {
write!(writer, "{}", location.get_displayer(self.library))?;
}
Ok(())
}
}
impl Function {
/// Get the name of the function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let function = module.create_function(&mut library).with_name("foo").build();
/// let name = function.get_name(&library);
/// # assert_eq!(name.get_name(&library), "foo");
/// ```
pub fn get_name(&self, library: &Library) -> Name {
let function = &library.functions[self.0];
function.name
}
/// Get the return type of the function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let void_ty = library.get_void_type();
/// # let function = module.create_function(&mut library).with_name("foo").build();
/// let return_type = function.get_return_type(&library);
/// # assert_eq!(return_type, void_ty);
/// ```
pub fn get_return_type(&self, library: &Library) -> Type {
let function = &library.functions[self.0];
match library.types[function.function_type.0] {
TypePayload::Function(return_type, _) => return_type,
_ => panic!("Function type was wrong"),
}
}
/// Get an argument from a function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let ty = library.get_int_type(8);
/// # let function = module.create_function(&mut library).with_name("func").with_arg("arg", ty).build();
/// let arg = function.get_arg(&library, 0);
/// # assert_eq!(arg.get_type(&library), ty);
/// ```
pub fn get_arg(&self, library: &Library, index: usize) -> Value {
let function = &library.functions[self.0];
assert!(
index < function.arguments.len(),
"Argument index {} is invalid {}",
index,
function.arguments.len()
);
function.arguments[index]
}
/// Get the number of arguments a function has.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let ty = library.get_int_type(8);
/// # let function = module.create_function(&mut library).with_name("func").with_arg("arg", ty).build();
/// let num_args = function.get_num_args(&library);
/// # assert_eq!(1, num_args);
/// ```
pub fn get_num_args(&self, library: &Library) -> usize {
let function = &library.functions[self.0];
function.arguments.len()
}
/// Create a new block in a function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let function = module.create_function(&mut library).with_name("func").build();;
/// let block_builder = function.create_block(&mut library);
/// ```
pub fn create_block<'a>(&self, library: &'a mut Library) -> BlockBuilder<'a> {
BlockBuilder::with_library_and_function(library, *self)
}
/// Get the attributes on the function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().with_name("module").build();
/// # let function = module.create_function(&mut library).with_name("func").with_attributes(FunctionAttributes::only(FunctionAttribute::Export)).build();
/// let attributes = function.get_attributes(&library);
/// # assert!(attributes.contains(FunctionAttribute::Export));
/// ```
pub fn get_attributes(&self, library: &Library) -> FunctionAttributes {
let function = &library.functions[self.0];
function.attributes
}
/// Get all the blocks in a function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let function = module.create_function(&mut library).with_name("func").build();;
/// let block_a = function.create_block(&mut library).build();
/// let block_b = function.create_block(&mut library).build();
/// let blocks = function.get_blocks(&library);
/// assert_eq!(blocks.count(), 2);
/// ```
pub fn get_blocks(&self, library: &Library) -> BlockIterator {
let function = &library.functions[self.0];
BlockIterator::new(&function.blocks)
}
/// Get all the arguments in a function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let u32_ty = library.get_uint_type(32);
/// # let function = module.create_function(&mut library).with_name("func").with_arg("a", u32_ty).build();
/// let mut args = function.get_args(&library);
/// assert_eq!(args.nth(0).unwrap().get_type(&library), u32_ty);
/// ```
pub fn get_args(&self, library: &Library) -> ValueIterator {
let function = &library.functions[self.0];
ValueIterator::new(&function.arguments)
}
/// Get the location of a function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let function = module.create_function(&mut library).with_name("func").build();;
/// let location = function.get_location(&library);
/// # assert_eq!(None, location);
/// # let location = library.get_location("foo.ya", 0, 13);
/// # let function = module.create_function(&mut library).with_name("func").with_location(location).build();;
/// # let location = function.get_location(&library);
/// # assert!(location.is_some());
/// ```
pub fn get_location(&self, library: &Library) -> Option<Location> {
let function = &library.functions[self.0];
function.location
}
pub fn get_displayer<'a>(&self, library: &'a Library) -> FunctionDisplayer<'a> {
FunctionDisplayer {
function: *self,
library,
}
}
}
pub struct FunctionBuilder<'a> {
library: &'a mut Library,
module: Module,
name: &'a str,
return_type: Type,
argument_names: Vec<&'a str>,
argument_types: Vec<Type>,
attributes: FunctionAttributes,
location: Option<Location>,
}
impl<'a> FunctionBuilder<'a> {
pub(crate) fn with_library_and_module(library: &'a mut Library, module: Module) -> Self {
let void_ty = library.get_void_type();
FunctionBuilder {
library,
module,
name: "",
return_type: void_ty,
argument_names: Vec::new(),
argument_types: Vec::new(),
attributes: Default::default(),
location: None,
}
}
/// Add a name for the function to the builder.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let function_builder = module.create_function(&mut library);
/// function_builder.with_name("func");
/// ```
pub fn with_name(mut self, name: &'a str) -> Self {
self.name = name;
self
}
/// Add a return type for the function.
///
/// The default return type is void if none is specified.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let u32_ty = library.get_uint_type(32);
/// # let function_builder = module.create_function(&mut library);
/// function_builder.with_return_type(u32_ty);
/// ```
pub fn with_return_type(mut self, return_type: Type) -> Self {
self.return_type = return_type;
self
}
/// Add the argument types to a function.
///
/// The default is no argument types.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let i8_ty = library.get_int_type(8);
/// # let u32_ty = library.get_uint_type(32);
/// # let function_builder = module.create_function(&mut library);
/// function_builder.with_arg("a", i8_ty).with_arg("b", u32_ty);
/// ```
pub fn with_arg(mut self, argument_name: &'a str, argument_type: Type) -> Self {
self.argument_names.push(argument_name);
self.argument_types.push(argument_type);
self
}
/// Sets the attributes for the function. This unions in the attributes with
/// any previously set attributes (allowing multiple calls to `with_attributes`)
/// to add attributes.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let builder = module.create_function(&mut library);
/// builder.with_attributes(FunctionAttributes::only(FunctionAttribute::Export));
/// ```
pub fn with_attributes(mut self, attributes: FunctionAttributes) -> Self {
self.attributes = self.attributes.union(attributes);
self
}
/// Sets the location of the function.
///
/// By default functions have no location.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let location = library.get_location("foo.ya", 0, 13);
/// # let module = library.create_module().build();
/// # let builder = module.create_function(&mut library);
/// builder.with_location(location);
/// ```
pub fn with_location(mut self, loc: Location) -> Self {
self.location = Some(loc);
self
}
/// Finalize and build the function.
///
/// # Examples
///
/// ```
/// # use yair::*;
/// # let mut library = Library::new();
/// # let module = library.create_module().build();
/// # let function_builder = module.create_function(&mut library).with_name("func");
/// let function = function_builder.build();
/// ```
pub fn build(self) -> Function {
debug_assert!(!self.name.is_empty(), "name must be non-0 in length");
let function_type = self
.library
.get_function_type(self.return_type, &self.argument_types);
let mut function = FunctionPayload {
name: self.library.get_name(self.name),
function_type,
arguments: Vec::new(),
blocks: Vec::new(),
attributes: self.attributes,
location: self.location,
};
for (argument_name, argument_type) in self.argument_names.iter().zip(self.argument_types) {
let name = self.library.get_name(argument_name);
let argument = self.library.values.insert(ValuePayload::Argument(Argument {
name,
ty: argument_type,
}));
function.arguments.push(Value(argument));
}
let func = Function(self.library.functions.insert(function));
self.library.modules[self.module.0].functions.push(func);
func
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[should_panic]
fn bad_arg_index() {
let mut library = Library::new();
let module = library.create_module().build();
let function = module
.create_function(&mut library)
.with_name("func")
.build();
let _ = function.get_arg(&library, 0);
}
}
pub struct BlockIterator {
vec: Vec<Block>,
next: usize,
}
impl BlockIterator {
fn new(iter: &[Block]) -> BlockIterator {
BlockIterator {
vec: iter.to_vec(),
next: 0,
}
}
}
impl Iterator for BlockIterator {
type Item = Block;
fn next(&mut self) -> Option<Self::Item> {
if self.next < self.vec.len() {
let next = self.next;
self.next += 1;
Some(self.vec[next])
} else {
None
}
}
}