vile / scheme / star_call.v
78 lines · 75 sloc · 2.21 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3// This first pass reports malformed keyword packets before an activation can
4// reuse the caller's tail environment. It borrows the machine's argument
5// stack and does not allocate or retain an argument array.
6@[direct_array_access]
7fn (m &Machine) validate_star_arguments(formals &StarFormals, base int, argc int) !int {
8 mut cursor := formals.required
9 for _ in 0 .. formals.optional {
10 if cursor >= argc || (formals.has_keys && m.stack[base + 1 + cursor].tag == .keyword) {
11 break
12 }
13 cursor++
14 }
15 if !formals.has_keys { return cursor }
16 mut position := cursor
17 for position < argc {
18 argument := m.stack[base + 1 + position]
19 if argument.tag != .keyword {
20 if formals.rest_slot < 0 {
21 return failure('non-keyword argument after keyword formals')
22 }
23 position++
24 continue
25 }
26 if position + 1 >= argc { return failure('keyword argument has no value') }
27 mut known := false
28 for key in formals.keys {
29 if argument.text() == key.name {
30 known = true
31 break
32 }
33 }
34 if !known && !formals.allow_other { return failure('unknown keyword argument') }
35 position += 2
36 }
37 return cursor
38}
39
40@[direct_array_access]
41fn (mut m Machine) bind_star_arguments(vm &VM, mut scope Environment, formals &StarFormals, base int, argc int, optional_end int) ! {
42 for index in 0 .. formals.required {
43 scope.slots[index] = m.stack[base + 1 + index]
44 }
45 for index in formals.required .. optional_end {
46 scope.slots[index] = m.stack[base + 1 + index]
47 }
48 if formals.has_keys {
49 mut position := optional_end
50 for position < argc {
51 argument := m.stack[base + 1 + position]
52 if argument.tag != .keyword {
53 position++
54 continue
55 }
56 for key in formals.keys {
57 if argument.text() == key.name {
58 scope.slots[key.slot] = m.stack[base + 2 + position]
59 break
60 }
61 }
62 position += 2
63 }
64 }
65 if formals.rest_slot >= 0 {
66 scope.slots[formals.rest_slot] = m.rest_arguments(vm, base, optional_end, argc)!
67 }
68}
69
70@[inline]
71fn (m &Machine) rest_arguments(vm &VM, base int, first int, argc int) !Value {
72 if first == argc { return nil_value() }
73 items := unsafe { m.stack[base + 1 + first .. base + 1 + argc] }
74 if vm.uses_bounded_operations() {
75 return vm.owner.bounded_files.argument_list(items)
76 }
77 return list(items)
78}
79