2 * $Id: astproc.c,v 1.21 2007/11/11 22:35:22 khansen Exp $
4 * Revision 1.21 2007/11/11 22:35:22 khansen
7 * Revision 1.20 2007/08/19 10:17:39 khansen
8 * allow symbols to be used without having been declared
10 * Revision 1.19 2007/08/12 18:58:12 khansen
11 * ability to generate pure 6502 binary (--pure-binary switch)
13 * Revision 1.18 2007/08/12 02:42:46 khansen
16 * Revision 1.17 2007/08/09 22:06:10 khansen
17 * ability to pass in reference to local label as argument to macro
19 * Revision 1.16 2007/08/09 20:48:46 khansen
20 * disable buggy code that can cause crash
22 * Revision 1.15 2007/08/09 20:33:40 khansen
25 * Revision 1.14 2007/08/08 22:40:01 khansen
26 * improved symbol lookup, definitions must precede usage
28 * Revision 1.13 2007/07/22 13:33:26 khansen
29 * convert tabs to whitespaces
31 * Revision 1.12 2005/01/09 11:17:57 kenth
33 * fixed bug in process_data(), merge_data()
34 * no longer truncation warning when fits in signed byte/word
36 * Revision 1.11 2005/01/05 02:28:13 kenth
38 * support for anonymous unions
41 * Revision 1.10 2004/12/29 21:44:41 kenth
43 * static indexing, sizeof improved
45 * Revision 1.9 2004/12/25 02:22:35 kenth
46 * fixed bug in reduce_user_storage()
48 * Revision 1.8 2004/12/19 19:58:29 kenth
51 * Revision 1.7 2004/12/18 16:57:39 kenth
52 * STORAGE_NODE(WORD/DWORD_DATATYPE) converts to BYTE
54 * Revision 1.6 2004/12/16 13:19:47 kenth
57 * Revision 1.5 2004/12/14 01:49:05 kenth
60 * Revision 1.4 2004/12/11 02:01:25 kenth
61 * added forward/backward branching
63 * Revision 1.3 2004/12/09 11:18:13 kenth
64 * added: warning, error node processing
66 * Revision 1.2 2004/12/06 04:52:24 kenth
67 * Major updates (xorcyst 1.1.0)
69 * Revision 1.1 2004/06/30 07:55:31 kenth
75 * (C) 2004 Kent Hansen
77 * The XORcyst is free software; you can redistribute it and/or modify
78 * it under the terms of the GNU General Public License as published by
79 * the Free Software Foundation; either version 2 of the License, or
80 * (at your option) any later version.
82 * The XORcyst is distributed in the hope that it will be useful,
83 * but WITHOUT ANY WARRANTY; without even the implied warranty of
84 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
85 * GNU General Public License for more details.
87 * You should have received a copy of the GNU General Public License
88 * along with The XORcyst; if not, write to the Free Software
89 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
93 * This file contains functions that process the Abstract Syntax Tree (AST).
94 * After the assembly file has been parsed into an AST, a number of passes are
95 * made on it to process it and transform it. The functions here are
96 * concerned with things like
98 * - symbol table generation
99 * - equates substitution
101 * - code and symbol validation
115 #define IS_SIGNED_BYTE_VALUE(v) (((v) >= -128) && ((v) <= 127))
116 #define IS_UNSIGNED_BYTE_VALUE(v) (((v) >= 0) && ((v) <= 255))
117 #define IS_BYTE_VALUE(v) (IS_SIGNED_BYTE_VALUE(v) || IS_UNSIGNED_BYTE_VALUE(v))
119 #define IS_SIGNED_WORD_VALUE(v) (((v) >= -32768) && ((v) <= 32767))
120 #define IS_UNSIGNED_WORD_VALUE(v) (((v) >= 0) && ((v) <= 65535))
121 #define IS_WORD_VALUE(v) (IS_SIGNED_WORD_VALUE(v) || IS_UNSIGNED_WORD_VALUE(v))
123 /*---------------------------------------------------------------------------*/
125 /** Number of errors issued during processing. */
126 static int err_count
= 0;
128 /** Number of warnings issued during processing. */
129 static int warn_count
= 0;
131 /* Keeps track of number of global labels encountered. */
132 static int label_count
= 0;
134 /* Keeps track of whether statement is in dataseg or codeseg. */
135 static int in_dataseg
= 0;
137 /* Default symbol modifiers, i.e. ZEROPAGE_FLAG, PUBLIC_FLAG */
138 static int modifiers
= 0;
140 /* Used when we are outputting pure 6502 binary */
141 static int dataseg_pc
;
142 static int codeseg_pc
;
144 /*---------------------------------------------------------------------------*/
146 /** Mapping from regular ASCII characters to custom character values.
147 * Used to transform .char arrays to regular .db arrays.
149 static unsigned char charmap
[256];
152 * Resets the custom character map.
153 * Every ASCII character is mapped to itself.
155 static void reset_charmap()
158 for (i
=0; i
<256; i
++) {
159 charmap
[i
] = (char)i
;
163 /*---------------------------------------------------------------------------*/
164 /* Forward/backward branching stuff */
166 struct tag_forward_branch_info
{
168 int index
; /* Index into refs */
172 typedef struct tag_forward_branch_info forward_branch_info
;
174 struct tag_backward_branch_info
{
179 typedef struct tag_backward_branch_info backward_branch_info
;
183 static forward_branch_info forward_branch
[BRANCH_MAX
];
185 static backward_branch_info backward_branch
[BRANCH_MAX
];
188 * Zaps forward/backward branch data.
190 static void branch_init()
193 for (i
=0; i
<BRANCH_MAX
; i
++) {
194 for (j
=0; j
<128; j
++) {
195 forward_branch
[i
].refs
[j
] = NULL
;
197 forward_branch
[i
].index
= 0;
198 forward_branch
[i
].counter
= 0;
199 backward_branch
[i
].decl
= NULL
;
200 backward_branch
[i
].counter
= 0;
204 /*---------------------------------------------------------------------------*/
208 * @param loc File location of error
209 * @param fmt printf-style format string
211 static void err(location loc
, const char *fmt
, ...)
216 /* Print error message w/ location info */
217 fprintf(stderr
, "error: %s:", loc
.file
);
218 LOCATION_PRINT(stderr
, loc
);
219 fprintf(stderr
, ": ");
220 vfprintf(stderr
, fmt
, ap
);
221 fprintf(stderr
, "\n");
225 /* Increase total error count */
231 * @param loc File location of warning
232 * @param fmt printf-style format string
234 static void warn(location loc
, const char *fmt
, ...)
237 if (!xasm_args
.no_warn
) {
239 /* Print warning message w/ location info */
240 fprintf(stderr
, "warning: %s:", loc
.file
);
241 LOCATION_PRINT(stderr
, loc
);
242 fprintf(stderr
, ": ");
243 vfprintf(stderr
, fmt
, ap
);
244 fprintf(stderr
, "\n");
248 /* Increase total warning count */
253 * Gets the number of errors encountered during processing.
254 * @return Number of errors
256 int astproc_err_count()
261 /*---------------------------------------------------------------------------*/
264 * Gets the processor function for a node type from a map.
265 * Used by astproc_walk().
266 * @param type The node type
267 * @param map A mapping from node types to processor functions
269 static astnodeproc
astproc_node_type_to_proc(astnode_type type
, const astnodeprocmap
*map
)
271 /* Try all map entries */
272 for (; map
->proc
!= NULL
; map
+= 1) {
273 if (map
->type
== type
) {
274 return map
->proc
; /* Match */
281 /*---------------------------------------------------------------------------*/
284 * Walks an abstract syntax tree recursively.
285 * @param n Node to walk
286 * @param arg Optional argument to pass to processor function
287 * @param map Mapping of node types to processor functions
289 static void astproc_walk_recursive(astnode
*n
, void *arg
, const astnodeprocmap
*map
, astnode
**next
)
293 if (n
== NULL
) { return; }
294 /* Process this node if it has a processor function */
295 astnodeproc p
= astproc_node_type_to_proc(astnode_get_type(n
), map
);
297 if (!p(n
, arg
, next
)) return; /* Don't walk children */
299 /* Walk the node's children recursively */
300 for (c
=n
->first_child
; c
!= NULL
; c
= t
) {
301 t
= c
->next_sibling
; /* default next node */
302 astproc_walk_recursive(c
, arg
, map
, &t
);
307 * Generic tree walker function.
309 * @param arg General-purpose argument passed to each node handler function
310 * @param map Array of (nodetype, handler function) tuples
312 void astproc_walk(astnode
*n
, void *arg
, const astnodeprocmap
*map
)
315 astproc_walk_recursive(n
, arg
, map
, &dummy
);
318 /*---------------------------------------------------------------------------*/
321 * Don't do any processing of this node or its children on this pass.
323 static int noop(astnode
*n
, void *arg
, astnode
**next
)
329 * Substitutes an identifier node with subst_expr if the id is equal to subst_id.
330 * @param n A node of type IDENTIFIER_NODE
331 * @param arg Array of length 2, containing (expr, id) pair
333 static int substitute_id(astnode
*n
, void *arg
, astnode
**next
)
335 /* arg is array containing expression and identifier */
336 astnode
**array
= (astnode
**)arg
;
337 astnode
*subst_expr
= array
[0];
338 astnode
*subst_id
= array
[1];
339 /* Test if this node and the identifier to replace are equal */
340 if (astnode_equal(n
, subst_id
)) {
341 /* They're equal, replace it by expression. */
342 astnode
*cl
= astnode_clone(subst_expr
, n
->loc
);
343 /* ### Generalize: traverse all children, set the flag */
344 if (astnode_get_type(cl
) == LOCAL_ID_NODE
) {
345 cl
->flags
|= 0x80; /* don't globalize it */
347 astnode_replace(n
, cl
);
357 * Substitutes expr for id in list.
358 * Used by macro expander to substitute a macro body parameter name with the
359 * actual expression used in the macro expansion.
360 * @param expr An expression
361 * @param id An identifier
362 * @param list A list of statements (macro body)
364 static void substitute_expr_for_id(astnode
*expr
, astnode
*id
, astnode
*list
)
366 /* Prepare argument to astproc_walk */
370 /* Table of callback functions for our purpose. */
371 static astnodeprocmap map
[] = {
372 { IDENTIFIER_NODE
, substitute_id
},
376 astproc_walk(list
, array
, map
);
379 /*---------------------------------------------------------------------------*/
382 * Globalizes a macro expanded local.
383 * This is done simply by concatenating the local label identifier with the
384 * global macro invocation counter.
385 * @param n A node of type LOCAL_LABEL_NODE or LOCAL_ID_NODE
386 * @param arg Namespace counter (int)
388 static int globalize_macro_expanded_local(astnode
*n
, void *arg
, astnode
**next
)
390 /* Only globalize if it's a reference to a label defined in the macro */
391 if (!(n
->flags
& 0x80)) {
394 /* Make it global by appending the macro expansion counter to the id */
396 sprintf(str
, "#%d", count
);
397 if (astnode_is_type(n
, LOCAL_LABEL_NODE
)) {
398 /* LOCAL_LABEL_NODE, use label field */
399 n
->label
= realloc(n
->label
, strlen(n
->label
)+strlen(str
)+1);
400 strcat(n
->label
, str
);
402 /* LOCAL_ID_NODE, use ident field */
403 assert(astnode_is_type(n
, LOCAL_ID_NODE
));
404 n
->ident
= realloc(n
->ident
, strlen(n
->ident
)+strlen(str
)+1);
405 strcat(n
->ident
, str
);
413 * Globalizes all locals in the body of a macro expansion.
414 * Used by the macro expander to ensure that local labels in macro expansions
416 * @param exp_body The expanded macro body
417 * @param count Unique macro namespace counter
419 static void globalize_macro_expanded_locals(astnode
*exp_body
, int count
)
421 /* Table of callback functions for our purpose. */
422 static astnodeprocmap map
[] = {
423 { LOCAL_ID_NODE
, globalize_macro_expanded_local
},
424 { LOCAL_LABEL_NODE
, globalize_macro_expanded_local
},
428 astproc_walk(exp_body
, (void *)count
, map
);
432 * Expands a macro; that is, replaces a macro invocation in the AST with the
433 * macro body. Substitutes parameter names for values.
434 * @param n Must be a node of type MACRO_NODE
435 * @param arg Not used
437 static int expand_macro(astnode
*n
, void *arg
, astnode
**next
)
447 /* Keeps track of the current/total number of macro expansions */
448 static int count
= 0;
449 /* Get the name of the macro to expand */
450 id
= astnode_get_child(n
, 0);
451 /* Look up its definition in symbol table */
452 symtab_entry
*e
= symtab_lookup(id
->ident
);
453 /* If it's not in the symbol table, error. */
455 err(n
->loc
, "unknown macro or directive `%s'", id
->ident
);
456 /* Remove from AST */
461 else if (e
->type
!= MACRO_SYMBOL
) {
462 err(n
->loc
, "cannot expand `%s'; not a macro", e
->id
);
463 /* Remove from AST */
469 /* e->def has pointer to proper MACRO_DECL_NODE */
470 decl
= (astnode
*)e
->def
;
471 /* Get the lists of formals and actuals */
472 formals
= astnode_get_child(decl
, 1);
473 actuals
= astnode_get_child(n
, 1);
474 /* Verify that argument count is correct */
475 if (astnode_get_child_count(formals
) != astnode_get_child_count(actuals
)) {
476 err(n
->loc
, "macro `%s' does not take %d argument(s)", id
->ident
, astnode_get_child_count(actuals
) );
477 /* Remove from AST */
482 /* Expand the body */
483 decl_body
= astnode_get_child(decl
, 2);
484 exp_body
= astnode_clone(decl_body
, n
->loc
);
485 assert(astnode_get_type(exp_body
) == LIST_NODE
);
486 /* Substitute actuals for formals */
487 for (i
=0; i
<astnode_get_child_count(actuals
); i
++) {
488 /* The id to substitute */
489 id
= astnode_get_child(formals
, i
);
490 /* The expression to substitute it with */
491 expr
= astnode_get_child(actuals
, i
);
493 substitute_expr_for_id(expr
, id
, exp_body
);
495 /* Make locals a bit more global */
496 globalize_macro_expanded_locals(exp_body
, count
);
497 /* Replace MACRO_NODE by the macro body instance */
499 astnode
*stmts
= astnode_remove_children(exp_body
);
500 astnode_replace(n
, stmts
);
502 astnode_finalize(exp_body
);
504 /* Discard the replaced node */
506 /* Increase macro expansion counter */
513 /*---------------------------------------------------------------------------*/
516 * Does constant folding of expression.
517 * If the expression can be folded, the original expression is replaced by the
518 * new one, and the original expression is finalized.
519 * @param expr Expression
520 * @return Original expression, if couldn't fold, otherwise new, folded expression
522 astnode
*astproc_fold_constants(astnode
*expr
)
527 if (expr
== NULL
) { return NULL
; }
529 if (astnode_is_type(expr
, ARITHMETIC_NODE
)) {
530 /* Fold operands recursively */
531 lhs
= astproc_fold_constants(LHS(expr
));
532 rhs
= astproc_fold_constants(RHS(expr
));
533 switch (expr
->oper
) {
551 /* See if it can be folded */
552 if ( (astnode_is_type(lhs
, INTEGER_NODE
)) &&
553 (astnode_is_type(rhs
, INTEGER_NODE
)) ) {
554 /* Both sides are integer literals, so fold. */
555 switch (expr
->oper
) {
556 case PLUS_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
+ rhs
->integer
, expr
->loc
); break;
557 case MINUS_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
- rhs
->integer
, expr
->loc
); break;
558 case MUL_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
* rhs
->integer
, expr
->loc
); break;
559 case DIV_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
/ rhs
->integer
, expr
->loc
); break;
560 case MOD_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
% rhs
->integer
, expr
->loc
); break;
561 case AND_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
& rhs
->integer
, expr
->loc
); break;
562 case OR_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
| rhs
->integer
, expr
->loc
); break;
563 case XOR_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
^ rhs
->integer
, expr
->loc
); break;
564 case SHL_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
<< rhs
->integer
, expr
->loc
); break;
565 case SHR_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
>> rhs
->integer
, expr
->loc
); break;
566 case LT_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
< rhs
->integer
, expr
->loc
); break;
567 case GT_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
> rhs
->integer
, expr
->loc
); break;
568 case EQ_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
== rhs
->integer
, expr
->loc
); break;
569 case NE_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
!= rhs
->integer
, expr
->loc
); break;
570 case LE_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
<= rhs
->integer
, expr
->loc
); break;
571 case GE_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
>= rhs
->integer
, expr
->loc
); break;
574 fprintf(stderr
, "internal error: operator not handled in astproc_fold_constants()\n");
579 if (folded
!= expr
) {
580 /* Replace expression by folded one. */
581 astnode_replace(expr
, folded
);
582 astnode_finalize(expr
);
586 else if ( (astnode_is_type(lhs
, STRING_NODE
)) &&
587 (astnode_is_type(rhs
, STRING_NODE
)) ) {
588 /* Both sides are string literals. */
589 /* Folding is defined only for certain operators. */
590 switch (expr
->oper
) {
592 /* String concatenation. */
593 folded
= astnode_create(STRING_NODE
, expr
->loc
);
594 folded
->string
= (char *)malloc(strlen(lhs
->string
) + strlen(rhs
->string
) + 1);
595 if (folded
->string
!= NULL
) {
596 strcpy(folded
->string
, lhs
->string
);
597 strcat(folded
->string
, rhs
->string
);
601 /* String comparison. */
602 case LT_OPERATOR
: folded
= astnode_create_integer(strcmp(lhs
->string
, rhs
->string
) < 0, expr
->loc
); break;
603 case GT_OPERATOR
: folded
= astnode_create_integer(strcmp(lhs
->string
, rhs
->string
) > 0, expr
->loc
); break;
604 case EQ_OPERATOR
: folded
= astnode_create_integer(strcmp(lhs
->string
, rhs
->string
) == 0, expr
->loc
); break;
605 case NE_OPERATOR
: folded
= astnode_create_integer(strcmp(lhs
->string
, rhs
->string
) != 0, expr
->loc
); break;
606 case LE_OPERATOR
: folded
= astnode_create_integer(strcmp(lhs
->string
, rhs
->string
) <= 0, expr
->loc
); break;
607 case GE_OPERATOR
: folded
= astnode_create_integer(strcmp(lhs
->string
, rhs
->string
) >= 0, expr
->loc
); break;
613 if (folded
!= expr
) {
614 /* Replace expression by folded one. */
615 astnode_replace(expr
, folded
);
616 astnode_finalize(expr
);
620 else if ((astnode_get_type(lhs
) == STRING_NODE
) &&
621 (astnode_get_type(rhs
) == INTEGER_NODE
) &&
622 (expr
->oper
== PLUS_OPERATOR
)) {
623 /* Left side is string and right side is integer.
624 Result is a string. */
626 sprintf(str
, "%d", rhs
->integer
);
627 folded
= astnode_create(STRING_NODE
, expr
->loc
);
628 folded
->string
= (char *)malloc(strlen(lhs
->string
) + strlen(str
) + 1);
629 if (folded
->string
!= NULL
) {
630 strcpy(folded
->string
, lhs
->string
);
631 strcat(folded
->string
, str
);
633 /* Replace expression by folded one. */
634 astnode_replace(expr
, folded
);
635 astnode_finalize(expr
);
638 else if ((astnode_get_type(rhs
) == STRING_NODE
) &&
639 (astnode_get_type(lhs
) == INTEGER_NODE
) &&
640 (expr
->oper
== PLUS_OPERATOR
)) {
641 /* Left side is integer and right side is string.
642 Result is a string. */
644 sprintf(str
, "%d", lhs
->integer
);
645 folded
= astnode_create(STRING_NODE
, expr
->loc
);
646 folded
->string
= (char *)malloc(strlen(str
) + strlen(rhs
->string
) + 1);
647 if (folded
->string
!= NULL
) {
648 strcpy(folded
->string
, str
);
649 strcat(folded
->string
, rhs
->string
);
651 /* Replace expression by folded one. */
652 astnode_replace(expr
, folded
);
653 astnode_finalize(expr
);
656 /* Use some mathematical identities... */
657 else if ((astnode_is_type(lhs
, INTEGER_NODE
) && (lhs
->integer
== 0))
658 && (expr
->oper
== PLUS_OPERATOR
)) {
660 astnode_remove_child(expr
, rhs
);
661 astnode_replace(expr
, rhs
);
662 astnode_finalize(expr
);
665 else if ((astnode_is_type(rhs
, INTEGER_NODE
) && (rhs
->integer
== 0))
666 && (expr
->oper
== PLUS_OPERATOR
)) {
668 astnode_remove_child(expr
, lhs
);
669 astnode_replace(expr
, lhs
);
670 astnode_finalize(expr
);
673 else if ((astnode_is_type(lhs
, INTEGER_NODE
) && (lhs
->integer
== 1))
674 && (expr
->oper
== MUL_OPERATOR
)) {
676 astnode_remove_child(expr
, rhs
);
677 astnode_replace(expr
, rhs
);
678 astnode_finalize(expr
);
681 else if ((astnode_is_type(rhs
, INTEGER_NODE
) && (rhs
->integer
== 1))
682 && ((expr
->oper
== MUL_OPERATOR
) || (expr
->oper
== DIV_OPERATOR
)) ) {
685 astnode_remove_child(expr
, lhs
);
686 astnode_replace(expr
, lhs
);
687 astnode_finalize(expr
);
691 /* No chance of folding this one. */
700 case UMINUS_OPERATOR
:
702 /* See if it can be folded */
703 if (astnode_is_type(lhs
, INTEGER_NODE
)) {
705 switch (expr
->oper
) {
706 case NEG_OPERATOR
: folded
= astnode_create_integer(~lhs
->integer
, expr
->loc
); break;
707 case NOT_OPERATOR
: folded
= astnode_create_integer(!lhs
->integer
, expr
->loc
); break;
708 case LO_OPERATOR
: folded
= astnode_create_integer(lhs
->integer
& 0xFF, expr
->loc
); break;
709 case HI_OPERATOR
: folded
= astnode_create_integer((lhs
->integer
>> 8) & 0xFF, expr
->loc
); break;
710 case UMINUS_OPERATOR
: folded
= astnode_create_integer(-lhs
->integer
, expr
->loc
); break;
713 /* Replace expression by folded one. */
714 astnode_replace(expr
, folded
);
715 astnode_finalize(expr
);
719 /* Couldn't fold this one. */
724 /* Couldn't fold it, return original expression */
728 /*---------------------------------------------------------------------------*/
731 * Substitutes identifier if it has a constant definition in symbol table.
732 * @param expr Node of type IDENTIFIER_NODE
734 static astnode
*substitute_ident(astnode
*expr
)
738 /* Look it up in symbol table */
739 e
= symtab_lookup(expr
->ident
);
741 /* Found it. Test if it's a define. */
742 if (e
->type
== CONSTANT_SYMBOL
) {
743 /* This is a defined symbol that should be
744 replaced by the expression it stands for */
745 c
= astnode_clone((astnode
*)e
->def
, expr
->loc
);
746 astnode_replace(expr
, c
);
747 astnode_finalize(expr
);
752 /* Didn't find it in symbol table. */
758 * Substitutes sizeof with proper constant.
759 * @param expr Node of type SIZEOF_NODE
761 static astnode
*reduce_sizeof(astnode
*expr
)
771 if (astnode_is_type(LHS(expr
), IDENTIFIER_NODE
)) {
772 /* Identifier might be the name of a user-defined type, OR
773 it might be the name of a variable of a user-defined type */
777 e
= symtab_global_lookup(id
->ident
);
784 type
= astnode_create_datatype(USER_DATATYPE
, astnode_clone(id
, id
->loc
), id
->loc
);
788 type
= astnode_clone(LHS(e
->def
), id
->loc
);
789 if (astnode_is_type(e
->def
, STORAGE_NODE
)) {
790 count
= astnode_clone(RHS(e
->def
), id
->loc
);
793 count
= astnode_create_integer(astnode_get_child_count(e
->def
)-1, id
->loc
);
798 /* Can't take sizeof of this symbol type */
804 type
= astnode_create_datatype(USER_DATATYPE
, astnode_clone(id
, id
->loc
), id
->loc
);
806 /* Replace identifier by datatype node */
807 astnode_replace(id
, type
);
808 astnode_finalize(id
);
811 switch (type
->datatype
) {
814 c
= astnode_create_integer(1, expr
->loc
);
815 astnode_replace(expr
, c
);
816 astnode_finalize(expr
);
821 c
= astnode_create_integer(2, expr
->loc
);
822 astnode_replace(expr
, c
);
823 astnode_finalize(expr
);
828 c
= astnode_create_integer(4, expr
->loc
);
829 astnode_replace(expr
, c
);
830 astnode_finalize(expr
);
835 /* Look up the data type in symbol table */
837 e
= symtab_global_lookup(id
->ident
);
843 /* Datatype is defined, replace sizeof with proper expression */
844 c
= astnode_clone((astnode
*)(e
->struc
.size
), ((astnode
*)(e
->struc
.size
))->loc
);
845 astnode_replace(expr
, c
);
846 astnode_finalize(expr
);
854 c
= astnode_create_integer(1, expr
->loc
);
855 astnode_replace(expr
, c
);
856 astnode_finalize(expr
);
862 /* Dunno the size of this symbol type */
867 /* Datatype not defined, error */
868 err(expr
->loc
, "size of `%s' is unknown", id
->ident
);
870 c
= astnode_create_integer(1, expr
->loc
);
871 astnode_replace(expr
, c
);
872 astnode_finalize(expr
);
878 err(expr
->loc
, "substitute_sizeof(): unknown type");
882 c
= astnode_create_arithmetic(
884 astnode_clone(expr
, expr
->loc
),
888 astnode_replace(expr
, c
);
889 astnode_finalize(expr
);
896 * Substitutes A::B with an expression.
897 * If A is a struct: substitute with offset of B
898 * If A is a union: substitute with 0
899 * If A is an enumeration: substitute with value for B
900 * @param expr Node of type SCOPE_NODE
902 static astnode
*reduce_scope(astnode
*expr
)
909 /* Look up the namespace */
910 namespace = LHS(expr
);
911 ns
= symtab_lookup(namespace->ident
);
913 /* Look up the local symbol */
914 symtab_push(ns
->symtab
);
916 sym
= symtab_lookup(symbol
->ident
);
918 /* See if we can replace it */
923 /* Replace with field offset */
924 c
= astnode_clone(sym
->field
.offset
, sym
->field
.offset
->loc
);
925 astnode_replace(expr
, c
);
926 astnode_finalize(expr
);
931 /* Replace with enum entry value */
932 c
= astnode_clone(sym
->def
, sym
->def
->loc
);
933 astnode_replace(expr
, c
);
934 astnode_finalize(expr
);
947 static astnode
*reduce_expression(astnode
*expr
);
950 * Handles remainder of fields in A.B.C.D . ..., where one or more fields may be indexed.
951 * @param expr Node of type DOT_NODE, INDEX_NODE or IDENTIFIER_NODE
953 static astnode
*reduce_dot_recursive(astnode
*expr
)
962 astnode
*index
= NULL
;
963 /* Get identifiers involved: 'right' is field in 'left' */
965 if (astnode_is_type(left
, INDEX_NODE
)) {
966 left
= LHS(left
); /* Need identifier */
969 if (astnode_is_type(right
, DOT_NODE
)) {
970 right
= LHS(right
); /* Need identifier */
972 if (astnode_is_type(right
, INDEX_NODE
)) {
974 right
= LHS(right
); /* Need identifier */
976 /* Lookup 'right' in 'left's symbol table (on stack) */
977 field
= symtab_lookup(right
->ident
);
978 /* Look up variable's type definition */
979 type
= LHS(field
->def
);
980 /* Copy its offset */
981 offset
= astnode_clone(field
->field
.offset
, right
->loc
);
983 /* Create expression: identifier + sizeof(datatype) * index */
984 offset
= astnode_create_arithmetic(
987 astnode_create_arithmetic(
989 astnode_create_sizeof(astnode_clone(type
, type
->loc
), expr
->loc
),
990 astnode_clone(index
, index
->loc
),
996 /* See if more subfields to process */
998 if (astnode_is_type(expr
, DOT_NODE
)) {
1000 def
= symtab_global_lookup(LHS(type
)->ident
);
1001 symtab_push(def
->symtab
);
1002 term
= reduce_dot_recursive(expr
);
1005 offset
= astnode_create_arithmetic(
1016 * Transforms A.B.C.D . ... to A + offset(B) + offset(C) + ...
1017 * No error checking, since validate_dotref() should have been called previously.
1018 * @param expr Node of type DOT_NODE
1020 static astnode
*reduce_dot(astnode
*expr
)
1022 symtab_entry
*father
;
1029 astnode
*index
= NULL
;
1030 /* Look up parent in global symbol table */
1031 left
= LHS(expr
); /* expr := left . right */
1032 if (astnode_is_type(left
, INDEX_NODE
)) {
1034 left
= LHS(left
); /* Need identifier */
1036 father
= symtab_lookup(left
->ident
);
1037 /* Look up variable's type definition */
1038 type
= LHS(father
->def
); /* DATATYPE_NODE */
1039 def
= symtab_lookup(LHS(type
)->ident
);
1040 /* 1st term of sum is the leftmost structure identifier */
1041 term1
= astnode_clone(left
, left
->loc
);
1042 if (index
!= NULL
) {
1043 /* Create expression: identifier + sizeof(datatype) * index */
1044 term1
= astnode_create_arithmetic(
1047 astnode_create_arithmetic(
1049 astnode_create_sizeof(astnode_clone(type
, type
->loc
), expr
->loc
),
1050 astnode_clone(index
, index
->loc
),
1056 /* Add offsets recursively */
1057 symtab_push(def
->symtab
);
1058 term2
= reduce_dot_recursive(expr
);
1060 /* Calculate final sum */
1061 sum
= astnode_create_arithmetic(
1067 sum
= reduce_expression(sum
);
1068 /* Replace dotted expression by sum */
1069 astnode_replace(expr
, sum
);
1070 astnode_finalize(expr
);
1075 * Reduces MASK operation to a field mask.
1076 * @param mask A node of type MASK_NODE
1078 static astnode
*reduce_mask(astnode
*mask
)
1086 /* Child is a scope node, record::field */
1088 /* Look up the namespace */
1089 namespace = LHS(expr
);
1090 ns
= symtab_lookup(namespace->ident
);
1092 /* Make sure it's a record */
1093 if (ns
->type
!= RECORD_SYMBOL
) {
1094 err(expr
->loc
, "`%s' is not a record");
1096 c
= astnode_create_integer(0, expr
->loc
);
1097 astnode_replace(mask
, c
);
1098 astnode_finalize(mask
);
1102 /* Look up the local symbol */
1103 symtab_push(ns
->symtab
);
1105 sym
= symtab_lookup(symbol
->ident
);
1107 /* Calculate field mask */
1108 // mask = ((1 << width) - 1) << offset
1109 c
= astnode_create_arithmetic(
1111 astnode_create_arithmetic(
1113 astnode_create_arithmetic(
1115 astnode_create_integer(1, expr
->loc
),
1116 astnode_clone(sym
->field
.size
, expr
->loc
),
1119 astnode_create_integer(1, expr
->loc
),
1122 astnode_clone(sym
->field
.offset
, expr
->loc
),
1125 c
= reduce_expression(c
);
1126 astnode_replace(mask
, c
);
1127 astnode_finalize(mask
);
1137 * Reduces identifier[expression] to identifier + sizeof(identifier type) * expression
1139 static astnode
*reduce_index(astnode
*expr
)
1147 index
= reduce_expression(RHS(expr
));
1148 /* Lookup identifier */
1149 e
= symtab_lookup(id
->ident
);
1150 /* Get its datatype */
1152 /* Create expression: identifier + sizeof(datatype) * index */
1153 c
= astnode_create_arithmetic(
1155 astnode_clone(id
, id
->loc
),
1156 astnode_create_arithmetic(
1158 astnode_create_sizeof(astnode_clone(type
, type
->loc
), expr
->loc
),
1159 astnode_clone(index
, index
->loc
),
1164 /* Replace index expression */
1165 astnode_replace(expr
, c
);
1166 astnode_finalize(expr
);
1167 /* Return the new expression */
1172 * Substitutes all identifiers that represent EQU defines with their
1173 * corresponding expression.
1174 * @param expr The expression whose defines to substitute
1176 static astnode
*substitute_defines(astnode
*expr
)
1178 switch (astnode_get_type(expr
)) {
1179 case ARITHMETIC_NODE
:
1180 substitute_defines(LHS(expr
));
1181 substitute_defines(RHS(expr
));
1184 case IDENTIFIER_NODE
:
1185 expr
= substitute_ident(expr
);
1189 expr
= reduce_sizeof(expr
);
1193 expr
= reduce_mask(expr
);
1197 substitute_defines(LHS(expr
));
1198 substitute_defines(RHS(expr
));
1202 substitute_defines(LHS(expr
));
1203 substitute_defines(RHS(expr
));
1216 static astnode
*reduce_highlevel_constructs(astnode
*expr
)
1218 switch (astnode_get_type(expr
)) {
1219 case ARITHMETIC_NODE
:
1220 reduce_highlevel_constructs(LHS(expr
));
1221 reduce_highlevel_constructs(RHS(expr
));
1225 expr
= reduce_scope(expr
);
1229 expr
= reduce_dot(expr
);
1233 expr
= reduce_index(expr
);
1244 * Really reduces an expression.
1245 * @param expr Expression to attempt to reduce
1247 static astnode
*reduce_expression_complete(astnode
*expr
)
1249 return astproc_fold_constants( reduce_highlevel_constructs( substitute_defines(expr
) ) );
1253 * Reduces an expression.
1254 * It does two things:
1255 * 1. Substitute all equates by their value
1256 * 2. Folds constants in the resulting expression
1257 * If the expression is reduced, the original expression is replaced by the
1258 * new one, the original is finalized, and a pointer to the new expression
1260 * If the expression is not reduced, the original pointer is returned.
1262 static astnode
*reduce_expression(astnode
*expr
)
1264 return astproc_fold_constants( substitute_defines(expr
) );
1268 * Reduces RECORD instance to a single byte (DB statement).
1269 * @param r Record's symbol table entry
1270 * @param expr Record initializer
1271 * @param flat List on which to append the reduced form
1273 static void reduce_record(symtab_entry
*r
, astnode
*init
, astnode
*flat
)
1275 ordered_field_list
*list
;
1282 /* Validate initializer */
1283 if (!astnode_is_type(init
, STRUC_NODE
)) {
1284 err(init
->loc
, "record initializer expected");
1287 /* Go through fields */
1288 symtab_push(r
->symtab
);
1289 result
= astnode_create_integer(0, init
->loc
);
1290 for (val
= init
->first_child
, list
= r
->struc
.fields
; (val
!= NULL
) && (list
!= NULL
); list
= list
->next
, val
= val
->next_sibling
) {
1291 if (astnode_is_type(val
, NULL_NODE
)) {
1294 if (astnode_is_type(val
, STRUC_NODE
)) {
1295 err(init
->loc
, "record field initializer expected");
1298 /* Get field definition */
1300 /* Calculate field mask */
1301 // mask = ((1 << width) - 1) << offset
1302 mask
= astnode_create_arithmetic(
1304 astnode_create_arithmetic(
1306 astnode_create_arithmetic(
1308 astnode_create_integer(1, val
->loc
),
1309 astnode_clone(e
->field
.size
, val
->loc
),
1312 astnode_create_integer(1, val
->loc
),
1315 astnode_clone(e
->field
.offset
, val
->loc
),
1318 /* Shift val left e->field.offset bits, AND with mask */
1319 term
= astnode_create_arithmetic(
1321 astnode_create_arithmetic(
1323 astnode_clone(val
, val
->loc
),
1324 astnode_clone(e
->field
.offset
, val
->loc
),
1330 /* OR the value with the result so far */
1331 result
= astnode_create_arithmetic(
1337 result
= reduce_expression(result
);
1339 /* Determine reason for stopping loop */
1341 err(init
->loc
, "too many field initializers");
1343 /* Make byte data node (packed record value) */
1344 repl
= astnode_create_data(
1345 astnode_create_datatype(BYTE_DATATYPE
, NULL
, init
->loc
),
1350 astnode_add_child(flat
, repl
);
1351 /* Restore old symbol table */
1356 * Reduces ENUM instance to DB.
1357 * @param e Enumeration's symbol table entry
1358 * @param expr Expression
1359 * @param flat List on which to append the reduced form
1361 static void reduce_enum(symtab_entry
*e
, astnode
*expr
, astnode
*list
)
1365 if (!astnode_is_type(expr
, IDENTIFIER_NODE
)) {
1366 err(expr
->loc
, "identifier expected");
1369 /* Look up the enumeration symbol */
1370 symtab_push(e
->symtab
);
1371 sym
= symtab_lookup(expr
->ident
);
1373 /* Make byte data node (symbol value) */
1374 repl
= astnode_create_data(
1375 astnode_create_datatype(BYTE_DATATYPE
, NULL
, expr
->loc
),
1376 astnode_clone(sym
->def
, expr
->loc
),
1380 astnode_add_child(list
, repl
);
1384 static void flatten_struc_recursive(symtab_entry
*s
, astnode
*init
, astnode
*flat
);
1387 * Flattens a union initializer to a sequence of native data values.
1388 * Verify similar to flattening of structure, but only single field allowed.
1389 * @param s Union's symbol table definition
1390 * @param init Union initializer
1391 * @param flat List on which to append the flattened form
1393 static void flatten_union_recursive(symtab_entry
*s
, astnode
*init
, astnode
*flat
)
1403 ordered_field_list
*list
;
1405 /* Validate initializer */
1406 if (!astnode_is_type(init
, STRUC_NODE
)) {
1407 err(init
->loc
, "union initializer expected");
1410 /* Go through fields */
1411 symtab_push(s
->symtab
);
1412 fill
= astnode_clone(s
->struc
.size
, flat
->loc
);
1413 for (val
= init
->first_child
, list
= s
->struc
.fields
; (val
!= NULL
) && (list
!= NULL
); list
= list
->next
, val
= val
->next_sibling
) {
1414 if (astnode_is_type(val
, NULL_NODE
)) {
1417 if (!astnode_equal(fill
, s
->struc
.size
)) {
1418 err(init
->loc
, "only one field of union can be initialized");
1421 /* Get field definition */
1423 /* Symbol definition is STORAGE_NODE w/ two children: type and count */
1425 count
= RHS(e
->def
);
1426 /* Decide what to do based on field type and value */
1427 switch (type
->datatype
) {
1431 case DWORD_DATATYPE
:
1432 if (astnode_is_type(val
, STRUC_NODE
)) {
1433 /* Handle multi-value array */
1434 temp
= astnode_clone(val
, val
->loc
);
1435 valvals
= astnode_remove_children(temp
);
1436 astnode_finalize(temp
);
1437 astnode_add_child(flat
,
1438 astnode_create_data(
1439 astnode_create_datatype(type
->datatype
, NULL
, type
->loc
),
1444 num
= astnode_get_child_count(val
);
1446 /* Output single value */
1447 astnode_add_child(flat
,
1448 astnode_create_data(
1449 astnode_create_datatype(type
->datatype
, NULL
, type
->loc
),
1450 astnode_clone(val
, val
->loc
),
1454 num
= astnode_is_type(val
, STRING_NODE
) ? strlen(val
->string
) : 1;
1456 if (num
> count
->integer
) {
1457 err(val
->loc
, "initializer for field `%s' exceeds field size", e
->id
);
1459 /* Fill in remainder of field if necessary: count - 1 */
1460 else if (count
->integer
> num
) {
1461 astnode_add_child(flat
,
1462 astnode_create_storage(
1463 astnode_create_datatype(type
->datatype
, NULL
, type
->loc
),
1464 astproc_fold_constants(
1465 astnode_create_arithmetic(
1467 astnode_clone(count
, count
->loc
),
1468 astnode_create_integer(num
, flat
->loc
),
1479 /* Look up user type definition */
1480 t
= symtab_global_lookup(LHS(type
)->ident
);
1483 flatten_struc_recursive(t
, val
, flat
);
1487 flatten_union_recursive(t
, val
, flat
);
1491 reduce_record(t
, val
, flat
);
1495 reduce_enum(t
, val
, flat
);
1503 /* Decrease fill amount according to field size */
1504 fill
= astproc_fold_constants(
1505 astnode_create_arithmetic(
1508 astnode_clone(e
->field
.size
, flat
->loc
),
1513 /* Determine reason for stopping loop */
1515 err(init
->loc
, "too many field initializers");
1517 if (fill
->integer
> 0) {
1518 /* Fill remainder of union with zeroes */
1519 astnode_add_child(flat
,
1520 astnode_create_storage(
1521 astnode_create_datatype(BYTE_DATATYPE
, NULL
, flat
->loc
),
1531 * Flattens a structure initializer to a sequence of native data values.
1532 * @param s Structure's symbol table definition
1533 * @param init Structure initializer
1534 * @param flat List on which to append the flattened form
1536 static void flatten_struc_recursive(symtab_entry
*s
, astnode
*init
, astnode
*flat
)
1546 ordered_field_list
*list
;
1548 /* Validate initializer */
1549 if (!astnode_is_type(init
, STRUC_NODE
)) {
1550 err(init
->loc
, "structure initializer expected");
1553 /* Go through fields */
1554 symtab_push(s
->symtab
);
1555 fill
= astnode_clone(s
->struc
.size
, flat
->loc
);
1556 for (val
= init
->first_child
, list
= s
->struc
.fields
; (val
!= NULL
) && (list
!= NULL
); list
= list
->next
, val
= val
->next_sibling
) {
1557 /* Get field definition */
1559 /* Check if normal field or anonymous union */
1560 if (e
->type
== UNION_SYMBOL
) {
1561 if (astnode_is_type(val
, NULL_NODE
)) {
1562 /* Output union size bytes to fill in field */
1563 astnode_add_child(flat
,
1564 astnode_create_storage(
1565 astnode_create_datatype(BYTE_DATATYPE
, NULL
, val
->loc
),
1566 astnode_clone(e
->struc
.size
, val
->loc
),
1571 flatten_union_recursive(e
, val
, flat
);
1572 /* Decrease fill amount according to union size */
1573 fill
= astproc_fold_constants(
1574 astnode_create_arithmetic(
1577 astnode_clone(e
->struc
.size
, flat
->loc
),
1584 /* Symbol definition is STORAGE_NODE w/ two children: type and count */
1586 count
= RHS(e
->def
);
1587 /* Decide what to do based on field type and value */
1588 switch (type
->datatype
) {
1592 case DWORD_DATATYPE
:
1593 if (astnode_is_type(val
, NULL_NODE
)) {
1594 /* Output field_size bytes to fill in field */
1595 astnode_add_child(flat
,
1596 astnode_create_storage(
1597 astnode_create_datatype(type
->datatype
, NULL
, type
->loc
),
1598 astnode_clone(count
, count
->loc
),
1603 if (astnode_is_type(val
, STRUC_NODE
)) {
1604 /* Handle multi-value array */
1605 temp
= astnode_clone(val
, val
->loc
);
1606 valvals
= astnode_remove_children(temp
);
1607 astnode_finalize(temp
);
1608 astnode_add_child(flat
,
1609 astnode_create_data(
1610 astnode_create_datatype(type
->datatype
, NULL
, type
->loc
),
1615 num
= astnode_get_child_count(val
);
1617 /* Output single value */
1618 astnode_add_child(flat
,
1619 astnode_create_data(
1620 astnode_create_datatype(type
->datatype
, NULL
, type
->loc
),
1621 astnode_clone(val
, val
->loc
),
1625 num
= astnode_is_type(val
, STRING_NODE
) ? strlen(val
->string
) : 1;
1627 if (astnode_is_type(count
, INTEGER_NODE
) && (count
->integer
< num
)) {
1628 err(val
->loc
, "initializer for field `%s' exceeds field size", e
->id
);
1630 /* Fill in remainder of field if necessary: count - 1 */
1631 else if ( (astnode_is_type(count
, INTEGER_NODE
) && (count
->integer
> num
))
1632 || !astnode_is_type(count
, INTEGER_NODE
) ) {
1633 astnode_add_child(flat
,
1634 astnode_create_storage(
1635 astnode_create_datatype(type
->datatype
, NULL
, flat
->loc
),
1636 astproc_fold_constants(
1637 astnode_create_arithmetic(
1639 astnode_clone(count
, flat
->loc
),
1640 astnode_create_integer(num
, flat
->loc
),
1652 /* Look up user type definition */
1653 t
= symtab_global_lookup(LHS(type
)->ident
);
1654 if (astnode_is_type(val
, NULL_NODE
)) {
1655 /* Output sizeof(type) bytes to fill in */
1656 astnode_add_child(flat
,
1657 astnode_create_storage(
1658 astnode_create_datatype(BYTE_DATATYPE
, NULL
, val
->loc
),
1659 astnode_clone(t
->struc
.size
, val
->loc
),
1666 flatten_struc_recursive(t
, val
, flat
);
1670 flatten_union_recursive(t
, val
, flat
);
1674 reduce_record(t
, val
, flat
);
1678 reduce_enum(t
, val
, flat
);
1687 /* Decrease fill amount according to field size */
1688 fill
= astproc_fold_constants(
1689 astnode_create_arithmetic(
1692 astnode_clone(e
->field
.size
, flat
->loc
),
1698 /* Determine reason for stopping loop */
1700 err(init
->loc
, "too many field initializers");
1702 else if (list
!= NULL
) {
1703 /* All fields not initialized; fill remainder of struc with zeroes */
1704 astnode_add_child(flat
,
1705 astnode_create_storage(
1706 astnode_create_datatype(BYTE_DATATYPE
, NULL
, flat
->loc
),
1712 astnode_finalize(fill
);
1718 * Converts data that is expressed in a high-level form (such as structure initializers)
1719 * to a simple sequence of bytes.
1720 * @param n The source node to flatten
1721 * @param type The type of data that n is an instance of
1722 * @param list List on which to append the resulting sequence of items (bytes/words/dwords)
1724 static void flatten_user_data(astnode
*n
, astnode
*type
, astnode
*list
)
1727 /* Look up type definition */
1728 def
= symtab_global_lookup(LHS(type
)->ident
);
1730 switch (def
->type
) {
1732 /* Flatten structure initializer to series of simple data statements */
1733 flatten_struc_recursive(def
, n
, list
);
1737 /* Flatten union initializer to series of simple data statements */
1738 flatten_union_recursive(def
, n
, list
);
1742 reduce_record(def
, n
, list
);
1746 reduce_enum(def
, n
, list
);
1755 /*---------------------------------------------------------------------------*/
1758 * Loads the character map specified by the node.
1759 * @param n Node of type CHARMAP_NODE
1761 static int load_charmap(astnode
*n
, void *arg
, astnode
**next
)
1763 /* TODO: should probably be done in the parsing phase (same path resolution as for INCSRC and INCBIN) */
1765 /* Get file descriptor */
1766 file
= astnode_get_child(n
, 0);
1767 /* Try to load the charmap */
1768 if (charmap_parse(file
->file_path
, charmap
) == 0) {
1769 err(n
->loc
, "could not open `%s' for reading", file
->file_path
);
1775 * First-time processing of instruction node.
1776 * @param n Node of type INSTRUCTION_NODE
1777 * @param arg Not used
1779 static int process_instruction(astnode
*n
, void *arg
, astnode
**next
)
1783 err(n
->loc
, "instructions not allowed in data segment");
1784 /* Remove from AST */
1786 astnode_finalize(n
);
1790 /* The instruction operand */
1791 expr
= astnode_get_child(n
, 0);
1792 /* Substitute defines and fold constants */
1793 reduce_expression(expr
);
1799 * First-time processing of data node.
1800 * @param n Node of type DATA_NODE
1801 * @param arg Not used
1803 static int process_data(astnode
*n
, void *arg
, astnode
**next
)
1811 type
= astnode_get_child(n
, 0);
1812 assert(astnode_is_type(type
, DATATYPE_NODE
));
1814 err(n
->loc
, "value not allowed in data segment");
1815 /* Replace with storage node */
1818 astnode_create_storage(
1819 astnode_create_datatype(BYTE_DATATYPE
, NULL
, n
->loc
),
1820 astnode_create_integer(1, n
->loc
),
1824 astnode_finalize(n
);
1827 if (type
->datatype
== USER_DATATYPE
) {
1828 /* Make sure the type exists */
1829 if (symtab_global_lookup(LHS(type
)->ident
) == NULL
) {
1830 err(n
->loc
, "unknown type `%s'", LHS(type
)->ident
);
1831 /* Remove from AST */
1833 astnode_finalize(n
);
1836 /* Attempt to reduce user data to native data */
1837 list
= astnode_create(LIST_NODE
, n
->loc
);
1838 for (expr
= type
->next_sibling
; expr
!= NULL
; expr
= expr
->next_sibling
) {
1839 flatten_user_data(expr
, type
, list
);
1841 /* Replace initializers with generated list */
1842 stmts
= astnode_remove_children(list
);
1843 astnode_replace(n
, stmts
);
1844 astnode_finalize(n
);
1845 astnode_finalize(list
);
1850 /* Go through the list of data values, replacing defines and folding constants */
1851 for (j
=1; j
<astnode_get_child_count(n
); j
++) {
1852 expr
= astnode_get_child(n
, j
);
1853 /* Substitute defines and fold constants */
1854 expr
= reduce_expression(expr
);
1855 /* If it's a string, replace by array of integers */
1856 /* (makes it easier to process later... favour regularity) */
1857 if (astnode_is_type(expr
, STRING_NODE
)) {
1858 astnode_remove_child(n
, expr
); /* Remove string */
1859 for (k
=strlen(expr
->string
)-1; k
>=0; k
--) {
1860 /* Check if we should map character from custom charmap */
1861 if (type
->datatype
== CHAR_DATATYPE
) {
1862 expr
->string
[k
] = charmap
[(unsigned)expr
->string
[k
]];
1864 /* Append character value to array */
1865 astnode_insert_child(n
, astnode_create_integer((unsigned char)expr
->string
[k
], n
->loc
), j
);
1867 if (type
->datatype
== CHAR_DATATYPE
) {
1868 /* It's normal byte array now */
1869 type
->datatype
= BYTE_DATATYPE
;
1871 j
+= strlen(expr
->string
)-1;
1872 astnode_finalize(expr
);
1879 * First-time processing of storage node.
1880 * @param n Node of type STORAGE_NODE
1881 * @param arg Not used
1883 static int process_storage(astnode
*n
, void *arg
, astnode
**next
)
1891 /* If not BYTE_DATATYPE, multiply by word/dword-size */
1892 switch (type
->datatype
) {
1894 case CHAR_DATATYPE
: item_size
= 1; break;
1895 case WORD_DATATYPE
: item_size
= 2; break;
1896 case DWORD_DATATYPE
: item_size
= 4; break;
1897 default: item_size
= 1; break; // ### Hmmm...
1899 if (item_size
!= 1) {
1900 new_expr
= astnode_create_arithmetic(
1902 astnode_clone(expr
, expr
->loc
),
1903 astnode_create_integer(item_size
, expr
->loc
),
1906 astnode_replace(expr
, new_expr
);
1907 astnode_finalize(expr
);
1909 type
->datatype
= BYTE_DATATYPE
;
1911 /* Substitute defines and fold constants */
1912 expr
= reduce_expression(expr
);
1913 // TODO: Validate range somewhere else than here please... ???
1914 if (astnode_is_type(expr
, INTEGER_NODE
)) {
1915 if ((expr
->integer
<= 0) || (expr
->integer
>= 0x10000)) {
1916 err(n
->loc
, "operand out of range");
1924 * @param n Node of type EQU_NODE
1925 * @param arg Not used
1927 static int process_equ(astnode
*n
, void *arg
, astnode
**next
)
1932 /* The expression which describes the value */
1933 expr
= astnode_clone(astnode_get_child(n
, 1), n
->loc
);
1934 /* Substitute defines and fold constants */
1935 expr
= reduce_expression(expr
);
1936 /* The identifier which is being defined */
1937 id
= astnode_get_child(n
, 0);
1938 /* Look up in symbol table */
1939 e
= symtab_lookup(id
->ident
);
1941 /* Symbol is being defined */
1942 // TODO: Check that expression is a constant?
1943 /* Enter it in symbol table */
1944 symtab_enter(id
->ident
, CONSTANT_SYMBOL
, expr
, 0);
1946 /* Symbol is being redefined */
1947 /* This is not allowed for EQU equate! */
1948 if (!astnode_equal((astnode
*)(e
->def
), expr
)) {
1949 warn(n
->loc
, "redefinition of `%s' is not identical; ignored", id
->ident
);
1952 /* Remove the equate node from the tree. */
1954 astnode_finalize(n
);
1960 * @param n Node of type ASSIGN_NODE
1961 * @param arg Not used
1963 static int process_assign(astnode
*n
, void *arg
, astnode
**next
)
1968 /* If it's part of ENUM declaration, don't touch */
1969 if (astnode_has_ancestor_of_type(n
, ENUM_DECL_NODE
)) {
1972 /* Very similar to EQU, except symbol 1) can be
1973 redefined and 2) is volatile (see end of proc) */
1974 /* The expression which describes the value */
1975 expr
= astnode_clone(astnode_get_child(n
, 1), n
->loc
);
1976 /* Substitute defines and fold constants */
1977 expr
= reduce_expression(expr
);
1978 /* The identifier which is being (re)defined */
1979 id
= astnode_get_child(n
, 0);
1980 /* Look up in symbol table */
1981 e
= symtab_lookup(id
->ident
);
1983 /* Symbol is being defined for the first time */
1984 /* Note that the VOLATILE_FLAG is set */
1985 symtab_enter(id
->ident
, CONSTANT_SYMBOL
, expr
, VOLATILE_FLAG
);
1987 /* Symbol is being redefined */
1988 /* This is OK for ASSIGN equate, simply replace definition */
1989 // ### store a list of definitions
1990 expr
->loc
= e
->def
->loc
;
1993 /* Remove the equate node from the tree. */
1995 astnode_finalize(n
);
2000 * Process IFDEF-node.
2001 * @param n Node of type IFDEF_NODE
2002 * @param arg Not used
2004 static int process_ifdef(astnode
*n
, void *arg
, astnode
**next
)
2009 /* The identifier which is being tested */
2010 id
= astnode_get_child(n
, 0);
2011 e
= symtab_lookup(id
->ident
);
2013 /* Symbol is defined. */
2014 /* Replace IFDEF node by the true-branch statement list */
2015 stmts
= astnode_remove_children(astnode_get_child(n
, 1));
2016 astnode_replace(n
, stmts
);
2019 /* Symbol is not defined. */
2020 /* Replace IFDEF node by the false-branch statement list (if any) */
2021 stmts
= astnode_remove_children( astnode_get_child(n
, 2));
2022 if (stmts
!= NULL
) {
2023 astnode_replace(n
, stmts
);
2029 /* Discard the original node */
2030 astnode_finalize(n
);
2035 * Process IFNDEF-node.
2036 * @param n Node of type IFNDEF_NODE
2037 * @param arg Not used
2039 static int process_ifndef(astnode
*n
, void *arg
, astnode
**next
)
2044 /* The identifier which is being tested */
2045 id
= astnode_get_child(n
, 0);
2046 e
= symtab_lookup(id
->ident
);
2048 /* Symbol is not defined. */
2049 /* Replace IFNDEF node by the true-branch statement list */
2050 stmts
= astnode_remove_children(astnode_get_child(n
, 1));
2051 astnode_replace(n
, stmts
);
2054 /* Symbol is defined. */
2055 /* Replace IFNDEF node by the false-branch statement list, if any */
2056 stmts
= astnode_remove_children(astnode_get_child(n
, 2));
2057 if (stmts
!= NULL
) {
2058 astnode_replace(n
, stmts
);
2064 /* Discard the original node */
2065 astnode_finalize(n
);
2071 * @param n Node of type IF_NODE
2072 * @param arg Not used
2074 static int process_if(astnode
*n
, void *arg
, astnode
**next
)
2080 /* IF_NODE has a list of CASE, DEFAULT nodes as children */
2081 for (c
= astnode_get_first_child(n
); c
!= NULL
; c
= astnode_get_next_sibling(c
) ) {
2082 if (astnode_is_type(c
, CASE_NODE
)) {
2083 /* The expression which is being tested */
2084 expr
= astnode_get_child(c
, 0);
2085 /* Try to reduce expression to literal */
2086 expr
= reduce_expression(expr
);
2087 /* Resulting expression must be an integer literal,
2088 since this is static evaluation.
2089 In other words, it can't contain label references.
2091 if (astnode_is_type(expr
, INTEGER_NODE
)) {
2092 /* Non-zero is true, zero is false */
2093 if (expr
->integer
) {
2094 /* Replace IF node by the true-branch statement list */
2095 stmts
= astnode_remove_children( astnode_get_child(c
, 1) );
2096 astnode_replace(n
, stmts
);
2097 astnode_finalize(n
);
2102 /* Error, expression is not constant */
2103 err(expr
->loc
, "conditional expression does not evaluate to literal");
2105 } else { /* DEFAULT_NODE */
2106 /* Replace IF node by the false-branch statement list */
2107 stmts
= astnode_remove_children(c
);
2108 astnode_replace(n
, stmts
);
2109 astnode_finalize(n
);
2114 /* No match, remove IF node from AST */
2116 astnode_finalize(n
);
2121 * Process dataseg-node.
2122 * @param n Node of type DATASEG_NODE
2123 * @param arg Not used
2125 static int process_dataseg(astnode
*n
, void *arg
, astnode
**next
)
2127 modifiers
= n
->modifiers
;
2128 in_dataseg
= 1; /* true */
2133 * Process codeseg-node.
2134 * @param n Node of type CODESEG_NODE
2135 * @param arg Not used
2137 static int process_codeseg(astnode
*n
, void *arg
, astnode
**next
)
2140 in_dataseg
= 0; /* false */
2146 * @param n Node of type ORG_NODE
2147 * @param arg Not used
2149 static int process_org(astnode
*n
, void *arg
, astnode
**next
)
2151 if (!xasm_args
.pure_binary
) {
2152 err(n
->loc
, "org directive can only be used when output format is pure 6502 binary");
2154 astnode
*addr
= astnode_get_child(n
, 0);
2155 addr
= reduce_expression_complete(addr
);
2156 if (astnode_is_type(addr
, INTEGER_NODE
)) {
2158 if ((addr
->integer
< 0) || (addr
->integer
>= 0x10000)) {
2159 err(n
->loc
, "org address out of 64K range");
2162 err(n
->loc
, "org address does not evaluate to literal");
2163 /* Remove from AST */
2165 astnode_finalize(n
);
2172 * Process REPT node.
2173 * @param n Node of type REPT_NODE
2174 * @param arg Not used
2176 static int process_rept(astnode
*n
, void *arg
, astnode
**next
)
2181 /* The repeat count */
2182 count
= astnode_get_child(n
, 0);
2183 /* Try to reduce count expression to literal */
2184 count
= reduce_expression_complete(count
);
2185 /* Resulting expression must be an integer literal,
2186 since this is static evaluation.
2188 if (astnode_is_type(count
, INTEGER_NODE
)) {
2189 if (count
->integer
< 0) {
2190 warn(n
->loc
, "REPT ignored; negative repeat count (%d)", count
->integer
);
2191 /* Remove from AST */
2193 astnode_finalize(n
);
2194 } else if (count
->integer
> 0) {
2195 /* Expand body <count> times */
2196 list
= astnode_clone(astnode_get_child(n
, 1), n
->loc
);
2197 stmts
= astnode_remove_children(list
);
2198 astnode_finalize(list
);
2199 while (--count
->integer
> 0) {
2200 list
= astnode_clone(astnode_get_child(n
, 1), n
->loc
);
2201 astnode_add_sibling(stmts
, astnode_remove_children(list
) );
2202 astnode_finalize(list
);
2204 astnode_replace(n
, stmts
);
2205 astnode_finalize(n
);
2208 /* count == 0, remove from AST */
2210 astnode_finalize(n
);
2213 err(n
->loc
, "repeat count does not evaluate to literal");
2214 /* Remove from AST */
2216 astnode_finalize(n
);
2222 * Process WHILE node.
2223 * @param n Node of type WHILE_NODE
2224 * @param arg Not used
2226 static int process_while(astnode
*n
, void *arg
, astnode
**next
)
2231 /* The boolean expression */
2232 expr
= astnode_get_child(n
, 0);
2233 /* Try to reduce expression to literal */
2234 expr
= reduce_expression(astnode_clone(expr
, expr
->loc
));
2235 /* Resulting expression must be an integer literal,
2236 since this is static evaluation.
2238 if (astnode_is_type(expr
, INTEGER_NODE
)) {
2239 /* Expand body if the expression is true */
2240 if (expr
->integer
) {
2241 list
= astnode_clone(astnode_get_child(n
, 1), n
->loc
);
2242 stmts
= astnode_remove_children(list
);
2243 astnode_finalize(list
);
2244 astnode_replace(n
, stmts
);
2245 astnode_add_sibling(stmts
, n
); /* Clever huh? */
2248 /* Remove WHILE node from AST */
2250 astnode_finalize(n
);
2253 err(n
->loc
, "while expression does not evaluate to literal");
2254 /* Remove WHILE node from AST */
2256 astnode_finalize(n
);
2258 astnode_finalize(expr
);
2262 /*---------------------------------------------------------------------------*/
2265 * Enters a macro into the symbol table.
2266 * @param n Must be a node of type MACRO_DECL_NODE
2267 * @param arg Not used
2269 static int enter_macro(astnode
*n
, void *arg
, astnode
**next
)
2271 astnode
*id
= astnode_get_child(n
, 0); /* Child 0 is macro identifier */
2272 assert(astnode_get_type(id
) == IDENTIFIER_NODE
);
2273 if (symtab_enter(id
->ident
, MACRO_SYMBOL
, n
, 0) == NULL
) {
2274 /* ### This could be allowed, you know... */
2275 err(n
->loc
, "duplicate symbol `%s'", id
->ident
);
2277 /* Remove from AST */
2279 // ### n is not finalized???
2284 * Enters a label into the symbol table.
2285 * @param n Must be a node of type LABEL_NODE
2287 static int enter_label(astnode
*n
, void *arg
, astnode
**next
)
2291 /* Make sure it's unique first */
2292 if (symtab_lookup(n
->ident
)) {
2293 err(n
->loc
, "duplicate symbol `%s'", n
->ident
);
2294 /* Remove from AST */
2296 astnode_finalize(n
);
2299 e
= symtab_enter(n
->ident
, LABEL_SYMBOL
, n
, (in_dataseg
? DATA_FLAG
: 0) | modifiers
);
2300 /* Check if hardcoded address */
2301 addr
= reduce_expression_complete(RHS(n
));
2302 if (astnode_is_type(addr
, INTEGER_NODE
)) {
2304 e
->address
= addr
->integer
;
2305 e
->flags
|= ADDR_FLAG
;
2306 } else if (!astnode_is_type(addr
, CURRENT_PC_NODE
)) {
2307 err(n
->loc
, "label address does not evaluate to literal");
2309 /* Increase namespace counter */
2317 * Enters a variable declaration in symbol table.
2318 * @param n Must be a node of type VAR_DECL_NODE
2320 static int enter_var(astnode
*n
, void *arg
, astnode
**next
)
2322 astnode
*id
= LHS(n
); /* Variable identifier */
2323 assert(astnode_get_type(id
) == IDENTIFIER_NODE
);
2324 /* Make sure it's unique first */
2325 if (symtab_lookup(id
->ident
)) {
2326 err(n
->loc
, "duplicate symbol `%s'", id
->ident
);
2327 /* Remove from AST */
2329 astnode_finalize(n
);
2332 /* Validate modifiers */
2333 if ((n
->modifiers
& ZEROPAGE_FLAG
) && !in_dataseg
) {
2334 warn(n
->loc
, "zeropage modifier has no effect in code segment");
2335 n
->modifiers
&= ~ZEROPAGE_FLAG
;
2338 symtab_enter(id
->ident
, VAR_SYMBOL
, astnode_clone(RHS(n
), n
->loc
), (in_dataseg
? DATA_FLAG
: 0) | n
->modifiers
| modifiers
);
2345 * Enters a procedure declaration in symbol table.
2346 * @param n Must be a node of type PROC_NODE
2348 static int enter_proc(astnode
*n
, void *arg
, astnode
**next
)
2352 err(n
->loc
, "procedures not allowed in data segment");
2353 /* Remove from AST */
2355 astnode_finalize(n
);
2358 id
= LHS(n
); /* Procedure identifier */
2359 assert(astnode_get_type(id
) == IDENTIFIER_NODE
);
2360 /* Make sure it's unique first */
2361 if (symtab_lookup(id
->ident
)) {
2362 err(n
->loc
, "duplicate symbol `%s'", id
->ident
);
2363 /* Remove from AST */
2365 astnode_finalize(n
);
2368 /* Enter it! RHS(n) is the list of procedure statements */
2369 symtab_enter(id
->ident
, PROC_SYMBOL
, RHS(n
), (in_dataseg
? DATA_FLAG
: 0) );
2370 /* Increase global namespace counter */
2378 * Enters a simple <identifier> <storage> structure member.
2379 * @param c Node of type VAR_DECL_NODE
2380 * @param offset Offset of this field
2381 * @param plist List of symbol table's entries
2382 * @param struc_id Structure identifier (for error messages)
2383 * @return New offset (old offset + size of this field)
2385 static astnode
*enter_struc_atomic_field(astnode
*c
, astnode
*offset
, ordered_field_list
***plist
, astnode
*struc_id
)
2388 astnode
*field_data
;
2389 astnode
*field_size
;
2391 /* c has two children: id and STORAGE_NODE */
2393 assert(astnode_get_type(field_id
) == IDENTIFIER_NODE
);
2394 field_data
= RHS(c
);
2395 reduce_expression(RHS(field_data
));
2396 /* Validate the declaration -- no data initialized */
2397 if (astnode_is_type(field_data
, DATA_NODE
)) {
2398 err(c
->loc
, "data initialization not allowed here");
2401 /* Try to enter field in structure's symbol table */
2405 astnode_clone(field_data
, field_data
->loc
),
2409 err(c
->loc
, "duplicate symbol `%s' in structure `%s'", field_id
->ident
, struc_id
->ident
);
2412 /* Add to ordered list of fields */
2413 (**plist
) = malloc(sizeof(ordered_field_list
));
2414 (**plist
)->entry
= fe
;
2415 (**plist
)->next
= NULL
;
2416 *plist
= &((**plist
)->next
);
2417 /* Set field offset */
2418 fe
->field
.offset
= astnode_clone(offset
, offset
->loc
);
2419 /* Calculate field size in bytes: sizeof(datatype) * count */
2420 field_size
= astnode_create_arithmetic(
2422 astnode_create_sizeof(astnode_clone(LHS(field_data
), field_data
->loc
), field_data
->loc
),
2423 astnode_clone(RHS(field_data
), field_data
->loc
),
2426 field_size
= reduce_expression(field_size
);
2427 /* Set field size */
2428 fe
->field
.size
= astnode_clone(field_size
, field_size
->loc
);
2429 /* Add field size to total offset */
2430 offset
= astnode_create_arithmetic(
2436 offset
= reduce_expression(offset
);
2440 static void enter_union_fields(symtab_entry
*, astnode
*);
2443 * Attempts to enter an (anonymous) union's members into structure's symbol table.
2444 * @param n Node of type UNION_DECL_NODE
2445 * @param offset Current parent structure offset
2446 * @param plist Ordered list of parent structure's fields
2448 astnode
*enter_struc_union_field(astnode
*n
, astnode
*offset
, ordered_field_list
***plist
, astnode
*struc_id
)
2450 ordered_field_list
*ls
;
2457 if (astnode_is_type(union_id
, IDENTIFIER_NODE
)) {
2458 err(n
->loc
, "anonymous union expected");
2461 /* Put UNION in symbol table */
2462 sprintf(id_str
, "%d", id
++);
2463 se
= symtab_enter(id_str
, UNION_SYMBOL
, n
, 0);
2464 enter_union_fields(se
, n
);
2465 /* Add to ordered list of fields */
2466 (**plist
) = malloc(sizeof(ordered_field_list
));
2467 (**plist
)->entry
= se
;
2468 (**plist
)->next
= NULL
;
2469 *plist
= &((**plist
)->next
);
2470 /* Add to parent structure as well, with same offsets */
2471 for (ls
= se
->struc
.fields
; ls
!= NULL
; ls
= ls
->next
) {
2472 /* Try to enter field in structure's symbol table */
2476 astnode_clone(ls
->entry
->def
, ls
->entry
->def
->loc
),
2480 err(ls
->entry
->def
->loc
, "duplicate symbol `%s' in structure `%s'", ls
->entry
->id
, struc_id
->ident
);
2483 /* Set field offset */
2484 fe
->field
.offset
= astnode_clone(offset
, offset
->loc
);
2485 /* Set field size */
2486 fe
->field
.size
= astnode_clone(se
->struc
.size
, offset
->loc
);
2488 /* Advance offset by size of union */
2489 offset
= astnode_create_arithmetic(
2492 astnode_clone(se
->struc
.size
, offset
->loc
),
2495 offset
= reduce_expression(offset
);
2500 * Enters struc type into symbol table based on AST node.
2501 * - Creates a symbol table for the structure
2502 * - Validates and enters all its fields
2503 * - Calculates offset of each field in the structure, and total size
2504 * @param n Node of type STRUC_DECL_NODE
2506 static int enter_struc(astnode
*n
, void *arg
, astnode
**next
)
2508 ordered_field_list
**plist
;
2512 astnode
*struc_id
= LHS(n
); /* Child 0 is struc identifier */
2513 /* Put STRUC in symbol table */
2514 se
= symtab_enter(struc_id
->ident
, STRUC_SYMBOL
, n
, 0);
2516 err(n
->loc
, "duplicate symbol `%s'", struc_id
->ident
);
2518 /* Put the fields of the structure in local symbol table */
2519 se
->symtab
= symtab_create();
2520 offset
= astnode_create_integer(0, n
->loc
); /* offset = 0 */
2521 plist
= &se
->struc
.fields
;
2522 for (c
= struc_id
->next_sibling
; c
!= NULL
; c
= c
->next_sibling
) {
2523 /* Check if it's a field declaration */
2524 if (astnode_is_type(c
, VAR_DECL_NODE
)) {
2525 offset
= enter_struc_atomic_field(c
, offset
, &plist
, struc_id
);
2527 /* Check if (anonymous) union */
2528 else if (astnode_is_type(c
, UNION_DECL_NODE
)) {
2529 offset
= enter_struc_union_field(c
, offset
, &plist
, struc_id
);
2531 err(c
->loc
, "field declaration expected");
2535 /* Store total size of structure */
2536 se
->struc
.size
= offset
;
2537 /* Restore previous symbol table */
2540 /* ### Remove STRUC node from AST */
2541 // astnode_remove(n);
2542 // astnode_finalize(n);
2547 * Enters fields of union into its symbol table.
2549 static void enter_union_fields(symtab_entry
*se
, astnode
*n
)
2551 ordered_field_list
**plist
;
2554 astnode
*field_data
;
2555 astnode
*field_size
;
2558 se
->symtab
= symtab_create();
2559 se
->struc
.size
= astnode_create_integer(0, n
->loc
);
2560 plist
= &se
->struc
.fields
;
2561 /* Process field declarations */
2562 for (c
= RHS(n
); c
!= NULL
; c
= c
->next_sibling
) {
2563 /* Make sure it's a field declaration */
2564 if (!astnode_is_type(c
, VAR_DECL_NODE
)) {
2565 err(c
->loc
, "field declaration expected");
2568 /* c has two children: id and STORAGE_NODE */
2570 assert(astnode_get_type(field_id
) == IDENTIFIER_NODE
);
2571 field_data
= RHS(c
);
2572 reduce_expression(RHS(field_data
));
2573 /* Validate the declaration -- no data initialized */
2574 if (astnode_is_type(field_data
, DATA_NODE
)) {
2575 err(c
->loc
, "data initialization not allowed here");
2578 /* Calculate field size in bytes: sizeof(datatype) * count */
2579 field_size
= astnode_create_arithmetic(
2581 astnode_create_sizeof(astnode_clone(LHS(field_data
), field_data
->loc
), field_data
->loc
),
2582 astnode_clone(RHS(field_data
), field_data
->loc
),
2585 field_size
= reduce_expression(field_size
);
2586 /* Make sure field size is a constant */
2587 if (!astnode_is_type(field_size
, INTEGER_NODE
)) {
2588 err(c
->loc
, "union member must be of constant size");
2589 astnode_finalize(field_size
);
2590 /* Use default size: 1 byte */
2591 field_size
= astnode_create_integer(1, field_data
->loc
);
2593 /* Try to enter field in structure's symbol table */
2597 astnode_clone(field_data
, field_data
->loc
),
2601 err(c
->loc
, "duplicate symbol `%s' in union `%s'", field_id
->ident
, se
->id
);
2602 astnode_finalize(field_size
);
2605 /* Add to ordered list of fields */
2606 (*plist
) = malloc(sizeof(ordered_field_list
));
2607 (*plist
)->entry
= fe
;
2608 (*plist
)->next
= NULL
;
2609 plist
= &((*plist
)->next
);
2610 /* Set field offset (0 for all) and size */
2611 fe
->field
.offset
= astnode_create_integer(0, n
->loc
);
2612 fe
->field
.size
= astnode_clone(field_size
, field_size
->loc
);
2613 /* See if field size of this member is largest so far */
2614 if (se
->struc
.size
->integer
< field_size
->integer
) {
2615 astnode_finalize(se
->struc
.size
);
2616 se
->struc
.size
= field_size
;
2618 astnode_finalize(field_size
);
2625 * Enters union type into symbol table based on AST node.
2626 * @param n Node of type UNION_DECL_NODE
2628 static int enter_union(astnode
*n
, void *arg
, astnode
**next
)
2631 astnode
*union_id
= astnode_get_child(n
, 0); /* Child 0 is union identifier */
2632 /* Check for anonymous union */
2633 if (astnode_is_type(union_id
, NULL_NODE
)) {
2634 err(n
->loc
, "anonymous union not allowed in global scope");
2636 /* Put UNION in symbol table */
2637 assert(astnode_get_type(union_id
) == IDENTIFIER_NODE
);
2638 se
= symtab_enter(union_id
->ident
, UNION_SYMBOL
, n
, 0);
2640 err(n
->loc
, "duplicate symbol `%s'", union_id
->ident
);
2642 /* Put the fields of the union in local symbol table */
2643 enter_union_fields(se
, n
);
2646 /* ### Remove UNION node from AST */
2647 // astnode_remove(n);
2648 // astnode_finalize(n);
2653 * Enters enumerated type into symbol table based on AST node.
2654 * @param n Node of type ENUM_DECL_NODE
2656 static int enter_enum(astnode
*n
, void *arg
, astnode
**next
)
2662 astnode
*enum_id
= astnode_get_child(n
, 0); /* Child 0 is enum identifier */
2663 /* Enter in global symbol table */
2664 assert(astnode_get_type(enum_id
) == IDENTIFIER_NODE
);
2665 se
= symtab_enter(enum_id
->ident
, ENUM_SYMBOL
, n
, 0);
2667 err(n
->loc
, "duplicate symbol `%s'", enum_id
->ident
);
2669 /* Add all the enum symbols to its own symbol table */
2670 se
->symtab
= symtab_create();
2672 for (c
= enum_id
->next_sibling
; c
!= NULL
; c
= c
->next_sibling
) {
2673 if (astnode_is_type(c
, IDENTIFIER_NODE
)) {
2676 val
= astnode_create_integer(0, c
->loc
);
2678 val
= astnode_create_integer(val
->integer
+1, c
->loc
);
2682 val
= reduce_expression_complete(astnode_clone(RHS(c
), RHS(c
)->loc
));
2683 if (!astnode_is_type(val
, INTEGER_NODE
)) {
2684 err(c
->loc
, "initializer does not evaluate to integer literal");
2685 astnode_finalize(val
);
2686 /* Use default value */
2687 val
= astnode_create_integer(0, c
->loc
);
2690 if (symtab_enter(id
->ident
, CONSTANT_SYMBOL
, val
, 0) == NULL
) {
2691 err(c
->loc
, "duplicate symbol `%s' in enumeration `%s'", id
->ident
, enum_id
->ident
);
2697 /* ### Remove ENUM node from AST */
2698 // astnode_remove(n);
2699 // astnode_finalize(n);
2704 * Enters record type into symbol table based on AST node.
2705 * @param n Node of type RECORD_DECL_NODE
2707 static int enter_record(astnode
*n
, void *arg
, astnode
**next
)
2709 ordered_field_list
**plist
;
2712 astnode
*field_width
;
2717 astnode
*record_id
= astnode_get_child(n
, 0); /* Child 0 is record identifier */
2718 assert(astnode_get_type(record_id
) == IDENTIFIER_NODE
);
2719 /* Enter in global symbol table */
2720 se
= symtab_enter(record_id
->ident
, RECORD_SYMBOL
, n
, 0);
2722 err(n
->loc
, "duplicate symbol `%s'", record_id
->ident
);
2725 /* Add all the record fields to record's own symbol table */
2726 se
->symtab
= symtab_create();
2728 plist
= &se
->struc
.fields
;
2729 for (c
= record_id
->next_sibling
; c
!= NULL
; c
= c
->next_sibling
) {
2730 /* c has two children: field identifier and its width */
2732 field_width
= astnode_clone(reduce_expression(RHS(c
)), RHS(c
)->loc
);
2733 /* Validate the width -- must be positive integer literal */
2734 if (!astnode_is_type(field_width
, INTEGER_NODE
)) {
2735 err(c
->loc
, "record member `%s' is not of constant size", field_id
->ident
);
2738 if ((field_width
->integer
<= 0) || (field_width
->integer
>= 8)) {
2739 err(c
->loc
, "width of record member `%s' is out of range (%d)", field_id
->ident
, field_width
->integer
);
2742 /* Attempt to enter field in record's symbol table */
2743 fe
= symtab_enter(field_id
->ident
, VAR_SYMBOL
, c
, 0);
2745 err(c
->loc
, "duplicate symbol `%s' in record `%s'", field_id
->ident
, record_id
->ident
);
2748 /* Add to ordered list of fields */
2749 (*plist
) = malloc(sizeof(ordered_field_list
));
2750 (*plist
)->entry
= fe
;
2751 (*plist
)->next
= NULL
;
2752 plist
= &((*plist
)->next
);
2753 /* Set field offset */
2754 offset
= offset
- field_width
->integer
;
2755 fe
->field
.offset
= astnode_create_integer(offset
, c
->loc
);
2756 /* Set field size (width) */
2757 fe
->field
.size
= field_width
;
2761 err(n
->loc
, "size of record `%s' (%d) exceeds 8 bits", record_id
->ident
, size
);
2763 /* Set size of record (in bits) */
2764 se
->struc
.size
= astnode_create_integer(size
, n
->loc
);
2768 /* ### Remove RECORD node from AST */
2769 // astnode_remove(n);
2770 // astnode_finalize(n);
2775 * Globalizes a local.
2776 * The node is morphed into its global equivalent (LABEL_NODE or IDENTIFIER_NODE).
2777 * @param n A node of type LOCAL_LABEL_NODE or LOCAL_ID_NODE
2778 * @param arg Pointer to namespace counter
2780 static int globalize_local(astnode
*n
, void *arg
, astnode
**next
)
2783 /* Make it global by appending namespace counter to the id */
2784 sprintf(str
, "#%d", label_count
);
2785 if (astnode_is_type(n
, LOCAL_LABEL_NODE
)) {
2786 /* Local label definition, use label field */
2787 n
->label
= realloc(n
->label
, strlen(n
->label
)+strlen(str
)+1);
2788 strcat(n
->label
, str
);
2789 /* This node is now a unique, global label */
2790 n
->type
= LABEL_NODE
;
2791 /* Make sure it's unique */
2792 if (symtab_lookup(n
->label
)) {
2793 err(n
->loc
, "duplicate symbol `%s'", n
->label
);
2794 /* Remove from AST */
2796 astnode_finalize(n
);
2799 /* Enter it in symbol table */
2800 symtab_enter(n
->label
, LABEL_SYMBOL
, n
, (in_dataseg
? DATA_FLAG
: 0) );
2803 /* Local label reference, use ident field */
2804 n
->ident
= realloc(n
->ident
, strlen(n
->ident
)+strlen(str
)+1);
2805 strcat(n
->ident
, str
);
2806 /* This node is now a unique, global identifier */
2807 n
->type
= IDENTIFIER_NODE
;
2813 * Tags symbols as extrn.
2814 * @param n A node of type EXTRN_NODE
2816 static int tag_extrn_symbols(astnode
*n
, void *arg
, astnode
**next
)
2822 /* Get symbol type specifier */
2823 type
= astnode_get_child(n
, 0);
2824 /* Go through the list of identifiers */
2825 list
= astnode_get_child(n
, 1);
2826 for (id
=astnode_get_first_child(list
); id
!= NULL
; id
=astnode_get_next_sibling(id
) ) {
2827 /* Look up identifier in symbol table */
2828 e
= symtab_lookup(id
->ident
);
2830 if (!(e
->flags
& EXTRN_FLAG
)) {
2831 /* Error, can't import a symbol that's defined locally! */
2832 // TODO: this is okay?
2833 err(n
->loc
, "`%s' declared as extrn but is defined locally", id
->ident
);
2837 // TODO: store external unit name
2838 switch (astnode_get_type(type
)) {
2840 /* Put it in symbol table */
2841 symtab_enter(id
->ident
, VAR_SYMBOL
, astnode_create_data(astnode_clone(type
, n
->loc
), NULL
, n
->loc
), EXTRN_FLAG
);
2845 /* type->integer is (LABEL|PROC)_SYMBOL */
2846 symtab_enter(id
->ident
, type
->integer
, NULL
, EXTRN_FLAG
);
2854 /* Remove extrn node from AST */
2856 astnode_finalize(n
);
2864 static int process_message(astnode
*n
, void *arg
, astnode
**next
)
2866 astnode
*mesg
= reduce_expression_complete(LHS(n
));
2867 if (astnode_is_type(mesg
, STRING_NODE
)) {
2868 printf("%s\n", mesg
->string
);
2870 else if (astnode_is_type(mesg
, INTEGER_NODE
)) {
2871 printf("%d\n", mesg
->integer
);
2874 err(mesg
->loc
, "string or integer argument expected");
2877 astnode_finalize(n
);
2884 static int process_warning(astnode
*n
, void *arg
, astnode
**next
)
2886 astnode
*mesg
= reduce_expression_complete(LHS(n
));
2887 if (astnode_is_type(mesg
, STRING_NODE
)) {
2888 warn(mesg
->loc
, mesg
->string
);
2891 err(mesg
->loc
, "string argument expected");
2894 astnode_finalize(n
);
2901 static int process_error(astnode
*n
, void *arg
, astnode
**next
)
2903 astnode
*mesg
= reduce_expression_complete(LHS(n
));
2904 if (astnode_is_type(mesg
, STRING_NODE
)) {
2905 err(mesg
->loc
, mesg
->string
);
2908 err(mesg
->loc
, "string argument expected");
2911 astnode_finalize(n
);
2916 * Processes a forward branch declaration.
2917 * @param n Node of type FORWARD_BRANCH_DECL_NODE
2918 * @param arg Not used
2920 static int process_forward_branch_decl(astnode
*n
, void *arg
, astnode
**next
)
2925 assert(!strchr(n
->ident
, '#'));
2926 /* Get branch info structure for label (+, ++, ...) */
2927 forward_branch_info
*fwd
= &forward_branch
[strlen(n
->ident
)-1];
2928 /* Morph n to globally unique label */
2929 sprintf(str
, "#%d", fwd
->counter
);
2930 n
->label
= (char *)realloc(n
->ident
, strlen(n
->ident
)+strlen(str
)+1);
2931 strcat(n
->label
, str
);
2932 n
->type
= LABEL_NODE
;
2933 symtab_enter(n
->label
, LABEL_SYMBOL
, n
, 0);
2934 /* Fix reference identifiers */
2935 for (i
=0; i
<fwd
->index
; i
++) {
2937 l
->ident
= (char *)realloc(l
->ident
, strlen(n
->ident
)+1);
2938 strcpy(l
->ident
, n
->ident
);
2940 /* Prepare for next declaration */
2947 * Processes a backward branch declaration.
2948 * @param n Node of type BACKWARD_BRANCH_DECL_NODE
2949 * @param arg Not used
2951 static int process_backward_branch_decl(astnode
*n
, void *arg
, astnode
**next
)
2954 assert(!strchr(n
->ident
, '#'));
2955 /* Get branch info */
2956 backward_branch_info
*bwd
= &backward_branch
[strlen(n
->ident
)-1];
2958 /* Morph n to globally unique label */
2959 sprintf(str
, "#%d", bwd
->counter
);
2960 n
->label
= (char *)realloc(n
->ident
, strlen(n
->ident
)+strlen(str
)+1);
2961 strcat(n
->label
, str
);
2962 n
->type
= LABEL_NODE
;
2963 symtab_enter(n
->label
, LABEL_SYMBOL
, n
, 0);
2964 /* Prepare for next declaration */
2970 * Processes a forward branch label reference.
2971 * @param n Node of type FORWARD_BRANCH_NODE
2972 * @param arg Not used
2974 static int process_forward_branch(astnode
*n
, void *arg
, astnode
**next
)
2976 /* Add n to proper forward_branch array */
2977 forward_branch_info
*fwd
= &forward_branch
[strlen(n
->ident
)-1];
2978 fwd
->refs
[fwd
->index
++] = n
;
2979 /* Change to identifier node */
2980 n
->type
= IDENTIFIER_NODE
;
2985 * Processes a backward branch label reference.
2986 * @param n Node of type BACKWARD_BRANCH_NODE
2987 * @param arg Not used
2989 static int process_backward_branch(astnode
*n
, void *arg
, astnode
**next
)
2991 /* Get branch info */
2992 backward_branch_info
*bwd
= &backward_branch
[strlen(n
->ident
)-1];
2993 /* Make sure it's a valid reference */
2994 if (bwd
->decl
!= NULL
) {
2996 n
->ident
= (char *)realloc(n
->ident
, strlen(bwd
->decl
->ident
)+1);
2997 strcpy(n
->ident
, bwd
->decl
->ident
);
2999 /* Change to identifier node */
3000 n
->type
= IDENTIFIER_NODE
;
3004 /*---------------------------------------------------------------------------*/
3006 static int is_field_ref(astnode
*n
)
3008 astnode
*p
= astnode_get_parent(n
);
3010 if (astnode_is_type(p
, DOT_NODE
)) return 1;
3011 /* Case 2: id.id[expr] */
3012 if (astnode_is_type(p
, INDEX_NODE
) && (n
== LHS(p
)) && astnode_is_type(astnode_get_parent(p
), DOT_NODE
) ) return 1;
3017 * Checks that the given identifier node is present in symbol table.
3018 * Issues error if it is not, and replaces with integer 0.
3019 * @param n A node of type IDENTIFIER_NODE
3021 static int validate_ref(astnode
*n
, void *arg
, astnode
**next
)
3024 symbol_ident_list list
;
3025 symtab_entry
*enum_def
;
3027 if (is_field_ref(n
)) {
3028 return 1; /* Validated by validate_dotref() */
3030 /* Look it up in symbol table */
3031 symtab_entry
* e
= symtab_lookup(n
->ident
);
3033 /* This identifier is unknown */
3034 /* Maybe it is part of an enumeration */
3035 symtab_list_type(ENUM_SYMBOL
, &list
);
3036 for (i
=0; i
<list
.size
; i
++) {
3037 enum_def
= symtab_lookup(list
.idents
[i
]);
3038 symtab_push(enum_def
->symtab
);
3039 e
= symtab_lookup(n
->ident
);
3043 /* Replace id by SCOPE_NODE */
3044 astnode
*scope
= astnode_create_scope(
3045 astnode_create_identifier(enum_def
->id
, n
->loc
),
3046 astnode_clone(n
, n
->loc
), n
->loc
);
3047 astnode_replace(n
, scope
);
3048 astnode_finalize(n
);
3054 symtab_list_finalize(&list
);
3055 /* If still not found, error */
3057 strtok(n
->ident
, "#"); /* Remove globalize junk */
3058 // err(n->loc, "unknown symbol `%s'", n->ident);
3059 /* ### Replace by integer 0 */
3060 //astnode_replace(n, astnode_create_integer(0, n->loc) );
3061 //astnode_finalize(n);
3062 warn(n
->loc
, "`%s' undeclared; assuming external label", n
->ident
);
3063 e
= symtab_enter(n
->ident
, LABEL_SYMBOL
, NULL
, EXTRN_FLAG
);
3067 /* Increase reference count */
3073 * Validates top-level (not part of structure) indexed identifier.
3074 * @param n Node of type INDEX_NODE
3075 * @param arg Not used
3077 static int validate_index(astnode
*n
, void *arg
, astnode
**next
)
3082 if (is_field_ref(LHS(n
))) {
3083 return 1; /* Validated by validate_dotref() */
3086 if (!astnode_is_type(id
, IDENTIFIER_NODE
)) {
3087 err(n
->loc
, "identifier expected");
3088 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3089 astnode_finalize(n
);
3092 e
= symtab_lookup(id
->ident
);
3095 if (!astnode_is_type(type
, DATATYPE_NODE
)) {
3096 err(n
->loc
, "`%s' cannot be indexed", id
->ident
);
3097 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3098 astnode_finalize(n
);
3101 // TODO: bounds check
3105 err(n
->loc
, "unknown symbol `%s'", id
->ident
);
3106 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3107 astnode_finalize(n
);
3114 * Checks that A::B is valid.
3115 * If it's not valid it is replaced by integer 0.
3116 * @param n Node of type SCOPE_NODE
3118 static int validate_scoperef(astnode
*n
, void *arg
, astnode
**next
)
3121 astnode
*namespace = LHS(n
);
3122 /* Look up namespace in global symbol table */
3123 symtab_entry
* e
= symtab_lookup(namespace->ident
);
3125 /* Error, this identifier is unknown */
3126 err(n
->loc
, "unknown namespace `%s'", namespace->ident
);
3127 /* Replace by integer 0 */
3128 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3129 astnode_finalize(n
);
3132 /* Get symbol on right of :: operator */
3134 /* Namespace was found, check its type */
3140 /* OK, check the symbol */
3141 symtab_push(e
->symtab
);
3142 e
= symtab_lookup(symbol
->ident
);
3144 /* Error, symbol is not in namespace */
3145 err(n
->loc
, "unknown symbol `%s' in namespace `%s'", symbol
->ident
, namespace->ident
);
3146 /* Replace by integer 0 */
3147 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3148 astnode_finalize(n
);
3154 err(n
->loc
, "`%s' is not a namespace", namespace->ident
);
3155 /* Replace by integer 0 */
3156 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3157 astnode_finalize(n
);
3165 * Validates right part of dotted reference recursively.
3166 * Assumes that left part's symbol table is on stack.
3167 * @param n Node of type DOT_NODE
3169 static void validate_dotref_recursive(astnode
*n
, astnode
*top
)
3174 symtab_entry
*field
;
3177 if (astnode_is_type(left
, INDEX_NODE
)) {
3178 left
= LHS(left
); /* Need identifier */
3181 if (astnode_is_type(right
, DOT_NODE
)) {
3182 right
= LHS(right
); /* Need identifier */
3184 if (astnode_is_type(right
, INDEX_NODE
)) {
3185 right
= LHS(right
); /* Need identifier */
3187 /* Lookup 'right' in 'left's symbol table */
3188 assert(astnode_get_type(right
) == IDENTIFIER_NODE
);
3189 field
= symtab_lookup(right
->ident
);
3190 if (field
== NULL
) {
3191 /* Error, this symbol is unknown */
3192 err(n
->loc
, "`%s' is not a member of `%s'", right
->ident
, left
->ident
);
3193 /* Replace by integer 0 */
3194 astnode_replace(top
, astnode_create_integer(0, top
->loc
) );
3195 astnode_finalize(top
);
3197 /* See if more subfields to process */
3199 if (astnode_is_type(n
, DOT_NODE
)) {
3200 /* Verify the variable's type -- should be user-defined */
3201 type
= LHS(field
->def
);
3202 if ((type
== NULL
) || (type
->datatype
!= USER_DATATYPE
)) {
3203 err(n
->loc
, "member `%s' of `%s' is not a structure", right
->ident
, left
->ident
);
3204 /* Replace by integer 0 */
3205 astnode_replace(top
, astnode_create_integer(0, top
->loc
) );
3206 astnode_finalize(top
);
3208 /* Look up variable's type definition and verify it's a structure */
3209 def
= symtab_global_lookup(LHS(type
)->ident
);
3211 err(n
->loc
, "member '%s' of '%s' is of unknown type (`%s')", right
->ident
, left
->ident
, LHS(type
)->ident
);
3212 /* Replace by integer 0 */
3213 astnode_replace(top
, astnode_create_integer(0, top
->loc
) );
3214 astnode_finalize(top
);
3215 } else if ( !((def
->type
== STRUC_SYMBOL
) || (def
->type
== UNION_SYMBOL
)) ) {
3216 err(n
->loc
, "member `%s' of `%s' is not a structure", right
->ident
, left
->ident
);
3217 /* Replace by integer 0 */
3218 astnode_replace(top
, astnode_create_integer(0, top
->loc
) );
3219 astnode_finalize(top
);
3222 symtab_push(def
->symtab
);
3223 validate_dotref_recursive(n
, top
);
3232 * Validates A.B.C.D. . ...
3233 * Replaces the whole thing with integer 0 if not.
3234 * @param n Node of type DOT_NODE
3236 static int validate_dotref(astnode
*n
, void *arg
, astnode
**next
)
3238 symtab_entry
*father
;
3242 if (astnode_has_ancestor_of_type(n
, DOT_NODE
)) {
3243 return 1; /* Already validated, since this function is recursive */
3245 /* Look up parent in global symbol table */
3246 left
= LHS(n
); /* n := left . right */
3247 if (astnode_is_type(left
, INDEX_NODE
)) {
3248 left
= LHS(left
); /* Need identifier */
3250 father
= symtab_lookup(left
->ident
);
3251 if (father
== NULL
) {
3252 /* Error, this symbol is unknown */
3253 err(n
->loc
, "unknown symbol `%s'", left
->ident
);
3254 /* Replace by integer 0 */
3255 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3256 astnode_finalize(n
);
3259 /* Increase reference count */
3260 father
->ref_count
++;
3261 /* Verify the variable's type -- should be user-defined */
3262 type
= LHS(father
->def
);
3263 if ((type
== NULL
) || (type
->datatype
!= USER_DATATYPE
)) {
3264 err(n
->loc
, "`%s' is not a structure", left
->ident
);
3265 /* Replace by integer 0 */
3266 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3267 astnode_finalize(n
);
3270 /* Look up variable's type definition and verify it's a structure */
3271 def
= symtab_lookup(LHS(type
)->ident
);
3273 err(n
->loc
, "'%s' is of unknown type (`%s')", left
->ident
, LHS(type
)->ident
);
3274 /* Replace by integer 0 */
3275 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3276 astnode_finalize(n
);
3278 } else if ( !((def
->type
== STRUC_SYMBOL
) || (def
->type
== UNION_SYMBOL
)) ) {
3279 err(n
->loc
, "`%s' is not a structure", left
->ident
);
3280 /* Replace by integer 0 */
3281 astnode_replace(n
, astnode_create_integer(0, n
->loc
) );
3282 astnode_finalize(n
);
3285 /* Verify fields recursively */
3286 symtab_push(def
->symtab
);
3287 validate_dotref_recursive(n
, n
);
3295 /*---------------------------------------------------------------------------*/
3298 * Evaluates expressions involved in conditional assembly, and removes the
3299 * appropriate branches from the AST.
3300 * Does some other stuff too, such as substitute equates and fold constants.
3302 void astproc_first_pass(astnode
*root
)
3304 /* Table of callback functions for our purpose. */
3305 static astnodeprocmap map
[] = {
3306 { LABEL_NODE
, enter_label
},
3307 { VAR_DECL_NODE
, enter_var
},
3308 { PROC_NODE
, enter_proc
},
3309 { STRUC_DECL_NODE
, enter_struc
},
3310 { UNION_DECL_NODE
, enter_union
},
3311 { ENUM_DECL_NODE
, enter_enum
},
3312 { RECORD_DECL_NODE
, enter_record
},
3313 { LOCAL_LABEL_NODE
, globalize_local
},
3314 { LOCAL_ID_NODE
, globalize_local
},
3315 { MACRO_DECL_NODE
, enter_macro
},
3316 { MACRO_NODE
, expand_macro
},
3317 { REPT_NODE
, process_rept
},
3318 { WHILE_NODE
, process_while
},
3319 { DATASEG_NODE
, process_dataseg
},
3320 { CODESEG_NODE
, process_codeseg
},
3321 { ORG_NODE
, process_org
},
3322 { CHARMAP_NODE
, load_charmap
},
3323 { INSTRUCTION_NODE
, process_instruction
},
3324 { DATA_NODE
, process_data
},
3325 { STORAGE_NODE
, process_storage
},
3326 { EQU_NODE
, process_equ
},
3327 { ASSIGN_NODE
, process_assign
},
3328 { IFDEF_NODE
, process_ifdef
},
3329 { IFNDEF_NODE
, process_ifndef
},
3330 { IF_NODE
, process_if
},
3331 { EXTRN_NODE
, tag_extrn_symbols
},
3332 { MESSAGE_NODE
, process_message
},
3333 { WARNING_NODE
, process_warning
},
3334 { ERROR_NODE
, process_error
},
3335 { FORWARD_BRANCH_DECL_NODE
, process_forward_branch_decl
},
3336 { BACKWARD_BRANCH_DECL_NODE
, process_backward_branch_decl
},
3337 { FORWARD_BRANCH_NODE
, process_forward_branch
},
3338 { BACKWARD_BRANCH_NODE
, process_backward_branch
},
3343 in_dataseg
= 0; /* codeseg is default */
3345 astproc_walk(root
, NULL
, map
);
3346 /* Remove all the volatile constants from the symbol table */
3347 /* These are the ones defined with the '=' operator, whose identifiers should
3348 all have been replaced by their value in the syntax tree now. Since
3349 they're not referenced anywhere we can safely dispose of them.
3350 The EQUates on the other hand should be kept, since they will
3351 possibly be exported. */
3352 #ifdef ENABLE_BUGGY_THING // ### FIXME
3355 symbol_ident_list list
;
3357 symtab_list_type(CONSTANT_SYMBOL
, &list
);
3358 for (i
= 0; i
< list
.size
; ++i
) {
3359 e
= symtab_lookup(list
.idents
[i
]);
3360 if (e
->flags
& VOLATILE_FLAG
) {
3361 symtab_remove(list
.idents
[i
]);
3364 symtab_list_finalize(&list
);
3369 /*---------------------------------------------------------------------------*/
3372 * Tags labels as public.
3373 * @param n A node of type PUBLIC_NODE
3375 static int tag_public_symbols(astnode
*n
, void *arg
, astnode
**next
)
3379 /* Go through the list of identifiers */
3380 for (id
=astnode_get_first_child(n
); id
!= NULL
; id
= astnode_get_next_sibling(id
) ) {
3381 /* Look up identifier in symbol table */
3382 e
= symtab_lookup(id
->ident
);
3384 /* Symbol exists. Set the proper flag unless ambiguous. */
3385 if (e
->flags
& EXTRN_FLAG
) {
3386 err(n
->loc
, "`%s' already declared extrn", id
->ident
);
3390 case CONSTANT_SYMBOL
:
3394 e
->flags
|= PUBLIC_FLAG
;
3398 err(n
->loc
, "`%s' is of non-exportable type", id
->ident
);
3403 /* Warning, can't export a symbol that's not defined. */
3404 warn(n
->loc
, "`%s' declared as public but is not defined", id
->ident
);
3407 /* Remove PUBLIC_NODE from AST */
3409 astnode_finalize(n
);
3415 * Sets alignment for a set of (data) labels.
3416 * @param n A node of type ALIGN_NODE
3418 static int tag_align_symbols(astnode
*n
, void *arg
, astnode
**next
)
3425 /* Go through the list of identifiers */
3427 for (id
=astnode_get_first_child(idents
); id
!= NULL
; id
= astnode_get_next_sibling(id
) ) {
3428 /* Look up identifier in symbol table */
3429 e
= symtab_lookup(id
->ident
);
3431 /* Symbol exists. Set the proper flag unless ambiguous. */
3432 if (!(e
->flags
& DATA_FLAG
)) {
3433 err(n
->loc
, "cannot align a code symbol (`%s')", id
->ident
);
3438 expr
= reduce_expression(RHS(n
));
3439 if (!astnode_is_type(expr
, INTEGER_NODE
)) {
3440 err(n
->loc
, "alignment expression must be an integer literal");
3441 } else if ((expr
->integer
< 0) || (expr
->integer
>= 0x10000)) {
3442 err(n
->loc
, "alignment expression out of range");
3443 } else if (expr
->integer
> 1) {
3445 switch (expr
->integer
) {
3462 e
->flags
|= ALIGN_FLAG
;
3467 err(n
->loc
, "alignment expression must be a power of 2");
3474 err(n
->loc
, "`%s' cannot be aligned", id
->ident
);
3480 /* Warning, can't align a symbol that's not defined. */
3481 warn(n
->loc
, "alignment ignored for undefined symbol `%s'", id
->ident
);
3484 /* Remove ALIGN_NODE from AST */
3486 astnode_finalize(n
);
3491 /*---------------------------------------------------------------------------*/
3494 * Removes unused labels from a syntax tree (and symbol table).
3495 * Unused labels are labels that are defined but not referenced anywhere.
3496 * This function assumes that the reference counts have already been calculated.
3498 void remove_unused_labels()
3503 symbol_ident_list list
;
3504 symtab_list_type(LABEL_SYMBOL
, &list
);
3505 for (i
=0; i
<list
.size
; i
++) {
3506 /* Look up label in symbol table */
3507 id
= list
.idents
[i
];
3508 symtab_entry
* e
= symtab_lookup(id
);
3509 /* If reference count is zero, AND label isn't declared public, remove it. */
3510 if ((e
->ref_count
== 0) && ((e
->flags
& PUBLIC_FLAG
) == 0)) {
3512 strtok(n
->label
, "#"); /* Remove globalize junk */
3513 warn(n
->loc
, "`%s' defined but not used", n
->label
);
3514 /* Remove label from AST */
3516 astnode_finalize(n
);
3517 //symtab_remove(n->label); ### FIXME leads to crash sometimes...
3520 symtab_list_finalize(&list
);
3524 * If the storage is of user-defined type, replaces it with
3525 * .DSB sizeof(type) * count
3527 static int reduce_user_storage(astnode
*n
, void *arg
, astnode
**next
)
3531 astnode
*byte_storage
;
3534 if (type
->datatype
== USER_DATATYPE
) {
3536 e
= symtab_lookup(LHS(type
)->ident
);
3538 /* Replace by DSB */
3540 byte_storage
= astnode_create_storage(
3541 astnode_create_datatype(BYTE_DATATYPE
, NULL
, type
->loc
),
3542 astnode_create_arithmetic(
3544 astnode_create_sizeof(
3545 astnode_create_identifier(LHS(type
)->ident
, n
->loc
),
3548 astnode_clone(count
, n
->loc
),
3553 astnode_replace(n
, byte_storage
);
3554 astnode_finalize(n
);
3555 *next
= byte_storage
;
3558 err(n
->loc
, "unknown symbol `%s'", LHS(type
)->ident
);
3559 /* Remove from AST */
3561 astnode_finalize(n
);
3569 * Second major pass over AST.
3571 void astproc_second_pass(astnode
*root
)
3573 /* Table of callback functions for our purpose. */
3574 static astnodeprocmap map
[] = {
3575 { IDENTIFIER_NODE
, validate_ref
},
3576 { SCOPE_NODE
, validate_scoperef
},
3577 { DOT_NODE
, validate_dotref
},
3578 { INDEX_NODE
, validate_index
},
3579 { PUBLIC_NODE
, tag_public_symbols
},
3580 { STORAGE_NODE
, reduce_user_storage
},
3581 { ALIGN_NODE
, tag_align_symbols
},
3582 { STRUC_DECL_NODE
, noop
},
3583 { UNION_DECL_NODE
, noop
},
3584 { ENUM_DECL_NODE
, noop
},
3585 { RECORD_DECL_NODE
, noop
},
3588 in_dataseg
= 0; /* codeseg is default */
3590 astproc_walk(root
, NULL
, map
);
3592 remove_unused_labels();
3595 /*---------------------------------------------------------------------------*/
3598 * Translates a single instruction.
3599 * @param n A node of type INSTRUCTION_NODE
3601 static int translate_instruction(astnode
*n
, void *arg
, astnode
**next
)
3604 /* Put the operand in final form */
3605 astnode
*o
= reduce_expression_complete( LHS(n
) );
3606 assert(o
== LHS(n
));
3607 /* Convert (mnemonic, addressing mode) pair to opcode */
3608 n
->instr
.opcode
= opcode_get(n
->instr
.mnemonic
, n
->instr
.mode
);
3609 /* Test if opcode is invalid */
3610 if (n
->instr
.opcode
== 0xFF) {
3611 /* Check for the special cases */
3612 if ((n
->instr
.mnemonic
== STX_MNEMONIC
) && (n
->instr
.mode
== ABSOLUTE_Y_MODE
)) {
3613 /* Doesn't have absolute version, "scale down" to zeropage */
3614 n
->instr
.mode
= ZEROPAGE_Y_MODE
;
3615 n
->instr
.opcode
= opcode_get(n
->instr
.mnemonic
, n
->instr
.mode
);
3616 } else if ((n
->instr
.mnemonic
== STY_MNEMONIC
) && (n
->instr
.mode
== ABSOLUTE_X_MODE
)) {
3617 /* Doesn't have absolute version, "scale down" to zeropage */
3618 n
->instr
.mode
= ZEROPAGE_X_MODE
;
3619 n
->instr
.opcode
= opcode_get(n
->instr
.mnemonic
, n
->instr
.mode
);
3620 } else if (n
->instr
.mode
== ABSOLUTE_MODE
) {
3621 /* Check for relative addressing (these are parsed as absolute mode) */
3622 switch (n
->instr
.mnemonic
) {
3631 /* Fix addressing mode and opcode */
3632 n
->instr
.mode
= RELATIVE_MODE
;
3633 n
->instr
.opcode
= opcode_get(n
->instr
.mnemonic
, n
->instr
.mode
);
3638 if (n
->instr
.opcode
!= 0xFF) {
3639 /* If the operand is a constant, see if we can "reduce" from
3640 absolute mode to zeropage mode */
3641 if ((astnode_is_type(o
, INTEGER_NODE
)) &&
3642 ((unsigned long)o
->integer
< 256) &&
3643 ((c
= opcode_zp_equiv(n
->instr
.opcode
)) != 0xFF)) {
3644 /* Switch to the zeromode version */
3645 n
->instr
.opcode
= c
;
3646 switch (n
->instr
.mode
) {
3647 case ABSOLUTE_MODE
: n
->instr
.mode
= ZEROPAGE_MODE
; break;
3648 case ABSOLUTE_X_MODE
: n
->instr
.mode
= ZEROPAGE_X_MODE
;break;
3649 case ABSOLUTE_Y_MODE
: n
->instr
.mode
= ZEROPAGE_Y_MODE
;break;
3650 default: /* Impossible to get here, right? */ break;
3653 /* If the operand is a constant, make sure it fits */
3654 if (astnode_is_type(o
, INTEGER_NODE
)) {
3655 switch (n
->instr
.mode
) {
3656 case IMMEDIATE_MODE
:
3658 case ZEROPAGE_X_MODE
:
3659 case ZEROPAGE_Y_MODE
:
3660 case PREINDEXED_INDIRECT_MODE
:
3661 case POSTINDEXED_INDIRECT_MODE
:
3662 /* Operand must fit in 8 bits */
3663 if (!IS_BYTE_VALUE(o
->integer
)) {
3664 warn(o
->loc
, "operand out of range; truncated");
3670 case ABSOLUTE_X_MODE
:
3671 case ABSOLUTE_Y_MODE
:
3673 /* Operand must fit in 8 bits */
3674 if ((unsigned long)o
->integer
>= 0x10000) {
3675 warn(o
->loc
, "operand out of range; truncated");
3676 o
->integer
&= 0xFFFF;
3681 /* Constant isn't allowed here is it? */
3688 else if (astnode_is_type(o
, STRING_NODE
)) {
3689 /* String operand doesn't make sense here */
3690 err(n
->loc
, "invalid operand");
3693 /* opcode_get() returned 0xFF */
3694 err(n
->loc
, "invalid addressing mode");
3700 * ### Is this really such a good idea?
3702 static int maybe_merge_data(astnode
*n
, void *arg
, astnode
**next
)
3707 /* Only merge if no debugging, otherwise line information is lost. */
3708 if (!xasm_args
.debug
&& astnode_is_type(*next
, DATA_NODE
) &&
3709 astnode_equal(type
, LHS(*next
)) ) {
3712 astnode_finalize( astnode_remove_child_at(temp
, 0) ); /* Remove datatype node */
3713 astnode_add_child(n
, astnode_remove_children(temp
) );
3714 astnode_finalize(temp
);
3717 /* Reduce expressions to final form */
3718 for (n
= n
->first_child
; n
!= NULL
; n
= temp
->next_sibling
) {
3719 temp
= reduce_expression_complete(n
);
3720 if (astnode_is_type(temp
, INTEGER_NODE
)) {
3721 /* Check that value fits according to datatype */
3722 switch (type
->datatype
) {
3724 if (!IS_BYTE_VALUE(temp
->integer
)) {
3725 warn(temp
->loc
, "operand out of range; truncated");
3726 temp
->integer
&= 0xFF;
3731 if (!IS_WORD_VALUE(temp
->integer
)) {
3732 warn(temp
->loc
, "operand out of range; truncated");
3733 temp
->integer
&= 0xFFFF;
3737 case DWORD_DATATYPE
:
3752 static int maybe_merge_storage(astnode
*n
, void *arg
, astnode
**next
)
3757 if (astnode_is_type(*next
, STORAGE_NODE
) &&
3758 astnode_equal(LHS(n
), LHS(*next
)) ) {
3761 astnode_finalize( astnode_remove_child_at(temp
, 0) ); /* Remove datatype node */
3763 /* Calculate new count */
3764 new_count
= astnode_create_arithmetic(
3766 astnode_remove_child_at(temp
, 0),
3767 astnode_clone(old_count
, n
->loc
),
3770 new_count
= reduce_expression_complete(new_count
);
3771 astnode_replace(old_count
, new_count
);
3772 astnode_finalize(old_count
);
3773 astnode_finalize(temp
);
3776 reduce_expression_complete(RHS(n
));
3782 * Replaces .proc by its label followed by statements.
3784 static int flatten_proc(astnode
*n
, void *arg
, astnode
**next
)
3786 astnode
*id
= LHS(n
);
3787 astnode
*list
= RHS(n
);
3789 id
->type
= LABEL_NODE
;
3790 astnode_insert_child(list
, id
, 0);
3791 astnode
*stmts
= astnode_remove_children(list
);
3792 astnode_replace(n
, stmts
);
3793 astnode_finalize(n
);
3801 static int flatten_var_decl(astnode
*n
, void *arg
, astnode
**next
)
3803 astnode
*stmts
= LHS(n
);
3804 astnode_remove_children(n
);
3805 stmts
->type
= LABEL_NODE
;
3806 astnode_replace(n
, stmts
);
3807 astnode_finalize(n
);
3813 * Third and final pass (if the output isn't pure 6502).
3814 * Translates instructions, merges data and storage nodes,
3815 * and reduces their operands to final form on the way.
3817 void astproc_third_pass(astnode
*root
)
3819 /* Table of callback functions for our purpose. */
3820 static astnodeprocmap map
[] = {
3821 { INSTRUCTION_NODE
, translate_instruction
},
3822 { DATA_NODE
, maybe_merge_data
},
3823 { STORAGE_NODE
, maybe_merge_storage
},
3824 { VAR_DECL_NODE
, flatten_var_decl
},
3825 { PROC_NODE
, flatten_proc
},
3826 { STRUC_DECL_NODE
, noop
},
3827 { UNION_DECL_NODE
, noop
},
3828 { ENUM_DECL_NODE
, noop
},
3829 { RECORD_DECL_NODE
, noop
},
3832 in_dataseg
= 0; /* codeseg is default */
3834 astproc_walk(root
, NULL
, map
);
3837 /*---------------------------------------------------------------------------*/
3840 * Evaluates the given expression, _without_ replacing it in the AST
3841 * (unlike astproc_reduce_expression() and friends).
3843 static astnode
*eval_expression(astnode
*expr
)
3845 switch (astnode_get_type(expr
)) {
3847 case ARITHMETIC_NODE
: {
3848 astnode
*lhs
= eval_expression(LHS(expr
));
3849 astnode
*rhs
= eval_expression(RHS(expr
));
3850 switch (expr
->oper
) {
3853 case MINUS_OPERATOR
:
3868 if (astnode_is_type(lhs
, INTEGER_NODE
)
3869 && astnode_is_type(rhs
, INTEGER_NODE
)) {
3870 /* Both sides are integer literals. */
3871 switch (expr
->oper
) {
3872 case PLUS_OPERATOR
: return astnode_create_integer(lhs
->integer
+ rhs
->integer
, expr
->loc
);
3873 case MINUS_OPERATOR
: return astnode_create_integer(lhs
->integer
- rhs
->integer
, expr
->loc
);
3874 case MUL_OPERATOR
: return astnode_create_integer(lhs
->integer
* rhs
->integer
, expr
->loc
);
3875 case DIV_OPERATOR
: return astnode_create_integer(lhs
->integer
/ rhs
->integer
, expr
->loc
);
3876 case MOD_OPERATOR
: return astnode_create_integer(lhs
->integer
% rhs
->integer
, expr
->loc
);
3877 case AND_OPERATOR
: return astnode_create_integer(lhs
->integer
& rhs
->integer
, expr
->loc
);
3878 case OR_OPERATOR
: return astnode_create_integer(lhs
->integer
| rhs
->integer
, expr
->loc
);
3879 case XOR_OPERATOR
: return astnode_create_integer(lhs
->integer
^ rhs
->integer
, expr
->loc
);
3880 case SHL_OPERATOR
: return astnode_create_integer(lhs
->integer
<< rhs
->integer
, expr
->loc
);
3881 case SHR_OPERATOR
: return astnode_create_integer(lhs
->integer
>> rhs
->integer
, expr
->loc
);
3882 case LT_OPERATOR
: return astnode_create_integer(lhs
->integer
< rhs
->integer
, expr
->loc
);
3883 case GT_OPERATOR
: return astnode_create_integer(lhs
->integer
> rhs
->integer
, expr
->loc
);
3884 case EQ_OPERATOR
: return astnode_create_integer(lhs
->integer
== rhs
->integer
, expr
->loc
);
3885 case NE_OPERATOR
: return astnode_create_integer(lhs
->integer
!= rhs
->integer
, expr
->loc
);
3886 case LE_OPERATOR
: return astnode_create_integer(lhs
->integer
<= rhs
->integer
, expr
->loc
);
3887 case GE_OPERATOR
: return astnode_create_integer(lhs
->integer
>= rhs
->integer
, expr
->loc
);
3889 default: /* ### Error, actually */
3893 /* Use some mathematical identities... */
3894 else if ((astnode_is_type(lhs
, INTEGER_NODE
) && (lhs
->integer
== 0))
3895 && (expr
->oper
== PLUS_OPERATOR
)) {
3896 /* 0+expr == expr */
3897 return astnode_clone(rhs
, rhs
->loc
);
3898 } else if ((astnode_is_type(rhs
, INTEGER_NODE
) && (rhs
->integer
== 0))
3899 && (expr
->oper
== PLUS_OPERATOR
)) {
3900 /* expr+0 == expr */
3901 return astnode_clone(lhs
, lhs
->loc
);
3902 } else if ((astnode_is_type(lhs
, INTEGER_NODE
) && (lhs
->integer
== 1))
3903 && (expr
->oper
== MUL_OPERATOR
)) {
3904 /* 1*expr == expr */
3905 return astnode_clone(rhs
, rhs
->loc
);
3906 } else if ((astnode_is_type(rhs
, INTEGER_NODE
) && (rhs
->integer
== 1))
3907 && ((expr
->oper
== MUL_OPERATOR
) || (expr
->oper
== DIV_OPERATOR
)) ) {
3908 /* expr*1 == expr */
3909 /* expr/1 == expr */
3910 return astnode_clone(lhs
, lhs
->loc
);
3919 case UMINUS_OPERATOR
:
3921 if (astnode_is_type(lhs
, INTEGER_NODE
)) {
3922 switch (expr
->oper
) {
3923 case NEG_OPERATOR
: return astnode_create_integer(~lhs
->integer
, expr
->loc
);
3924 case NOT_OPERATOR
: return astnode_create_integer(!lhs
->integer
, expr
->loc
);
3925 case LO_OPERATOR
: return astnode_create_integer(lhs
->integer
& 0xFF, expr
->loc
);
3926 case HI_OPERATOR
: return astnode_create_integer((lhs
->integer
>> 8) & 0xFF, expr
->loc
);
3927 case UMINUS_OPERATOR
: return astnode_create_integer(-lhs
->integer
, expr
->loc
);
3936 return astnode_clone(expr
, expr
->loc
);
3938 case IDENTIFIER_NODE
: {
3939 symtab_entry
*e
= symtab_lookup(expr
->ident
);
3940 // ### assert(e->type == LABEL_SYMBOL);
3941 if (e
->flags
& ADDR_FLAG
)
3942 return astnode_create_integer(e
->address
, expr
->loc
);
3945 case CURRENT_PC_NODE
:
3946 return astnode_create_integer(in_dataseg
? dataseg_pc
: codeseg_pc
, expr
->loc
);
3955 * Sets the address of the label to be the currently calculated PC.
3957 static int set_label_address(astnode
*label
, void *arg
, astnode
**next
)
3959 symtab_entry
*e
= symtab_lookup(label
->ident
);
3960 // ### assert(e && (e->type == LABEL_SYMBOL));
3961 e
->address
= in_dataseg
? dataseg_pc
: codeseg_pc
;
3962 e
->flags
|= ADDR_FLAG
;
3967 * Sets the current PC to the address specified by the ORG node.
3969 static int set_pc_from_org(astnode
*org
, void *arg
, astnode
**next
)
3971 astnode
*addr
= LHS(org
);
3972 assert(astnode_is_type(addr
, INTEGER_NODE
));
3974 dataseg_pc
= addr
->integer
;
3976 codeseg_pc
= addr
->integer
;
3981 * Ensures that the given symbol is defined.
3983 static int ensure_symbol_is_defined(astnode
*id
, void *arg
, astnode
**next
)
3985 symtab_entry
*e
= symtab_lookup(id
->ident
);
3987 if ((e
->flags
& EXTRN_FLAG
) && !(e
->flags
& ERROR_UNDEFINED_FLAG
)) {
3988 err(id
->loc
, "cannot generate pure binary because `%s' is not defined", id
->ident
);
3989 e
->flags
|= ERROR_UNDEFINED_FLAG
;
3995 * Increments PC according to the size of the instruction.
3997 static int inc_pc_by_instruction(astnode
*instr
, void *arg
, astnode
**next
)
3999 assert(!in_dataseg
);
4002 unsigned char zp_op
= opcode_zp_equiv(instr
->instr
.opcode
);
4003 if (zp_op
!= 0xFF) {
4004 /* See if we can optimize this to a ZP-instruction */
4005 astnode
*operand
= eval_expression(LHS(instr
));
4006 if (operand
&& astnode_is_type(operand
, INTEGER_NODE
)) {
4007 if ((operand
->integer
>= 0) && (operand
->integer
< 256)) {
4008 instr
->instr
.opcode
= zp_op
;
4010 astnode_finalize(operand
);
4014 codeseg_pc
+= opcode_length(instr
->instr
.opcode
);
4019 * Increments PC according to the size of the defined data.
4021 static int inc_pc_by_data(astnode
*data
, void *arg
, astnode
**next
)
4023 astnode
*type
= LHS(data
);
4024 int count
= astnode_get_child_count(data
) - 1;
4026 assert(!in_dataseg
);
4027 switch (type
->datatype
) {
4028 case BYTE_DATATYPE
: nbytes
= count
; break;
4029 case WORD_DATATYPE
: nbytes
= count
* 2; break;
4030 case DWORD_DATATYPE
: nbytes
= count
* 4; break;
4035 codeseg_pc
+= nbytes
;
4040 * Increments PC according to the size of the included binary.
4042 static int inc_pc_by_binary(astnode
*node
, void *arg
, astnode
**next
)
4044 assert(!in_dataseg
);
4045 codeseg_pc
+= node
->binary
.size
;
4050 * Increments PC according to the size of the storage.
4052 static int inc_pc_by_storage(astnode
*storage
, void *arg
, astnode
**next
)
4054 astnode
*type
= LHS(storage
);
4055 assert(type
->datatype
== BYTE_DATATYPE
);
4056 astnode
*count
= eval_expression(RHS(storage
));
4058 if (astnode_get_type(count
) == INTEGER_NODE
) {
4060 dataseg_pc
+= count
->integer
;
4062 codeseg_pc
+= count
->integer
;
4064 astnode_finalize(count
);
4070 * This pass is only performed if the output format is pure 6502.
4071 * It ensures that it is actually possible to generate pure 6502
4072 * for this syntax tree (i.e. no external symbols).
4073 * Furthermore, it calculates the address of all labels, so that
4074 * everything is ready for the final output phase.
4076 void astproc_fourth_pass(astnode
*root
)
4079 /* ### Should loop while there's a change in the address of
4080 one or more labels */
4081 for (x
= 0; x
< 2; ++x
) {
4082 in_dataseg
= 0; /* codeseg is default */
4085 /* Table of callback functions for our purpose. */
4086 static astnodeprocmap map
[] = {
4087 { DATASEG_NODE
, process_dataseg
},
4088 { CODESEG_NODE
, process_codeseg
},
4089 { ORG_NODE
, set_pc_from_org
},
4090 { LABEL_NODE
, set_label_address
},
4091 { IDENTIFIER_NODE
, ensure_symbol_is_defined
},
4092 { INSTRUCTION_NODE
, inc_pc_by_instruction
},
4093 { DATA_NODE
, inc_pc_by_data
},
4094 { STORAGE_NODE
, inc_pc_by_storage
},
4095 { BINARY_NODE
, inc_pc_by_binary
},
4096 { STRUC_DECL_NODE
, noop
},
4097 { UNION_DECL_NODE
, noop
},
4098 { ENUM_DECL_NODE
, noop
},
4099 { RECORD_DECL_NODE
, noop
},
4103 astproc_walk(root
, NULL
, map
);
4107 /*---------------------------------------------------------------------------*/
4110 * Writes an instruction.
4112 static int write_instruction(astnode
*instr
, void *arg
, astnode
**next
)
4114 FILE *fp
= (FILE *)arg
;
4115 unsigned char op
= instr
->instr
.opcode
;
4116 int len
= opcode_length(op
);
4120 astnode
*operand
= eval_expression(LHS(instr
));
4121 if(!astnode_is_type(operand
, INTEGER_NODE
)) {
4122 /* ### This is rather fatal, it should be a literal by this point */
4123 err(instr
->loc
, "operand does not evaluate to literal");
4125 int value
= operand
->integer
;
4127 /* Check if it's a relative jump */
4137 /* Calculate difference between target and address of next instruction */
4138 value
= value
- (codeseg_pc
+ 2);
4139 if (!IS_BYTE_VALUE(value
)) {
4140 err(operand
->loc
, "branch out of range");
4146 if (!IS_BYTE_VALUE(value
)) {
4147 warn(operand
->loc
, "operand out of range; truncated");
4152 fputc((unsigned char)value
, fp
);
4155 if (!IS_WORD_VALUE(value
)) {
4156 warn(operand
->loc
, "operand out of range; truncated");
4159 fputc((unsigned char)value
, fp
);
4160 fputc((unsigned char)(value
>> 8), fp
);
4163 astnode_finalize(operand
);
4165 codeseg_pc
+= opcode_length(instr
->instr
.opcode
);
4172 static int write_data(astnode
*data
, void *arg
, astnode
**next
)
4174 FILE *fp
= (FILE *)arg
;
4175 astnode
*type
= LHS(data
);
4177 assert(!in_dataseg
);
4178 for (expr
= RHS(data
); expr
!= NULL
; expr
= astnode_get_next_sibling(expr
) ) {
4180 astnode
*e
= eval_expression(expr
);
4181 assert(e
->type
== INTEGER_NODE
);
4183 switch (type
->datatype
) {
4185 if (!IS_BYTE_VALUE(value
)) {
4186 warn(expr
->loc
, "operand out of range; truncated");
4189 fputc((unsigned char)value
, fp
);
4194 if (!IS_WORD_VALUE(value
)) {
4195 warn(expr
->loc
, "operand out of range; truncated");
4198 fputc((unsigned char)value
, fp
);
4199 fputc((unsigned char)(value
>> 8), fp
);
4203 case DWORD_DATATYPE
:
4204 fputc((unsigned char)value
, fp
);
4205 fputc((unsigned char)(value
>> 8), fp
);
4206 fputc((unsigned char)(value
>> 16), fp
);
4207 fputc((unsigned char)(value
>> 24), fp
);
4215 astnode_finalize(e
);
4221 * Writes storage (padding).
4223 static int write_storage(astnode
*storage
, void *arg
, astnode
**next
)
4225 FILE *fp
= (FILE *)arg
;
4226 astnode
*type
= LHS(storage
);
4227 astnode
*count
= eval_expression(RHS(storage
));
4228 assert(type
->datatype
== BYTE_DATATYPE
);
4229 assert(!in_dataseg
);
4232 assert(astnode_get_type(count
) == INTEGER_NODE
);
4233 for (i
= 0; i
< count
->integer
; ++i
)
4235 codeseg_pc
+= count
->integer
;
4236 astnode_finalize(count
);
4244 static int write_binary(astnode
*node
, void *arg
, astnode
**next
)
4246 FILE *fp
= (FILE *)arg
;
4247 assert(!in_dataseg
);
4248 fwrite(node
->binary
.data
, 1, node
->binary
.size
, fp
);
4249 codeseg_pc
+= node
->binary
.size
;
4254 * This pass is only performed if the output format is pure 6502.
4255 * It writes the binary code.
4257 void astproc_fifth_pass(astnode
*root
)
4259 FILE *fp
= fopen(xasm_args
.output_file
, "wb");
4261 fprintf(stderr
, "could not open '%s' for writing\n", xasm_args
.output_file
);
4265 /* Table of callback functions for our purpose. */
4266 static astnodeprocmap map
[] = {
4267 { DATASEG_NODE
, process_dataseg
},
4268 { CODESEG_NODE
, process_codeseg
},
4269 { ORG_NODE
, set_pc_from_org
},
4270 { INSTRUCTION_NODE
, write_instruction
},
4271 { DATA_NODE
, write_data
},
4272 { STORAGE_NODE
, write_storage
},
4273 { BINARY_NODE
, write_binary
},
4274 { STRUC_DECL_NODE
, noop
},
4275 { UNION_DECL_NODE
, noop
},
4276 { ENUM_DECL_NODE
, noop
},
4277 { RECORD_DECL_NODE
, noop
},
4280 in_dataseg
= 0; /* codeseg is default */
4284 astproc_walk(root
, fp
, map
);