about summary refs log tree commit diff stats
path: root/cpp/028space_surround
blob: 9899ed894a67f2d79986be95e13a4b07e52f0415 (plain) (blame)
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
//: So far you can have global variables by not setting default-space, and
//: local variables by setting default-space. You can isolate variables
//: between those extremes by creating 'surrounding' spaces.
//:
//: (Surrounding spaces are like lexical scopes in other languages.)

:(scenario "surrounding_space")
# location 1 in space 1 refers to the space surrounding the default space, here 20.
recipe main [
  default-space:address:space <- copy 10:literal
  0:address:space <- copy 20:literal
  1:integer <- copy 32:literal
  1:integer/space:1 <- copy 33:literal
]
+run: instruction main/1
+mem: storing 20 in location 11
+run: instruction main/2
+mem: storing 32 in location 12
+run: instruction main/3
+mem: storing 33 in location 22

//: If you think of a space as a collection of variables with a common
//: lifetime, surrounding allows managing shorter lifetimes inside a longer
//: one.

:(replace{} "int space(const reagent& x)")
int space(const reagent& x) {
  return space(x, space_index(x), Current_routine.calls.top().default_space);
}

int space(const reagent& x, int space_index, int base) {
  if (space_index == 0) return base;
  return space(x, space_index-1, Memory[base+1]);
}

int space_index(const reagent& x) {
  for (size_t i = 0; i < x.properties.size(); ++i) {
    if (x.properties[i].first == "space")
      return to_int(x.properties[i].second[0]);
  }
  return 0;
}