Debian Codegraph @

src/global.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 // Global stuff - things that are needed by several modules
6 // 4 Oct 2006 Fixed a typo in a comment
7 // 22 Nov 2007 Added warn_on_indented_labels
8 // 2 Jun 2014 Added warn_on_old_for and warn_on_type_mismatch
9 // 19 Nov 2014 Merged Johann Klasek's report listing generator patch
10 // 23 Nov 2014 Merged Martin Piper's "--msvc" error output patch
11 // 9 Jan 2018 Made '/' a syntax char to allow for "//" comments
12 // 14 Apr 2020 Added config vars for "ignore zeroes" and "segment warnings to errors"
13 #include "global.h"
14 #include <string.h> // for strcmp()
15 #include "platform.h"
16 #include "acme.h"
17 #include "alu.h"
18 #include "cpu.h"
19 #include "dynabuf.h"
20 #include "encoding.h"
21 #include "input.h"
22 #include "macro.h"
23 #include "output.h"
24 #include "pseudoopcodes.h"
25 #include "section.h"
26 #include "symbol.h"
27 #include "tree.h"
28 #include "typesystem.h"
29
30
31 // constants
32 char s_untitled[] = "<untitled>"; // FIXME - this is actually const
33
34
35 // Exception messages during assembly
36 const char exception_negative_size[] = "Negative size argument.";
37 const char exception_no_left_brace [] = "Expected '{' character.";
38 const char exception_no_memory_left[] = "Out of memory.";
39 const char exception_no_right_brace [] = "Expected '}', found EOF instead.";
40 //const char exception_not_yet[] = "Sorry, feature not yet implemented.";
41 // TODO - show actual value in error message
42 const char exception_number_out_of_range[] = "Number out of range.";
43 const char exception_number_out_of_8b_range[] = "Number does not fit in 8 bits.";
44 static const char exception_number_out_of_16b_range[] = "Number does not fit in 16 bits.";
45 static const char exception_number_out_of_24b_range[] = "Number does not fit in 24 bits.";
46 const char exception_pc_undefined[] = "Program counter undefined.";
47 const char exception_symbol_defined[] = "Symbol already defined.";
48 const char exception_syntax[] = "Syntax error.";
49 // default value for number of errors before exiting
50 #define MAXERRORS 10
51
52 // Flag table:
53 // This table contains flags for all the 256 possible byte values. The
54 // assembler reads the table whenever it needs to know whether a byte is
55 // allowed to be in a label name, for example.
56 // Bits Meaning when set
57 // 7....... Byte allowed to start keyword
58 // .6...... Byte allowed in keyword
59 // ..5..... Byte is upper case, can be lowercased by OR-ing this bit(!)
60 // ...4.... special character for input syntax: 0x00 TAB LF CR SPC / : ; }
61 // ....3... preceding sequence of '-' characters is anonymous backward
62 // label. Currently only set for ')', ',' and CHAR_EOS.
63 // .....210 currently unused
64 const char global_byte_flags[256] = {
65 /*$00*/ 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,// control characters
66 0x00, 0x10, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00,
67 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
68 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
69 /*$20*/ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,// " !"#$%&'"
70 0x00, 0x08, 0x00, 0x00, 0x08, 0x00, 0x00, 0x10,// "()*+,-./"
71 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,// "01234567"
72 0x40, 0x40, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,// "89:;<=>?"
73 /*$40*/ 0x00, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0,// "@ABCDEFG"
74 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0,// "HIJKLMNO"
75 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0, 0xe0,// "PQRSTUVW"
76 0xe0, 0xe0, 0xe0, 0x00, 0x00, 0x00, 0x00, 0xc0,// "XYZ[\]^_"
77 /*$60*/ 0x00, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,// "`abcdefg"
78 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,// "hijklmno"
79 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,// "pqrstuvw"
80 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x10, 0x00, 0x00,// "xyz{|}~" BACKSPACE
81 /*$80*/ 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,// umlauts etc. ...
82 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
83 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
84 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
85 /*$a0*/ 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
86 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
87 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
88 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
89 /*$c0*/ 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
90 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
91 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
92 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
93 /*$e0*/ 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
94 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
95 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
96 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0,
97 };
98
99
100 // variables
101 struct report *report = NULL;
102 struct config config;
103 struct pass pass;
104 struct sanity sanity;
105
106 // set configuration to default values
107 void config_default(struct config *conf)
108 {
109 conf->pseudoop_prefix = '!'; // can be changed to '.' by CLI switch
110 conf->process_verbosity = 0; // level of additional output
111 conf->warn_on_indented_labels = TRUE; // warn if indented label is encountered
112 conf->warn_on_type_mismatch = FALSE; // use type-checking system
113 conf->warn_bin_mask = 3; // %11 -> warn if not divisible by four
114 conf->max_errors = MAXERRORS; // errors before giving up
115 conf->sanity_limit = SANITY_LIMIT; // changed by --maxdepth
116 conf->format_msvc = FALSE; // enabled by --msvc
117 conf->format_color = FALSE; // enabled by --color
118 conf->msg_stream = stderr; // set to stdout by --use-stdout
119 conf->honor_leading_zeroes = TRUE; // disabled by --ignore-zeroes
120 conf->strict_segments = FALSE; // enabled by --strict-segments and V0.98
121 conf->all_warnings_are_errors = FALSE; // enabled by --strict
122 conf->test_new_features = FALSE; // enabled by --test
123 conf->dialect = V__CURRENT_VERSION; // changed by --dialect
124 conf->politeness = 0; // changed by --please
125 conf->debuglevel = DEBUGLEVEL_DEBUG; // changed by --debuglevel, used by "!debug"
126 conf->platform_lib_prefix = PLATFORM_LIBPREFIX;
127 conf->initial_cpu_type = NULL;
128 conf->symbollist_filename = NULL;
129 conf->vicelabels_filename = NULL;
130 conf->output_filename = NULL;
131 conf->outfile_format = OUTFILE_FORMAT_UNSPECIFIED;
132 conf->report_filename = NULL;
133 conf->mem_init_value = NO_VALUE_GIVEN; // set by --initmem
134 conf->initial_pc = NO_VALUE_GIVEN; // set by --setpc
135 conf->outfile_start = NO_VALUE_GIVEN; // set by --from-to
136 conf->outfile_limit = NO_VALUE_GIVEN; // end+1, set by --from-to
137 }
138
139 // memory allocation stuff
140
141 // allocate memory and die if not available
142 void *safe_malloc(size_t size)
143 {
144 void *block = malloc(size);
145
146 if (block == NULL)
147 throw_serious_error(exception_no_memory_left);
148
149 return block;
150 }
151
152
153 // Parser stuff
154
155
156 static boolean in_addr_block = FALSE;
157 static boolean in_nowarn_block = FALSE;
158
159 // set new value for "we are in !addr block" flag,
160 // return old value
161 // (called by "!addr { }")
162 boolean parser_change_addr_block_flag(boolean new_value)
163 {
164 boolean old_value = in_addr_block;
165
166 in_addr_block = new_value;
167 return old_value;
168 }
169 // set new value for "we are in !nowarn block" flag,
170 // return old value
171 // (called by "!nowarn { }")
172 boolean parser_change_nowarn_block_flag(boolean new_value)
173 {
174 boolean old_value = in_nowarn_block;
175
176 in_nowarn_block = new_value;
177 return old_value;
178 }
179
180 #define SF_FOUND_BLANK (1u << 0) // statement started with space or tab
181 #define SF_FOUND_SYMBOL (1u << 1) // statement had label or symbol definition
182 #define SF_ADDR_PREFIX (1u << 2) // explicit symbol definition is an address
183 #define SF_NOWARN_PREFIX (1u << 3) // suppress warnings for this statement
184 static bits statement_flags;
185
186 // called by "!addr" pseudo op if used without block
187 extern void parser_set_addr_prefix(void)
188 {
189 statement_flags |= SF_ADDR_PREFIX;
190 }
191 // called by "!nowarn" pseudo op if used without block
192 extern void parser_set_nowarn_prefix(void)
193 {
194 statement_flags |= SF_NOWARN_PREFIX;
195 }
196
197 // Check and return whether first symbol of statement. Complain if not.
198 static int first_symbol_of_statement(void)
199 {
200 if (statement_flags & SF_FOUND_SYMBOL) {
201 throw_error("Unknown mnemonic");
202 parser_skip_remainder();
203 return FALSE;
204 }
205 statement_flags |= SF_FOUND_SYMBOL; // now there has been one
206 return TRUE;
207 }
208
209
210 // parse label definition (can be either global or local).
211 // name must be held in GlobalDynaBuf.
212 // called by parse_symbol_definition, parse_backward_anon_def, parse_forward_anon_def
213 // "powers" is used by backward anons to allow changes
214 static void set_label(scope_t scope, bits force_bit, bits powers)
215 {
216 struct symbol *symbol;
217 struct object result;
218
219 if ((statement_flags & SF_FOUND_BLANK) && config.warn_on_indented_labels) {
220 throw_finalpass_warning("Label name not in leftmost column.");
221 }
222 symbol = symbol_find(scope);
223 result.type = &type_number;
224 programcounter_read_asterisk(&result.u.number);
225 symbol_set_object(symbol, &result, powers);
226 if (force_bit)
227 symbol_set_force_bit(symbol, force_bit);
228 // global labels must open new scope for cheap locals
229 if (scope == SCOPE_GLOBAL)
230 section_new_cheap_scope(section_now);
231 }
232
233
234 // call with symbol name in GlobalDynaBuf and '=' already eaten.
235 // fn is exported so "!set" pseudo opcode can call it.
236 // "powers" is for "!set" pseudo opcode so changes are allowed (see symbol.h for powers)
237 void parse_assignment(scope_t scope, bits force_bit, bits powers)
238 {
239 struct symbol *symbol;
240 struct object result;
241
242 symbol = symbol_find(scope);
243 ALU_any_result(&result);
244 // if wanted, mark as address reference
245 if (in_addr_block || (statement_flags & SF_ADDR_PREFIX)) {
246 // FIXME - checking types explicitly is ugly...
247 if (result.type == &type_number)
248 result.u.number.addr_refs = 1;
249 }
250 symbol_set_object(symbol, &result, powers);
251 if (force_bit)
252 symbol_set_force_bit(symbol, force_bit);
253 }
254
255
256 // parse symbol definition (can be either global or local, may turn out to be a label).
257 // name must be held in GlobalDynaBuf.
258 static void parse_symbol_definition(scope_t scope)
259 {
260 bits force_bit;
261
262 force_bit = parser_get_force_bit(); // skips spaces after (yes, force bit is allowed for label definitions)
263 if (GotByte == '=') {
264 // explicit symbol definition (symbol = <something>)
265 GetByte(); // eat '='
266 parse_assignment(scope, force_bit, POWER_NONE);
267 parser_ensure_EOS();
268 } else {
269 // implicit symbol definition (label)
270 set_label(scope, force_bit, POWER_NONE);
271 }
272 }
273
274
275 // Parse global symbol definition or assembler mnemonic
276 static void parse_mnemo_or_global_symbol_def(void)
277 {
278 // read keyword and ask current cpu type if it's a mnemonic
279 if (cpu_current_type->keyword_is_mnemonic(parser_read_keyword()))
280 return; // statement has been handled
281
282 // if we're here, it wasn't a mnemonic, so it can only be a symbol name
283 if (!first_symbol_of_statement())
284 return; // more than one symbol, error has been reported
285
286 // Now GotByte = illegal char
287 // 04 Jun 2005: this fix should help to explain "strange" error messages.
288 // 17 May 2014: now it works for UTF-8 as well.
289 if ((*GLOBALDYNABUF_CURRENT == (char) 0xa0)
290 || ((GlobalDynaBuf->size >= 2) && (GLOBALDYNABUF_CURRENT[0] == (char) 0xc2) && (GLOBALDYNABUF_CURRENT[1] == (char) 0xa0))) {
291 throw_finalpass_warning("Symbol name starts with a shift-space character.");
292 }
293 parse_symbol_definition(SCOPE_GLOBAL);
294 }
295
296
297 // parse (cheap) local symbol definition
298 static void parse_local_symbol_def(void)
299 {
300 scope_t scope;
301
302 if (!first_symbol_of_statement())
303 return;
304
305 if (input_read_scope_and_symbol_name(&scope) == 0)
306 parse_symbol_definition(scope);
307 }
308
309
310 // parse anonymous backward label definition. Called with GotByte == '-'
311 static void parse_backward_anon_def(void)
312 {
313 if (!first_symbol_of_statement())
314 return;
315
316 dynabuf_clear(GlobalDynaBuf);
317 do {
318 DYNABUF_APPEND(GlobalDynaBuf, '-');
319 } while (GetByte() == '-');
320 dynabuf_append(GlobalDynaBuf, '\0');
321 // backward anons change their value!
322 set_label(section_now->local_scope, NO_FORCE_BIT, POWER_CHANGE_VALUE);
323 }
324
325
326 // parse anonymous forward label definition. called with GotByte == ?
327 static void parse_forward_anon_def(void)
328 {
329 if (!first_symbol_of_statement())
330 return;
331
332 dynabuf_clear(GlobalDynaBuf);
333 dynabuf_append(GlobalDynaBuf, '+');
334 while (GotByte == '+') {
335 DYNABUF_APPEND(GlobalDynaBuf, '+');
336 GetByte();
337 }
338 symbol_fix_forward_anon_name(TRUE); // TRUE: increment counter
339 dynabuf_append(GlobalDynaBuf, '\0');
340 //printf("[%d, %s]\n", section_now->local_scope, GlobalDynaBuf->buffer);
341 set_label(section_now->local_scope, NO_FORCE_BIT, POWER_NONE);
342 }
343
344
345 static enum shortcut current_shortcut_state = SHORTCUT_NONE;
346 // return current shortcut state
347 enum shortcut parser_get_shortcut(void)
348 {
349 return current_shortcut_state;
350 }
351 // start or end processing a !break/!continue/!return keyword
352 void parser_set_shortcut(enum shortcut new_shortcut)
353 {
354 //printf("Changing shortcut state from %d to %d.\n", current_shortcut_state, new_shortcut);
355 switch (new_shortcut) {
356 case SHORTCUT_NONE:
357 if (current_shortcut_state == SHORTCUT_NONE)
358 BUG("ShortcutDoubleNone", 0);
359 current_shortcut_state = new_shortcut;
360 break;
361 case SHORTCUT_BREAK:
362 case SHORTCUT_CONT:
363 case SHORTCUT_RETURN:
364 if (current_shortcut_state != SHORTCUT_NONE)
365 BUG("ShortcutDouble", current_shortcut_state);
366 current_shortcut_state = new_shortcut;
367 break;
368 default:
369 BUG("IllegalShortcut", new_shortcut);
370 }
371 }
372 // status var to tell mainloop (actually "statement loop") to exit.
373 // this is better than the error handler exiting directly, because
374 // there are cases where an error message is followed by an info message
375 // (like "macro redefined _here_" and "original definition _there_"),
376 // and this way the program does not exit between the two.
377 // FIXME - there is still the problem of not getting a dump of the macro call stack for the final error!
378 static boolean too_many_errors = FALSE;
379
380 // Parse block, beginning with next byte.
381 // End reason (either CHAR_EOB or CHAR_EOF) can be found in GotByte afterwards
382 // Has to be re-entrant.
383 void parse_until_eob_or_eof(void)
384 {
385 // start with next byte
386 // (don't SKIPSPACE() here, we want to warn about "label not in leftmost column"!)
387 GetByte();
388 // loop until end of block or end of file
389 while ((GotByte != CHAR_EOB) && (GotByte != CHAR_EOF)) {
390 // process one statement
391 statement_flags = 0; // no spaces, no labels, no !addr, no !nowarn
392 // Parse until end of statement. Only loops in these cases:
393 // - statement contains label and something else
394 // - "!ifdef"/"!ifndef" is used without block
395 // - "!addr"/"!nowarn" is used without block
396 do {
397 // check for pseudo opcodes was moved out of switch,
398 // because prefix character is now configurable.
399 if (GotByte == config.pseudoop_prefix) {
400 pseudoopcode_parse();
401 } else {
402 switch (GotByte) {
403 case CHAR_EOS: // end of statement
404 // Ignore now, act later
405 // (stops from being "default")
406 break;
407 case ' ': // space
408 statement_flags |= SF_FOUND_BLANK;
409 /*FALLTHROUGH*/
410 case CHAR_SOL: // start of line
411 GetByte(); // skip
412 break;
413 case '-':
414 parse_backward_anon_def();
415 break;
416 case '+':
417 GetByte();
418 if ((GotByte == LOCAL_PREFIX)
419 || (GotByte == CHEAP_PREFIX)
420 || (BYTE_CONTINUES_KEYWORD(GotByte)))
421 macro_parse_call();
422 else
423 parse_forward_anon_def();
424 break;
425 case '*':
426 notreallypo_setpc(); // define program counter (fn is in pseudoopcodes.c)
427 break;
428 case LOCAL_PREFIX:
429 case CHEAP_PREFIX:
430 parse_local_symbol_def();
431 break;
432 default:
433 if (BYTE_STARTS_KEYWORD(GotByte)) {
434 parse_mnemo_or_global_symbol_def();
435 } else {
436 throw_error(exception_syntax); // FIXME - include char in error message!
437 parser_skip_remainder();
438 }
439 }
440 }
441 } while (GotByte != CHAR_EOS); // until end-of-statement
442 output_end_statement(); // adjust program counter
443 // did the error handler decide to give up?
444 if (too_many_errors)
445 exit(ACME_finalize(EXIT_FAILURE));
446 // was any of the shortcut POs used?
447 if (current_shortcut_state == SHORTCUT_NONE) {
448 // go on with next byte
449 GetByte(); //NEXTANDSKIPSPACE();
450 } else {
451 // ignore remainder of block:
452 input_block_skip();
453 }
454 }
455 }
456
457
458 // Skip space. If GotByte is CHAR_SOB ('{'), parse block and return TRUE.
459 // Otherwise (if there is no block), return FALSE.
460 // Don't forget to call EnsureEOL() afterwards.
461 int parse_optional_block(void)
462 {
463 SKIPSPACE();
464 if (GotByte != CHAR_SOB)
465 return FALSE;
466
467 parse_until_eob_or_eof();
468 if (GotByte != CHAR_EOB)
469 throw_serious_error(exception_no_right_brace);
470 GetByte();
471 return TRUE;
472 }
473
474 // parse a whole source code file
475 // file name must be given in platform style, i.e.
476 // "directory/basename.extension" on linux,
477 // "directory.basename/extension" on RISC OS, etc.
478 // and the pointer must remain valid forever!
479 void parse_source_code_file(FILE *fd, const char *eternal_plat_filename)
480 {
481 struct inputchange_buf icb;
482 const char *ppb; // path buffer in platform format
483 boolean break_cont_allowed;
484 boolean return_allowed;
485
486 // be verbose
487 if (config.process_verbosity >= 3)
488 printf("Parsing source file \"%s\".\n", eternal_plat_filename);
489
490 // remember base for relative paths and set new one:
491 ppb = input_plat_pathref_filename;
492 input_plat_pathref_filename = eternal_plat_filename;
493 // remember input and set up new one:
494 inputchange_new_file(&icb, fd, eternal_plat_filename);
495 // remember whether break/continue/return are allowed and forbid them in
496 // new file (just to enforce "clean code"):
497 break_cont_allowed = parser_allow_break_cont(FALSE);
498 return_allowed = parser_allow_return(FALSE);
499
500 // parse block and check end reason
501 parse_until_eob_or_eof();
502 if (GotByte != CHAR_EOF)
503 throw_error("Expected EOF, found '}' instead." );
504
505 // restore states of break/continue/return
506 parser_allow_return(return_allowed);
507 parser_allow_break_cont(break_cont_allowed);
508 // restore outer input
509 inputchange_back(&icb);
510 // restore outer base for relative paths
511 input_plat_pathref_filename = ppb;
512 }
513
514 // read optional info about parameter length
515 bits parser_get_force_bit(void)
516 {
517 char byte;
518 bits force_bit = 0;
519
520 if (GotByte == '+') {
521 byte = GetByte();
522 if (byte == '1')
523 force_bit = NUMBER_FORCES_8;
524 else if (byte == '2')
525 force_bit = NUMBER_FORCES_16;
526 else if (byte == '3')
527 force_bit = NUMBER_FORCES_24;
528 if (force_bit)
529 GetByte();
530 else
531 throw_error("Illegal postfix.");
532 }
533 SKIPSPACE();
534 return force_bit;
535 }
536
537 // return current state and set new state of "allow !break and !continue" flag
538 boolean parser_allow_break_cont(boolean new_state)
539 {
540 static boolean flag = FALSE;
541 boolean temp;
542
543 temp = flag;
544 flag = new_state;
545 return temp;
546 }
547 // return current state and set new state of "allow !return" flag
548 boolean parser_allow_return(boolean new_state)
549 {
550 static boolean flag = FALSE;
551 boolean temp;
552
553 temp = flag;
554 flag = new_state;
555 return temp;
556 }
557
558
559 // Error handling
560
561 // This function will do the actual output for warnings, errors and serious
562 // errors. It shows the given message string, as well as the current
563 // context: file name, line number, source type and source title.
564 // if the "optional alternative location" given is NULL, the current location is used
565 static void print_msg(const char *message, const char *ansicolor, const char *type, struct location *opt_alt_loc)
566 {
567 const char *resetcolor = "\033[0m";
568 struct location location;
569
570 if (!config.format_color) {
571 ansicolor = "";
572 resetcolor = "";
573 }
574
575 // optional alternative location given?
576 if (opt_alt_loc)
577 location = *opt_alt_loc; // use alternative location
578 else
579 input_get_location(&location); // use current location
580
581 if (config.format_msvc) {
582 fprintf(config.msg_stream, "%s(%d) : %s%s%s (%s %s): %s\n",
583 location.plat_filename, location.line_number,
584 ansicolor, type, resetcolor,
585 section_now->type, section_now->title, message);
586 } else {
587 fprintf(config.msg_stream, "%s%s%s - File %s, line %d (%s %s): %s\n",
588 ansicolor, type, resetcolor,
589 location.plat_filename, location.line_number,
590 section_now->type, section_now->title, message);
591 }
592 }
593
594 // flag, tells throw_error how to behave. set to FALSE by throw__done_with_cli_args().
595 // this is needed because errors like "\xZZ is not a valid backslash sequence" are
596 // handled by calling throw_error(), but they can happen
597 // - in cli args, using the "-D SYMBOL=VALUE" syntax, where we want to exit, and
598 // - in source codes, where we want a "file=F, line=N" output and go on!
599 static boolean error_is_in_cli_args = TRUE;
600
601 // generate debug/info/warning/error message
602 // if the "optional alternative location" given is NULL, the current location is used
603 void throw_message(enum debuglevel level, const char msg[], struct location *opt_alt_loc)
604 {
605 // FIXME: we only expect normal errors in cli args, no warnings or
606 // other stuff, so enable this:
607 //if (error_is_in_cli_args)
608 // BUG("damn");
609
610 // if level is taken from source, ensure valid value:
611 if (level < DEBUGLEVEL_SERIOUS)
612 level = DEBUGLEVEL_SERIOUS;
613
614 switch (level) {
615 case DEBUGLEVEL_SERIOUS:
616 // output a serious error
617 // (assembly stops, for example if outbuffer overruns).
618 PLATFORM_SERIOUS(msg);
619 print_msg(msg, "\033[1m\033[31m", "Serious error", opt_alt_loc); // bold + red
620 //++pass.counters.errors; // FIXME - needed when problem below is solved
621 exit(ACME_finalize(EXIT_FAILURE)); // FIXME - this inhibits output of macro call stack
622 case DEBUGLEVEL_ERROR:
623 // output an error
624 // (something is wrong, no output file will be generated).
625 PLATFORM_ERROR(msg);
626 print_msg(msg, "\033[31m", "Error", opt_alt_loc); // red
627 ++pass.counters.errors;
628 if (pass.counters.errors >= config.max_errors)
629 too_many_errors = TRUE; // this causes mainloop to exit
630 break;
631 case DEBUGLEVEL_WARNING:
632 // output a warning
633 // (something looks wrong, like "label name starts with shift-space character")
634 // first check if warnings should be suppressed right now:
635 if (in_nowarn_block || (statement_flags & SF_NOWARN_PREFIX))
636 break;
637 PLATFORM_WARNING(msg);
638 print_msg(msg, "\033[33m", "Warning", opt_alt_loc); // yellow
639 ++pass.counters.warnings;
640 // then check if warnings should be handled like errors:
641 if (config.all_warnings_are_errors) {
642 ++pass.counters.errors;
643 if (pass.counters.errors >= config.max_errors)
644 too_many_errors = TRUE; // this causes mainloop to exit
645 }
646 break;
647 case DEBUGLEVEL_INFO:
648 PLATFORM_INFO(msg);
649 print_msg(msg, "\033[32m", "Info", opt_alt_loc); // green
650 break;
651 default:
652 // debug
653 print_msg(msg, "\033[36m", "Debug", opt_alt_loc); // cyan
654 break;
655 }
656 }
657
658 // output a warning (something looks wrong)
659 void throw_warning(const char msg[])
660 {
661 throw_message(DEBUGLEVEL_WARNING, msg, NULL);
662 }
663
664 // output an error (something is wrong, no output file will be generated).
665 // the assembler will try to go on with the assembly, so the user gets to know
666 // about more than one of their typos at a time.
667 void throw_error(const char msg[])
668 {
669 if (error_is_in_cli_args)
670 ACME_cli_args_error(msg); // does not return...
671 else
672 throw_message(DEBUGLEVEL_ERROR, msg, NULL);
673 }
674
675 // output a serious error (assembly stops, for example if outbuffer overruns).
676 extern void throw_serious_error(const char msg[])
677 {
678 throw_message(DEBUGLEVEL_SERIOUS, msg, NULL);
679 }
680
681 // output a warning, but only if we are in first pass, otherwise suppress
682 // (only use this if using throw_finalpass_warning is impossible,
683 // for example in cases where the code is skipped in later passes)
684 void throw_pass1_warning(const char msg[])
685 {
686 if (pass.number == 1)
687 throw_warning(msg);
688 }
689
690 // output a warning, but only if we are in final pass, otherwise suppress
691 // (for example "converted float to int for XOR" -> must be done in
692 // final pass because values might be undefined earlier!)
693 void throw_finalpass_warning(const char msg[])
694 {
695 if (pass.flags.is_final_pass)
696 throw_warning(msg);
697 }
698
699 // throw "macro twice"/"symbol twice" error
700 // first output error as "error", then location of initial definition as "info"
701 void throw_redef_error(const char error_msg[], struct location *old_def, const char info_msg[])
702 {
703 const char *buffered_section_type;
704 char *buffered_section_title;
705
706 // show error with current location
707 throw_error(error_msg);
708
709 // symbol structs do not necessarily have valid location data:
710 if (old_def->plat_filename == NULL)
711 return;
712
713 // CAUTION, ugly kluge: fiddle with section_now data to generate
714 // "earlier definition" section.
715 // buffer old section
716 buffered_section_type = section_now->type;
717 buffered_section_title = section_now->title;
718 // set new (fake) section
719 // FIXME - maybe store section in definition, just as location is stored?
720 // then we could use real data here instead of faking it, but it would
721 // take a bit more memory...
722 section_now->type = "earlier";
723 section_now->title = "section";
724 // show info message with location of earlier definition
725 throw_message(DEBUGLEVEL_INFO, info_msg, old_def);
726 // restore old section
727 section_now->type = buffered_section_type;
728 section_now->title = buffered_section_title;
729 }
730
731 // ugly kluge, switches throw_error() from cli args mode to normal mode
732 void throw__done_with_cli_args(void)
733 {
734 error_is_in_cli_args = FALSE;
735 }
736
737 // handle bugs
738 // FIXME - use a local buffer and sprintf/snprintf to put error code into message!
739 void BUG(const char *message, int code)
740 {
741 throw_warning("Bug in ACME, code follows");
742 fprintf(stderr, "(0x%x:)", code);
743 throw_serious_error(message);
744 }
745
746 // process error that might vanish if symbols change:
747 // if current pass is an "error output" pass, actually throw error.
748 // otherwise just increment counter to let mainloop know this pass wasn't successful.
749 void countorthrow_value_error(const char *msg)
750 {
751 boolean complain;
752
753 if (config.dialect >= V0_98__PATHS_AND_SYMBOLCHANGE)
754 complain = pass.flags.throw_all_errors; // since 0.98, "value errors" are only thrown if pass flag is set
755 else
756 complain = TRUE; // in earlier versions they were always thrown
757
758 if (complain)
759 throw_error(msg);
760 else
761 ++pass.counters.suppressed_errors;
762 }
763
764
765 // insert object (in case of list, will iterate/recurse until done)
766 void output_object(struct object *object, struct iter_context *iter)
767 {
768 struct listitem *item;
769 int length;
770 char *read;
771
772 if (object->type == &type_number) {
773 if (object->u.number.ntype == NUMTYPE_UNDEFINED)
774 iter->fn(0);
775 else if (object->u.number.ntype == NUMTYPE_INT)
776 iter->fn(object->u.number.val.intval);
777 else if (object->u.number.ntype == NUMTYPE_FLOAT)
778 iter->fn(object->u.number.val.fpval);
779 else
780 BUG("IllegalNumberType0", object->u.number.ntype);
781 } else if (object->type == &type_list) {
782 // iterate over list
783 item = object->u.listhead->next;
784 while (item != object->u.listhead) {
785 output_object(&item->u.payload, iter);
786 item = item->next;
787 }
788 } else if (object->type == &type_string) {
789 // iterate over string
790 read = object->u.string->payload;
791 length = object->u.string->length;
792 // single-char strings are accepted, to be more compatible with
793 // versions before 0.97 (and empty strings are not really a problem...)
794 if (iter->accept_long_strings || (length < 2)) {
795 while (length--)
796 iter->fn(iter->stringxor ^ encoding_encode_char(*(read++)));
797 } else {
798 throw_error("There's more than one character."); // see alu.c for the original of this error
799 }
800 } else {
801 BUG("IllegalObjectType", 0);
802 }
803 }
804
805
806 // output 8-bit value with range check
807 void output_8(intval_t value)
808 {
809 if ((value < -0x80) || (value > 0xff))
810 countorthrow_value_error(exception_number_out_of_8b_range);
811 output_byte(value);
812 }
813
814
815 // output 16-bit value with range check big-endian
816 void output_be16(intval_t value)
817 {
818 if ((value < -0x8000) || (value > 0xffff))
819 countorthrow_value_error(exception_number_out_of_16b_range);
820 output_byte(value >> 8);
821 output_byte(value);
822 }
823
824
825 // output 16-bit value with range check little-endian
826 void output_le16(intval_t value)
827 {
828 if ((value < -0x8000) || (value > 0xffff))
829 countorthrow_value_error(exception_number_out_of_16b_range);
830 output_byte(value);
831 output_byte(value >> 8);
832 }
833
834
835 // output 24-bit value with range check big-endian
836 void output_be24(intval_t value)
837 {
838 if ((value < -0x800000) || (value > 0xffffff))
839 countorthrow_value_error(exception_number_out_of_24b_range);
840 output_byte(value >> 16);
841 output_byte(value >> 8);
842 output_byte(value);
843 }
844
845
846 // output 24-bit value with range check little-endian
847 void output_le24(intval_t value)
848 {
849 if ((value < -0x800000) || (value > 0xffffff))
850 countorthrow_value_error(exception_number_out_of_24b_range);
851 output_byte(value);
852 output_byte(value >> 8);
853 output_byte(value >> 16);
854 }
855
856
857 // FIXME - the range checks below are commented out because 32-bit
858 // signed integers cannot exceed the range of 32-bit signed integers.
859 // But now that 64-bit machines are the norm, "intval_t" might be a
860 // 64-bit int. I need to address this problem one way or another.
861
862
863 // output 32-bit value (without range check) big-endian
864 void output_be32(intval_t value)
865 {
866 // if ((value < -0x80000000) || (value > 0xffffffff))
867 // countorthrow_value_error(exception_number_out_of_32b_range);
868 output_byte(value >> 24);
869 output_byte(value >> 16);
870 output_byte(value >> 8);
871 output_byte(value);
872 }
873
874
875 // output 32-bit value (without range check) little-endian
876 void output_le32(intval_t value)
877 {
878 // if ((value < -0x80000000) || (value > 0xffffffff))
879 // countorthrow_value_error(exception_number_out_of_32b_range);
880 output_byte(value);
881 output_byte(value >> 8);
882 output_byte(value >> 16);
883 output_byte(value >> 24);
884 }
885
886
887 // string shown in CLI error message if outputformat_set() returns nonzero:
888 const char outputformat_names[] = "'plain', 'cbm', 'apple'";
889
890 // convert output format name held in DynaBuf to enum.
891 // returns OUTFILE_FORMAT_UNSPECIFIED on error.
892 enum outfile_format outputformat_find(void)
893 {
894 if (strcmp(GlobalDynaBuf->buffer, "plain") == 0)
895 return OUTFILE_FORMAT_PLAIN;
896 else if (strcmp(GlobalDynaBuf->buffer, "cbm") == 0)
897 return OUTFILE_FORMAT_CBM;
898 else if (strcmp(GlobalDynaBuf->buffer, "apple") == 0)
899 return OUTFILE_FORMAT_APPLE;
900 // else if (strcmp(GlobalDynaBuf->buffer, "o65") == 0)
901 // return OUTFILE_FORMAT_O65;
902
903 return OUTFILE_FORMAT_UNSPECIFIED;
904 }