about summary refs log tree commit diff stats
path: root/014literal_string.cc
blob: eb5422ff481f7bf338e804587767c45ec0825852 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
//: For convenience, some instructions will take literal arrays of characters
//: (text or strings).
//:
//: Instead of quotes, we'll use [] to delimit strings. That'll reduce the
//: need for escaping since we can support nested brackets. And we can also
//: imagine that 'recipe' might one day itself be defined in Mu, doing its own
//: parsing.

:(scenarios load)
:(scenario string_literal)
def main [
  1:address:array:character <- copy [abc def]
]
+parse:   ingredient: {"abc def": "literal-string"}

:(scenario string_literal_with_colons)
def main [
  1:address:array:character <- copy [abc:def/ghi]
]
+parse:   ingredient: {"abc:def/ghi": "literal-string"}

:(before "End Mu Types Initialization")
put(Type_ordinal, "literal-string", 0);

:(before "End next_word Special-cases")
if (in.peek() == '[') {
  string result = slurp_quoted(in);
  skip_whitespace_and_comments_but_not_newline(in);
  return result;
}

:(code)
string slurp_quoted(istream& in) {
  ostringstream out;
  assert(has_data(in));  assert(in.peek() == '[');  out << static_cast<char>(in.get());  // slurp the '['
  if (is_code_string(in, out))
    slurp_quoted_comment_aware(in, out);
  else
    slurp_quoted_comment_oblivious(in, out);
  return out.str();
}

// A string is a code string (ignores comments when scanning for matching
// brackets) if it contains a newline at the start before any non-whitespace.
bool is_code_string(istream& in, ostream& out) {
  while (has_data(in)) {
    char c = in.get();
    if (!isspace(c)) {
      in.putback(c);
      return false;
    }
    out << c;
    if (c == '\n') {
      return true;
    }
  }
  return false;
}

// Read a regular string. Regular strings can only contain other regular
// strings.
void slurp_quoted_comment_oblivious(istream& in, ostream& out) {
  int brace_depth = 1;
  while (has_data(in)) {
    char c = in.get();
    if (c == '\\') {
      slurp_one_past_backslashes(in, out);
      continue;
    }
    out << c;
    if (c == '[') ++brace_depth;
    if (c == ']') --brace_depth;
    if (brace_depth == 0) break;
  }
  if (!has_data(in) && brace_depth > 0) {
    raise << "unbalanced '['\n" << end();
    out.clear();
  }
}

// Read a code string. Code strings can contain either code or regular strings.
void slurp_quoted_comment_aware(istream& in, ostream& out) {
  char c;
  while (in >> c) {
    if (c == '\\') {
      slurp_one_past_backslashes(in, out);
      continue;
    }
    if (c == '#') {
      out << c;
      while (has_data(in) && in.peek() != '\n') out << static_cast<char>(in.get());
      continue;
    }
    if (c == '[') {
      in.putback(c);
      // recurse
      out << slurp_quoted(in);
      continue;
    }
    out << c;
    if (c == ']') return;
  }
  raise << "unbalanced '['\n" << end();
  out.clear();
}

:(after "Parsing reagent(string s)")
if (starts_with(s, "[")) {
  if (*s.rbegin() != ']') return;  // unbalanced bracket; handled elsewhere
  name = s;
  // delete [] delimiters
  name.erase(0, 1);
  strip_last(name);
  type = new type_tree("literal-string", 0);
  return;
}

//: Unlike other reagents, escape newlines in literal strings to make them
//: more friendly to trace().

:(after "string to_string(const reagent& r)")
  if (is_literal_text(r))
    return emit_literal_string(r.name);

:(code)
bool is_literal_text(const reagent& x) {
  return x.type && x.type->name == "literal-string";
}

string emit_literal_string(string name) {
  size_t pos = 0;
  while (pos != string::npos)
    pos = replace(name, "\n", "\\n", pos);
  return "{\""+name+"\": \"literal-string\"}";
}

