1 /*****************************************************************************/
5 /* Expression evaluation for the ca65 macroassembler */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
10 /* Römerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
54 /* #include "objcode.h" */
63 /*****************************************************************************/
65 /*****************************************************************************/
69 /* Since all expressions are first packed into expression trees, and each
70 * expression tree node is allocated on the heap, we add some type of special
71 * purpose memory allocation here: Instead of freeing the nodes, we save some
72 * number of freed nodes for later and remember them in a single linked list
73 * using the Left link.
75 #define MAX_FREE_NODES 64
76 static ExprNode* FreeExprNodes = 0;
77 static unsigned FreeNodeCount = 0;
81 /*****************************************************************************/
83 /*****************************************************************************/
87 static ExprNode* NewExprNode (void)
88 /* Create a new expression node */
92 /* Do we have some nodes in the list already? */
94 /* Use first node from list */
96 FreeExprNodes = N->Left;
98 /* Allocate fresh memory */
99 N = xmalloc (sizeof (ExprNode));
102 N->Left = N->Right = 0;
110 static void FreeExprNode (ExprNode* E)
114 if (FreeNodeCount < MAX_FREE_NODES) {
115 /* Remember this node for later */
116 E->Left = FreeExprNodes;
119 /* Free the memory */
127 /*****************************************************************************/
129 /*****************************************************************************/
133 static ExprNode* Expr0 (void);
137 int IsByteRange (long Val)
138 /* Return true if this is a byte value */
140 return (Val & ~0xFFL) == 0;
145 int IsWordRange (long Val)
146 /* Return true if this is a word value */
148 return (Val & ~0xFFFF) == 0;
153 static int FuncBlank (void)
154 /* Handle the .BLANK builtin function */
156 /* Assume no tokens if the closing brace follows (this is not correct in
157 * all cases, since the token may be the closing brace, but this will
158 * give a syntax error anyway and may not be handled by .BLANK.
160 if (Tok == TOK_RPAREN) {
164 /* Skip any tokens */
166 while (!TokIsSep (Tok)) {
167 if (Tok == TOK_LPAREN) {
169 } else if (Tok == TOK_RPAREN) {
185 static int FuncConst (void)
186 /* Handle the .CONST builtin function */
188 /* Read an expression */
189 ExprNode* Expr = Expression ();
191 /* Check the constness of the expression */
192 int Result = IsConstExpr (Expr);
194 /* Free the expression */
203 static int FuncDefined (void)
204 /* Handle the .DEFINED builtin function */
206 static const char* Keys[] = {
212 char Name [sizeof (SVal)];
216 /* First argument is a symbol name */
217 if (Tok != TOK_IDENT) {
218 Error (ERR_IDENT_EXPECTED);
219 if (Tok != TOK_RPAREN) {
225 /* Remember the name, then skip it */
229 /* Comma and scope spec may follow */
230 if (Tok == TOK_COMMA) {
235 /* An identifier must follow */
236 if (Tok != TOK_IDENT) {
237 Error (ERR_IDENT_EXPECTED);
241 /* Get the scope, then skip it */
242 Scope = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
245 /* Check if we got a valid keyword */
247 Error (ERR_ILLEGAL_SCOPE);
253 case 0: Scope = SCOPE_ANY; break;
254 case 1: Scope = SCOPE_GLOBAL; break;
255 case 2: Scope = SCOPE_LOCAL; break;
256 default: Internal ("Invalid scope: %d", Scope);
266 /* Search for the symbol */
267 Result = SymIsDef (SVal, Scope);
275 static int DoMatch (enum TC EqualityLevel)
276 /* Handle the .MATCH and .XMATCH builtin functions */
283 /* A list of tokens follows. Read this list and remember it building a
284 * single linked list of tokens including attributes. The list is
285 * terminated by a comma.
287 while (Tok != TOK_COMMA) {
289 /* We may not end-of-line of end-of-file here */
290 if (TokIsSep (Tok)) {
291 Error (ERR_UNEXPECTED_EOL);
295 /* Get a node with this token */
296 Node = NewTokNode ();
298 /* Insert the node into the list */
313 /* Read the second list which is terminated by the right parenthesis and
314 * compare each token against the one in the first list.
318 while (Tok != TOK_RPAREN) {
320 /* We may not end-of-line of end-of-file here */
321 if (TokIsSep (Tok)) {
322 Error (ERR_UNEXPECTED_EOL);
326 /* Compare the tokens if the result is not already known */
329 /* The second list is larger than the first one */
331 } else if (TokCmp (Node) < EqualityLevel) {
332 /* Tokens do not match */
337 /* Next token in first list */
342 /* Next token in current list */
346 /* Check if there are remaining tokens in the first list */
351 /* Free the token list */
358 /* Done, return the result */
364 static int FuncMatch (void)
365 /* Handle the .MATCH function */
367 return DoMatch (tcSameToken);
372 static int FuncReferenced (void)
373 /* Handle the .REFERENCED builtin function */
377 if (Tok != TOK_IDENT) {
378 Error (ERR_IDENT_EXPECTED);
379 if (Tok != TOK_RPAREN) {
383 Result = SymIsRef (SVal, SCOPE_ANY);
393 static int FuncStrAt (void)
394 /* Handle the .STRAT function */
396 char Str [sizeof(SVal)];
399 /* String constant expected */
400 if (Tok != TOK_STRCON) {
401 Error (ERR_STRCON_EXPECTED);
407 /* Remember the string and skip it */
411 /* Comma must follow */
414 /* Expression expected */
415 Index = ConstExpression ();
417 /* Must be a valid index */
418 if (Index >= (long) strlen (Str)) {
423 /* Return the char, handle as unsigned. Be sure to translate it into
424 * the target character set.
426 return (unsigned char) TgtTranslateChar (Str [(size_t)Index]);
431 static int FuncStrLen (void)
432 /* Handle the .STRLEN function */
434 /* String constant expected */
435 if (Tok != TOK_STRCON) {
437 Error (ERR_STRCON_EXPECTED);
438 /* Smart error recovery */
439 if (Tok != TOK_RPAREN) {
446 /* Get the length of the string */
447 int Len = strlen (SVal);
449 /* Skip the string */
452 /* Return the length */
460 static int FuncTCount (void)
461 /* Handle the .TCOUNT function */
463 /* We have a list of tokens that ends with the closing paren. Skip
464 * the tokens, handling nested braces and count them.
468 while (Parens != 0 || Tok != TOK_RPAREN) {
470 /* Check for end of line or end of input. Since the calling function
471 * will check for the closing paren, we don't need to print an error
472 * here, just bail out.
474 if (TokIsSep (Tok)) {
481 /* Keep track of the nesting level */
483 case TOK_LPAREN: ++Parens; break;
484 case TOK_RPAREN: --Parens; break;
492 /* Return the number of tokens */
498 static int FuncXMatch (void)
499 /* Handle the .XMATCH function */
501 return DoMatch (tcIdentical);
506 static ExprNode* Function (int (*F) (void))
507 /* Handle builtin functions */
511 /* Skip the keyword */
514 /* Expression must be enclosed in braces */
515 if (Tok != TOK_LPAREN) {
516 Error (ERR_LPAREN_EXPECTED);
518 return GenLiteralExpr (0);
522 /* Call the function itself */
525 /* Closing brace must follow */
528 /* Return an expression node with the boolean code */
529 return GenLiteralExpr (Result);
534 static ExprNode* Factor (void)
542 N = GenLiteralExpr (IVal);
547 N = GenLiteralExpr (TgtTranslateChar (IVal));
553 if (Tok != TOK_IDENT) {
554 Error (ERR_IDENT_EXPECTED);
555 N = GenLiteralExpr (0); /* Dummy */
557 S = SymRef (SVal, SCOPE_GLOBAL);
558 if (SymIsConst (S)) {
559 /* Use the literal value instead */
560 N = GenLiteralExpr (GetSymVal (S));
562 /* Create symbol node */
572 S = SymRef (SVal, SCOPE_LOCAL);
573 if (SymIsConst (S)) {
574 /* Use the literal value instead */
575 N = GenLiteralExpr (GetSymVal (S));
577 /* Create symbol node */
594 N->Op = EXPR_UNARY_MINUS;
631 N = Function (FuncBlank);
635 N = Function (FuncConst);
639 N = GenLiteralExpr (CPUIsets[CPU]);
644 N = Function (FuncDefined);
648 N = Function (FuncMatch);
652 N = Function (FuncReferenced);
656 N = Function (FuncStrAt);
660 N = Function (FuncStrLen);
664 N = Function (FuncTCount);
668 N = GenLiteralExpr (time (0));
673 N = GenLiteralExpr (VERSION);
679 N = Function (FuncXMatch);
683 if (LooseCharTerm && Tok == TOK_STRCON && strlen(SVal) == 1) {
684 /* A character constant */
685 N = GenLiteralExpr (TgtTranslateChar (SVal[0]));
687 N = GenLiteralExpr (0); /* Dummy */
698 static ExprNode* Term (void)
702 /* Read left hand side */
705 /* Handle multiplicative operations */
706 while (Tok == TOK_MUL || Tok == TOK_DIV || Tok == TOK_MOD ||
707 Tok == TOK_AND || Tok == TOK_XOR || Tok == TOK_SHL ||
710 /* Create a new node and insert the left expression */
711 ExprNode* Left = Root;
712 Root = NewExprNode ();
715 /* Determine the operator token */
717 case TOK_MUL: Root->Op = EXPR_MUL; break;
718 case TOK_DIV: Root->Op = EXPR_DIV; break;
719 case TOK_MOD: Root->Op = EXPR_MOD; break;
720 case TOK_AND: Root->Op = EXPR_AND; break;
721 case TOK_XOR: Root->Op = EXPR_XOR; break;
722 case TOK_SHL: Root->Op = EXPR_SHL; break;
723 case TOK_SHR: Root->Op = EXPR_SHR; break;
724 default: Internal ("Invalid token");
728 /* Parse the right hand side */
729 Root->Right = Factor ();
733 /* Return the expression tree we've created */
739 static ExprNode* SimpleExpr (void)
743 /* Read left hand side */
746 /* Handle additive operations */
747 while (Tok == TOK_PLUS || Tok == TOK_MINUS || Tok == TOK_OR) {
749 /* Create a new node and insert the left expression */
750 ExprNode* Left = Root;
751 Root = NewExprNode ();
754 /* Determine the operator token */
756 case TOK_PLUS: Root->Op = EXPR_PLUS; break;
757 case TOK_MINUS: Root->Op = EXPR_MINUS; break;
758 case TOK_OR: Root->Op = EXPR_OR; break;
759 default: Internal ("Invalid token");
763 /* Parse the right hand side */
764 Root->Right = Term ();
768 /* Return the expression tree we've created */
774 static ExprNode* BoolExpr (void)
775 /* Evaluate a boolean expression */
777 /* Read left hand side */
778 ExprNode* Root = SimpleExpr ();
780 /* Handle booleans */
781 while (Tok == TOK_EQ || Tok == TOK_NE || Tok == TOK_LT ||
782 Tok == TOK_GT || Tok == TOK_LE || Tok == TOK_GE) {
784 /* Create a new node and insert the left expression */
785 ExprNode* Left = Root;
786 Root = NewExprNode ();
789 /* Determine the operator token */
791 case TOK_EQ: Root->Op = EXPR_EQ; break;
792 case TOK_NE: Root->Op = EXPR_NE; break;
793 case TOK_LT: Root->Op = EXPR_LT; break;
794 case TOK_GT: Root->Op = EXPR_GT; break;
795 case TOK_LE: Root->Op = EXPR_LE; break;
796 case TOK_GE: Root->Op = EXPR_GE; break;
797 default: Internal ("Invalid token");
801 /* Parse the right hand side */
802 Root->Right = SimpleExpr ();
806 /* Return the expression tree we've created */
812 static ExprNode* Expr2 (void)
813 /* Boolean operators: AND and XOR */
815 /* Read left hand side */
816 ExprNode* Root = BoolExpr ();
818 /* Handle booleans */
819 while (Tok == TOK_BAND || Tok == TOK_BXOR) {
821 /* Create a new node and insert the left expression */
822 ExprNode* Left = Root;
823 Root = NewExprNode ();
826 /* Determine the operator token */
828 case TOK_BAND: Root->Op = EXPR_BAND; break;
829 case TOK_BXOR: Root->Op = EXPR_BXOR; break;
830 default: Internal ("Invalid token");
834 /* Parse the right hand side */
835 Root->Right = BoolExpr ();
839 /* Return the expression tree we've created */
845 static ExprNode* Expr1 (void)
846 /* Boolean operators: OR */
848 /* Read left hand side */
849 ExprNode* Root = Expr2 ();
851 /* Handle booleans */
852 while (Tok == TOK_BOR) {
854 /* Create a new node and insert the left expression */
855 ExprNode* Left = Root;
856 Root = NewExprNode ();
859 /* Determine the operator token */
861 case TOK_BOR: Root->Op = EXPR_BOR; break;
862 default: Internal ("Invalid token");
866 /* Parse the right hand side */
867 Root->Right = Expr2 ();
871 /* Return the expression tree we've created */
877 static ExprNode* Expr0 (void)
878 /* Boolean operators: NOT */
882 /* Handle booleans */
883 if (Tok == TOK_BNOT) {
885 /* Create a new node */
886 Root = NewExprNode ();
888 /* Determine the operator token */
890 case TOK_BNOT: Root->Op = EXPR_BNOT; break;
891 default: Internal ("Invalid token");
895 /* Parse the left hand side, allow more BNOTs */
896 Root->Left = Expr0 ();
900 /* Read left hand side */
905 /* Return the expression tree we've created */
911 static ExprNode* SimplifyExpr (ExprNode* Root)
912 /* Try to simplify the given expression tree */
915 SimplifyExpr (Root->Left);
916 SimplifyExpr (Root->Right);
917 if (IsConstExpr (Root)) {
918 /* The complete expression is constant */
919 Root->V.Val = GetExprVal (Root);
920 Root->Op = EXPR_LITERAL;
921 FreeExpr (Root->Left);
922 FreeExpr (Root->Right);
923 Root->Left = Root->Right = 0;
931 ExprNode* Expression (void)
932 /* Evaluate an expression, build the expression tree on the heap and return
933 * a pointer to the root of the tree.
936 return SimplifyExpr (Expr0 ());
941 long ConstExpression (void)
942 /* Parse an expression. Check if the expression is const, and print an error
943 * message if not. Return the value of the expression, or a dummy, if it is
947 /* Read the expression, and call finalize (exception here, since we
950 ExprNode* Expr = FinalizeExpr (Expression ());
952 /* Return the value */
953 if (IsConstExpr (Expr)) {
954 return GetExprVal (Expr);
956 Error (ERR_CONSTEXPR_EXPECTED);
963 void FreeExpr (ExprNode* Root)
964 /* Free the expression, Root is pointing to. */
967 FreeExpr (Root->Left);
968 FreeExpr (Root->Right);
975 ExprNode* GenLiteralExpr (long Val)
976 /* Return an expression tree that encodes the given literal value */
978 ExprNode* Expr = NewExprNode ();
979 Expr->Op = EXPR_LITERAL;
986 ExprNode* GenCurrentPC (void)
987 /* Return the current program counter as expression */
993 /* Create SegmentBase + Offset */
994 Left = NewExprNode ();
995 Left->Op = EXPR_SECTION;
996 Left->V.SegNum = GetSegNum ();
998 Root = NewExprNode ();
1000 Root->Right = GenLiteralExpr (GetPC ());
1001 Root->Op = EXPR_PLUS;
1003 /* Absolute mode, just return PC value */
1004 Root = GenLiteralExpr (GetPC ());
1012 ExprNode* GenSwapExpr (ExprNode* Expr)
1013 /* Return an extended expression with lo and hi bytes swapped */
1015 ExprNode* N = NewExprNode ();
1023 ExprNode* GenBranchExpr (unsigned Offs)
1024 /* Return an expression that encodes the difference between current PC plus
1025 * offset and the target expression (that is, Expression() - (*+Offs) ).
1034 Left = NewExprNode ();
1035 Left->Op = EXPR_SECTION;
1036 Left->V.SegNum = GetSegNum ();
1040 N->Right = GenLiteralExpr (GetPC () + Offs);
1043 N = GenLiteralExpr (GetPC () + Offs);
1046 /* Create the root node */
1047 Root = NewExprNode ();
1048 Root->Left = Expression ();
1050 Root->Op = EXPR_MINUS;
1052 /* Return the result */
1053 return SimplifyExpr (Root);
1058 ExprNode* GenULabelExpr (unsigned Num)
1059 /* Return an expression for an unnamed label with the given index */
1061 /* Get an expression node */
1062 ExprNode* Node = NewExprNode ();
1064 /* Set the values */
1065 Node->Op = EXPR_ULABEL;
1068 /* Return the new node */
1074 ExprNode* GenByteExpr (ExprNode* Expr)
1075 /* Force the given expression into a byte and return the result */
1077 /* Use the low byte operator to force the expression into byte size */
1078 ExprNode* Root = NewExprNode ();
1080 Root->Op = EXPR_BYTE0;
1082 /* Return the result */
1088 ExprNode* GenWordExpr (ExprNode* Expr)
1089 /* Force the given expression into a word and return the result. */
1091 /* AND the expression by $FFFF to force it into word size */
1092 ExprNode* Root = NewExprNode ();
1094 Root->Op = EXPR_AND;
1095 Root->Right = GenLiteralExpr (0xFFFF);
1097 /* Return the result */
1103 ExprNode* GenNE (ExprNode* Expr, long Val)
1104 /* Generate an expression that compares Expr and Val for inequality */
1106 /* Generate a compare node */
1107 ExprNode* Root = NewExprNode ();
1110 Root->Right = GenLiteralExpr (Val);
1112 /* Return the result */
1118 int IsConstExpr (ExprNode* Root)
1119 /* Return true if the given expression is a constant expression, that is, one
1120 * with no references to external symbols.
1126 if (EXPR_IS_LEAF (Root->Op)) {
1134 if (SymHasUserMark (Sym)) {
1135 if (Verbosity > 0) {
1138 PError (GetSymPos (Sym), ERR_CIRCULAR_REFERENCE);
1142 Const = SymIsConst (Sym);
1143 SymUnmarkUser (Sym);
1151 } else if (EXPR_IS_UNARY (Root->Op)) {
1153 return IsConstExpr (Root->Left);
1157 /* We must handle shortcut boolean expressions here */
1161 if (IsConstExpr (Root->Left)) {
1162 /* lhs is const, if it is zero, don't eval right */
1163 if (GetExprVal (Root->Left) == 0) {
1166 return IsConstExpr (Root->Right);
1169 /* lhs not const --> tree not const */
1175 if (IsConstExpr (Root->Left)) {
1176 /* lhs is const, if it is not zero, don't eval right */
1177 if (GetExprVal (Root->Left) != 0) {
1180 return IsConstExpr (Root->Right);
1183 /* lhs not const --> tree not const */
1189 /* All others are handled normal */
1190 return IsConstExpr (Root->Left) && IsConstExpr (Root->Right);
1197 static void CheckByteExpr (const ExprNode* N, int* IsByte)
1198 /* Internal routine that is recursively called to check if there is a zeropage
1199 * symbol in the expression tree.
1203 switch (N->Op & EXPR_TYPEMASK) {
1209 if (SymIsZP (N->V.Sym)) {
1211 } else if (SymHasExpr (N->V.Sym)) {
1212 /* Check if this expression is a byte expression */
1213 *IsByte = IsByteExpr (GetSymExpr (N->V.Sym));
1218 if (GetSegType (N->V.SegNum) == SEGTYPE_ZP) {
1226 case EXPR_UNARYNODE:
1227 CheckByteExpr (N->Left, IsByte);
1230 case EXPR_BINARYNODE:
1231 CheckByteExpr (N->Left, IsByte);
1232 CheckByteExpr (N->Right, IsByte);
1236 Internal ("Unknown expression op: %02X", N->Op);
1243 int IsByteExpr (ExprNode* Root)
1244 /* Return true if this is a byte expression */
1248 if (IsConstExpr (Root)) {
1249 if (Root->Op != EXPR_LITERAL) {
1250 SimplifyExpr (Root);
1252 return IsByteRange (GetExprVal (Root));
1253 } else if (Root->Op == EXPR_BYTE0 || Root->Op == EXPR_BYTE1 ||
1254 Root->Op == EXPR_BYTE2 || Root->Op == EXPR_BYTE3) {
1255 /* Symbol forced to have byte range */
1258 /* We have undefined symbols in the expression. Assume that the
1259 * expression is a byte expression if there is at least one symbol
1260 * declared as zeropage in it. Being wrong here is not a very big
1261 * problem since the linker knows about all symbols and detects
1262 * error like mixing absolute and zeropage labels.
1265 CheckByteExpr (Root, &IsByte);
1272 long GetExprVal (ExprNode* Expr)
1273 /* Get the value of a constant expression */
1283 return GetSymVal (Expr->V.Sym);
1286 return GetExprVal (Expr->Left) + GetExprVal (Expr->Right);
1289 return GetExprVal (Expr->Left) - GetExprVal (Expr->Right);
1292 return GetExprVal (Expr->Left) * GetExprVal (Expr->Right);
1295 Left = GetExprVal (Expr->Left);
1296 Right = GetExprVal (Expr->Right);
1298 Error (ERR_DIV_BY_ZERO);
1301 return Left / Right;
1304 Left = GetExprVal (Expr->Left);
1305 Right = GetExprVal (Expr->Right);
1307 Error (ERR_MOD_BY_ZERO);
1310 return Left % Right;
1313 return GetExprVal (Expr->Left) | GetExprVal (Expr->Right);
1316 return GetExprVal (Expr->Left) ^ GetExprVal (Expr->Right);
1319 return GetExprVal (Expr->Left) & GetExprVal (Expr->Right);
1322 return GetExprVal (Expr->Left) << GetExprVal (Expr->Right);
1325 return GetExprVal (Expr->Left) >> GetExprVal (Expr->Right);
1328 return (GetExprVal (Expr->Left) == GetExprVal (Expr->Right));
1331 return (GetExprVal (Expr->Left) != GetExprVal (Expr->Right));
1334 return (GetExprVal (Expr->Left) < GetExprVal (Expr->Right));
1337 return (GetExprVal (Expr->Left) > GetExprVal (Expr->Right));
1340 return (GetExprVal (Expr->Left) <= GetExprVal (Expr->Right));
1343 return (GetExprVal (Expr->Left) >= GetExprVal (Expr->Right));
1345 case EXPR_UNARY_MINUS:
1346 return -GetExprVal (Expr->Left);
1349 return ~GetExprVal (Expr->Left);
1352 return GetExprVal (Expr->Left) & 0xFF;
1355 return (GetExprVal (Expr->Left) >> 8) & 0xFF;
1358 return (GetExprVal (Expr->Left) >> 16) & 0xFF;
1361 return (GetExprVal (Expr->Left) >> 24) & 0xFF;
1364 Left = GetExprVal (Expr->Left);
1365 return ((Left >> 8) & 0x00FF) | ((Left << 8) & 0xFF00);
1368 return GetExprVal (Expr->Left) && GetExprVal (Expr->Right);
1371 return GetExprVal (Expr->Left) || GetExprVal (Expr->Right);
1374 return (GetExprVal (Expr->Left) != 0) ^ (GetExprVal (Expr->Right) != 0);
1377 return !GetExprVal (Expr->Left);
1380 Internal ("GetExprVal called for EXPR_ULABEL");
1385 Internal ("Unknown Op type: %u", Expr->Op);
1393 static ExprNode* RemoveSyms (ExprNode* Expr, int MustClone)
1394 /* Remove resolved symbols from the tree by cloning symbol expressions */
1396 /* Accept NULL pointers */
1401 /* Special node handling */
1405 if (SymHasExpr (Expr->V.Sym)) {
1406 /* The symbol has an expression tree */
1407 SymEntry* Sym = Expr->V.Sym;
1408 if (SymHasUserMark (Sym)) {
1409 /* Circular definition */
1413 PError (GetSymPos (Sym), ERR_CIRCULAR_REFERENCE);
1414 return GenLiteralExpr (0); /* Return a dummy value */
1417 Expr = RemoveSyms (GetSymExpr (Sym), 1);
1418 SymUnmarkUser (Sym);
1420 } else if (SymIsConst (Expr->V.Sym)) {
1421 /* The symbol is a constant */
1422 return GenLiteralExpr (GetSymVal (Expr->V.Sym));
1427 if (ULabCanResolve ()) {
1428 ExprNode* NewExpr = ULabResolve (Expr->V.Val);
1436 /* Clone the current node if needed */
1439 /* Create a new node */
1440 ExprNode* Clone = NewExprNode ();
1442 /* Clone the operation */
1443 Clone->Op = Expr->Op;
1445 /* Clone the attribute if needed */
1450 Clone->V.Val = Expr->V.Val;
1454 Clone->V.Sym = Expr->V.Sym;
1458 Clone->V.SegNum = Expr->V.SegNum;
1463 /* Clone the tree nodes */
1464 Clone->Left = RemoveSyms (Expr->Left, MustClone);
1465 Clone->Right = RemoveSyms (Expr->Right, MustClone);
1472 /* Nothing to clone */
1473 Expr->Left = RemoveSyms (Expr->Left, MustClone);
1474 Expr->Right = RemoveSyms (Expr->Right, MustClone);
1484 static ExprNode* ConstExtract (ExprNode* Expr, long* Val, int Sign)
1485 /* Extract and evaluate all constant factors in an subtree that has only
1486 * additions and subtractions.
1489 if (Expr->Op == EXPR_LITERAL) {
1491 *Val -= Expr->V.Val;
1493 *Val += Expr->V.Val;
1495 FreeExprNode (Expr);
1499 if (Expr->Op == EXPR_PLUS || Expr->Op == EXPR_MINUS) {
1502 Left = ConstExtract (Expr->Left, Val, Sign);
1503 if (Expr->Op == EXPR_MINUS) {
1506 Right = ConstExtract (Expr->Right, Val, Sign);
1507 if (Left == 0 && Right == 0) {
1508 FreeExprNode (Expr);
1510 } else if (Left == 0) {
1511 FreeExprNode (Expr);
1513 } else if (Right == 0) {
1514 FreeExprNode (Expr);
1517 /* Check for SEG - SEG which is now possible */
1518 if (Left->Op == EXPR_SECTION && Right->Op == EXPR_SECTION &&
1519 Left->V.SegNum == Right->V.SegNum) {
1520 /* SEG - SEG, remove it completely */
1521 FreeExprNode (Left);
1522 FreeExprNode (Right);
1523 FreeExprNode (Expr);
1527 Expr->Right = Right;
1533 /* Some other sort of node, finalize the terms */
1535 Expr->Left = FinalizeExpr (Expr->Left);
1538 Expr->Right = FinalizeExpr (Expr->Right);
1546 ExprNode* FinalizeExpr (ExprNode* Expr)
1547 /* Resolve any symbols by cloning the symbol expression tree instead of the
1548 * symbol reference, then try to simplify the expression as much as possible.
1549 * This function must only be called if all symbols are resolved (no undefined
1556 Expr = RemoveSyms (Expr, 0);
1557 Expr = ConstExtract (Expr, &Val, 1);
1559 /* Reduced to a literal value */
1560 Expr = GenLiteralExpr (Val);
1562 /* Extracted a value */
1566 N->Right = GenLiteralExpr (Val);
1574 ExprNode* CloneExpr (ExprNode* Expr)
1575 /* Clone the given expression tree. The function will simply clone symbol
1576 * nodes, it will not resolve them.
1581 /* Accept NULL pointers */
1586 /* Get a new node */
1587 Clone = NewExprNode ();
1589 /* Clone the operation */
1590 Clone->Op = Expr->Op;
1592 /* Clone the attribute if needed */
1597 Clone->V.Val = Expr->V.Val;
1601 Clone->V.Sym = Expr->V.Sym;
1605 Clone->V.SegNum = Expr->V.SegNum;
1610 /* Clone the tree nodes */
1611 Clone->Left = CloneExpr (Expr->Left);
1612 Clone->Right = CloneExpr (Expr->Right);
1620 void WriteExpr (ExprNode* Expr)
1621 /* Write the given expression to the object file */
1623 /* Null expressions are encoded by a type byte of zero */
1629 /* Write the expression code */
1630 ObjWrite8 (Expr->Op);
1632 /* If the is a leafnode, write the expression attribute, otherwise
1633 * write the expression operands.
1638 ObjWrite32 (Expr->V.Val);
1642 /* Maybe we should use a code here? */
1643 CHECK (SymIsImport (Expr->V.Sym)); /* Safety */
1644 ObjWriteVar (GetSymIndex (Expr->V.Sym));
1648 ObjWrite8 (Expr->V.SegNum);
1652 Internal ("WriteExpr: Cannot write EXPR_ULABEL nodes");
1656 /* Not a leaf node */
1657 WriteExpr (Expr->Left);
1658 WriteExpr (Expr->Right);