about summary refs log tree commit diff stats
path: root/021check_instruction.cc
blob: 6347dfb3336a9eada26677d090a27b68da1a7cfb (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
226
227
228
229
230
231
232
//: Introduce a new transform to perform various checks in instructions before
//: we start running them. It'll be extensible, so that we can add checks for
//: new recipes as we extend 'run' to support them.
//:
//: Doing checking in a separate part complicates things, because the values
//: of variables in memory and the processor (current_recipe_name,
//: current_instruction) aren't available at checking time. If I had a more
//: sophisticated layer system I'd introduce the simpler version first and
//: transform it in a separate layer or set of layers.

:(before "End Checks")
Transform.push_back(check_instruction);  // idempotent

:(code)
void check_instruction(const recipe_ordinal r) {
  trace(9991, "transform") << "--- perform checks for recipe " << get(Recipe, r).name << end();
  map<string, vector<type_ordinal> > metadata;
  for (int i = 0;  i < SIZE(get(Recipe, r).steps);  ++i) {
    instruction& inst = get(Recipe, r).steps.at(i);
    if (inst.is_label) continue;
    switch (inst.operation) {
      // Primitive Recipe Checks
      case COPY: {
        if (SIZE(inst.products) > SIZE(inst.ingredients)) {
          raise << maybe(get(Recipe, r).name) << "too many products in '" << to_original_string(inst) << "'\n" << end();
          break;
        }
        for (int i = 0;  i < SIZE(inst.products);  ++i) {
          if (!types_coercible(inst.products.at(i), inst.ingredients.at(i))) {
            raise << maybe(get(Recipe, r).name) << "can't copy '" << inst.ingredients.at(i).original_string << "' to '" << inst.products.at(i).original_string << "'; types don't match\n" << end();
            goto finish_checking_instruction;
          }
        }
        break;
      }
      // End Primitive Recipe Checks
      default: {
        // Defined Recipe Checks
        // End Defined Recipe Checks
      }
    }
    finish_checking_instruction:;
  }
}

:(scenario copy_checks_reagent_count)
% Hide_errors = true;
def main [
  1:num, 2:num <- copy 34
]
+error: main: too many products in '1:num, 2:num <- copy 34'

:(scenario write_scalar_to_array_disallowed)
% Hide_errors = true;
def main [
  1:array:num <- copy 34
]
+error: main: can't copy '34' to '1:array:num'; types don't match

:(scenario write_scalar_to_array_disallowed_2)
% Hide_errors = true;
def main [
  1:num, 2:array:num <- copy 34, 35
]
+error: main: can't copy '35' to '2:array:num'; types don't match

:(scenario write_scalar_to_address_disallowed)
% Hide_errors = true;
def main [
  1:&:num <- copy 34
]
+error: main: can't copy '34' to '1:&:num'; types don't match

:(scenario write_address_to_character_disallowed)
% Hide_errors = true;
def main [
  1:&:num <- copy 12/unsafe
  2:char <- copy 1:&:num
]
+error: main: can't copy '1:&:num' to '2:char'; types don't match

:(scenario write_number_to_character_allowed)
def main [
  1:num <- copy 97
  2:char <- copy 1:num
]
$error: 0

:(code)
// types_match with some leniency
bool types_coercible(reagent/*copy*/ to, reagent/*copy*/ from) {
  // Begin types_coercible(reagent to, reagent from)
  if (types_match_sub(to, from)) return true;
  if (is_real_mu_number(from) && is_mu_character(to)) return true;
  // End types_coercible Special-cases
  return false;
}

bool types_match_sub(const reagent& to, const reagent& from) {
  // to sidestep type-checking, use /unsafe in the source.
  // this will be highlighted in red inside vim. just for setting up some tests.
  if (is_unsafe(from)) return true;
  if (is_literal(from)) {
    if (is_mu_array(to)) return false;
    // End Matching Types For Literal(to)
    if (!to.type) return false;
    // allow writing null to any address
    if (is_mu_address(to)) return from.name == "null";
    return size_of(to) == 1;  // literals are always scalars
  }
  return types_strictly_match_sub(to, from);
}
// variant for others to call
bool types_match(reagent/*copy*/ to, reagent/*copy*/ from) {
  // Begin types_match(reagent to, reagent from)
  return types_match_sub(to, from);
}

//: copy arguments for later layers
bool types_strictly_match_sub(const reagent& to, const reagent& from) {
  if (to.type == NULL) return false;  // error
  if (is_literal(from) && to.type->value == Number_type_ordinal) return true;
  // to sidestep type-checking, use /unsafe in the source.
  // this will be highlighted in red inside vim. just for setting up some tests.
  if (is_unsafe(from)) return true;
  // '_' never raises type error
  if (is_dummy(to)) return true;
  if (!to.type) return !from.type;
  return types_strictly_match(to.type, from.type);
}
// variant for others to call
bool types_strictly_match(reagent/*copy*/ to, reagent/*copy*/ from) {
  // Begin types_strictly_match(reagent to, reagent from)
  return types_strictly_match_sub(to, from);
}

bool types_strictly_match(const type_tree* to, const type_tree* from) {
  if (from == to) return true;
  if (!to) return false;
  if (!from) return to->atom && to->value == 0;
  if (from->atom != to->atom) return false;
  if (from->atom) {
    if (from->value == -1) return from->name == to->name;
    return from->value == to->value;
  }
  if (types_strictly_match(to->left, from->left) && types_strictly_match(to->right, from->right))
    return true;
  // fallback: (x) == x
  if (to->right == NULL && types_strictly_match(to->left, from)) return true;
  if (from->right == NULL && types_strictly_match(to, from->left)) return true;
  return false;
}

void test_unknown_type_does_not_match_unknown_type() {
  reagent a("a:foo");
  reagent b("b:bar");
  CHECK(!types_strictly_match(a, b));
}

void test_unknown_type_matches_itself() {
  reagent a("a:foo");
  reagent b("b:foo");
  CHECK(types_strictly_match(a, b));
}

void test_type_abbreviations_match_raw_types() {
  put(Type_abbreviations, "text", new_type_tree("address:array:character"));
  // a has type (address buffer (address array character))
  reagent a("a:address:buffer:text");
  expand_type_abbreviations(a.type);
  // b has type (address buffer address array character)
  reagent b("b:address:buffer:address:array:character");
  CHECK(types_strictly_match(a, b));
  delete Type_abbreviations["text"];
  put(Type_abbreviations, "text", NULL);
}

//: helpers

bool is_unsafe(const reagent& r) {
  return has_property(r, "unsafe");
}

bool is_mu_array(reagent/*copy*/ r) {
  // End Preprocess is_mu_array(reagent r)
  return is_mu_array(r.type);
}
bool is_mu_array(const type_tree* type) {
  if (!type) return false;
  if (is_literal(type)) return false;
  if (type->atom) return false;
  if (!type->left->atom) {
    raise << "invalid type " << to_string(type) << '\n' << end();
    return false;
  }
  return type->left->value == Array_type_ordinal;
}

bool is_mu_boolean(reagent/*copy*/ r) {
  // End Preprocess is_mu_boolean(reagent r)
  if (!r.type) return false;
  if (is_literal(r)) return false;
  if (!r.type->atom) return false;
  return r.type->value == Boolean_type_ordinal;
}

bool is_mu_number(reagent/*copy*/ r) {
  if (is_mu_character(r.type)) return true;  // permit arithmetic on unicode code points
  return is_real_mu_number(r);
}

bool is_real_mu_number(reagent/*copy*/ r) {
  // End Preprocess is_mu_number(reagent r)
  if (!r.type) return false;
  if (!r.type->atom) return false;
  if (is_literal(r)) {
    return r.type->name == "literal-fractional-number"
        || r.type->name == "literal";
  }
  return r.type->value == Number_type_ordinal;
}

bool is_mu_character(reagent/*copy*/ r) {
  // End Preprocess is_mu_character(reagent r)
  return is_mu_character(r.type);
}
bool is_mu_character(const type_tree* type) {
  if (!type) return false;
  if (!type->atom) return false;
  if (is_literal(type)) return false;
  return type->value == Character_type_ordinal;
}
s="s">" << " To load files and run only the tests in explicitly loaded files (for apps):\n" << " mu --test-only-app test file1.mu file2.mu ...\n" << " To load all files with a numeric prefix in a directory:\n" << " mu directory1 directory2 ...\n" << " You can test directories just like files.\n" << " mu test directory1 directory2 ...\n" << " To pass ingredients to a mu program, provide them after '--':\n" << " mu file_or_dir1 file_or_dir2 ... -- ingredient1 ingredient2 ...\n" << " To see where a mu program is spending its time:\n" << " mu --profile file_or_dir1 file_or_dir2 ...\n" << " this slices and dices time spent in various profile.* output files\n" << "\n" << " To browse a trace generated by a previous run:\n" << " mu browse-trace file\n" ; return 0; } //: Support for option parsing. //: Options always begin with '--' and are always the first arguments. An //: option will never follow a non-option. :(before "End Commandline Parsing") char** arg = &argv[1]; while (argc > 1 && starts_with(*arg, "--")) { if (false) ; // no-op branch just so any further additions can consistently always start with 'else' // End Commandline Options(*arg) else cerr << "skipping unknown option " << *arg << '\n'; --argc; ++argv; ++arg; } //:: Helper function used by the above fragment of code (and later layers too, //:: who knows?). //: The :(code) directive appends function definitions to the end of the //: project. Regardless of where functions are defined, we can call them //: anywhere we like as long as we format the function header in a specific //: way: put it all on a single line without indent, end the line with ') {' //: and no trailing whitespace. As long as functions uniformly start this //: way, our 'build*' scripts contain a little command to automatically //: generate declarations for them. :(code) bool is_equal(char* s, const char* lit) { return strncmp(s, lit, strlen(lit)) == 0; } bool starts_with(const string& s, const string& pat) { string::const_iterator a=s.begin(), b=pat.begin(); for (/*nada*/; a!=s.end() && b!=pat.end(); ++a, ++b) if (*a != *b) return false; return b == pat.end(); } //: I'll throw some style conventions here for want of a better place for them. //: As a rule I hate style guides. Do what you want, that's my motto. But since //: we're dealing with C/C++, the one big thing we want to avoid is undefined //: behavior. If a compiler ever encounters undefined behavior it can make //: your program do anything it wants. //: //: For reference, my checklist of undefined behaviors to watch out for: //: out-of-bounds access //: uninitialized variables //: use after free //: dereferencing invalid pointers: null, a new of size 0, others //: //: casting a large number to a type too small to hold it //: //: integer overflow //: division by zero and other undefined expressions //: left-shift by negative count //: shifting values by more than or equal to the number of bits they contain //: bitwise operations on signed numbers //: //: Converting pointers to types of different alignment requirements //: T* -> void* -> T*: defined //: T* -> U* -> T*: defined if non-function pointers and alignment requirements are same //: function pointers may be cast to other function pointers //: //: Casting a numeric value into a value that can't be represented by the target type (either directly or via static_cast) //: //: To guard against these, some conventions: //: //: 0. Initialize all primitive variables in functions and constructors. //: //: 1. Minimize use of pointers and pointer arithmetic. Avoid 'new' and //: 'delete' as far as possible. Rely on STL to perform memory management to //: avoid use-after-free issues (and memory leaks). //: //: 2. Avoid naked arrays to avoid out-of-bounds access. Never use operator[] //: except with map. Use at() with STL vectors and so on. //: //: 3. Valgrind all the things. //: //: 4. Avoid unsigned numbers. Not strictly an undefined-behavior issue, but //: the extra range doesn't matter, and it's one less confusing category of //: interaction gotchas to worry about. //: //: Corollary: don't use the size() method on containers, since it returns an //: unsigned and that'll cause warnings about mixing signed and unsigned, //: yadda-yadda. Instead use this macro below to perform an unsafe cast to //: signed. We'll just give up immediately if a container's ever too large. //: Basically, Mu is not concerned about this being a little slower than it //: could be. (https://gist.github.com/rygorous/e0f055bfb74e3d5f0af20690759de5a7) //: //: Addendum to corollary: We're going to uniformly use int everywhere, to //: indicate that we're oblivious to number size, and since Clang on 32-bit //: platforms doesn't yet support multiplication over 64-bit integers, and //: since multiplying two integers seems like a more common situation to end //: up in than integer overflow. :(before "End Includes") #define SIZE(X) (assert((X).size() < (1LL<<(sizeof(int)*8-2))), static_cast<int>((X).size())) //: 5. Integer overflow is guarded against at runtime using the -ftrapv flag //: to the compiler, supported by Clang (GCC version only works sometimes: //: http://stackoverflow.com/questions/20851061/how-to-make-gcc-ftrapv-work). :(before "atexit(reset)") initialize_signal_handlers(); // not always necessary, but doesn't hurt //? cerr << INT_MAX+1 << '\n'; // test overflow //? assert(false); // test SIGABRT :(code) // based on https://spin.atomicobject.com/2013/01/13/exceptions-stack-traces-c void initialize_signal_handlers() { struct sigaction action; bzero(&action, sizeof(action)); action.sa_sigaction = dump_and_exit; sigemptyset(&action.sa_mask); sigaction(SIGABRT, &action, NULL); // assert() failure or integer overflow on linux (with -ftrapv) sigaction(SIGILL, &action, NULL); // integer overflow on OS X (with -ftrapv) } void dump_and_exit(int sig, siginfo_t* /*unused*/, void* /*unused*/) { switch (sig) { case SIGABRT: #ifndef __APPLE__ cerr << "SIGABRT: might be an integer overflow if it wasn't an assert() failure or exception\n"; _Exit(1); #endif break; case SIGILL: #ifdef __APPLE__ cerr << "SIGILL: most likely caused by integer overflow\n"; _Exit(1); #endif break; default: break; } } :(before "End Includes") #include <signal.h> //: For good measure we'll also enable SIGFPE. :(before "atexit(reset)") feenableexcept(FE_OVERFLOW | FE_UNDERFLOW); //? assert(sizeof(int) == 4 && sizeof(float) == 4); //? // | exp | mantissa //? int smallest_subnormal = 0b00000000000000000000000000000001; //? float smallest_subnormal_f = *reinterpret_cast<float*>(&smallest_subnormal); //? cerr << "ε: " << smallest_subnormal_f << '\n'; //? cerr << "ε/2: " << smallest_subnormal_f/2 << " (underflow)\n"; // test SIGFPE :(before "End Includes") #include <fenv.h> :(code) #ifdef __APPLE__ // Public domain polyfill for feenableexcept on OS X // http://www-personal.umich.edu/~williams/archive/computation/fe-handling-example.c int feenableexcept(unsigned int excepts) { static fenv_t fenv; unsigned int new_excepts = excepts & FE_ALL_EXCEPT; unsigned int old_excepts; if (fegetenv(&fenv)) return -1; old_excepts = fenv.__control & FE_ALL_EXCEPT; fenv.__control &= ~new_excepts; fenv.__mxcsr &= ~(new_excepts << 7); return fesetenv(&fenv) ? -1 : old_excepts; } #endif //: 6. Map's operator[] being non-const is fucking evil. :(before "Globals") // can't generate prototypes for these // from http://stackoverflow.com/questions/152643/idiomatic-c-for-reading-from-a-const-map template<typename T> typename T::mapped_type& get(T& map, typename T::key_type const& key) { typename T::iterator iter(map.find(key)); assert(iter != map.end()); return iter->second; } template<typename T> typename T::mapped_type const& get(const T& map, typename T::key_type const& key) { typename T::const_iterator iter(map.find(key)); assert(iter != map.end()); return iter->second; } template<typename T> typename T::mapped_type const& put(T& map, typename T::key_type const& key, typename T::mapped_type const& value) { // map[key] requires mapped_type to have a zero-arg (default) constructor map.insert(std::make_pair(key, value)).first->second = value; return value; } template<typename T> bool contains_key(T& map, typename T::key_type const& key) { return map.find(key) != map.end(); } template<typename T> typename T::mapped_type& get_or_insert(T& map, typename T::key_type const& key) { return map[key]; } //: The contract: any container that relies on get_or_insert should never call //: contains_key. //: 7. istreams are a royal pain in the arse. You have to be careful about //: what subclass you try to putback into. You have to watch out for the pesky //: failbit and badbit. Just avoid eof() and use this helper instead. :(code) bool has_data(istream& in) { return in && !in.eof(); } :(before "End Includes") #include <assert.h> #include <iostream> using std::istream; using std::ostream; using std::iostream; using std::cin; using std::cout; using std::cerr; #include <iomanip> #include <string.h> #include <string> using std::string; #include <algorithm> using std::min; using std::max;