1 //: So far you can have global variables by not setting default-space, and
 2 //: local variables by setting default-space. You can isolate variables
 3 //: between those extremes by creating 'surrounding' spaces.
 4 //:
 5 //: (Surrounding spaces are like lexical scopes in other languages.)
 6 
 7 :(scenario surrounding_space)
 8 # location 1 in space 1 refers to the space surrounding the default space, here 20.
 9 def main [
10   # pretend address:array:location; in practice we'll use 'new'
11   10:num <- copy 5  # length
12   # pretend address:array:location; in practice we'll use 'new"
13   20:num <- copy 5  # length
14   # actual start of this recipe
15   default-space:space <- copy 10/unsafe
16   #: later layers will explain the /names: property
17   0:space/names:dummy <- copy 20/unsafe
18   1:num <- copy 32
19   1:num/space:1 <- copy 33
20 ]
21 def dummy [  # just for the /names: property above
22 ]
23 # chain space: 10 + (length) 1
24 +mem: storing 20 in location 11
25 # store to default space: 10 + (skip length) 1 + (index) 1
26 +mem: storing 32 in location 12
27 # store to chained space: (contents of location 12) 20 + (length) 1 + (index) 1
28 +mem: storing 33 in location 22
29 
30 //: If you think of a space as a collection of variables with a common
31 //: lifetime, surrounding allows managing shorter lifetimes inside a longer
32 //: one.
33 
34 :(replace{} "int space_base(const reagent& x)")
35 int space_base(const reagent& x) {
36   int base = current_call().default_space ? current_call().default_space : 0;
37   return space_base(x, space_index(x), base);
38 }
39 
40 int space_base(const reagent& x, int space_index, int base) {
41   if (space_index == 0)
42     return base;
43   return space_base(x, space_index-1, get_or_insert(Memory, base+/*skip length*/1));
44 }
45 
46 int space_index(const reagent& x) {
47   for (int i = 0;  i < SIZE(x.properties);  ++i) {
48     if (x.properties.at(i).first == "space") {
49       if (!x.properties.at(i).second || x.properties.at(i).second->right)
50         raise << maybe(current_recipe_name()) << "/space metadata should take exactly one value in '" << x.original_string << "'\n" << end();
51       return to_integer(x.properties.at(i).second->value);
52     }
53   }
54   return 0;
55 }
56 
57 :(scenario permit_space_as_variable_name)
58 def main [
59   space:num <- copy 0
60 ]