about summary refs log tree commit diff stats
path: root/044space_surround.cc
blob: 445be78c3ca9e82104c45132a688d8da671ea8cf (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
43
44
45
46
47
48
49
50
51
52
//: 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 [
  10:number <- copy 5:literal  # pretend array
  20:number <- copy 5:literal  # pretend array
  default-space:address:array:location <- copy 10:literal
  0:address:array:location/names:dummy <- copy 20:literal  # later layers will explain the /names: property
  1:number <- copy 32:literal
  1:number/space:1 <- copy 33:literal
]
+run: instruction main/3
+mem: storing 20 in location 11
+run: instruction main/4
+mem: storing 32 in location 12
+run: instruction main/5
+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{} "index_t space_base(const reagent& x)")
index_t space_base(const reagent& x) {
  return space_base(x, space_index(x), Current_routine->calls.front().default_space);
}

index_t space_base(const reagent& x, index_t space_index, index_t base) {
//?   trace("foo") << "base of space " << space_index << '\n'; //? 1
  if (space_index == 0) {
//?     trace("foo") << "base of space " << space_index << " is " << base << '\n'; //? 1
    return base;
  }
//?   trace("foo") << "base of space " << space_index << " is " << Memory[base+1] << '\n'; //? 1
  index_t result = space_base(x, space_index-1, Memory[base+1]);
  return result;
}

index_t space_index(const reagent& x) {
  for (index_t i = 0; i < x.properties.size(); ++i) {
    if (x.properties.at(i).first == "space") {
      assert(x.properties.at(i).second.size() == 1);
      return to_integer(x.properties.at(i).second.at(0));
    }
  }
  return 0;
}
a id='n580' href='#n580'>580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734