1 /*****************************************************************************/
5 /* Expression evaluation for the ca65 macroassembler */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@musoftware.de */
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 /*****************************************************************************/
60 /*****************************************************************************/
62 /*****************************************************************************/
66 /* Since all expressions are first packed into expression trees, and each
67 * expression tree node is allocated on the heap, we add some type of special
68 * purpose memory allocation here: Instead of freeing the nodes, we save some
69 * number of freed nodes for later and remember them in a single linked list
70 * using the Left link.
72 #define MAX_FREE_NODES 64
73 static ExprNode* FreeExprNodes = 0;
74 static unsigned FreeNodeCount = 0;
78 /*****************************************************************************/
80 /*****************************************************************************/
84 static ExprNode* NewExprNode (void)
85 /* Create a new expression node */
89 /* Do we have some nodes in the list already? */
91 /* Use first node from list */
93 FreeExprNodes = N->Left;
95 /* Allocate fresh memory */
96 N = xmalloc (sizeof (ExprNode));
99 N->Left = N->Right = 0;
107 static void FreeExprNode (ExprNode* E)
111 if (FreeNodeCount < MAX_FREE_NODES) {
112 /* Remember this node for later */
113 E->Left = FreeExprNodes;
116 /* Free the memory */
124 /*****************************************************************************/
126 /*****************************************************************************/
130 static ExprNode* Expr0 (void);
134 int IsByteRange (long Val)
135 /* Return true if this is a byte value */
137 return (Val & ~0xFFL) == 0;
142 int IsWordRange (long Val)
143 /* Return true if this is a word value */
145 return (Val & ~0xFFFF) == 0;
150 static int FuncBlank (void)
151 /* Handle the .BLANK builtin function */
153 /* Assume no tokens if the closing brace follows (this is not correct in
154 * all cases, since the token may be the closing brace, but this will
155 * give a syntax error anyway and may not be handled by .BLANK.
157 if (Tok == TOK_RPAREN) {
161 /* Skip any tokens */
163 while (!TokIsSep (Tok)) {
164 if (Tok == TOK_LPAREN) {
166 } else if (Tok == TOK_RPAREN) {
182 static int FuncConst (void)
183 /* Handle the .CONST builtin function */
185 /* Read an expression */
186 ExprNode* Expr = Expression ();
188 /* Check the constness of the expression */
189 int Result = IsConstExpr (Expr);
191 /* Free the expression */
200 static int FuncDefined (void)
201 /* Handle the .DEFINED builtin function */
203 static const char* Keys[] = {
209 char Name [sizeof (SVal)];
213 /* First argument is a symbol name */
214 if (Tok != TOK_IDENT) {
215 Error (ERR_IDENT_EXPECTED);
216 if (Tok != TOK_RPAREN) {
222 /* Remember the name, then skip it */
226 /* Comma and scope spec may follow */
227 if (Tok == TOK_COMMA) {
232 /* An identifier must follow */
233 if (Tok != TOK_IDENT) {
234 Error (ERR_IDENT_EXPECTED);
238 /* Get the scope, then skip it */
239 Scope = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
242 /* Check if we got a valid keyword */
244 Error (ERR_ILLEGAL_SCOPE);
250 case 0: Scope = SCOPE_ANY; break;
251 case 1: Scope = SCOPE_GLOBAL; break;
252 case 2: Scope = SCOPE_LOCAL; break;
253 default: Internal ("Invalid scope: %d", Scope);
263 /* Search for the symbol */
264 Result = SymIsDef (SVal, Scope);
272 static int DoMatch (enum TC EqualityLevel)
273 /* Handle the .MATCH and .XMATCH builtin functions */
280 /* A list of tokens follows. Read this list and remember it building a
281 * single linked list of tokens including attributes. The list is
282 * terminated by a comma.
284 while (Tok != TOK_COMMA) {
286 /* We may not end-of-line of end-of-file here */
287 if (TokIsSep (Tok)) {
288 Error (ERR_UNEXPECTED_EOL);
292 /* Get a node with this token */
293 Node = NewTokNode ();
295 /* Insert the node into the list */
310 /* Read the second list which is terminated by the right parenthesis and
311 * compare each token against the one in the first list.
315 while (Tok != TOK_RPAREN) {
317 /* We may not end-of-line of end-of-file here */
318 if (TokIsSep (Tok)) {
319 Error (ERR_UNEXPECTED_EOL);
323 /* Compare the tokens if the result is not already known */
326 /* The second list is larger than the first one */
328 } else if (TokCmp (Node) < EqualityLevel) {
329 /* Tokens do not match */
334 /* Next token in first list */
339 /* Next token in current list */
343 /* Check if there are remaining tokens in the first list */
348 /* Free the token list */
355 /* Done, return the result */
361 static int FuncMatch (void)
362 /* Handle the .MATCH function */
364 return DoMatch (tcSameToken);
369 static int FuncReferenced (void)
370 /* Handle the .REFERENCED builtin function */
374 if (Tok != TOK_IDENT) {
375 Error (ERR_IDENT_EXPECTED);
376 if (Tok != TOK_RPAREN) {
380 Result = SymIsRef (SVal, SCOPE_ANY);
390 static int FuncStrAt (void)
391 /* Handle the .STRAT function */
393 char Str [sizeof(SVal)];
396 /* String constant expected */
397 if (Tok != TOK_STRCON) {
398 Error (ERR_STRCON_EXPECTED);
404 /* Remember the string and skip it */
408 /* Comma must follow */
411 /* Expression expected */
412 Index = ConstExpression ();
414 /* Must be a valid index */
415 if (Index >= (long) strlen (Str)) {
420 /* Return the char, handle as unsigned. Be sure to translate it into
421 * the target character set.
423 return (unsigned char) TgtTranslateChar (Str [(size_t)Index]);
428 static int FuncStrLen (void)
429 /* Handle the .STRLEN function */
431 /* String constant expected */
432 if (Tok != TOK_STRCON) {
434 Error (ERR_STRCON_EXPECTED);
435 /* Smart error recovery */
436 if (Tok != TOK_RPAREN) {
443 /* Get the length of the string */
444 int Len = strlen (SVal);
446 /* Skip the string */
449 /* Return the length */
457 static int FuncTCount (void)
458 /* Handle the .TCOUNT function */
460 /* We have a list of tokens that ends with the closing paren. Skip
461 * the tokens, handling nested braces and count them.
465 while (Parens != 0 || Tok != TOK_RPAREN) {
467 /* Check for end of line or end of input. Since the calling function
468 * will check for the closing paren, we don't need to print an error
469 * here, just bail out.
471 if (TokIsSep (Tok)) {
478 /* Keep track of the nesting level */
480 case TOK_LPAREN: ++Parens; break;
481 case TOK_RPAREN: --Parens; break;
489 /* Return the number of tokens */
495 static int FuncXMatch (void)
496 /* Handle the .XMATCH function */
498 return DoMatch (tcIdentical);
503 static ExprNode* Function (int (*F) (void))
504 /* Handle builtin functions */
508 /* Skip the keyword */
511 /* Expression must be enclosed in braces */
512 if (Tok != TOK_LPAREN) {
513 Error (ERR_LPAREN_EXPECTED);
515 return LiteralExpr (0);
519 /* Call the function itself */
522 /* Closing brace must follow */
525 /* Return an expression node with the boolean code */
526 return LiteralExpr (Result);
531 static ExprNode* Factor (void)
539 N = LiteralExpr (IVal);
544 N = LiteralExpr (TgtTranslateChar (IVal));
550 if (Tok != TOK_IDENT) {
551 Error (ERR_IDENT_EXPECTED);
552 N = LiteralExpr (0); /* Dummy */
554 S = SymRef (SVal, SCOPE_GLOBAL);
555 if (SymIsConst (S)) {
556 /* Use the literal value instead */
557 N = LiteralExpr (GetSymVal (S));
559 /* Create symbol node */
569 S = SymRef (SVal, SCOPE_LOCAL);
570 if (SymIsConst (S)) {
571 /* Use the literal value instead */
572 N = LiteralExpr (GetSymVal (S));
574 /* Create symbol node */
591 N->Op = EXPR_UNARY_MINUS;
628 N = Function (FuncBlank);
632 N = Function (FuncConst);
636 N = LiteralExpr (GetCPU());
641 N = Function (FuncDefined);
645 N = Function (FuncMatch);
649 N = Function (FuncReferenced);
653 N = Function (FuncStrAt);
657 N = Function (FuncStrLen);
661 N = Function (FuncTCount);
665 N = LiteralExpr (time (0));
670 N = Function (FuncXMatch);
674 if (LooseCharTerm && Tok == TOK_STRCON && strlen(SVal) == 1) {
675 /* A character constant */
676 N = LiteralExpr (TgtTranslateChar (SVal[0]));
678 N = LiteralExpr (0); /* Dummy */
689 static ExprNode* Term (void)
693 /* Read left hand side */
696 /* Handle multiplicative operations */
697 while (Tok == TOK_MUL || Tok == TOK_DIV || Tok == TOK_MOD ||
698 Tok == TOK_AND || Tok == TOK_XOR || Tok == TOK_SHL ||
701 /* Create a new node and insert the left expression */
702 ExprNode* Left = Root;
703 Root = NewExprNode ();
706 /* Determine the operator token */
708 case TOK_MUL: Root->Op = EXPR_MUL; break;
709 case TOK_DIV: Root->Op = EXPR_DIV; break;
710 case TOK_MOD: Root->Op = EXPR_MOD; break;
711 case TOK_AND: Root->Op = EXPR_AND; break;
712 case TOK_XOR: Root->Op = EXPR_XOR; break;
713 case TOK_SHL: Root->Op = EXPR_SHL; break;
714 case TOK_SHR: Root->Op = EXPR_SHR; break;
715 default: Internal ("Invalid token");
719 /* Parse the right hand side */
720 Root->Right = Factor ();
724 /* Return the expression tree we've created */
730 static ExprNode* SimpleExpr (void)
734 /* Read left hand side */
737 /* Handle additive operations */
738 while (Tok == TOK_PLUS || Tok == TOK_MINUS || Tok == TOK_OR) {
740 /* Create a new node and insert the left expression */
741 ExprNode* Left = Root;
742 Root = NewExprNode ();
745 /* Determine the operator token */
747 case TOK_PLUS: Root->Op = EXPR_PLUS; break;
748 case TOK_MINUS: Root->Op = EXPR_MINUS; break;
749 case TOK_OR: Root->Op = EXPR_OR; break;
750 default: Internal ("Invalid token");
754 /* Parse the right hand side */
755 Root->Right = Term ();
759 /* Return the expression tree we've created */
765 static ExprNode* BoolExpr (void)
766 /* Evaluate a boolean expression */
768 /* Read left hand side */
769 ExprNode* Root = SimpleExpr ();
771 /* Handle booleans */
772 while (Tok == TOK_EQ || Tok == TOK_NE || Tok == TOK_LT ||
773 Tok == TOK_GT || Tok == TOK_LE || Tok == TOK_GE) {
775 /* Create a new node and insert the left expression */
776 ExprNode* Left = Root;
777 Root = NewExprNode ();
780 /* Determine the operator token */
782 case TOK_EQ: Root->Op = EXPR_EQ; break;
783 case TOK_NE: Root->Op = EXPR_NE; break;
784 case TOK_LT: Root->Op = EXPR_LT; break;
785 case TOK_GT: Root->Op = EXPR_GT; break;
786 case TOK_LE: Root->Op = EXPR_LE; break;
787 case TOK_GE: Root->Op = EXPR_GE; break;
788 default: Internal ("Invalid token");
792 /* Parse the right hand side */
793 Root->Right = SimpleExpr ();
797 /* Return the expression tree we've created */
803 static ExprNode* Expr2 (void)
804 /* Boolean operators: AND and XOR */
806 /* Read left hand side */
807 ExprNode* Root = BoolExpr ();
809 /* Handle booleans */
810 while (Tok == TOK_BAND || Tok == TOK_BXOR) {
812 /* Create a new node and insert the left expression */
813 ExprNode* Left = Root;
814 Root = NewExprNode ();
817 /* Determine the operator token */
819 case TOK_BAND: Root->Op = EXPR_BAND; break;
820 case TOK_BXOR: Root->Op = EXPR_BXOR; break;
821 default: Internal ("Invalid token");
825 /* Parse the right hand side */
826 Root->Right = BoolExpr ();
830 /* Return the expression tree we've created */
836 static ExprNode* Expr1 (void)
837 /* Boolean operators: OR */
839 /* Read left hand side */
840 ExprNode* Root = Expr2 ();
842 /* Handle booleans */
843 while (Tok == TOK_BOR) {
845 /* Create a new node and insert the left expression */
846 ExprNode* Left = Root;
847 Root = NewExprNode ();
850 /* Determine the operator token */
852 case TOK_BOR: Root->Op = EXPR_BOR; break;
853 default: Internal ("Invalid token");
857 /* Parse the right hand side */
858 Root->Right = Expr2 ();
862 /* Return the expression tree we've created */
868 static ExprNode* Expr0 (void)
869 /* Boolean operators: NOT */
873 /* Handle booleans */
874 if (Tok == TOK_BNOT) {
876 /* Create a new node */
877 Root = NewExprNode ();
879 /* Determine the operator token */
881 case TOK_BNOT: Root->Op = EXPR_BNOT; break;
882 default: Internal ("Invalid token");
886 /* Parse the left hand side, allow more BNOTs */
887 Root->Left = Expr0 ();
891 /* Read left hand side */
896 /* Return the expression tree we've created */
902 static ExprNode* SimplifyExpr (ExprNode* Root)
903 /* Try to simplify the given expression tree */
906 SimplifyExpr (Root->Left);
907 SimplifyExpr (Root->Right);
908 if (IsConstExpr (Root)) {
909 /* The complete expression is constant */
910 Root->V.Val = GetExprVal (Root);
911 Root->Op = EXPR_LITERAL;
912 FreeExpr (Root->Left);
913 FreeExpr (Root->Right);
914 Root->Left = Root->Right = 0;
922 ExprNode* Expression (void)
923 /* Evaluate an expression, build the expression tree on the heap and return
924 * a pointer to the root of the tree.
927 return SimplifyExpr (Expr0 ());
932 long ConstExpression (void)
933 /* Parse an expression. Check if the expression is const, and print an error
934 * message if not. Return the value of the expression, or a dummy, if it is
938 /* Read the expression, and call finalize (exception here, since we
941 ExprNode* Expr = FinalizeExpr (Expression ());
943 /* Return the value */
944 if (IsConstExpr (Expr)) {
945 return GetExprVal (Expr);
947 Error (ERR_CONSTEXPR_EXPECTED);
954 ExprNode* LiteralExpr (long Val)
955 /* Return an expression tree that encodes the given literal value */
957 ExprNode* Expr = NewExprNode ();
958 Expr->Op = EXPR_LITERAL;
965 ExprNode* CurrentPC (void)
966 /* Return the current program counter as expression */
972 /* Create SegmentBase + Offset */
973 Left = NewExprNode ();
974 Left->Op = EXPR_SECTION;
975 Left->V.SegNum = GetSegNum ();
977 Root = NewExprNode ();
979 Root->Right = LiteralExpr (GetPC ());
980 Root->Op = EXPR_PLUS;
982 /* Absolute mode, just return PC value */
983 Root = LiteralExpr (GetPC ());
991 ExprNode* SwapExpr (ExprNode* Expr)
992 /* Return an extended expression with lo and hi bytes swapped */
994 ExprNode* N = NewExprNode ();
1002 ExprNode* BranchExpr (unsigned Offs)
1003 /* Return an expression that encodes the difference between current PC plus
1004 * offset and the target expression (that is, Expression() - (*+Offs) ).
1013 Left = NewExprNode ();
1014 Left->Op = EXPR_SECTION;
1015 Left->V.SegNum = GetSegNum ();
1019 N->Right = LiteralExpr (GetPC () + Offs);
1022 N = LiteralExpr (GetPC () + Offs);
1025 /* Create the root node */
1026 Root = NewExprNode ();
1027 Root->Left = Expression ();
1029 Root->Op = EXPR_MINUS;
1031 /* Return the result */
1032 return SimplifyExpr (Root);
1037 ExprNode* ULabelExpr (unsigned Num)
1038 /* Return an expression for an unnamed label with the given index */
1040 /* Get an expression node */
1041 ExprNode* Node = NewExprNode ();
1043 /* Set the values */
1044 Node->Op = EXPR_ULABEL;
1047 /* Return the new node */
1053 void FreeExpr (ExprNode* Root)
1054 /* Free the expression, Root is pointing to. */
1057 FreeExpr (Root->Left);
1058 FreeExpr (Root->Right);
1059 FreeExprNode (Root);
1065 ExprNode* ForceWordExpr (ExprNode* Expr)
1066 /* Force the given expression into a word and return the result. */
1068 /* And the expression by $FFFF to force it into word size */
1069 ExprNode* Root = NewExprNode ();
1071 Root->Op = EXPR_AND;
1072 Root->Right = LiteralExpr (0xFFFF);
1074 /* Return the result */
1080 int IsConstExpr (ExprNode* Root)
1081 /* Return true if the given expression is a constant expression, that is, one
1082 * with no references to external symbols.
1088 if (EXPR_IS_LEAF (Root->Op)) {
1096 if (SymHasUserMark (Sym)) {
1097 if (Verbosity > 0) {
1100 PError (GetSymPos (Sym), ERR_CIRCULAR_REFERENCE);
1104 Const = SymIsConst (Sym);
1105 SymUnmarkUser (Sym);
1113 } else if (EXPR_IS_UNARY (Root->Op)) {
1115 return IsConstExpr (Root->Left);
1119 /* We must handle shortcut boolean expressions here */
1123 if (IsConstExpr (Root->Left)) {
1124 /* lhs is const, if it is zero, don't eval right */
1125 if (GetExprVal (Root->Left) == 0) {
1128 return IsConstExpr (Root->Right);
1131 /* lhs not const --> tree not const */
1137 if (IsConstExpr (Root->Left)) {
1138 /* lhs is const, if it is not zero, don't eval right */
1139 if (GetExprVal (Root->Left) != 0) {
1142 return IsConstExpr (Root->Right);
1145 /* lhs not const --> tree not const */
1151 /* All others are handled normal */
1152 return IsConstExpr (Root->Left) && IsConstExpr (Root->Right);
1159 static void CheckByteExpr (const ExprNode* N, int* IsByte)
1160 /* Internal routine that is recursively called to check if there is a zeropage
1161 * symbol in the expression tree.
1165 switch (N->Op & EXPR_TYPEMASK) {
1171 if (SymIsZP (N->V.Sym)) {
1173 } else if (SymHasExpr (N->V.Sym)) {
1174 /* Check if this expression is a byte expression */
1175 *IsByte = IsByteExpr (GetSymExpr (N->V.Sym));
1180 if (GetSegType (N->V.SegNum) == SEGTYPE_ZP) {
1188 case EXPR_UNARYNODE:
1189 CheckByteExpr (N->Left, IsByte);
1192 case EXPR_BINARYNODE:
1193 CheckByteExpr (N->Left, IsByte);
1194 CheckByteExpr (N->Right, IsByte);
1198 Internal ("Unknown expression op: %02X", N->Op);
1205 int IsByteExpr (ExprNode* Root)
1206 /* Return true if this is a byte expression */
1210 if (IsConstExpr (Root)) {
1211 if (Root->Op != EXPR_LITERAL) {
1212 SimplifyExpr (Root);
1214 return IsByteRange (GetExprVal (Root));
1215 } else if (Root->Op == EXPR_BYTE0 || Root->Op == EXPR_BYTE1 ||
1216 Root->Op == EXPR_BYTE2 || Root->Op == EXPR_BYTE3) {
1217 /* Symbol forced to have byte range */
1220 /* We have undefined symbols in the expression. Assume that the
1221 * expression is a byte expression if there is at least one symbol
1222 * declared as zeropage in it. Being wrong here is not a very big
1223 * problem since the linker knows about all symbols and detects
1224 * error like mixing absolute and zeropage labels.
1227 CheckByteExpr (Root, &IsByte);
1234 long GetExprVal (ExprNode* Expr)
1235 /* Get the value of a constant expression */
1245 return GetSymVal (Expr->V.Sym);
1248 return GetExprVal (Expr->Left) + GetExprVal (Expr->Right);
1251 return GetExprVal (Expr->Left) - GetExprVal (Expr->Right);
1254 return GetExprVal (Expr->Left) * GetExprVal (Expr->Right);
1257 Left = GetExprVal (Expr->Left);
1258 Right = GetExprVal (Expr->Right);
1260 Error (ERR_DIV_BY_ZERO);
1263 return Left / Right;
1266 Left = GetExprVal (Expr->Left);
1267 Right = GetExprVal (Expr->Right);
1269 Error (ERR_MOD_BY_ZERO);
1272 return Left % Right;
1275 return GetExprVal (Expr->Left) | GetExprVal (Expr->Right);
1278 return GetExprVal (Expr->Left) ^ GetExprVal (Expr->Right);
1281 return GetExprVal (Expr->Left) & GetExprVal (Expr->Right);
1284 return GetExprVal (Expr->Left) << GetExprVal (Expr->Right);
1287 return GetExprVal (Expr->Left) >> GetExprVal (Expr->Right);
1290 return (GetExprVal (Expr->Left) == GetExprVal (Expr->Right));
1293 return (GetExprVal (Expr->Left) != GetExprVal (Expr->Right));
1296 return (GetExprVal (Expr->Left) < GetExprVal (Expr->Right));
1299 return (GetExprVal (Expr->Left) > GetExprVal (Expr->Right));
1302 return (GetExprVal (Expr->Left) <= GetExprVal (Expr->Right));
1305 return (GetExprVal (Expr->Left) >= GetExprVal (Expr->Right));
1307 case EXPR_UNARY_MINUS:
1308 return -GetExprVal (Expr->Left);
1311 return ~GetExprVal (Expr->Left);
1314 return GetExprVal (Expr->Left) & 0xFF;
1317 return (GetExprVal (Expr->Left) >> 8) & 0xFF;
1320 return (GetExprVal (Expr->Left) >> 16) & 0xFF;
1323 return (GetExprVal (Expr->Left) >> 24) & 0xFF;
1326 Left = GetExprVal (Expr->Left);
1327 return ((Left >> 8) & 0x00FF) | ((Left << 8) & 0xFF00);
1330 return GetExprVal (Expr->Left) && GetExprVal (Expr->Right);
1333 return GetExprVal (Expr->Left) || GetExprVal (Expr->Right);
1336 return (GetExprVal (Expr->Left) != 0) ^ (GetExprVal (Expr->Right) != 0);
1339 return !GetExprVal (Expr->Left);
1342 Internal ("GetExprVal called for EXPR_ULABEL");
1347 Internal ("Unknown Op type: %u", Expr->Op);
1355 static ExprNode* RemoveSyms (ExprNode* Expr, int MustClone)
1356 /* Remove resolved symbols from the tree by cloning symbol expressions */
1358 /* Accept NULL pointers */
1363 /* Special node handling */
1367 if (SymHasExpr (Expr->V.Sym)) {
1368 /* The symbol has an expression tree */
1369 SymEntry* Sym = Expr->V.Sym;
1370 if (SymHasUserMark (Sym)) {
1371 /* Circular definition */
1375 PError (GetSymPos (Sym), ERR_CIRCULAR_REFERENCE);
1376 return LiteralExpr (0); /* Return a dummy value */
1379 Expr = RemoveSyms (GetSymExpr (Sym), 1);
1380 SymUnmarkUser (Sym);
1382 } else if (SymIsConst (Expr->V.Sym)) {
1383 /* The symbol is a constant */
1384 return LiteralExpr (GetSymVal (Expr->V.Sym));
1389 if (ULabCanResolve ()) {
1390 ExprNode* NewExpr = ULabResolve (Expr->V.Val);
1398 /* Clone the current node if needed */
1401 /* Create a new node */
1402 ExprNode* Clone = NewExprNode ();
1404 /* Clone the operation */
1405 Clone->Op = Expr->Op;
1407 /* Clone the attribute if needed */
1412 Clone->V.Val = Expr->V.Val;
1416 Clone->V.Sym = Expr->V.Sym;
1420 Clone->V.SegNum = Expr->V.SegNum;
1425 /* Clone the tree nodes */
1426 Clone->Left = RemoveSyms (Expr->Left, MustClone);
1427 Clone->Right = RemoveSyms (Expr->Right, MustClone);
1434 /* Nothing to clone */
1435 Expr->Left = RemoveSyms (Expr->Left, MustClone);
1436 Expr->Right = RemoveSyms (Expr->Right, MustClone);
1446 static ExprNode* ConstExtract (ExprNode* Expr, long* Val, int Sign)
1447 /* Extract and evaluate all constant factors in an subtree that has only
1448 * additions and subtractions.
1451 if (Expr->Op == EXPR_LITERAL) {
1453 *Val -= Expr->V.Val;
1455 *Val += Expr->V.Val;
1457 FreeExprNode (Expr);
1461 if (Expr->Op == EXPR_PLUS || Expr->Op == EXPR_MINUS) {
1464 Left = ConstExtract (Expr->Left, Val, Sign);
1465 if (Expr->Op == EXPR_MINUS) {
1468 Right = ConstExtract (Expr->Right, Val, Sign);
1469 if (Left == 0 && Right == 0) {
1470 FreeExprNode (Expr);
1472 } else if (Left == 0) {
1473 FreeExprNode (Expr);
1475 } else if (Right == 0) {
1476 FreeExprNode (Expr);
1479 /* Check for SEG - SEG which is now possible */
1480 if (Left->Op == EXPR_SECTION && Right->Op == EXPR_SECTION &&
1481 Left->V.SegNum == Right->V.SegNum) {
1482 /* SEG - SEG, remove it completely */
1483 FreeExprNode (Left);
1484 FreeExprNode (Right);
1485 FreeExprNode (Expr);
1489 Expr->Right = Right;
1495 /* Some other sort of node, finalize the terms */
1497 Expr->Left = FinalizeExpr (Expr->Left);
1500 Expr->Right = FinalizeExpr (Expr->Right);
1508 ExprNode* FinalizeExpr (ExprNode* Expr)
1509 /* Resolve any symbols by cloning the symbol expression tree instead of the
1510 * symbol reference, then try to simplify the expression as much as possible.
1511 * This function must only be called if all symbols are resolved (no undefined
1518 Expr = RemoveSyms (Expr, 0);
1519 Expr = ConstExtract (Expr, &Val, 1);
1521 /* Reduced to a literal value */
1522 Expr = LiteralExpr (Val);
1524 /* Extracted a value */
1528 N->Right = LiteralExpr (Val);
1536 ExprNode* CloneExpr (ExprNode* Expr)
1537 /* Clone the given expression tree. The function will simply clone symbol
1538 * nodes, it will not resolve them.
1543 /* Accept NULL pointers */
1548 /* Get a new node */
1549 Clone = NewExprNode ();
1551 /* Clone the operation */
1552 Clone->Op = Expr->Op;
1554 /* Clone the attribute if needed */
1559 Clone->V.Val = Expr->V.Val;
1563 Clone->V.Sym = Expr->V.Sym;
1567 Clone->V.SegNum = Expr->V.SegNum;
1572 /* Clone the tree nodes */
1573 Clone->Left = CloneExpr (Expr->Left);
1574 Clone->Right = CloneExpr (Expr->Right);
1582 void WriteExpr (ExprNode* Expr)
1583 /* Write the given expression to the object file */
1585 /* Null expressions are encoded by a type byte of zero */
1591 /* Write the expression code */
1592 ObjWrite8 (Expr->Op);
1594 /* If the is a leafnode, write the expression attribute, otherwise
1595 * write the expression operands.
1600 ObjWrite32 (Expr->V.Val);
1604 /* Maybe we should use a code here? */
1605 CHECK (SymIsImport (Expr->V.Sym)); /* Safety */
1606 ObjWrite16 (GetSymIndex (Expr->V.Sym));
1610 ObjWrite8 (Expr->V.SegNum);
1614 Internal ("WriteExpr: Cannot write EXPR_ULABEL nodes");
1618 /* Not a leaf node */
1619 WriteExpr (Expr->Left);
1620 WriteExpr (Expr->Right);