Debian Codegraph @

src/alu.c

raw symbols SCIP
1 // ACME - a crossassembler for producing 6502/65c02/65816/65ce02 code.
2 // Copyright (C) 1998-2025 Marco Baye
3 // Have a look at "acme.c" for further info
4 //
5 // Arithmetic/logic unit
6 // 11 Oct 2006 Improved float reading in parse_number_literal()
7 // 24 Nov 2007 Now accepts floats starting with decimal point
8 // 31 Jul 2009 Changed ASR again, just to be on the safe side.
9 // 14 Jan 2014 Changed associativity of "power-of" operator,
10 // so a^b^c now means a^(b^c).
11 // 7 May 2014 C-style "==" operators are now recognized.
12 // 31 May 2014 Added "0b" binary number prefix as alternative to "%".
13 // 28 Apr 2015 Added symbol name output to "value not defined" error.
14 // 1 Feb 2019 Prepared to make "honor leading zeroes" optionally (now done)
15
16 // the words "operand"/"operator"/"operation" are too similar, so:
17 // "op" means operator/operation
18 // "arg" means argument (used instead of "operand")
19
20 #include "alu.h"
21 #include <stdlib.h>
22 #include <math.h> // only for fp support
23 #include <string.h> // for memcpy()
24 #include "platform.h"
25 #include "dynabuf.h"
26 #include "encoding.h"
27 #include "global.h"
28 #include "input.h"
29 #include "output.h"
30 #include "section.h"
31 #include "symbol.h"
32 #include "tree.h"
33
34
35 // constants
36
37 #define ERRORMSG_INITIALSIZE 256 // ad hoc
38 #define FUNCTION_INITIALSIZE 16 // enough for "is_string"
39 #define HALF_INITIAL_STACK_SIZE 8
40 static const char exception_div_by_zero[] = "Division by zero.";
41 static const char exception_no_value[] = "No value given.";
42 static const char exception_paren_open[] = "Too many '('.";
43 static const char exception_not_number[] = "Expression did not return a number.";
44 static const char exception_float_to_int[]= "Converted to integer for binary logic operator.";
45 static const char exception_lengthnot1[] = "String length is not 1.";
46
47 enum op_group {
48 OPGROUP_SPECIAL, // start/end of expression, and parentheses
49 OPGROUP_MONADIC, // {result} = {op} {arg}
50 OPGROUP_DYADIC // {result} = {arg1} {op} {arg2}
51 };
52 enum op_id {
53 // special (pseudo) operators:
54 OPID_TERMINATOR, // (preliminary) end of expression (quasi-dyadic)
55 OPID_START_EXPRESSION, // start of expression
56 OPID_SUBEXPR_PAREN, // (v '(' starts subexpression (quasi-monadic)
57 OPID_START_LIST, // [1,2] '[' starts non-empty list literal (quasi-monadic, followed by dyadic OPID_LIST_APPEND)
58 OPID_SUBEXPR_BRACKET, // v[ '[' starts subexpression (quasi-monadic, after dyadic OPID_ATINDEX)
59 // monadic operators (including functions):
60 OPID_NOT, // !v NOT v bit-wise NOT
61 OPID_NEGATE, // -v negation
62 OPID_LOWBYTEOF, // <v low byte of
63 OPID_HIGHBYTEOF, // >v high byte of
64 OPID_BANKBYTEOF, // ^v bank byte of
65 OPID_ADDRESS, // addr(v) FIXME - add nonaddr()?
66 OPID_INT, // int(v)
67 OPID_FLOAT, // float(v)
68 OPID_SIN, // sin(v)
69 OPID_COS, // cos(v)
70 OPID_TAN, // tan(v)
71 OPID_ARCSIN, // arcsin(v)
72 OPID_ARCCOS, // arccos(v)
73 OPID_ARCTAN, // arctan(v)
74 OPID_LEN, // len(v)
75 OPID_ISNUMBER, // is_number(v)
76 OPID_ISLIST, // is_list(v)
77 OPID_ISSTRING, // is_string(v)
78 OPID_DEC, // dec(v)
79 OPID_HEX, // hex(v)
80 // add CHR function to create 1-byte string? or rather add \xAB escape sequence?
81 // dyadic operators:
82 OPID_POWEROF, // v^w
83 OPID_MULTIPLY, // v*w
84 OPID_DIVIDE, // v/w division
85 OPID_INTDIV, // v/w v DIV w integer division
86 OPID_MODULO, // v%w v MOD w remainder
87 OPID_SHIFTLEFT, // v<<w v ASL w v LSL w shift left
88 OPID_ASR, // v>>w v ASR w arithmetic shift right
89 OPID_LSR, // v>>>w v LSR w logical shift right
90 OPID_ADD, // v+w
91 OPID_SUBTRACT, // v-w
92 OPID_EQUALS, // v=w
93 OPID_LESSOREQUAL, // v<=w
94 OPID_LESSTHAN, // v< w
95 OPID_GREATEROREQUAL, // v>=w
96 OPID_GREATERTHAN, // v> w
97 OPID_NOTEQUAL, // v!=w v<>w v><w
98 OPID_AND, // v&w v AND w
99 OPID_OR, // v|w v OR w
100 OPID_EOR, // v EOR w v XOR w deprecated!
101 OPID_XOR, // v XOR w
102 OPID_LIST_APPEND, // used internally when building list literal
103 OPID_ATINDEX, // v[w]
104 };
105 struct op {
106 int priority;
107 enum op_group group;
108 enum op_id id;
109 const char *text_version;
110 };
111 static struct op ops_terminating_char = {0, OPGROUP_SPECIAL, OPID_TERMINATOR, "end of expression" };
112 static struct op ops_start_expression = {2, OPGROUP_SPECIAL, OPID_START_EXPRESSION, "start of expression" };
113 static struct op ops_subexpr_paren = {4, OPGROUP_SPECIAL, OPID_SUBEXPR_PAREN, "left parenthesis" };
114 static struct op ops_start_list = {6, OPGROUP_SPECIAL, OPID_START_LIST, "start list" };
115 static struct op ops_subexpr_bracket = {8, OPGROUP_SPECIAL, OPID_SUBEXPR_BRACKET, "open index" };
116 static struct op ops_list_append = {14, OPGROUP_DYADIC, OPID_LIST_APPEND, "append to list" };
117 static struct op ops_or = {16, OPGROUP_DYADIC, OPID_OR, "logical or" };
118 static struct op ops_eor = {18, OPGROUP_DYADIC, OPID_EOR, "exclusive or" }; // FIXME - remove
119 static struct op ops_xor = {18, OPGROUP_DYADIC, OPID_XOR, "exclusive or" };
120 static struct op ops_and = {20, OPGROUP_DYADIC, OPID_AND, "logical and" };
121 static struct op ops_equals = {22, OPGROUP_DYADIC, OPID_EQUALS, "test for equality" };
122 static struct op ops_not_equal = {24, OPGROUP_DYADIC, OPID_NOTEQUAL, "test for inequality" };
123 // same priority for all comparison operators
124 static struct op ops_less_or_equal = {26, OPGROUP_DYADIC, OPID_LESSOREQUAL, "less than or equal" };
125 static struct op ops_less_than = {26, OPGROUP_DYADIC, OPID_LESSTHAN, "less than" };
126 static struct op ops_greater_or_equal = {26, OPGROUP_DYADIC, OPID_GREATEROREQUAL, "greater than or equal" };
127 static struct op ops_greater_than = {26, OPGROUP_DYADIC, OPID_GREATERTHAN, "greater than" };
128 // same priority for all byte extraction operators
129 static struct op ops_low_byte_of = {28, OPGROUP_MONADIC, OPID_LOWBYTEOF, "low byte of" };
130 static struct op ops_high_byte_of = {28, OPGROUP_MONADIC, OPID_HIGHBYTEOF, "high byte of" };
131 static struct op ops_bank_byte_of = {28, OPGROUP_MONADIC, OPID_BANKBYTEOF, "bank byte of" };
132 // same priority for all shift operators (left-associative, though they could be argued to be made right-associative :))
133 static struct op ops_shift_left = {30, OPGROUP_DYADIC, OPID_SHIFTLEFT, "shift left" };
134 static struct op ops_asr = {30, OPGROUP_DYADIC, OPID_ASR, "arithmetic shift right" };
135 static struct op ops_lsr = {30, OPGROUP_DYADIC, OPID_LSR, "logical shift right" };
136 // same priority for "+" and "-"
137 static struct op ops_add = {32, OPGROUP_DYADIC, OPID_ADD, "addition" };
138 static struct op ops_subtract = {32, OPGROUP_DYADIC, OPID_SUBTRACT, "subtraction" };
139 // same priority for "*", "/" and "%"
140 static struct op ops_multiply = {34, OPGROUP_DYADIC, OPID_MULTIPLY, "multiplication" };
141 static struct op ops_divide = {34, OPGROUP_DYADIC, OPID_DIVIDE, "division" };
142 static struct op ops_intdiv = {34, OPGROUP_DYADIC, OPID_INTDIV, "integer division" };
143 static struct op ops_modulo = {34, OPGROUP_DYADIC, OPID_MODULO, "modulo" };
144 // highest "real" priorities
145 static struct op ops_negate = {36, OPGROUP_MONADIC, OPID_NEGATE, "negation" };
146 #define PRIO_POWEROF 37 // the single right-associative operator, so this gets checked explicitly
147 static struct op ops_powerof = {PRIO_POWEROF, OPGROUP_DYADIC, OPID_POWEROF, "power of" };
148 static struct op ops_not = {38, OPGROUP_MONADIC, OPID_NOT, "logical not" };
149 static struct op ops_atindex = {40, OPGROUP_DYADIC, OPID_ATINDEX, "indexing" };
150 // function calls act as if they were monadic operators.
151 // they need high priorities to make sure they are evaluated once the
152 // parentheses' content is known:
153 // "sin(3 + 4) DYADIC_OPERATOR 5" becomes "sin 7 DYADIC_OPERATOR 5",
154 // so function calls' priority must be higher than all dyadic operators.
155 static struct op ops_addr = {42, OPGROUP_MONADIC, OPID_ADDRESS, "address()" };
156 static struct op ops_int = {42, OPGROUP_MONADIC, OPID_INT, "int()" };
157 static struct op ops_float = {42, OPGROUP_MONADIC, OPID_FLOAT, "float()" };
158 static struct op ops_sin = {42, OPGROUP_MONADIC, OPID_SIN, "sin()" };
159 static struct op ops_cos = {42, OPGROUP_MONADIC, OPID_COS, "cos()" };
160 static struct op ops_tan = {42, OPGROUP_MONADIC, OPID_TAN, "tan()" };
161 static struct op ops_arcsin = {42, OPGROUP_MONADIC, OPID_ARCSIN, "arcsin()" };
162 static struct op ops_arccos = {42, OPGROUP_MONADIC, OPID_ARCCOS, "arccos()" };
163 static struct op ops_arctan = {42, OPGROUP_MONADIC, OPID_ARCTAN, "arctan()" };
164 static struct op ops_len = {42, OPGROUP_MONADIC, OPID_LEN, "len()" };
165 static struct op ops_isnumber = {42, OPGROUP_MONADIC, OPID_ISNUMBER, "is_number()" };
166 static struct op ops_islist = {42, OPGROUP_MONADIC, OPID_ISLIST, "is_list()" };
167 static struct op ops_isstring = {42, OPGROUP_MONADIC, OPID_ISSTRING, "is_string()" };
168 static struct op ops_dec = {42, OPGROUP_MONADIC, OPID_DEC, "dec()" };
169 static struct op ops_hex = {42, OPGROUP_MONADIC, OPID_HEX, "hex()" };
170
171
172 // variables
173 static STRUCT_DYNABUF_REF(errormsg_dyna_buf, ERRORMSG_INITIALSIZE); // to build variable-length error messages
174 static STRUCT_DYNABUF_REF(function_dyna_buf, FUNCTION_INITIALSIZE); // for fn names
175 // operator stack, current size and stack pointer:
176 static struct op **op_stack = NULL;
177 static int opstack_size = HALF_INITIAL_STACK_SIZE;
178 static int op_sp;
179 // argument stack, current size and stack pointer:
180 static struct object *arg_stack = NULL;
181 static int argstack_size = HALF_INITIAL_STACK_SIZE;
182 static int arg_sp;
183 enum alu_state {
184 STATE_EXPECT_ARG_OR_MONADIC_OP,
185 STATE_EXPECT_DYADIC_OP,
186 STATE_MAX_GO_ON, // "border value" to find the stoppers:
187 STATE_ERROR, // error has occurred
188 STATE_END // standard end
189 };
190 static enum alu_state alu_state; // deterministic finite automaton
191 // predefined stuff
192 static struct ronode op_tree[] = {
193 PREDEF_START,
194 PREDEFNODE("asr", &ops_asr),
195 PREDEFNODE("lsr", &ops_lsr),
196 PREDEFNODE("asl", &ops_shift_left),
197 PREDEFNODE("lsl", &ops_shift_left),
198 PREDEFNODE("div", &ops_intdiv),
199 PREDEFNODE("mod", &ops_modulo),
200 PREDEFNODE("and", &ops_and),
201 PREDEFNODE("or", &ops_or),
202 PREDEFNODE("eor", &ops_eor), // FIXME - remove
203 PREDEF_END("xor", &ops_xor),
204 // ^^^^ this marks the last element
205 };
206 static struct ronode function_tree[] = {
207 PREDEF_START,
208 PREDEFNODE("addr", &ops_addr),
209 PREDEFNODE("address", &ops_addr),
210 PREDEFNODE("int", &ops_int),
211 PREDEFNODE("float", &ops_float),
212 PREDEFNODE("len", &ops_len),
213 PREDEFNODE("is_number", &ops_isnumber),
214 PREDEFNODE("is_list", &ops_islist),
215 PREDEFNODE("is_string", &ops_isstring),
216 PREDEFNODE("dec", &ops_dec),
217 PREDEFNODE("hex", &ops_hex),
218 PREDEFNODE("arcsin", &ops_arcsin),
219 PREDEFNODE("arccos", &ops_arccos),
220 PREDEFNODE("arctan", &ops_arctan),
221 PREDEFNODE("sin", &ops_sin),
222 PREDEFNODE("cos", &ops_cos),
223 PREDEF_END("tan", &ops_tan),
224 // ^^^^ this marks the last element
225 };
226
227 #define PUSH_OP(x) \
228 do { \
229 op_stack[op_sp] = (x); \
230 if (++op_sp >= opstack_size) \
231 enlarge_operator_stack(); \
232 } while (0)
233
234 #define PUSH_INT_ARG(i, f, r) \
235 do { \
236 arg_stack[arg_sp].type = &type_number; \
237 arg_stack[arg_sp].u.number.ntype = NUMTYPE_INT; \
238 arg_stack[arg_sp].u.number.flags = (f); \
239 arg_stack[arg_sp].u.number.val.intval = (i); \
240 arg_stack[arg_sp++].u.number.addr_refs = (r); \
241 } while (0)
242 #define PUSH_FP_ARG(fp, f) \
243 do { \
244 arg_stack[arg_sp].type = &type_number; \
245 arg_stack[arg_sp].u.number.ntype = NUMTYPE_FLOAT;\
246 arg_stack[arg_sp].u.number.flags = (f); \
247 arg_stack[arg_sp].u.number.val.fpval = (fp); \
248 arg_stack[arg_sp++].u.number.addr_refs = 0; \
249 } while (0)
250
251
252 // double the size of the operator stack
253 static void enlarge_operator_stack(void)
254 {
255 opstack_size *= 2;
256 //printf("Doubling op stack size to %d.\n", opstack_size);
257 op_stack = realloc(op_stack, opstack_size * sizeof(*op_stack));
258 if (op_stack == NULL)
259 throw_serious_error(exception_no_memory_left);
260 }
261
262
263 // double the size of the argument stack
264 static void enlarge_argument_stack(void)
265 {
266 argstack_size *= 2;
267 //printf("Doubling arg stack size to %d.\n", argstack_size);
268 arg_stack = realloc(arg_stack, argstack_size * sizeof(*arg_stack));
269 if (arg_stack == NULL)
270 throw_serious_error(exception_no_memory_left);
271 }
272
273
274 // not-so-braindead algorithm for calculating "to the power of" function for
275 // integer arguments.
276 // my_pow(whatever, 0) returns 1.
277 // my_pow(0, whatever_but_zero) returns 0.
278 static intval_t my_pow(intval_t mantissa, intval_t exponent)
279 {
280 intval_t result = 1;
281
282 while (exponent) {
283 // handle exponent's lowmost bit
284 if (exponent & 1)
285 result *= mantissa;
286 // square the mantissa, halve the exponent
287 mantissa *= mantissa;
288 exponent >>= 1;
289 }
290 return result;
291 }
292
293
294 // arithmetic shift right (works even if C compiler does not support it)
295 static intval_t my_asr(intval_t left, intval_t right)
296 {
297 // if first argument is positive or zero, ASR and LSR are equivalent,
298 // so just do it and return the result:
299 if (left >= 0)
300 return left >> right;
301
302 // However, if the first argument is negative, the result is
303 // implementation-defined: While most compilers will do ASR, some others
304 // might do LSR instead, and *theoretically*, it is even possible for a
305 // compiler to define silly stuff like "shifting a negative value to the
306 // right will always return -1".
307 // Therefore, in case of a negative argument, we'll use this quick and
308 // simple workaround:
309 return ~((~left) >> right);
310 }
311
312
313 // if wanted, throw "Value not defined" error
314 // This function is not allowed to change DynaBuf because the symbol's name
315 // might be stored there!
316 static void is_not_defined(struct symbol *symbol, char *name, size_t length)
317 {
318 if (!pass.flags.complain_about_undefined)
319 return;
320
321 // only complain once per symbol
322 if (symbol->has_been_reported)
323 return;
324
325 symbol->has_been_reported = TRUE;
326
327 dynabuf_clear(errormsg_dyna_buf);
328 dynabuf_add_string(errormsg_dyna_buf, "Symbol not defined (");
329 length += errormsg_dyna_buf->size;
330
331 dynabuf_add_string(errormsg_dyna_buf, name);
332 if (errormsg_dyna_buf->size < length) {
333 BUG("IllegalSymbolNameLength", errormsg_dyna_buf->size - length);
334 } else {
335 errormsg_dyna_buf->size = length;
336 }
337 dynabuf_add_string(errormsg_dyna_buf, ").");
338 dynabuf_append(errormsg_dyna_buf, '\0');
339 throw_error(errormsg_dyna_buf->buffer);
340 }
341
342
343 // Lookup (and create, if necessary) symbol tree item and return its value.
344 // DynaBuf holds the symbol's name and "scope" its scope.
345 // The name length must be given explicitly because of anonymous forward labels;
346 // their internal name is different (longer) than their displayed name.
347 // FIXME - just split this up into two different buffers, "user name" and "internal name", that way the scope can be changed to a prefix as well!
348 // This function is not allowed to change DynaBuf because that's where the
349 // symbol name is stored!
350 // returns pointer to symbol because the "unpseudopc" caller needs it
351 static struct symbol *get_symbol_value(scope_t scope, size_t name_length, boolean check_pass_number)
352 {
353 struct symbol *symbol;
354 struct object *arg;
355
356 symbol = symbol_find(scope);
357 symbol->has_been_read = TRUE;
358 if (symbol->object.type == NULL) {
359 // finish symbol item by making it an undefined number
360 symbol->object.type = &type_number;
361 symbol->object.u.number.ntype = NUMTYPE_UNDEFINED;
362 symbol->object.u.number.flags = NUMBER_EVER_UNDEFINED; // reading undefined taints it
363 symbol->object.u.number.addr_refs = 0;
364 } else {
365 // FIXME - add sanity check for UNDEFINED where EVER_UNDEFINED is false -> BUG()!
366 // (because the only way to have UNDEFINED is the block above, and EVER_UNDEFINED taints everything it touches)
367
368 // special kluge for anonymous backward labels:
369 // if they are referenced before they are defined, the last
370 // value of the previous pass would be used! so we check the
371 // pass number and if the value is from the previous pass, we
372 // delete it:
373 if (check_pass_number && (symbol->pass_number != pass.number))
374 symbol->object.u.number.ntype = NUMTYPE_UNDEFINED;
375 }
376 // first push on arg stack, so we have a local copy we can "unpseudo"
377 arg = &arg_stack[arg_sp++];
378 *arg = symbol->object;
379
380 // if needed, output "value not defined" error
381 // if (!(arg->type->is_defined(arg)))
382 // FIXME - now that lists with undefined items are "undefined", this fails in
383 // case of "!if len(some_list) {", so check for undefined _numbers_ explicitly:
384 if ((arg->type == &type_number) && (arg->u.number.ntype == NUMTYPE_UNDEFINED))
385 is_not_defined(symbol, GLOBALDYNABUF_CURRENT, name_length);
386 // FIXME - if arg is list, increment ref count!
387 return symbol; // only needed by "unpseudopc" caller
388 }
389
390
391 // parse program counter ('*')
392 static void parse_program_counter(void) // now GotByte = "*"
393 {
394 struct number pc;
395 struct object *arg;
396
397 GetByte();
398 programcounter_read_asterisk(&pc);
399 // push to arg stack
400 arg = &arg_stack[arg_sp++];
401 arg->type = &type_number;
402 arg->u.number = pc;
403 }
404
405
406 // make new string object
407 // (exported because symbol.c calls this for strings given on command line)
408 void string_prepare_string(struct object *self, int len)
409 {
410 self->type = &type_string;
411 self->u.string = safe_malloc(sizeof(*(self->u.string)) + len);
412 self->u.string->payload[len] = 0; // terminate, to facilitate string_print()
413 self->u.string->length = len; // length does not include the added terminator
414 self->u.string->refs = 1;
415 }
416 // parse string or character
417 // characters will be converted using the current encoding, strings are kept as-is.
418 static void parse_quoted(char closing_quote)
419 {
420 boolean is_string;
421 intval_t value;
422
423 if (input_read_string_literal(closing_quote))
424 goto fail; // unterminated or escaping error
425
426 if (config.dialect >= V0_97__BACKSLASH_ESCAPING) {
427 // since version 0.97, 'x' means character code and "x" means string:
428 is_string = (closing_quote == '"');
429 } else {
430 // older versions did not support strings, both types of quotes were treated the same:
431 is_string = FALSE;
432 }
433
434 if (is_string) {
435 string_prepare_string(&arg_stack[arg_sp], GlobalDynaBuf->size); // create string object and put on arg stack
436 memcpy(arg_stack[arg_sp].u.string->payload, GLOBALDYNABUF_CURRENT, GlobalDynaBuf->size); // copy payload
437 ++arg_sp;
438 } else {
439 // character code:
440
441 // too short?
442 if (GlobalDynaBuf->size == 0) {
443 throw_error("There is no character in quotes.");
444 goto fail;
445 }
446
447 // too long?
448 if (GlobalDynaBuf->size != 1)
449 throw_error("There's more than one character.");
450 // parse character
451 value = encoding_encode_char(GLOBALDYNABUF_CURRENT[0]);
452 PUSH_INT_ARG(value, 0, 0); // no flags, no addr refs
453 }
454 // now GotByte = char following closing quote (or CHAR_EOS on error)
455 return;
456
457 fail:
458 PUSH_INT_ARG(0, 0, 0); // dummy, no flags, no addr refs
459 alu_state = STATE_ERROR;
460 }
461
462
463 // Parse binary value. Apart from '0' and '1', it also accepts the characters
464 // '.' and '#', this is much more readable. The current value is stored as soon
465 // as a character is read that is none of those given above.
466 static void parse_binary_literal(void) // now GotByte = "%" or "b"
467 {
468 intval_t value = 0;
469 bits flags = 0;
470 int digits = -1; // digit counter
471
472 for (;;) {
473 ++digits;
474 switch (GetByte()) {
475 case '0':
476 case '.':
477 value <<= 1;
478 continue;
479 case '1':
480 case '#':
481 value = (value << 1) | 1;
482 continue;
483 }
484 break; // found illegal character
485 }
486 if (!digits) {
487 throw_error("Binary literal without any digits.");
488 }
489 if (digits & config.warn_bin_mask) {
490 throw_finalpass_warning("Binary literal with strange number of digits.");
491 }
492 // set force bits
493 if (config.honor_leading_zeroes) {
494 if (digits > 8) {
495 if (digits > 16) {
496 if (value < 65536)
497 flags |= NUMBER_FORCES_24;
498 } else {
499 if (value < 256)
500 flags |= NUMBER_FORCES_16;
501 }
502 }
503 }
504 PUSH_INT_ARG(value, flags, 0);
505 // now GotByte = non-binary char
506 }
507
508
509 // Parse hexadecimal value. It accepts "0" to "9", "a" to "f" and "A" to "F".
510 // The current value is stored as soon as a character is read that is none of
511 // those given above.
512 static void parse_hex_literal(void) // now GotByte = "$" or "x"
513 {
514 char byte;
515 int digits = -1; // digit counter
516 bits flags = 0;
517 intval_t value = 0;
518
519 for (;;) {
520 ++digits;
521 byte = GetByte();
522 // if digit or legal character, add value
523 if ((byte >= '0') && (byte <= '9')) {
524 value = (value << 4) + (byte - '0');
525 continue;
526 }
527 if ((byte >= 'a') && (byte <= 'f')) {
528 value = (value << 4) + (byte - 'a') + 10;
529 continue;
530 }
531 if ((byte >= 'A') && (byte <= 'F')) {
532 value = (value << 4) + (byte - 'A') + 10;
533 continue;
534 }
535 break; // found illegal character
536 }
537 if (!digits)
538 throw_error("Hex literal without any digits.");
539 // set force bits
540 if (config.honor_leading_zeroes) {
541 if (digits > 2) {
542 if (digits > 4) {
543 if (value < 65536)
544 flags |= NUMBER_FORCES_24;
545 } else {
546 if (value < 256)
547 flags |= NUMBER_FORCES_16;
548 }
549 }
550 }
551 PUSH_INT_ARG(value, flags, 0);
552 // Now GotByte = non-hexadecimal char
553 }
554
555
556 // parse fractional part of a floating-point value
557 static void parse_frac_part(int integer_part) // now GotByte = first digit after decimal point
558 {
559 double denominator = 1,
560 fpval = integer_part;
561
562 // parse digits until no more
563 while ((GotByte >= '0') && (GotByte <= '9')) {
564 fpval = 10 * fpval + (GotByte & 15); // this works. it's ASCII.
565 denominator *= 10;
566 GetByte();
567 }
568 // FIXME - add possibility to read 'e' and exponent!
569 PUSH_FP_ARG(fpval / denominator, 0);
570 }
571
572
573 // Parse a decimal value. As decimal values don't use any prefixes, this
574 // function expects the first digit to be read already.
575 // If the first two digits are "0x", this function branches to the one for
576 // parsing hexadecimal values.
577 // If the first two digits are "0b", this function branches to the one for
578 // parsing binary values.
579 // If a decimal point is read, this function branches to the one for parsing
580 // floating-point values.
581 // This function accepts '0' through '9' and one dot ('.') as the decimal
582 // point. The current value is stored as soon as a character is read that is
583 // none of those given above. Float usage is only activated when a decimal
584 // point has been found, so don't expect "100000000000000000000" to work.
585 // CAUTION: "100000000000000000000.0" won't work either, because when the
586 // decimal point gets parsed, the integer value will have overflown already.
587 static void parse_number_literal(void) // now GotByte = first digit
588 {
589 intval_t intval = (GotByte & 15); // this works. it's ASCII.
590
591 GetByte();
592 // check for "0b" (binary) and "0x" (hexadecimal) prefixes
593 if (intval == 0) {
594 if (GotByte == 'b') {
595 parse_binary_literal();
596 return;
597 }
598 if (GotByte == 'x') {
599 parse_hex_literal();
600 return;
601 }
602 }
603 // parse digits until no more
604 while ((GotByte >= '0') && (GotByte <= '9')) {
605 intval = 10 * intval + (GotByte & 15); // ASCII, see above
606 GetByte();
607 }
608 // check whether it's a float
609 if (GotByte == '.') {
610 // read fractional part
611 GetByte();
612 parse_frac_part(intval);
613 } else {
614 PUSH_INT_ARG(intval, 0, 0);
615 }
616 // now GotByte = non-decimal char
617 }
618
619
620 // Parse octal value. It accepts "0" to "7". The current value is stored as
621 // soon as a character is read that is none of those given above.
622 static void parse_octal_literal(void) // now GotByte = first octal digit
623 {
624 intval_t value = 0;
625 bits flags = 0;
626 int digits = 0; // digit counter
627
628 while ((GotByte >= '0') && (GotByte <= '7')) {
629 value = (value << 3) + (GotByte & 7); // this works. it's ASCII.
630 ++digits;
631 GetByte();
632 }
633 // set force bits
634 if (config.honor_leading_zeroes) {
635 if (digits > 3) {
636 if (digits > 6) {
637 if (value < 65536)
638 flags |= NUMBER_FORCES_24;
639 } else {
640 if (value < 256)
641 flags |= NUMBER_FORCES_16;
642 }
643 }
644 }
645 PUSH_INT_ARG(value, flags, 0);
646 // Now GotByte = non-octal char
647 }
648
649
650 // parse function call (sin(), cos(), arctan(), ...)
651 static void parse_function_call(void) // now GotByte = '('
652 {
653 void *node_body;
654
655 // make lower case version of name in local dynamic buffer
656 dynabuf_to_lower(function_dyna_buf, GlobalDynaBuf);
657 // search for tree item
658 if (tree_easy_scan(function_tree, &node_body, function_dyna_buf)) {
659 PUSH_OP((struct op *) node_body);
660 } else {
661 throw_error("Unknown function.");
662 alu_state = STATE_ERROR;
663 }
664 }
665
666
667 // make empty list
668 static void list_init_list(struct object *self)
669 {
670 self->type = &type_list;
671 self->u.listhead = safe_malloc(sizeof(*(self->u.listhead)));
672 self->u.listhead->next = self->u.listhead;
673 self->u.listhead->prev = self->u.listhead;
674 self->u.listhead->u.listinfo.length = 0;
675 self->u.listhead->u.listinfo.refs = 1;
676 }
677 // extend list by appending a single object
678 static void list_append_object(struct listitem *head, const struct object *obj)
679 {
680 struct listitem *item;
681
682 item = safe_malloc(sizeof(*item));
683 item->u.payload = *obj;
684 item->next = head;
685 item->prev = head->prev;
686 item->next->prev = item;
687 item->prev->next = item;
688 head->u.listinfo.length++;
689 }
690 // extend list by appending all items of a list
691 static void list_append_list(struct listitem *selfhead, struct listitem *otherhead)
692 {
693 struct listitem *item;
694
695 if (selfhead == otherhead)
696 BUG("ExtendingListWithItself", 0);
697 item = otherhead->next;
698 while (item != otherhead) {
699 list_append_object(selfhead, &item->u.payload);
700 item = item->next;
701 }
702 }
703
704
705 // helper function for "monadic &" (either octal value or "unpseudo" operator)
706 // returns nonzero on (syntax) error
707 static int parse_octal_or_unpseudo(void) // now GotByte = '&'
708 {
709 unsigned int unpseudo_count = 1;
710 struct pseudopc *context;
711 struct symbol *symbol;
712 scope_t scope;
713
714 // first count ampersand characters so we know how many layers to "unpseudo":
715 while (GetByte() == '&')
716 ++unpseudo_count;
717
718 // check for octal number:
719 if ((unpseudo_count == 1) && (GotByte >= '0') & (GotByte <= '7')) {
720 parse_octal_literal(); // now GotByte = non-octal char
721 return 0; // ok
722 }
723
724 // it's not an octal number, so it must be something to "unpseudo":
725 if (GotByte == '*') {
726 // program counter
727 parse_program_counter();
728 context = pseudopc_get_context();
729 } else if (BYTE_STARTS_KEYWORD(GotByte) || (GotByte == LOCAL_PREFIX) || (GotByte == CHEAP_PREFIX)) {
730 // symbol
731 if (input_read_scope_and_symbol_name(&scope)) // now GotByte = illegal char
732 return 1; // error (no string given)
733
734 symbol = get_symbol_value(scope, GlobalDynaBuf->size - 1, FALSE); // -1 to not count terminator, no pass number check
735 if (symbol->object.type != &type_number) {
736 throw_error("Un-pseudopc operator '&' can only be applied to number symbols.");
737 return 0; // "ok" (because the error above does not inhibit parsing)
738 }
739 context = symbol->pseudopc;
740 // } else if (...) {
741 // // anonymous symbol
742 // "unpseudo"-ing anonymous symbols is not supported
743 } else {
744 throw_error("Expected octal value or symbol name after '&'.");
745 return 1; // error
746 }
747 // now process argument on arg stack (sp has been incremented)
748 pseudopc_unpseudo(&arg_stack[arg_sp - 1].u.number, context, unpseudo_count);
749 return 0; // ok
750 }
751
752
753 // helper function to tell user not to use the "EOR" operator anymore
754 // this gets called from two places, depending on whether the result
755 // would be defined or not - to make sure the user sees it.
756 static void eor_is_obsolete(void)
757 {
758 if (config.dialect >= V0_98__PATHS_AND_SYMBOLCHANGE)
759 throw_error("the \"EOR\" operator is obsolete; use \"XOR\" instead.");
760 else
761 throw_finalpass_warning("\"EOR\" is deprecated; use \"XOR\" instead.");
762 }
763
764
765 // expression parser
766
767
768 // handler for special operators like parentheses and start/end of expression
769 #define PREVIOUS_ARGUMENT (arg_stack[arg_sp - 2])
770 #define NEWEST_ARGUMENT (arg_stack[arg_sp - 1])
771 #define PREVIOUS_OPERATOR (op_stack[op_sp - 2])
772 #define NEWEST_OPERATOR (op_stack[op_sp - 1])
773 static void handle_special_operator(struct expression *expression, enum op_id previous)
774 {
775 // when this gets called, "current" operator is OPID_TERMINATOR
776 switch (previous) {
777 case OPID_START_EXPRESSION:
778 alu_state = STATE_END; // we are done
779 // don't touch "is_parenthesized", because start/end are obviously not "real" operators
780 // not really needed, but there are sanity checks for stack pointers:
781 // remove previous operator by overwriting with newest one...
782 PREVIOUS_OPERATOR = NEWEST_OPERATOR;
783 --op_sp; // ...and shrinking operator stack
784 break;
785 case OPID_SUBEXPR_PAREN:
786 expression->is_parenthesized = TRUE; // found parentheses. if this is not the outermost level, the outermost level will fix this flag later on.
787 if (GotByte == ')') {
788 // matching parenthesis
789 GetByte(); // eat ')'
790 op_sp -= 2; // remove both SUBEXPR_PAREN and TERMINATOR
791 alu_state = STATE_EXPECT_DYADIC_OP;
792 } else {
793 // unmatched parenthesis, as in "lda ($80,x)"
794 ++(expression->open_parentheses); // count
795 // remove previous operator by overwriting with newest one...
796 PREVIOUS_OPERATOR = NEWEST_OPERATOR;
797 --op_sp; // ...and shrinking operator stack
798 }
799 break;
800 case OPID_START_LIST:
801 if (GotByte == ',') {
802 GetByte(); // eat ','
803 NEWEST_OPERATOR = &ops_list_append; // change "end of expression" to "append"
804 } else if (GotByte == ']') {
805 GetByte(); // eat ']'
806 op_sp -= 2; // remove both START_LIST and TERMINATOR
807 alu_state = STATE_EXPECT_DYADIC_OP;
808 } else {
809 // unmatched bracket
810 throw_error("Unterminated list.");
811 alu_state = STATE_ERROR;
812 // remove previous operator by overwriting with newest one...
813 PREVIOUS_OPERATOR = NEWEST_OPERATOR;
814 --op_sp; // ...and shrinking operator stack
815 }
816 break;
817 case OPID_SUBEXPR_BRACKET:
818 if (GotByte == ']') {
819 GetByte(); // eat ']'
820 op_sp -= 2; // remove both SUBEXPR_BRACKET and TERMINATOR
821 alu_state = STATE_EXPECT_DYADIC_OP;
822 } else {
823 // unmatched bracket
824 throw_error("Unterminated index spec.");
825 alu_state = STATE_ERROR;
826 // remove previous operator by overwriting with newest one...
827 PREVIOUS_OPERATOR = NEWEST_OPERATOR;
828 --op_sp; // ...and shrinking operator stack
829 }
830 break;
831 default:
832 BUG("IllegalOperatorId", previous);
833 }
834 }
835 // put dyadic operator on stack and try to reduce stacks by performing
836 // high-priority operations: as long as the second-to-last operator
837 // has a higher priority than the last one, perform the operation of
838 // that second-to-last one and remove it from stack.
839 static void push_dyadic_and_check(struct expression *expression, struct op *op)
840 {
841 PUSH_OP(op); // put newest operator on stack
842 if (alu_state < STATE_MAX_GO_ON)
843 alu_state = STATE_EXPECT_ARG_OR_MONADIC_OP;
844 while (alu_state == STATE_EXPECT_ARG_OR_MONADIC_OP) {
845 // if there is only one operator left on op stack, it must be
846 // "start of expression", so there isn't anything to do here:
847 if (op_sp < 2)
848 return;
849
850 // if previous operator has lower piority, nothing to do here:
851 if (PREVIOUS_OPERATOR->priority < NEWEST_OPERATOR->priority)
852 return;
853
854 // if priorities are the same, check associativity:
855 if ((PREVIOUS_OPERATOR->priority == NEWEST_OPERATOR->priority)
856 && (NEWEST_OPERATOR->priority == PRIO_POWEROF)) {
857 if (config.dialect >= V0_94_6__RIGHT_ASSOC_POWER) {
858 return; // since 0.94.6, "power of" operator is right-associative, so we cannot do the lefthand operation yet
859 } else {
860 // in older versions, it was left-associative, so we go on
861 }
862 }
863
864 // ok, so now perform operation indicated by previous operator!
865 switch (PREVIOUS_OPERATOR->group) {
866 case OPGROUP_MONADIC:
867 // stacks: ... ... previous op(monadic) newest arg newest op(dyadic)
868 if (arg_sp < 1)
869 BUG("ArgStackEmpty", arg_sp);
870 NEWEST_ARGUMENT.type->monadic_op(&NEWEST_ARGUMENT, PREVIOUS_OPERATOR);
871 expression->is_parenthesized = FALSE; // operation was something other than parentheses
872 // now remove previous operator by overwriting with newest one...
873 PREVIOUS_OPERATOR = NEWEST_OPERATOR;
874 --op_sp; // ...and shrinking operator stack
875 break;
876 case OPGROUP_DYADIC:
877 // stacks: previous arg previous op(dyadic) newest arg newest op(dyadic)
878 if (arg_sp < 2)
879 BUG("NotEnoughArgs", arg_sp);
880 PREVIOUS_ARGUMENT.type->dyadic_op(&PREVIOUS_ARGUMENT, PREVIOUS_OPERATOR, &NEWEST_ARGUMENT);
881 expression->is_parenthesized = FALSE; // operation was something other than parentheses
882 // now remove previous operator by overwriting with newest one...
883 PREVIOUS_OPERATOR = NEWEST_OPERATOR;
884 --op_sp; // ...and shrinking operator stack
885 --arg_sp; // and then shrink argument stack because two arguments just became one
886 break;
887 case OPGROUP_SPECIAL:
888 // stacks: ... ... previous op(special) newest arg newest op(dyadic)
889 if (NEWEST_OPERATOR->id != OPID_TERMINATOR)
890 BUG("StrangeOperator", NEWEST_OPERATOR->id);
891 handle_special_operator(expression, PREVIOUS_OPERATOR->id);
892 // the function above fixes both stacks and "is_parenthesized"!
893 break;
894 default:
895 BUG("IllegalOperatorGroup", PREVIOUS_OPERATOR->group);
896 }
897 }
898 }
899
900
901 // expect argument or monadic operator (hopefully inlined)
902 // returns TRUE if it ate any non-space (-> so expression isn't empty)
903 // returns FALSE if first non-space is delimiter (-> end of expression)
904 static boolean expect_argument_or_monadic_operator(struct expression *expression)
905 {
906 struct op *op;
907 int ugly_length_kluge;
908 boolean perform_negation;
909 scope_t scope; // for parsing symbols
910
911 SKIPSPACE();
912 switch (GotByte) {
913 case '+': // anonymous forward label
914 // count plus signs to build name of anonymous label
915 dynabuf_clear(GlobalDynaBuf);
916 do {
917 DYNABUF_APPEND(GlobalDynaBuf, '+');
918 } while (GetByte() == '+');
919 ugly_length_kluge = GlobalDynaBuf->size; // FIXME - get rid of this!
920 symbol_fix_forward_anon_name(FALSE); // FALSE: do not increment counter
921 get_symbol_value(section_now->local_scope, ugly_length_kluge, FALSE); // no prefix, no pass number check
922 goto now_expect_dyadic_op;
923
924 case '-': // NEGATION operator or anonymous backward label
925 // count minus signs in case it's an anonymous backward label
926 perform_negation = FALSE;
927 dynabuf_clear(GlobalDynaBuf);
928 do {
929 DYNABUF_APPEND(GlobalDynaBuf, '-');
930 perform_negation = !perform_negation;
931 } while (GetByte() == '-');
932 SKIPSPACE();
933 if (BYTE_FOLLOWS_ANON(GotByte)) {
934 dynabuf_append(GlobalDynaBuf, '\0');
935 get_symbol_value(section_now->local_scope, GlobalDynaBuf->size - 1, TRUE); // no prefix, -1 to not count terminator, check pass number
936 goto now_expect_dyadic_op;
937 }
938
939 if (perform_negation)
940 PUSH_OP(&ops_negate);
941 // State doesn't change
942 break;//goto done;
943 // Real monadic operators (state doesn't change, still ExpectMonadic)
944 case '!': // NOT operator
945 op = &ops_not;
946 goto get_byte_and_push_monadic;
947
948 case '<': // LOWBYTE operator
949 op = &ops_low_byte_of;
950 goto get_byte_and_push_monadic;
951
952 case '>': // HIGHBYTE operator
953 op = &ops_high_byte_of;
954 goto get_byte_and_push_monadic;
955
956 case '^': // BANKBYTE operator
957 op = &ops_bank_byte_of;
958 goto get_byte_and_push_monadic;
959
960 // special operators
961 case '[': // start of list literal
962 list_init_list(&arg_stack[arg_sp++]); // put empty list on arg stack
963 NEXTANDSKIPSPACE();
964 if (GotByte == ']') {
965 // list literal is empty, so we're basically done
966 GetByte();
967 goto now_expect_dyadic_op;
968
969 } else {
970 // non-empty list literal
971 PUSH_OP(&ops_start_list); // quasi-monadic "start of list", makes sure earlier ops do not process empty list
972 push_dyadic_and_check(expression, &ops_list_append); // dyadic "append to list", so next arg will be appended to list
973 //now we're back in STATE_EXPECT_ARG_OR_MONADIC_OP
974 }
975 break;//goto done;
976
977 case '(': // left parenthesis
978 op = &ops_subexpr_paren;
979 goto get_byte_and_push_monadic;
980
981 // arguments (state changes to ExpectDyadic)
982 case '"': // character (old) or string (new)
983 case '\'': // character
984 // Character will be converted using current encoding
985 parse_quoted(GotByte);
986 // Now GotByte = char following closing quote
987 goto now_expect_dyadic_op;
988
989 case '%': // Binary value
990 parse_binary_literal(); // Now GotByte = non-binary char
991 goto now_expect_dyadic_op;
992
993 case '&': // octal value or "unpseudo" operator applied to label
994 if (parse_octal_or_unpseudo() == 0)
995 goto now_expect_dyadic_op;
996
997 // if we're here, there was an error (like "no string given"):
998 alu_state = STATE_ERROR;
999 break;//goto done;
1000 case '$': // Hexadecimal value
1001 parse_hex_literal();
1002 // Now GotByte = non-hexadecimal char
1003 goto now_expect_dyadic_op;
1004
1005 case '*': // Program counter
1006 parse_program_counter();
1007 // Now GotByte = char after closing quote
1008 goto now_expect_dyadic_op;
1009
1010 // FIXME - find a way to tell decimal point and LOCAL_PREFIX apart!
1011 case '.': // local symbol or fractional part of float value
1012 GetByte(); // start after '.'
1013 // check for fractional part of float value
1014 if ((GotByte >= '0') && (GotByte <= '9')) {
1015 parse_frac_part(0); // now GotByte = non-decimal char
1016 goto now_expect_dyadic_op;
1017 }
1018
1019 // here we need to put '.' into GlobalDynaBuf even though we have already skipped it:
1020 if (input_read_scope_and_symbol_name_KLUGED(&scope) == 0) { // now GotByte = illegal char
1021 get_symbol_value(scope, GlobalDynaBuf->size - 1, FALSE); // -1 to not count terminator, no pass number check
1022 goto now_expect_dyadic_op; // ok
1023 }
1024
1025 // if we're here, an error has been thrown because there was no string after the '.'.
1026 alu_state = STATE_ERROR;
1027 break;//goto done;
1028 case CHEAP_PREFIX: // cheap local symbol
1029 //printf("looking in cheap scope %d\n", section_now->cheap_scope);
1030 if (input_read_scope_and_symbol_name(&scope) == 0) { // now GotByte = illegal char
1031 get_symbol_value(scope, GlobalDynaBuf->size - 1, FALSE); // -1 to not count terminator, no pass number check
1032 goto now_expect_dyadic_op; // ok
1033 }
1034
1035 // if we're here, an error has been thrown because there was no string after the '@'.
1036 alu_state = STATE_ERROR;
1037 break;//goto done;
1038 // decimal values and global symbols
1039 default: // all other characters
1040 if ((GotByte >= '0') && (GotByte <= '9')) {
1041 parse_number_literal();
1042 // now GotByte = non-decimal char
1043 goto now_expect_dyadic_op;
1044 }
1045
1046 if (BYTE_STARTS_KEYWORD(GotByte)) {
1047 register int length;
1048
1049 // read global label (or "NOT")
1050 length = parser_read_keyword();
1051 // now GotByte = illegal char
1052 // Check for NOT. Okay, it's hardcoded,
1053 // but so what? Sue me...
1054 if ((length == 3)
1055 && ((GlobalDynaBuf->buffer[0] | 32) == 'n')
1056 && ((GlobalDynaBuf->buffer[1] | 32) == 'o')
1057 && ((GlobalDynaBuf->buffer[2] | 32) == 't')) {
1058 PUSH_OP(&ops_not);
1059 // state doesn't change
1060 } else {
1061 if (GotByte == '(') {
1062 parse_function_call();
1063 // i thought about making the parentheses optional, so you can write "a = sin b"
1064 // just like "a = not b". but then each new function name would have to be made
1065 // a reserved keyword, otherwise stuff like "a = sin * < b" would be ambiguous:
1066 // it could mean either "compare sine of PC to b" or "multiply 'sin' by low byte
1067 // of b".
1068 // however, apart from that check above, function calls have nothing to do with
1069 // parentheses: "sin(x+y)" gets parsed just like "not(x+y)".
1070 } else {
1071 get_symbol_value(SCOPE_GLOBAL, GlobalDynaBuf->size - 1, FALSE); // no prefix, -1 to not count terminator, no pass number check
1072 goto now_expect_dyadic_op;
1073 }
1074 }
1075 } else {
1076 // illegal character read - so don't go on
1077 // we found end-of-expression instead of an argument,
1078 // that's either an empty expression or an erroneous one!
1079 PUSH_INT_ARG(0, 0, 0); // push dummy argument so stack checking code won't bark FIXME - use undefined?
1080 if (op_stack[op_sp - 1] == &ops_start_expression) {
1081 push_dyadic_and_check(expression, &ops_terminating_char);
1082 } else {
1083 throw_error(exception_syntax);
1084 alu_state = STATE_ERROR;
1085 }
1086 return FALSE; // found delimiter
1087 }
1088 break;//goto done;
1089
1090 // no other possibilities, so here are the shared endings
1091
1092 get_byte_and_push_monadic:
1093 GetByte();
1094 PUSH_OP(op);
1095 // state doesn't change
1096 break;
1097
1098 now_expect_dyadic_op:
1099 // bugfix: if in error state, do not change state back to valid one
1100 if (alu_state < STATE_MAX_GO_ON)
1101 alu_state = STATE_EXPECT_DYADIC_OP;
1102 break;
1103 }
1104 //done:
1105 return TRUE; // parsed something
1106 }
1107
1108
1109 // expect dyadic operator (hopefully inlined)
1110 static void expect_dyadic_operator(struct expression *expression)
1111 {
1112 void *node_body;
1113 struct op *op;
1114
1115 SKIPSPACE();
1116 switch (GotByte) {
1117 // single-character dyadic operators
1118 case '^': // "to the power of"
1119 op = &ops_powerof;
1120 goto get_byte_and_push_dyadic;
1121
1122 case '+': // add
1123 op = &ops_add;
1124 goto get_byte_and_push_dyadic;
1125
1126 case '-': // subtract
1127 op = &ops_subtract;
1128 goto get_byte_and_push_dyadic;
1129
1130 case '*': // multiply
1131 op = &ops_multiply;
1132 goto get_byte_and_push_dyadic;
1133
1134 case '/': // divide
1135 op = &ops_divide;
1136 goto get_byte_and_push_dyadic;
1137
1138 case '%': // modulo
1139 op = &ops_modulo;
1140 goto get_byte_and_push_dyadic;
1141
1142 case '&': // bitwise AND
1143 op = &ops_and;
1144 goto get_byte_and_push_dyadic;
1145
1146 case '|': // bitwise OR
1147 op = &ops_or;
1148 goto get_byte_and_push_dyadic;
1149
1150 // this part is commented out because there is no XOR character defined
1151 // case ???: // bitwise exclusive OR
1152 // op = &ops_xor;
1153 // goto get_byte_and_push_dyadic;
1154
1155 case '=': // is equal
1156 op = &ops_equals;
1157 // atm, accept both "=" and "==". in future, prefer "=="!
1158 if (GetByte() == '=') {
1159 GetByte(); // eat second '=' character
1160 } else {
1161 //throw_finalpass_warning("old-style \"=\" comparison detected, please use \"==\" instead."); ACTIVATE!
1162 }
1163 goto push_dyadic_op;
1164
1165 case '[': // indexing operator
1166 GetByte(); // eat char
1167 // first put high-priority dyadic on stack,
1168 // then low-priority special ops_subexpr_bracket
1169 push_dyadic_and_check(expression, &ops_atindex);
1170 // now we're in STATE_EXPECT_ARG_OR_MONADIC_OP
1171 PUSH_OP(&ops_subexpr_bracket);
1172 return;
1173
1174 // multi-character dyadic operators
1175 case '!': // "!="
1176 GetByte(); // eat '!'
1177 if (parser_expect('=')) {
1178 op = &ops_not_equal;
1179 goto push_dyadic_op;
1180 }
1181
1182 alu_state = STATE_ERROR;
1183 break;//goto end;
1184 case '<': // "<", "<=", "<<" and "<>"
1185 switch (GetByte()) {
1186 case '=': // "<=", less or equal
1187 op = &ops_less_or_equal;
1188 goto get_byte_and_push_dyadic;
1189
1190 case '<': // "<<", shift left
1191 op = &ops_shift_left;
1192 goto get_byte_and_push_dyadic;
1193
1194 case '>': // "<>", not equal
1195 op = &ops_not_equal;
1196 goto get_byte_and_push_dyadic;
1197
1198 default: // "<", less than
1199 op = &ops_less_than;
1200 goto push_dyadic_op;
1201
1202 }
1203 //break; unreachable
1204 case '>': // ">", ">=", ">>", ">>>" and "><"
1205 switch (GetByte()) {
1206 case '=': // ">=", greater or equal
1207 op = &ops_greater_or_equal;
1208 goto get_byte_and_push_dyadic;
1209
1210 case '<': // "><", not equal
1211 op = &ops_not_equal;
1212 goto get_byte_and_push_dyadic;
1213
1214 case '>': // ">>" or ">>>", shift right
1215 op = &ops_asr; // arithmetic shift right
1216 if (GetByte() != '>')
1217 goto push_dyadic_op;
1218
1219 op = &ops_lsr; // logical shift right
1220 goto get_byte_and_push_dyadic;
1221
1222 default: // ">", greater than
1223 op = &ops_greater_than;
1224 goto push_dyadic_op;
1225
1226 }
1227 //break; unreachable
1228 // end of expression or text version of dyadic operator
1229 default:
1230 // check string versions of operators
1231 if (BYTE_STARTS_KEYWORD(GotByte)) {
1232 parser_read_and_lower_keyword();
1233 // now GotByte = illegal char
1234 // search for tree item
1235 if (tree_easy_scan(op_tree, &node_body, GlobalDynaBuf)) {
1236 op = node_body;
1237 goto push_dyadic_op;
1238 }
1239
1240 throw_error("Unknown operator.");
1241 alu_state = STATE_ERROR;
1242 //goto end;
1243 } else {
1244 // we found end-of-expression when expecting an operator, that's ok.
1245 op = &ops_terminating_char;
1246 goto push_dyadic_op;
1247 }
1248 }
1249 //end:
1250 return; // TODO - change the two points that go here and add a BUG() instead
1251
1252 // shared endings
1253 get_byte_and_push_dyadic:
1254 GetByte();
1255 push_dyadic_op:
1256 push_dyadic_and_check(expression, op);
1257 }
1258
1259
1260 // helper function: create and output error message about (argument/)operator/argument combination
1261 static void unsupported_operation(const struct object *optional, const struct op *op, const struct object *arg)
1262 {
1263 if (optional) {
1264 if (op->group != OPGROUP_DYADIC)
1265 BUG("OperatorIsNotDyadic", op->id);
1266 } else {
1267 if (op->group != OPGROUP_MONADIC)
1268 BUG("OperatorIsNotMonadic", op->id);
1269 }
1270 dynabuf_clear(errormsg_dyna_buf);
1271 dynabuf_add_string(errormsg_dyna_buf, "Operation not supported: Cannot apply \"");
1272 dynabuf_add_string(errormsg_dyna_buf, op->text_version);
1273 dynabuf_add_string(errormsg_dyna_buf, "\" to \"");
1274 if (optional) {
1275 dynabuf_add_string(errormsg_dyna_buf, optional->type->name);
1276 dynabuf_add_string(errormsg_dyna_buf, "\" and \"");
1277 }
1278 dynabuf_add_string(errormsg_dyna_buf, arg->type->name);
1279 dynabuf_add_string(errormsg_dyna_buf, "\".");
1280 dynabuf_append(errormsg_dyna_buf, '\0');
1281 throw_error(errormsg_dyna_buf->buffer);
1282 }
1283
1284
1285 // int/float
1286
1287 // int:
1288 // create byte-sized int object (for comparison results, converted characters, ...)
1289 // FIXME - as this does not set the FITS_BYTE flag, why "byte-sized"?! why not int_create_int?
1290 static void int_create_byte(struct object *self, intval_t byte)
1291 {
1292 self->type = &type_number;
1293 self->u.number.ntype = NUMTYPE_INT;
1294 self->u.number.flags = 0;
1295 self->u.number.val.intval = byte;
1296 self->u.number.addr_refs = 0;
1297 }
1298
1299 // int:
1300 // convert to float
1301 inline static void int_to_float(struct object *self)
1302 {
1303 self->u.number.ntype = NUMTYPE_FLOAT;
1304 self->u.number.val.fpval = self->u.number.val.intval;
1305 }
1306
1307 // float:
1308 // convert to int
1309 inline static void float_to_int(struct object *self)
1310 {
1311 self->u.number.ntype = NUMTYPE_INT;
1312 self->u.number.val.intval = self->u.number.val.fpval;
1313 }
1314
1315 // list:
1316 // replace with item at index
1317 static void list_to_item(struct object *self, int index)
1318 {
1319 struct listitem *item;
1320
1321 item = self->u.listhead->next;
1322 while (index) {
1323 item = item->next;
1324 --index;
1325 }
1326 self->u.listhead->u.listinfo.refs--; // FIXME - call some fn for this (and do _after_ next line)
1327 *self = item->u.payload; // FIXME - if item is a list, it would gain a ref by this...
1328 }
1329
1330 // string:
1331 // replace with char at index
1332 static void string_to_byte(struct object *self, int index)
1333 {
1334 intval_t byte;
1335
1336 byte = encoding_encode_char(self->u.string->payload[index]);
1337 self->u.string->refs--; // FIXME - call a function for this...
1338 int_create_byte(self, byte);
1339 }
1340
1341 // int/float:
1342 // return DEFINED flag
1343 static boolean number_is_defined(const struct object *self)
1344 {
1345 return self->u.number.ntype != NUMTYPE_UNDEFINED;
1346 }
1347
1348 // list:
1349 // return TRUE only if completely defined
1350 static boolean list_is_defined(const struct object *self)
1351 {
1352 struct listitem *item;
1353
1354 // iterate over items: if an undefined one is found, return FALSE
1355 item = self->u.listhead->next;
1356 while (item != self->u.listhead) {
1357 if (!(item->u.payload.type->is_defined(&item->u.payload)))
1358 return FALSE; // we found something undefined
1359
1360 item = item->next;
1361 }
1362 // otherwise, list is defined
1363 return TRUE;
1364 }
1365
1366 // string:
1367 // ...is always considered "defined"
1368 static boolean object_return_true(const struct object *self)
1369 {
1370 return TRUE;
1371 }
1372
1373 // int/float:
1374 // check if new value differs from old
1375 // returns FALSE in case of undefined value(s), because undefined is not necessarily different!
1376 static boolean number_differs(const struct object *self, const struct object *other)
1377 {
1378 if (self->u.number.ntype == NUMTYPE_UNDEFINED)
1379 return FALSE;
1380
1381 if (other->u.number.ntype == NUMTYPE_UNDEFINED)
1382 return FALSE;
1383
1384 if (self->u.number.ntype == NUMTYPE_INT) {
1385 if (other->u.number.ntype == NUMTYPE_INT)
1386 return self->u.number.val.intval != other->u.number.val.intval;
1387 else
1388 return self->u.number.val.intval != other->u.number.val.fpval;
1389 } else {
1390 if (other->u.number.ntype == NUMTYPE_INT)
1391 return self->u.number.val.fpval != other->u.number.val.intval;
1392 else
1393 return self->u.number.val.fpval != other->u.number.val.fpval;
1394 }
1395 }
1396 // list:
1397 // check if new value differs from old
1398 static boolean list_differs(const struct object *self, const struct object *other)
1399 {
1400 struct listitem *arthur,
1401 *ford;
1402
1403 if (self->u.listhead->u.listinfo.length != other->u.listhead->u.listinfo.length)
1404 return TRUE; // lengths differ
1405
1406 // same length, so iterate over lists and check items
1407 arthur = self->u.listhead->next;
1408 ford = other->u.listhead->next;
1409 while (arthur != self->u.listhead) {
1410 if (ford == other->u.listhead)
1411 BUG("ListLengthError", 0);
1412 if (arthur->u.payload.type != ford->u.payload.type)
1413 return TRUE; // item types differ
1414
1415 if (arthur->u.payload.type->differs(&arthur->u.payload, &ford->u.payload))
1416 return TRUE; // item values differ
1417
1418 arthur = arthur->next;
1419 ford = ford->next;
1420 }
1421 if (ford != other->u.listhead)
1422 BUG("ListLengthError", 1);
1423 return FALSE; // no difference found
1424 }
1425 // string:
1426 // check if new value differs from old
1427 static boolean string_differs(const struct object *self, const struct object *other)
1428 {
1429 if (self->u.string->length != other->u.string->length)
1430 return TRUE;
1431
1432 return !!memcmp(self->u.string->payload, other->u.string->payload, self->u.string->length);
1433 }
1434
1435 // int/float:
1436 // assign new value
1437 static boolean number_assign(struct object *self, const struct object *new_value, boolean accept_change)
1438 {
1439 bits own_flags = self->u.number.flags,
1440 other_flags = new_value->u.number.flags;
1441 // local copies of the flags are used because
1442 // self->...flags might get overwritten when copying struct over, and
1443 // new_value-> is const so shouldn't be touched.
1444 boolean redefined = FALSE;
1445
1446 // accepting a different value is easily done by just forgetting the old one:
1447 if (accept_change) {
1448 self->u.number.ntype = NUMTYPE_UNDEFINED;
1449 own_flags &= ~(NUMBER_FITS_BYTE);
1450 }
1451
1452 // copy struct over?
1453 if (self->u.number.ntype != NUMTYPE_UNDEFINED) {
1454 // symbol is already defined, so compare new and old values
1455 // if values differ, remember to tell caller
1456 if (number_differs(self, new_value))
1457 redefined = TRUE; // -> throw "symbol already defined" error
1458 }
1459 // use new value:
1460 *self = *new_value; // copy type and flags/value/addr_refs
1461
1462 // now fix flags:
1463
1464 // if symbol has no force bits of its own, use the ones from new value:
1465 if ((own_flags & NUMBER_FORCEBITS) == 0)
1466 own_flags = (own_flags & ~NUMBER_FORCEBITS) | (other_flags & NUMBER_FORCEBITS);
1467
1468 // tainted symbols without "fits byte" flag must never get that flag
1469 if ((own_flags & (NUMBER_EVER_UNDEFINED | NUMBER_FITS_BYTE)) == NUMBER_EVER_UNDEFINED)
1470 other_flags &= ~NUMBER_FITS_BYTE;
1471 // now OR together "fits byte", "defined" and "tainted"
1472 // (any hypothetical problems like "what if new value is later found out
1473 // to _not_ fit byte?" would be detected in a later pass because trying
1474 // to assign that new value would throw an error)
1475 own_flags |= other_flags & (NUMBER_FITS_BYTE | NUMBER_EVER_UNDEFINED);
1476
1477 self->u.number.flags = own_flags;
1478 return redefined;
1479 }
1480
1481
1482 // list:
1483 // assign new value
1484 static boolean list_assign(struct object *self, const struct object *new_value, boolean accept_change)
1485 {
1486 boolean redefined = FALSE;
1487
1488 if ((!accept_change) && list_differs(self, new_value))
1489 redefined = TRUE; // -> throw "symbol already defined" error
1490
1491 *self = *new_value;
1492 return redefined;
1493 }
1494
1495 // string:
1496 // assign new value
1497 static boolean string_assign(struct object *self, const struct object *new_value, boolean accept_change)
1498 {
1499 boolean redefined = FALSE;
1500
1501 if ((!accept_change) && string_differs(self, new_value))
1502 redefined = TRUE; // -> throw "symbol already defined" error
1503
1504 *self = *new_value;
1505 return redefined;
1506 }
1507
1508
1509 // undefined:
1510 // handle monadic operator (includes functions)
1511 static void undef_handle_monadic_operator(struct object *self, const struct op *op)
1512 {
1513 switch (op->id) {
1514 case OPID_INT:
1515 case OPID_FLOAT:
1516 self->u.number.addr_refs = 0;
1517 break;
1518 case OPID_SIN:
1519 case OPID_COS:
1520 case OPID_TAN:
1521 case OPID_ARCSIN:
1522 case OPID_ARCCOS:
1523 case OPID_ARCTAN:
1524 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1525 self->u.number.addr_refs = 0;
1526 break;
1527 case OPID_NOT:
1528 case OPID_NEGATE:
1529 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1530 self->u.number.addr_refs = -(self->u.number.addr_refs); // negate address ref count
1531 break;
1532 case OPID_LOWBYTEOF:
1533 case OPID_HIGHBYTEOF:
1534 case OPID_BANKBYTEOF:
1535 self->u.number.flags |= NUMBER_FITS_BYTE;
1536 self->u.number.flags &= ~NUMBER_FORCEBITS;
1537 self->u.number.addr_refs = 0;
1538 break;
1539 case OPID_DEC:
1540 case OPID_HEX:
1541 // undefined number results in empty string:
1542 // (so program grows in later passes but does not shrink)
1543 string_prepare_string(self, 0); // replace self with zero-length string
1544 // we just converted an undefined argument into a result that is
1545 // defined, so the expression parser won't count it as undefined
1546 // when returning to the caller. therefore, we count it ourself:
1547 ++pass.counters.undefineds;
1548 break;
1549 // add new monadic operators here
1550 // case OPID_:
1551 // break;
1552 default:
1553 unsupported_operation(NULL, op, self);
1554 }
1555 }
1556
1557 // int:
1558 // helper function to replace int object with string version (either decimal or hexadecimal)
1559 // (also see number_print() further down which does something similar but not identical)
1560 #define NUMBUFSIZE 64 // large enough(tm) even for 64bit systems
1561 static void int_to_string(struct object *self, const char formatstring[])
1562 {
1563 char buffer[NUMBUFSIZE];
1564 int length;
1565
1566 #if _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
1567 length = snprintf(buffer, NUMBUFSIZE, formatstring, (long) self->u.number.val.intval);
1568 #else
1569 length = sprintf(buffer, formatstring, (long) self->u.number.val.intval);
1570 #endif
1571 string_prepare_string(self, length); // create string object and put on arg stack
1572 // (the fn above has already put a terminator at the correct position)
1573 memcpy(self->u.string->payload, buffer, length);
1574 }
1575
1576 // prototype for int/float passing
1577 static void float_handle_monadic_operator(struct object *self, const struct op *op);
1578 // int:
1579 // handle monadic operator (includes functions)
1580 static void int_handle_monadic_operator(struct object *self, const struct op *op)
1581 {
1582 int refs = 0; // default for "addr_refs", shortens this fn
1583
1584 switch (op->id) {
1585 case OPID_INT:
1586 break;
1587 case OPID_FLOAT:
1588 int_to_float(self);
1589 break;
1590 case OPID_SIN:
1591 case OPID_COS:
1592 case OPID_TAN:
1593 case OPID_ARCSIN:
1594 case OPID_ARCCOS:
1595 case OPID_ARCTAN:
1596 // convert int to fp and ask fp handler to do the work
1597 int_to_float(self);
1598 float_handle_monadic_operator(self, op); // TODO - put recursion check around this?
1599 return; // float handler has done everything
1600
1601 case OPID_NOT:
1602 self->u.number.val.intval = ~(self->u.number.val.intval);
1603 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1604 refs = -(self->u.number.addr_refs); // negate address ref count
1605 break;
1606 case OPID_NEGATE:
1607 self->u.number.val.intval = -(self->u.number.val.intval);
1608 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1609 refs = -(self->u.number.addr_refs); // negate address ref count as well
1610 break;
1611 case OPID_LOWBYTEOF:
1612 self->u.number.val.intval = (self->u.number.val.intval) & 255;
1613 self->u.number.flags |= NUMBER_FITS_BYTE;
1614 self->u.number.flags &= ~NUMBER_FORCEBITS;
1615 break;
1616 case OPID_HIGHBYTEOF:
1617 self->u.number.val.intval = ((self->u.number.val.intval) >> 8) & 255;
1618 self->u.number.flags |= NUMBER_FITS_BYTE;
1619 self->u.number.flags &= ~NUMBER_FORCEBITS;
1620 break;
1621 case OPID_BANKBYTEOF:
1622 self->u.number.val.intval = ((self->u.number.val.intval) >> 16) & 255;
1623 self->u.number.flags |= NUMBER_FITS_BYTE;
1624 self->u.number.flags &= ~NUMBER_FORCEBITS;
1625 break;
1626 case OPID_DEC:
1627 int_to_string(self, "%ld"); // decimal format
1628 break;
1629 case OPID_HEX:
1630 int_to_string(self, "%lx"); // hexadecimal format
1631 break;
1632 // add new monadic operators here
1633 // case OPID_:
1634 // break;
1635 default:
1636 unsupported_operation(NULL, op, self);
1637 }
1638 self->u.number.addr_refs = refs; // update address refs with local copy
1639 }
1640
1641 // float:
1642 // helper function for asin/acos:
1643 // make sure arg is in [-1, 1] range before calling function
1644 static void float_ranged_fn(double (*fn)(double), struct object *self)
1645 {
1646 if ((self->u.number.val.fpval >= -1) && (self->u.number.val.fpval <= 1)) {
1647 self->u.number.val.fpval = fn(self->u.number.val.fpval);
1648 } else {
1649 throw_error("Argument out of range."); // TODO - add number output to error message
1650 self->u.number.val.fpval = 0;
1651 }
1652 }
1653
1654 // float:
1655 // handle monadic operator (includes functions)
1656 static void float_handle_monadic_operator(struct object *self, const struct op *op)
1657 {
1658 int refs = 0; // default for "addr_refs", shortens this fn
1659
1660 switch (op->id) {
1661 case OPID_INT:
1662 float_to_int(self);
1663 break;
1664 case OPID_FLOAT:
1665 break;
1666 case OPID_SIN:
1667 self->u.number.val.fpval = sin(self->u.number.val.fpval);
1668 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1669 break;
1670 case OPID_COS:
1671 self->u.number.val.fpval = cos(self->u.number.val.fpval);
1672 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1673 break;
1674 case OPID_TAN:
1675 self->u.number.val.fpval = tan(self->u.number.val.fpval);
1676 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1677 break;
1678 case OPID_ARCSIN:
1679 float_ranged_fn(asin, self);
1680 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1681 break;
1682 case OPID_ARCCOS:
1683 float_ranged_fn(acos, self);
1684 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1685 break;
1686 case OPID_ARCTAN:
1687 self->u.number.val.fpval = atan(self->u.number.val.fpval);
1688 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1689 break;
1690 case OPID_NEGATE:
1691 self->u.number.val.fpval = -(self->u.number.val.fpval);
1692 self->u.number.flags &= ~NUMBER_FITS_BYTE;
1693 refs = -(self->u.number.addr_refs); // negate address ref count as well
1694 break;
1695 case OPID_NOT:
1696 case OPID_LOWBYTEOF:
1697 case OPID_HIGHBYTEOF:
1698 case OPID_BANKBYTEOF:
1699 // convert fp to int and ask int handler to do the work
1700 float_to_int(self);
1701 int_handle_monadic_operator(self, op); // TODO - put recursion check around this?
1702 return; // int handler has done everything
1703
1704 // add new monadic operators here
1705 // case OPID_:
1706 // break;
1707 default:
1708 unsupported_operation(NULL, op, self);
1709 }
1710 self->u.number.addr_refs = refs; // update address refs with local copy
1711 }
1712
1713 // num:
1714 // handle monadic operator (includes functions)
1715 static void number_handle_monadic_operator(struct object *self, const struct op *op)
1716 {
1717 // first check operators where we don't care about number type or value
1718 switch (op->id) {
1719 case OPID_ADDRESS:
1720 self->u.number.addr_refs = 1; // result now is an address
1721 return;
1722
1723 case OPID_ISNUMBER:
1724 int_create_byte(self, TRUE);
1725 return;
1726
1727 case OPID_ISLIST:
1728 case OPID_ISSTRING:
1729 int_create_byte(self, FALSE);
1730 return;
1731
1732 default:
1733 break;
1734 }
1735 // it's none of those, so split according to number type
1736 switch (self->u.number.ntype) {
1737 case NUMTYPE_UNDEFINED:
1738 undef_handle_monadic_operator(self, op);
1739 break;
1740 case NUMTYPE_INT:
1741 int_handle_monadic_operator(self, op);
1742 break;
1743 case NUMTYPE_FLOAT:
1744 float_handle_monadic_operator(self, op);
1745 break;
1746 default:
1747 BUG("IllegalNumberType1", self->u.number.ntype);
1748 }
1749 }
1750
1751 // list:
1752 // handle monadic operator (includes functions)
1753 static void list_handle_monadic_operator(struct object *self, const struct op *op)
1754 {
1755 int length;
1756
1757 switch (op->id) {
1758 case OPID_LEN:
1759 length = self->u.listhead->u.listinfo.length;
1760 self->u.listhead->u.listinfo.refs--; // FIXME - call some list_decrement_refs() instead...
1761 self->type = &type_number;
1762 self->u.number.ntype = NUMTYPE_INT;
1763 self->u.number.flags = 0;
1764 self->u.number.val.intval = length;
1765 self->u.number.addr_refs = 0;
1766 break;
1767 case OPID_ISLIST:
1768 int_create_byte(self, TRUE);
1769 break;
1770 case OPID_ISNUMBER:
1771 case OPID_ISSTRING:
1772 int_create_byte(self, FALSE);
1773 break;
1774 default:
1775 unsupported_operation(NULL, op, self);
1776 }
1777 }
1778
1779 // string:
1780 // handle monadic operator (includes functions)
1781 static void string_handle_monadic_operator(struct object *self, const struct op *op)
1782 {
1783 int length;
1784
1785 switch (op->id) {
1786 case OPID_LEN:
1787 length = self->u.string->length;
1788 self->u.string->refs--; // FIXME - call some string_decrement_refs() instead...
1789 self->type = &type_number;
1790 self->u.number.ntype = NUMTYPE_INT;
1791 self->u.number.flags = 0;
1792 self->u.number.val.intval = length;
1793 self->u.number.addr_refs = 0;
1794 break;
1795 case OPID_ISNUMBER:
1796 case OPID_ISLIST:
1797 int_create_byte(self, FALSE);
1798 break;
1799 case OPID_ISSTRING:
1800 int_create_byte(self, TRUE);
1801 break;
1802 default:
1803 unsupported_operation(NULL, op, self);
1804 }
1805 }
1806
1807 // int/float:
1808 // merge result flags
1809 // (used by both int and float handlers for comparison operators)
1810 static void intfloat_fix_result_after_comparison(struct object *self, const struct object *other, intval_t result)
1811 {
1812 bits flags;
1813
1814 self->type = &type_number;
1815 self->u.number.ntype = NUMTYPE_INT;
1816 self->u.number.val.intval = result;
1817 self->u.number.addr_refs = 0;
1818 flags = (self->u.number.flags | other->u.number.flags) & NUMBER_EVER_UNDEFINED; // EVER_UNDEFINED flags are ORd together
1819 flags |= NUMBER_FITS_BYTE; // comparison results are either 0 or 1, so fit in byte
1820 // (FORCEBITS are cleared)
1821 self->u.number.flags = flags;
1822 }
1823 // (used by both int and float handlers for all other dyadic operators)
1824 static void intfloat_fix_result_after_dyadic(struct object *self, const struct object *other)
1825 {
1826 self->u.number.flags |= other->u.number.flags & (NUMBER_EVER_UNDEFINED | NUMBER_FORCEBITS); // EVER_UNDEFINED and FORCEBITs are ORd together
1827 self->u.number.flags &= ~NUMBER_FITS_BYTE; // clear FITS_BYTE because result could be anything
1828 }
1829
1830 // undefined/int/float:
1831 // handle dyadic operator
1832 // (both args are numbers, but at least one of them is undefined!)
1833 static void undef_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other)
1834 {
1835 int refs = 0; // default for "addr_refs", shortens this fn
1836
1837 switch (op->id) {
1838 case OPID_POWEROF:
1839 case OPID_MULTIPLY:
1840 case OPID_DIVIDE:
1841 case OPID_INTDIV:
1842 case OPID_MODULO:
1843 case OPID_SHIFTLEFT:
1844 case OPID_ASR:
1845 case OPID_LSR:
1846 break;
1847
1848 case OPID_SUBTRACT:
1849 refs = self->u.number.addr_refs - other->u.number.addr_refs; // subtract address references
1850 break;
1851
1852 case OPID_LESSOREQUAL:
1853 case OPID_LESSTHAN:
1854 case OPID_GREATEROREQUAL:
1855 case OPID_GREATERTHAN:
1856 case OPID_NOTEQUAL:
1857 case OPID_EQUALS:
1858 // only for comparisons:
1859 self->u.number.flags |= NUMBER_FITS_BYTE; // result is either 0 or 1, so fits in byte
1860 self->u.number.flags &= ~NUMBER_FORCEBITS; // FORCEBITS are cleared
1861 goto shared;
1862
1863 case OPID_EOR:
1864 eor_is_obsolete();
1865 /*FALLTHROUGH*/
1866 case OPID_XOR:
1867 case OPID_AND:
1868 case OPID_OR:
1869 case OPID_ADD:
1870 refs = self->u.number.addr_refs + other->u.number.addr_refs; // add address references
1871 break;
1872 // add new dyadic operators here
1873 // case OPID_:
1874 // break;
1875 default:
1876 unsupported_operation(self, op, other);
1877 return;
1878 }
1879 // CAUTION: comparisons goto label below instead of jumping here
1880 self->u.number.flags |= (other->u.number.flags & NUMBER_FORCEBITS); // FORCEBITs are ORd together
1881 self->u.number.flags &= ~NUMBER_FITS_BYTE; // clear FITS_BYTE because result could be anything
1882 shared:
1883 self->u.number.flags |= (other->u.number.flags & NUMBER_EVER_UNDEFINED); // EVER_UNDEFINED flags are ORd together
1884 self->u.number.ntype = NUMTYPE_UNDEFINED;
1885 self->u.number.addr_refs = refs; // update address refs with local copy
1886 }
1887
1888 // prototype for int/float passing
1889 static void float_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other);
1890 // int:
1891 // handle dyadic operator
1892 static void int_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other)
1893 {
1894 int refs = 0; // default for "addr_refs", shortens this fn
1895
1896 // first check type of second arg:
1897 if (other->u.number.ntype == NUMTYPE_INT) {
1898 // ok
1899 } else if (other->u.number.ntype == NUMTYPE_FLOAT) {
1900 // handle according to operation
1901 switch (op->id) {
1902 case OPID_POWEROF:
1903 case OPID_MULTIPLY:
1904 case OPID_DIVIDE:
1905 case OPID_INTDIV:
1906 case OPID_ADD:
1907 case OPID_SUBTRACT:
1908 case OPID_EQUALS:
1909 case OPID_LESSOREQUAL:
1910 case OPID_LESSTHAN:
1911 case OPID_GREATEROREQUAL:
1912 case OPID_GREATERTHAN:
1913 case OPID_NOTEQUAL:
1914 // become float, delegate to float handler
1915 int_to_float(self);
1916 float_handle_dyadic_operator(self, op, other); // TODO - put recursion check around this?
1917 return; // float handler has done everything
1918
1919 case OPID_LSR:
1920 case OPID_AND:
1921 case OPID_OR:
1922 case OPID_EOR:
1923 case OPID_XOR:
1924 // convert other to int, warning user
1925 throw_finalpass_warning(exception_float_to_int);
1926 /*FALLTHROUGH*/
1927 case OPID_MODULO:
1928 case OPID_SHIFTLEFT:
1929 case OPID_ASR:
1930 // convert other to int
1931 float_to_int(other);
1932 break;
1933 // add new dyadic operators here:
1934 // case OPID_:
1935 // break;
1936 default:
1937 unsupported_operation(self, op, other);
1938 return;
1939 }
1940 // add new types here:
1941 // } else if (other->u.number.ntype == NUMTYPE_) {
1942 // ...
1943 } else {
1944 unsupported_operation(self, op, other);
1945 return;
1946 }
1947 // maybe put this into an extra "int_dyadic_int" function?
1948 // sanity check, now "other" must be an int
1949 if (other->u.number.ntype != NUMTYPE_INT)
1950 BUG("SecondArgIsNotAnInt", op->id);
1951
1952 // part 2: now we got rid of non-ints, perform actual operation:
1953 switch (op->id) {
1954 case OPID_POWEROF:
1955 if (other->u.number.val.intval >= 0) {
1956 self->u.number.val.intval = my_pow(self->u.number.val.intval, other->u.number.val.intval);
1957 } else {
1958 throw_error("Exponent is negative.");
1959 self->u.number.val.intval = 0;
1960 }
1961 break;
1962 case OPID_MULTIPLY:
1963 self->u.number.val.intval *= other->u.number.val.intval;
1964 break;
1965 case OPID_DIVIDE:
1966 case OPID_INTDIV:
1967 if (other->u.number.val.intval) {
1968 self->u.number.val.intval /= other->u.number.val.intval;
1969 break;
1970 }
1971 // "division by zero" output is below
1972 /*FALLTHROUGH*/
1973 case OPID_MODULO:
1974 if (other->u.number.val.intval) {
1975 self->u.number.val.intval %= other->u.number.val.intval;
1976 } else {
1977 throw_error(exception_div_by_zero);
1978 self->u.number.val.intval = 0;
1979 }
1980 break;
1981 case OPID_ADD:
1982 self->u.number.val.intval += other->u.number.val.intval;
1983 refs = self->u.number.addr_refs + other->u.number.addr_refs; // add address references
1984 break;
1985 case OPID_SUBTRACT:
1986 self->u.number.val.intval -= other->u.number.val.intval;
1987 refs = self->u.number.addr_refs - other->u.number.addr_refs; // subtract address references
1988 break;
1989 case OPID_SHIFTLEFT:
1990 self->u.number.val.intval <<= other->u.number.val.intval;
1991 break;
1992 case OPID_ASR:
1993 self->u.number.val.intval = my_asr(self->u.number.val.intval, other->u.number.val.intval);
1994 break;
1995 case OPID_LSR:
1996 self->u.number.val.intval = ((uintval_t) (self->u.number.val.intval)) >> other->u.number.val.intval;
1997 break;
1998 case OPID_LESSOREQUAL:
1999 intfloat_fix_result_after_comparison(self, other, self->u.number.val.intval <= other->u.number.val.intval);
2000 return;
2001
2002 case OPID_LESSTHAN:
2003 intfloat_fix_result_after_comparison(self, other, self->u.number.val.intval < other->u.number.val.intval);
2004 return;
2005
2006 case OPID_GREATEROREQUAL:
2007 intfloat_fix_result_after_comparison(self, other, self->u.number.val.intval >= other->u.number.val.intval);
2008 return;
2009
2010 case OPID_GREATERTHAN:
2011 intfloat_fix_result_after_comparison(self, other, self->u.number.val.intval > other->u.number.val.intval);
2012 return;
2013
2014 case OPID_NOTEQUAL:
2015 intfloat_fix_result_after_comparison(self, other, self->u.number.val.intval != other->u.number.val.intval);
2016 return;
2017
2018 case OPID_EQUALS:
2019 intfloat_fix_result_after_comparison(self, other, self->u.number.val.intval == other->u.number.val.intval);
2020 return;
2021
2022 case OPID_AND:
2023 self->u.number.val.intval &= other->u.number.val.intval;
2024 refs = self->u.number.addr_refs + other->u.number.addr_refs; // add address references
2025 break;
2026 case OPID_OR:
2027 self->u.number.val.intval |= other->u.number.val.intval;
2028 refs = self->u.number.addr_refs + other->u.number.addr_refs; // add address references
2029 break;
2030 case OPID_EOR:
2031 eor_is_obsolete();
2032 /*FALLTHROUGH*/
2033 case OPID_XOR:
2034 self->u.number.val.intval ^= other->u.number.val.intval;
2035 refs = self->u.number.addr_refs + other->u.number.addr_refs; // add address references
2036 break;
2037 // add new dyadic operators here
2038 // case OPID_:
2039 // break;
2040 default:
2041 unsupported_operation(self, op, other);
2042 return;
2043 }
2044 // CAUTION: comparisons call intfloat_fix_result_after_comparison instead of jumping here
2045 self->u.number.addr_refs = refs; // update address refs with local copy
2046 intfloat_fix_result_after_dyadic(self, other); // fix result flags
2047 }
2048
2049 // float:
2050 // handle dyadic operator
2051 static void float_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other)
2052 {
2053 int refs = 0; // default for "addr_refs", shortens this fn
2054
2055 // first check type of second arg:
2056 if (other->u.number.ntype == NUMTYPE_FLOAT) {
2057 // ok
2058 } else if (other->u.number.ntype == NUMTYPE_INT) {
2059 // handle according to operation
2060 switch (op->id) {
2061 // these want two floats
2062 case OPID_POWEROF:
2063 case OPID_MULTIPLY:
2064 case OPID_DIVIDE:
2065 case OPID_INTDIV:
2066 case OPID_ADD:
2067 case OPID_SUBTRACT:
2068 case OPID_LESSOREQUAL:
2069 case OPID_LESSTHAN:
2070 case OPID_GREATEROREQUAL:
2071 case OPID_GREATERTHAN:
2072 case OPID_NOTEQUAL:
2073 case OPID_EQUALS:
2074 // convert other to float
2075 int_to_float(other);
2076 break;
2077 // these jump to int handler anyway
2078 case OPID_MODULO:
2079 case OPID_LSR:
2080 case OPID_AND:
2081 case OPID_OR:
2082 case OPID_EOR:
2083 case OPID_XOR:
2084 // these actually want a float and an int
2085 case OPID_SHIFTLEFT:
2086 case OPID_ASR:
2087 break;
2088 // add new dyadic operators here
2089 // case OPID_:
2090 // break;
2091 default:
2092 unsupported_operation(self, op, other);
2093 return;
2094 }
2095 // add new types here
2096 // } else if (other->u.number.ntype == NUMTYPE_) {
2097 // ...
2098 } else {
2099 unsupported_operation(self, op, other);
2100 return;
2101 }
2102
2103 switch (op->id) {
2104 case OPID_POWEROF:
2105 self->u.number.val.fpval = pow(self->u.number.val.fpval, other->u.number.val.fpval);
2106 break;
2107 case OPID_MULTIPLY:
2108 self->u.number.val.fpval *= other->u.number.val.fpval;
2109 break;
2110 case OPID_DIVIDE:
2111 if (other->u.number.val.fpval) {
2112 self->u.number.val.fpval /= other->u.number.val.fpval;
2113 } else {
2114 throw_error(exception_div_by_zero);
2115 self->u.number.val.fpval = 0;
2116 }
2117 break;
2118 case OPID_INTDIV:
2119 if (other->u.number.val.fpval) {
2120 self->u.number.val.intval = self->u.number.val.fpval / other->u.number.val.fpval; // fp becomes int!
2121 } else {
2122 throw_error(exception_div_by_zero);
2123 self->u.number.val.intval = 0;
2124 }
2125 self->u.number.ntype = NUMTYPE_INT; // result is int
2126 break;
2127 case OPID_LSR:
2128 case OPID_AND:
2129 case OPID_OR:
2130 case OPID_EOR:
2131 case OPID_XOR:
2132 throw_finalpass_warning(exception_float_to_int);
2133 /*FALLTHROUGH*/
2134 case OPID_MODULO:
2135 float_to_int(self);
2136 // int handler will check other and, if needed, convert to int
2137 int_handle_dyadic_operator(self, op, other); // TODO - put recursion check around this?
2138 return; // int handler has done everything
2139
2140 case OPID_ADD:
2141 self->u.number.val.fpval += other->u.number.val.fpval;
2142 refs = self->u.number.addr_refs + other->u.number.addr_refs; // add address references
2143 break;
2144 case OPID_SUBTRACT:
2145 self->u.number.val.fpval -= other->u.number.val.fpval;
2146 refs = self->u.number.addr_refs - other->u.number.addr_refs; // subtract address references
2147 break;
2148 case OPID_SHIFTLEFT:
2149 if (other->u.number.ntype == NUMTYPE_FLOAT)
2150 float_to_int(other);
2151 self->u.number.val.fpval *= pow(2.0, other->u.number.val.intval);
2152 break;
2153 case OPID_ASR:
2154 if (other->u.number.ntype == NUMTYPE_FLOAT)
2155 float_to_int(other);
2156 self->u.number.val.fpval /= (1 << other->u.number.val.intval); // FIXME - why not use pow() as in SL above?
2157 break;
2158 case OPID_LESSOREQUAL:
2159 intfloat_fix_result_after_comparison(self, other, self->u.number.val.fpval <= other->u.number.val.fpval);
2160 return;
2161
2162 case OPID_LESSTHAN:
2163 intfloat_fix_result_after_comparison(self, other, self->u.number.val.fpval < other->u.number.val.fpval);
2164 return;
2165
2166 case OPID_GREATEROREQUAL:
2167 intfloat_fix_result_after_comparison(self, other, self->u.number.val.fpval >= other->u.number.val.fpval);
2168 return;
2169
2170 case OPID_GREATERTHAN:
2171 intfloat_fix_result_after_comparison(self, other, self->u.number.val.fpval > other->u.number.val.fpval);
2172 return;
2173
2174 case OPID_NOTEQUAL:
2175 intfloat_fix_result_after_comparison(self, other, self->u.number.val.fpval != other->u.number.val.fpval);
2176 return;
2177
2178 case OPID_EQUALS:
2179 intfloat_fix_result_after_comparison(self, other, self->u.number.val.fpval == other->u.number.val.fpval);
2180 return;
2181
2182 // add new dyadic operators here
2183 // case OPID_:
2184 // break;
2185 default:
2186 unsupported_operation(self, op, other);
2187 return;
2188 }
2189 // CAUTION: comparisons call intfloat_fix_result_after_comparison instead of jumping here
2190 self->u.number.addr_refs = refs; // update address refs with local copy
2191 intfloat_fix_result_after_dyadic(self, other); // fix result flags
2192 }
2193
2194 // num:
2195 // handle dyadic operator
2196 static void number_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other)
2197 {
2198 // first check type of second arg:
2199 if (other->type != &type_number) {
2200 unsupported_operation(self, op, other);
2201 return;
2202 }
2203
2204 if ((self->u.number.ntype == NUMTYPE_UNDEFINED)
2205 || (other->u.number.ntype == NUMTYPE_UNDEFINED))
2206 undef_handle_dyadic_operator(self, op, other);
2207 else if (self->u.number.ntype == NUMTYPE_INT)
2208 int_handle_dyadic_operator(self, op, other);
2209 else if (self->u.number.ntype == NUMTYPE_FLOAT)
2210 float_handle_dyadic_operator(self, op, other);
2211 else
2212 BUG("IllegalNumberType2", self->u.number.ntype);
2213 }
2214
2215
2216 // helper function for lists and strings, check index
2217 // return zero on success, nonzero on error
2218 static int get_valid_index(int *target, int length, const struct object *self, const struct op *op, struct object *other)
2219 {
2220 int index;
2221
2222 if (other->type != &type_number) {
2223 unsupported_operation(self, op, other);
2224 return 1;
2225 }
2226 if (other->u.number.ntype == NUMTYPE_UNDEFINED) {
2227 throw_error("Index is undefined.");
2228 return 1;
2229 }
2230 if (other->u.number.ntype == NUMTYPE_FLOAT)
2231 float_to_int(other);
2232 if (other->u.number.ntype != NUMTYPE_INT)
2233 BUG("IllegalNumberType3", other->u.number.ntype);
2234
2235 index = other->u.number.val.intval;
2236 // negative indices access from the end
2237 if (index < 0)
2238 index += length;
2239 if ((index < 0) || (index >= length)) {
2240 throw_error("Index out of range.");
2241 return 1;
2242 }
2243 *target = index;
2244 return 0; // ok
2245 }
2246
2247 // list:
2248 // handle dyadic operator
2249 static void list_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other)
2250 {
2251 struct listitem *item;
2252 int length;
2253 int index;
2254
2255 length = self->u.listhead->u.listinfo.length;
2256 switch (op->id) {
2257 case OPID_LIST_APPEND:
2258 list_append_object(self->u.listhead, other);
2259 // no need to check/update ref count of "other": it loses the ref on the stack and gains one in the list
2260 return;
2261
2262 case OPID_ATINDEX:
2263 if (get_valid_index(&index, length, self, op, other))
2264 return; // error has been thrown
2265
2266 list_to_item(self, index);
2267 return; // ok
2268
2269 case OPID_ADD:
2270 if (other->type != &type_list)
2271 break; // complain
2272 item = self->u.listhead; // get ref to first list
2273 list_init_list(self); // replace first list on arg stack with new one
2274 list_append_list(self->u.listhead, item);
2275 item->u.listinfo.refs--; // FIXME - call a function for this...
2276 item = other->u.listhead;
2277 list_append_list(self->u.listhead, item);
2278 item->u.listinfo.refs--; // FIXME - call a function for this...
2279 return;
2280
2281 case OPID_EQUALS:
2282 if (other->type != &type_list)
2283 break; // complain FIXME - return FALSE?
2284 int_create_byte(self, !list_differs(self, other));
2285 // FIXME - call function to decrement refs!
2286 return;
2287
2288 case OPID_NOTEQUAL:
2289 if (other->type != &type_list)
2290 break; // complain FIXME - return TRUE?
2291 int_create_byte(self, list_differs(self, other));
2292 // FIXME - call function to decrement refs!
2293 return;
2294
2295 //case ...: // maybe comparisons?
2296 default:
2297 break; // complain
2298 }
2299 unsupported_operation(self, op, other);
2300 }
2301
2302 // string:
2303 // handle dyadic operator
2304 static void string_handle_dyadic_operator(struct object *self, const struct op *op, struct object *other)
2305 {
2306 int length;
2307 int index;
2308 struct string *arthur,
2309 *ford;
2310
2311 length = self->u.string->length;
2312 switch (op->id) {
2313 case OPID_ATINDEX:
2314 if (get_valid_index(&index, length, self, op, other))
2315 return; // error has already been reported
2316
2317 string_to_byte(self, index);
2318 return; // ok
2319
2320 case OPID_ADD:
2321 if (other->type != &type_string)
2322 break; // complain
2323 arthur = self->u.string;
2324 ford = other->u.string;
2325 string_prepare_string(self, arthur->length + ford->length); // create string object and put on arg stack
2326 memcpy(self->u.string->payload, arthur->payload, arthur->length);
2327 memcpy(self->u.string->payload + arthur->length, ford->payload, ford->length);
2328 arthur->refs--; // FIXME - call a function for this...
2329 ford->refs--; // FIXME - call a function for this...
2330 return;
2331
2332 case OPID_EQUALS:
2333 if (other->type != &type_string)
2334 break; // complain FIXME - return FALSE?
2335 arthur = self->u.string;
2336 ford = other->u.string;
2337 int_create_byte(self, !string_differs(self, other));
2338 arthur->refs--; // FIXME - call a function for this...
2339 ford->refs--; // FIXME - call a function for this...
2340 return;
2341
2342 case OPID_NOTEQUAL:
2343 if (other->type != &type_string)
2344 break; // complain FIXME - return TRUE?
2345 arthur = self->u.string;
2346 ford = other->u.string;
2347 int_create_byte(self, string_differs(self, other));
2348 arthur->refs--; // FIXME - call a function for this...
2349 ford->refs--; // FIXME - call a function for this...
2350 return;
2351
2352 //case ...: // maybe comparisons?
2353 default:
2354 break; // complain
2355 }
2356 unsupported_operation(self, op, other);
2357 }
2358
2359 // int/float:
2360 // set flags according to result
2361 static void number_fix_result(struct object *self)
2362 {
2363 // only allow a single force bit
2364 if (self->u.number.flags & NUMBER_FORCES_24)
2365 self->u.number.flags &= ~(NUMBER_FORCES_16 | NUMBER_FORCES_8);
2366 else if (self->u.number.flags & NUMBER_FORCES_16)
2367 self->u.number.flags &= ~NUMBER_FORCES_8;
2368 }
2369
2370 // list/string:
2371 // no need to fix results
2372 static void object_no_op(struct object *self)
2373 {
2374 }
2375
2376 // int/float:
2377 // print value for user message
2378 // (also see int_to_string() further up which does something similar but not identical)
2379 static void number_print(const struct object *self, struct dynabuf *db)
2380 {
2381 char buffer[NUMBUFSIZE];
2382
2383 if (self->u.number.ntype == NUMTYPE_UNDEFINED) {
2384 dynabuf_add_string(db, "<UNDEFINED NUMBER>");
2385 } else if (self->u.number.ntype == NUMTYPE_INT) {
2386 #if _BSD_SOURCE || _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L
2387 snprintf(buffer, NUMBUFSIZE, "%ld (0x%lx)", (long) self->u.number.val.intval, (long) self->u.number.val.intval);
2388 #else
2389 sprintf(buffer, "%ld (0x%lx)", (long) self->u.number.val.intval, (long) self->u.number.val.intval);
2390 #endif
2391 dynabuf_add_string(db, buffer);
2392 } else if (self->u.number.ntype == NUMTYPE_FLOAT) {
2393 // write up to 30 significant characters.
2394 // remaining 10 should suffice for sign,
2395 // decimal point, exponent, terminator etc.
2396 sprintf(buffer, "%.30g", self->u.number.val.fpval);
2397 dynabuf_add_string(db, buffer);
2398 } else {
2399 BUG("IllegalNumberType5", self->u.number.ntype);
2400 }
2401 }
2402
2403 // list:
2404 // print value for user message
2405 static void list_print(const struct object *self, struct dynabuf *db)
2406 {
2407 struct listitem *item;
2408 int length;
2409 struct object *obj;
2410 const char *prefix = ""; // first item does not get a prefix
2411
2412 dynabuf_append(db, '[');
2413 length = self->u.listhead->u.listinfo.length;
2414 item = self->u.listhead->next;
2415 while (length--) {
2416 obj = &item->u.payload;
2417 dynabuf_add_string(db, prefix);
2418 obj->type->print(obj, db);
2419 item = item->next;
2420 prefix = ", "; // following items are prefixed
2421 }
2422 dynabuf_append(db, ']');
2423 }
2424
2425 // string:
2426 // print value for user message
2427 static void string_print(const struct object *self, struct dynabuf *db)
2428 {
2429 dynabuf_add_string(db, self->u.string->payload); // there is a terminator after the actual payload, so this works
2430 }
2431
2432 // number:
2433 // is not iterable
2434 static int has_no_length(const struct object *self)
2435 {
2436 return -1; // not iterable
2437 }
2438
2439 // list:
2440 // return length
2441 static int list_get_length(const struct object *self)
2442 {
2443 return self->u.listhead->u.listinfo.length;
2444 }
2445
2446 // string:
2447 // return length
2448 static int string_get_length(const struct object *self)
2449 {
2450 return self->u.string->length;
2451 }
2452
2453 // number:
2454 // cannot be indexed
2455 static void cannot_be_indexed(const struct object *self, struct object *target, int index)
2456 {
2457 BUG("TriedToIndexNumber", index);
2458 }
2459
2460 // list:
2461 // return item at index
2462 static void list_at(const struct object *self, struct object *target, int index)
2463 {
2464 *target = *self;
2465 list_to_item(target, index);
2466 }
2467
2468 // string:
2469 // return char at index
2470 static void string_at(const struct object *self, struct object *target, int index)
2471 {
2472 *target = *self;
2473 string_to_byte(target, index);
2474 }
2475
2476 // "class" definitions
2477 struct type type_number = {
2478 "number",
2479 number_is_defined,
2480 number_differs,
2481 number_assign,
2482 number_handle_monadic_operator,
2483 number_handle_dyadic_operator,
2484 number_fix_result,
2485 number_print,
2486 has_no_length,
2487 cannot_be_indexed
2488 };
2489 struct type type_list = {
2490 "list",
2491 list_is_defined,
2492 list_differs,
2493 list_assign,
2494 list_handle_monadic_operator,
2495 list_handle_dyadic_operator,
2496 object_no_op, // no need to fix list results
2497 list_print,
2498 list_get_length,
2499 list_at
2500 };
2501 struct type type_string = {
2502 "string",
2503 object_return_true, // strings are always defined
2504 string_differs,
2505 string_assign,
2506 string_handle_monadic_operator,
2507 string_handle_dyadic_operator,
2508 object_no_op, // no need to fix string results
2509 string_print,
2510 string_get_length,
2511 string_at
2512 };
2513
2514
2515 // this is what the exported functions call
2516 // returns nonzero on parse error
2517 static int parse_expression(struct expression *expression)
2518 {
2519 struct object *result = &expression->result;
2520
2521 // make sure stacks are ready (if not yet initialised, do it now)
2522 if (arg_stack == NULL)
2523 enlarge_argument_stack();
2524 if (op_stack == NULL)
2525 enlarge_operator_stack();
2526
2527 // init
2528 expression->is_empty = TRUE; // becomes FALSE when first valid char gets parsed
2529 expression->open_parentheses = 0;
2530 expression->is_parenthesized = FALSE; // '(' operator sets this to TRUE, all others to FALSE. outermost operator wins!
2531 //expression->number will be overwritten later, so no need to init
2532
2533 op_sp = 0; // operator stack pointer
2534 arg_sp = 0; // argument stack pointer
2535 // begin by reading an argument (or a monadic operator)
2536 PUSH_OP(&ops_start_expression);
2537 alu_state = STATE_EXPECT_ARG_OR_MONADIC_OP;
2538 do {
2539 // check arg stack size. enlarge if needed
2540 if (arg_sp >= argstack_size)
2541 enlarge_argument_stack();
2542 // (op stack size is checked whenever pushing an operator)
2543 switch (alu_state) {
2544 case STATE_EXPECT_ARG_OR_MONADIC_OP:
2545 if (expect_argument_or_monadic_operator(expression))
2546 expression->is_empty = FALSE;
2547 break;
2548 case STATE_EXPECT_DYADIC_OP:
2549 expect_dyadic_operator(expression);
2550 break;
2551 case STATE_MAX_GO_ON: // suppress
2552 case STATE_ERROR: // compiler
2553 case STATE_END: // warnings
2554 break;
2555 }
2556 } while (alu_state < STATE_MAX_GO_ON);
2557 // done. check state.
2558 if (alu_state == STATE_END) {
2559 // check for bugs
2560 if (arg_sp != 1)
2561 BUG("ArgStackNotEmpty", arg_sp);
2562 if (op_sp != 1)
2563 BUG("OperatorStackNotEmpty", op_sp);
2564 // copy result
2565 *result = arg_stack[0];
2566 // if there was nothing to parse, mark as undefined FIXME - change this! make "nothing" its own result type; only numbers may be undefined
2567 // (so ALU_defined_int() can react)
2568 if (expression->is_empty) {
2569 result->type = &type_number;
2570 result->u.number.ntype = NUMTYPE_UNDEFINED;
2571 result->u.number.flags = NUMBER_EVER_UNDEFINED;
2572 result->u.number.addr_refs = 0;
2573 } else {
2574 // not empty. undefined?
2575 if (!(result->type->is_defined(result))) {
2576 // then count (in all passes)
2577 ++pass.counters.undefineds;
2578 }
2579 }
2580 // do some checks depending on int/float
2581 result->type->fix_result(result);
2582 return 0; // ok
2583 } else {
2584 // State is STATE_ERROR. Errors have already been reported,
2585 // but we must make sure not to pass bogus data to caller.
2586 // FIXME - just use the return value to indicate "there were errors, do not use result!"
2587 result->type = &type_number;
2588 result->u.number.ntype = NUMTYPE_UNDEFINED; // maybe use NUMTYPE_INT to suppress follow-up errors?
2589 result->u.number.flags = 0;
2590 //result->u.number.val.intval = 0;
2591 result->u.number.addr_refs = 0;
2592 // make sure no additional (spurious) errors are reported:
2593 parser_skip_remainder();
2594 // FIXME - remove this when new function interface gets used:
2595 // callers must decide for themselves what to do when expression
2596 // parser returns error (and may decide to call parser_skip_remainder)
2597 return 1; // error
2598 }
2599 }
2600
2601
2602 // store int value (if undefined, store zero)
2603 // For empty expressions, an error is thrown.
2604 // OPEN_PARENTHESIS: complain
2605 // EMPTY: complain
2606 // UNDEFINED: allow
2607 // FLOAT: convert to int
2608 void ALU_any_int(intval_t *target) // ACCEPT_UNDEFINED
2609 {
2610 struct expression expression;
2611
2612 parse_expression(&expression); // FIXME - check return value and pass to caller!
2613 if (expression.open_parentheses)
2614 throw_error(exception_paren_open);
2615 if (expression.is_empty)
2616 throw_error(exception_no_value);
2617 if (expression.result.type == &type_number) {
2618 if (expression.result.u.number.ntype == NUMTYPE_UNDEFINED)
2619 *target = 0;
2620 else if (expression.result.u.number.ntype == NUMTYPE_INT)
2621 *target = expression.result.u.number.val.intval;
2622 else if (expression.result.u.number.ntype == NUMTYPE_FLOAT)
2623 *target = expression.result.u.number.val.fpval;
2624 else
2625 BUG("IllegalNumberType6", expression.result.u.number.ntype);
2626 } else if (expression.result.type == &type_string) {
2627 // accept single-char strings, to be more
2628 // compatible with versions before 0.97:
2629 if (expression.result.u.string->length != 1) {
2630 throw_error(exception_lengthnot1);
2631 } else {
2632 // FIXME - throw a warning?
2633 }
2634 string_to_byte(&(expression.result), 0);
2635 *target = expression.result.u.number.val.intval;
2636 } else {
2637 *target = 0;
2638 throw_error(exception_not_number);
2639 }
2640 }
2641
2642
2643 // stores int value and flags (floats are transformed to int)
2644 // if result is empty or undefined, serious error is thrown
2645 // OPEN_PARENTHESIS: complain
2646 // EMPTY: complain _seriously_
2647 // UNDEFINED: complain _seriously_
2648 // FLOAT: convert to int
2649 // FIXME - only very few callers actually _need_ a serious error to be thrown,
2650 // so throw a normal one here and pass ok/fail as return value, so caller can react.
2651 void ALU_defined_int(struct number *intresult) // no ACCEPT constants?
2652 {
2653 struct expression expression;
2654 boolean buf = pass.flags.complain_about_undefined;
2655
2656 pass.flags.complain_about_undefined = TRUE;
2657 parse_expression(&expression); // FIXME - check return value and pass to caller!
2658 pass.flags.complain_about_undefined = buf;
2659 /*
2660 FIXME - that "buffer COMPLAIN status" thing no longer works: now that we have
2661 lists, stuff like
2662 [2, 3, undefined][0]
2663 or
2664 len([2,3,undefined])
2665 throws errors even though the result is defined!
2666 */
2667 if (expression.open_parentheses)
2668 throw_error(exception_paren_open);
2669 if (expression.is_empty)
2670 throw_serious_error(exception_no_value);
2671 if (expression.result.type == &type_number) {
2672 if (expression.result.u.number.ntype == NUMTYPE_UNDEFINED) {
2673 throw_serious_error("Value not defined.");
2674 expression.result.u.number.val.intval = 0;
2675 } else if (expression.result.u.number.ntype == NUMTYPE_INT) {
2676 // ok
2677 } else if (expression.result.u.number.ntype == NUMTYPE_FLOAT) {
2678 float_to_int(&expression.result);
2679 } else {
2680 BUG("IllegalNumberType7", expression.result.u.number.ntype);
2681 }
2682 } else if (expression.result.type == &type_string) {
2683 // accept single-char strings, to be more
2684 // compatible with versions before 0.97:
2685 if (expression.result.u.string->length != 1) {
2686 throw_error(exception_lengthnot1);
2687 } else {
2688 // FIXME - throw a warning?
2689 }
2690 string_to_byte(&(expression.result), 0);
2691 } else {
2692 throw_serious_error(exception_not_number);
2693 }
2694 *intresult = expression.result.u.number;
2695 }
2696
2697
2698 // Store int value and flags.
2699 // This function allows for "paren" '(' too many. Needed when parsing indirect
2700 // addressing modes where internal indices have to be possible.
2701 // For empty expressions, an error is thrown.
2702 // OPEN_PARENTHESIS: depends on arg
2703 // UNDEFINED: allow
2704 // EMPTY: complain
2705 // FLOAT: convert to int
2706 void ALU_addrmode_int(struct expression *expression, int paren) // ACCEPT_UNDEFINED | ACCEPT_OPENPARENTHESIS
2707 {
2708 parse_expression(expression); // FIXME - check return value and pass to caller!
2709 if (expression->result.type == &type_number) {
2710 // convert float to int
2711 if (expression->result.u.number.ntype == NUMTYPE_FLOAT)
2712 float_to_int(&(expression->result));
2713 else if (expression->result.u.number.ntype == NUMTYPE_UNDEFINED)
2714 expression->result.u.number.val.intval = 0;
2715 } else if (expression->result.type == &type_string) {
2716 // accept single-char strings, to be more
2717 // compatible with versions before 0.97:
2718 if (expression->result.u.string->length != 1) {
2719 throw_error(exception_lengthnot1);
2720 } else {
2721 // FIXME - throw a warning?
2722 }
2723 string_to_byte(&(expression->result), 0);
2724 } else {
2725 throw_error(exception_not_number);
2726 }
2727 if (expression->open_parentheses > paren) {
2728 expression->open_parentheses = 0;
2729 throw_error(exception_paren_open);
2730 }
2731 if (expression->is_empty)
2732 throw_error(exception_no_value);
2733 }
2734
2735
2736 // Store resulting object
2737 // For empty expressions, an error is thrown.
2738 // OPEN_PARENTHESIS: complain
2739 // EMPTY: complain
2740 // UNDEFINED: allow
2741 // FLOAT: keep
2742 void ALU_any_result(struct object *result) // ACCEPT_UNDEFINED | ACCEPT_FLOAT
2743 {
2744 struct expression expression;
2745
2746 parse_expression(&expression); // FIXME - check return value and pass to caller!
2747 *result = expression.result;
2748 if (expression.open_parentheses)
2749 throw_error(exception_paren_open);
2750 if (expression.is_empty)
2751 throw_error(exception_no_value);
2752 }
2753
2754
2755 /* TODO
2756
2757 maybe move
2758 if (expression.is_empty)
2759 throw_error(exception_no_value);
2760 to end of parse_expression()
2761
2762
2763 // stores int value and flags, allowing for "paren" '(' too many (x-indirect addr).
2764 void ALU_addrmode_int(struct expression *expression, int paren)
2765 mnemo.c
2766 when parsing addressing modes needvalue!
2767
2768 // store resulting object
2769 void ALU_any_result(struct object *result)
2770 macro.c
2771 macro call, when parsing call-by-value arg don't care
2772 pseudoopcodes.c
2773 !set don't care
2774 when throwing user-specified errors don't care
2775 iterator for !by, !wo, etc. needvalue!
2776 byte values in !raw, !tx, etc. needvalue!
2777 !scrxor needvalue!
2778 symbol.c
2779 explicit symbol definition don't care
2780
2781 // stores int value and flags (floats are transformed to int)
2782 // if result was undefined, serious error is thrown
2783 void ALU_defined_int(struct number *intresult)
2784 flow.c
2785 when parsing loop conditions make bool serious
2786 pseudoopcodes.c
2787 *= (FIXME, allow undefined) needvalue!
2788 !initmem error
2789 !fill (1st arg) (maybe allow undefined?) needvalue!
2790 !skip (maybe allow undefined?) needvalue!
2791 !align (1st + 2nd arg) (maybe allow undefined?) needvalue!
2792 !pseudopc (FIXME, allow undefined) needvalue!
2793 !if make bool serious
2794 twice in !for serious
2795 twice for !binary (maybe allow undefined?) needvalue!
2796 //!enum
2797
2798 // store int value (0 if result was undefined)
2799 void ALU_any_int(intval_t *target)
2800 pseudoopcodes.c
2801 !xor needvalue!
2802 !fill (2nd arg) needvalue!
2803 !align (3rd arg) needvalue!
2804 */