size_t replace(string& str, const string& from, const string& to, size_t n) {
  size_t result = str.find(from, n);
  if (result != string::npos)
    str.replace(result, from.length(), to);
  return result;
}

void strip_last(string& s) {
  if (!s.empty()) s.erase(SIZE(s)-1);
}

void slurp_one_past_backslashes(istream& in, ostream& out) {
  // When you encounter a backslash, strip it out and pass through any
  // following run of backslashes. If we 'escaped' a single following
  // character, then the character '\' would be:
  //   '\\' escaped once
  //   '\\\\' escaped twice
  //   '\\\\\\\\' escaped thrice (8 backslashes)
  // ..and so on. With our approach it'll be:
  //   '\\' escaped once
  //   '\\\' escaped twice
  //   '\\\\' escaped thrice
  // This only works as long as backslashes aren't also overloaded to create
  // special characters. So Mu doesn't follow C's approach of overloading
  // backslashes both to escape quote characters and also as a notation for
  // unprintable characters like '\n'.
  while (has_data(in)) {
    char c = in.get();
    out << c;
    if (c != '\\') break;
  }
}

:(scenario string_literal_nested)
def main [
  1:address:array:character <- copy [abc [def]]
]
+parse:   ingredient: {"abc [def]": "literal-string"}

:(scenario string_literal_escaped)
def main [
  1:address:array:character <- copy [abc \[def]
]
+parse:   ingredient: {"abc [def": "literal-string"}

:(scenario string_literal_escaped_twice)
def main [
  1:address:array:character <- copy [
abc \\[def]
]
+parse:   ingredient: {"\nabc \[def": "literal-string"}

:(scenario string_literal_and_comment)
def main [
  1:address:array:character <- copy [abc]  # comment
]
+parse: --- defining main
+parse: instruction: copy
+parse:   number of ingredients: 1
+parse:   ingredient: {"abc": "literal-string"}
+parse:   product: {1: ("address" "array" "character")}

:(scenario string_literal_escapes_newlines_in_trace)
def main [
  copy [abc
def]
]
+parse:   ingredient: {"abc\ndef": "literal-string"}

:(scenario string_literal_can_skip_past_comments)
def main [
  copy [
    # ']' inside comment
    bar
  ]
]
+parse:   ingredient: {"\n    # ']' inside comment\n    bar\n  ": "literal-string"}

:(scenario string_literal_empty)
def main [
  copy []
]
+parse:   ingredient: {"": "literal-string"}

:(scenario multiple_unfinished_recipes)
% Hide_errors = true;
def f1 [
def f2 [
+error: unbalanced '['
default-space x:num <- copy 0 y:num <- copy 3 ] # allocate space for x and y, as well as the chaining slot at 0 +mem: array length is 3 :(before "End is_disqualified Special-cases") if (x.name == "number-of-locals") x.initialized = true; :(before "End is_special_name Special-cases") if (s == "number-of-locals") return true; :(before "End Rewrite Instruction(curr, recipe result)") // rewrite 'new-default-space' to // ``` // default-space:space <- new location:type, number-of-locals:literal // ``` // where number-of-locals is Name[recipe][""] if (curr.name == "new-default-space") { rewrite_default_space_instruction(curr); } :(code) void rewrite_default_space_instruction(instruction& curr) { if (!curr.ingredients.empty()) raise << "'" << to_original_string(curr) << "' can't take any ingredients\n" << end(); curr.name = "new"; curr.ingredients.push_back(reagent("location:type")); curr.ingredients.push_back(reagent("number-of-locals:literal")); if (!curr.products.empty()) raise << "new-default-space can't take any results\n" << end(); curr.products.push_back(reagent("default-space:space")); } :(after "Begin Preprocess read_memory(x)") if (x.name == "number-of-locals") { vector<double> result; result.push_back(Name[get(Recipe_ordinal, current_recipe_name())][""]); if (result.back() == 0) raise << "no space allocated for default-space in recipe " << current_recipe_name() << "; are you using names?\n" << end(); return result; } :(after "Begin Preprocess write_memory(x, data)") if (x.name == "number-of-locals") { raise << maybe(current_recipe_name()) << "can't write to special name 'number-of-locals'\n" << end(); return; } //:: 'local-scope' is like 'new-default-space' except that we'll reclaim the //:: default-space when the routine exits :(scenario local_scope) def main [ 1:num <- foo 2:num <- foo 3:bool <- equal 1:num, 2:num ] def foo [ local-scope result:num <- copy default-space:space return result:num ] # both calls to foo should have received the same default-space +mem: storing 1 in location 3 :(scenario local_scope_frees_up_addresses) def main [ local-scope x:text <- new [abc] ] +mem: clearing x:text :(before "End Rewrite Instruction(curr, recipe result)") if (curr.name == "local-scope") { rewrite_default_space_instruction(curr); } //: todo: do this in a transform, rather than magically in the 'return' instruction :(after "Falling Through End Of Recipe") try_reclaim_locals(); :(after "Starting Reply") try_reclaim_locals(); :(code) void try_reclaim_locals() { if (!Reclaim_memory) return; // only reclaim routines starting with 'local-scope' const recipe_ordinal r = get(Recipe_ordinal, current_recipe_name()); const recipe& exiting_recipe = get(Recipe, r); if (exiting_recipe.steps.empty()) return; const instruction& inst = exiting_recipe.steps.at(0); if (inst.name_before_rewrite != "local-scope") return; // reclaim any local variables unless they're being returned vector<double> zeros; for (int i = /*leave default space for last*/1; i < SIZE(exiting_recipe.steps); ++i) { const instruction& inst = exiting_recipe.steps.at(i); for (int i = 0; i < SIZE(inst.products); ++i) { const reagent& product = inst.products.at(i); // local variables only if (has_property(product, "lookup")) continue; if (has_property(product, "raw")) continue; // tests often want to check such locations after they run if (escaping(product)) continue; // End Checks For Reclaiming Locals trace(9999, "mem") << "clearing " << product.original_string << end(); zeros.resize(size_of(product)); write_memory(product, zeros); } } trace(9999, "mem") << "automatically abandoning " << current_call().default_space << end(); abandon(current_call().default_space, inst.products.at(0).type->right, /*refcount*/1 + /*array length*/1 + /*number-of-locals*/Name[r][""]); } //: Reclaiming local variables above requires remembering what name an //: instruction had before any rewrites or transforms. :(before "End instruction Fields") string name_before_rewrite; :(before "End instruction Clear") name_before_rewrite.clear(); :(before "End next_instruction(curr)") curr->name_before_rewrite = curr->name; :(code) // is this reagent one of the values returned by the current (return) instruction? // is the corresponding ingredient saved in the caller? bool escaping(const reagent& r) { assert(Current_routine); // run-time only // nothing escapes when you fall through past end of recipe if (current_step_index() >= SIZE(Current_routine->steps())) return false; for (long long i = 0; i < SIZE(current_instruction().ingredients); ++i) { if (r == current_instruction().ingredients.at(i)) { if (caller_uses_product(i)) return true; } } return false; } //: since we don't decrement refcounts for escaping values above, make sure we //: don't increment them when the caller saves them either :(before "End should_update_refcounts() Special-cases") if (Writing_products_of_instruction) { const instruction& inst = current_instruction(); // should_update_refcounts() Special-cases When Writing Products Of Primitive Instructions if (is_primitive(inst.operation)) return true; if (!contains_key(Recipe, inst.operation)) return true; const recipe& callee = get(Recipe, inst.operation); if (callee.steps.empty()) return true; return callee.steps.at(0).name_before_rewrite != "local-scope"; // callees that call local-scope are already dealt with before return } :(code) bool caller_uses_product(int product_index) { assert(Current_routine); // run-time only assert(!Current_routine->calls.empty()); if (Current_routine->calls.size() == 1) return false; const call& caller = *++Current_routine->calls.begin(); const instruction& caller_inst = to_instruction(caller); if (product_index >= SIZE(caller_inst.products)) return false; return !is_dummy(caller_inst.products.at(product_index)); } :(scenario local_scope_frees_up_addresses_inside_containers) container foo [ x:num y:&:num ] def main [ local-scope x:&:num <- new number:type y:foo <- merge 34, x:&:num # x and y are both cleared when main returns ] +mem: clearing x:&:num +mem: decrementing refcount of 1006: 2 -> 1 +mem: clearing y:foo +mem: decrementing refcount of 1006: 1 -> 0 +mem: automatically abandoning 1006 :(scenario local_scope_returns_addresses_inside_containers) container foo [ x:num y:&:num ] def f [ local-scope x:&:num <- new number:type *x:&:num <- copy 12 y:foo <- merge 34, x:&:num # since y is 'escaping' f, it should not be cleared return y:foo ] def main [ 1:foo <- f 3:num <- get 1:foo, x:offset 4:&:num <- get 1:foo, y:offset 5:num <- copy *4:&:num 1:foo <- put 1:foo, y:offset, 0 4:&:num <- copy 0 ] +mem: storing 34 in location 1 +mem: storing 1006 in location 2 +mem: storing 34 in location 3 # refcount of 1:foo shouldn't include any stray ones from f +run: {4: ("address" "number")} <- get {1: "foo"}, {y: "offset"} +mem: incrementing refcount of 1006: 1 -> 2 # 1:foo wasn't abandoned/cleared +run: {5: "number"} <- copy {4: ("address" "number"), "lookup": ()} +mem: storing 12 in location 5 +run: {1: "foo"} <- put {1: "foo"}, {y: "offset"}, {0: "literal"} +mem: decrementing refcount of 1006: 2 -> 1 +run: {4: ("address" "number")} <- copy {0: "literal"} +mem: decrementing refcount of 1006: 1 -> 0 +mem: automatically abandoning 1006 :(scenario local_scope_claims_return_values_when_not_saved) def f [ local-scope x:&:num <- new number:type return x:&:num ] def main [ f # doesn't save result ] # x reclaimed +mem: automatically abandoning 1004 # f's local scope reclaimed +mem: automatically abandoning 1000 //:: all recipes must set default-space one way or another :(before "End Globals") bool Hide_missing_default_space_errors = true; :(before "End Checks") Transform.push_back(check_default_space); // idempotent :(code) void check_default_space(const recipe_ordinal r) { if (Hide_missing_default_space_errors) return; // skip previous core tests; this is only for Mu code const recipe& caller = get(Recipe, r); // End check_default_space Special-cases // assume recipes with only numeric addresses know what they're doing (usually tests) if (!contains_non_special_name(r)) return; trace(9991, "transform") << "--- check that recipe " << caller.name << " sets default-space" << end(); if (caller.steps.empty()) return; if (caller.steps.at(0).products.empty() || caller.steps.at(0).products.at(0).name != "default-space") { raise << caller.name << " does not seem to start with 'local-scope' or 'default-space'\n" << end(); } } :(after "Load Mu Prelude") Hide_missing_default_space_errors = false; :(after "Test Runs") Hide_missing_default_space_errors = true; :(after "Running Main") Hide_missing_default_space_errors = false; :(code) bool contains_non_special_name(const recipe_ordinal r) { for (map<string, int>::iterator p = Name[r].begin(); p != Name[r].end(); ++p) { if (p->first.empty()) continue; if (p->first.find("stash_") == 0) continue; // generated by rewrite_stashes_to_text (cross-layer) if (!is_special_name(p->first)) return true; } return false; } // reagent comparison -- only between reagents in a single recipe bool operator==(const reagent& a, const reagent& b) { if (a.name != b.name) return false; if (property(a, "space") != property(b, "space")) return false; return true; } bool operator<(const reagent& a, const reagent& b) { int aspace = 0, bspace = 0; if (has_property(a, "space")) aspace = to_integer(property(a, "space")->value); if (has_property(b, "space")) bspace = to_integer(property(b, "space")->value); if (aspace != bspace) return aspace < bspace; return a.name < b.name; }