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 0  # refcount
12   11:num <- copy 5  # length
13   # pretend address:array:location; in practice we'll use 'new"
14   20:num <- copy 0  # refcount
15   21:num <- copy 5  # length
16   # actual start of this recipe
17   default-space:space <- copy 10/unsafe
18   #: later layers will explain the /names: property
19   0:space/names:dummy <- copy 20/unsafe
20   1:num <- copy 32
21   1:num/space:1 <- copy 33
22 ]
23 def dummy [  # just for the /names: property above
24 ]
25 # chain space: 10 + (refcount and length) 2
26 +mem: storing 20 in location 12
27 # store to default space: 10 + (skip refcount and length) 2 + (index) 1
28 +mem: storing 32 in location 13
29 # store to chained space: (contents of location 12) 20 + (refcount and length) 2 + (index) 1
30 +mem: storing 33 in location 23
31 
32 :(before "End Checks For Reclaiming Locals")
33 if (space_index(inst.products.at(i)) > 0) continue;
34 
35 //: If you think of a space as a collection of variables with a common
36 //: lifetime, surrounding allows managing shorter lifetimes inside a longer
37 //: one.
38 
39 :(replace{} "int space_base(const reagent& x)")
40 int space_base(const reagent& x) {
41   int base = current_call().default_space ? (current_call().default_space+/*skip refcount*/1) : 0;
42   return space_base(x, space_index(x), base);
43 }
44 
45 int space_base(const reagent& x, int space_index, int base) {
46   if (space_index == 0)
47   ¦ return base;
48   int result = space_base(x, space_index-1, get_or_insert(Memory, base+/*skip length*/1))+/*skip refcount*/1;
49   return result;
50 }
51 
52 int space_index(const reagent& x) {
53   for (int i = 0;  i < SIZE(x.properties);  ++i) {
54   ¦ if (x.properties.at(i).first == "space") {
55   ¦ ¦ if (!x.properties.at(i).second || x.properties.at(i).second->right)
56   ¦ ¦ ¦ raise << maybe(current_recipe_name()) << "/space metadata should take exactly one value in '" << x.original_string << "'\n" << end();
57   ¦ ¦ return to_integer(x.properties.at(i).second->value);
58   ¦ }
59   }
60   return 0;
61 }
62 
63 :(scenario permit_space_as_variable_name)
64 def main [
65   space:num <- copy 0
66 ]