1 /*****************************************************************************/
5 /* Expression evaluation for the ca65 macroassembler */
9 /* (C) 1998-2004 Ullrich von Bassewitz */
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 /*****************************************************************************/
59 #include "studyexpr.h"
67 /*****************************************************************************/
69 /*****************************************************************************/
73 /* Since all expressions are first packed into expression trees, and each
74 * expression tree node is allocated on the heap, we add some type of special
75 * purpose memory allocation here: Instead of freeing the nodes, we save some
76 * number of freed nodes for later and remember them in a single linked list
77 * using the Left link.
79 #define MAX_FREE_NODES 64
80 static ExprNode* FreeExprNodes = 0;
81 static unsigned FreeNodeCount = 0;
85 /*****************************************************************************/
87 /*****************************************************************************/
91 static ExprNode* NewExprNode (unsigned Op)
92 /* Create a new expression node */
96 /* Do we have some nodes in the list already? */
98 /* Use first node from list */
100 FreeExprNodes = N->Left;
102 /* Allocate fresh memory */
103 N = xmalloc (sizeof (ExprNode));
106 N->Left = N->Right = 0;
114 static void FreeExprNode (ExprNode* E)
118 if (E->Op == EXPR_SYMBOL) {
119 /* Remove the symbol reference */
120 SymDelExprRef (E->V.Sym, E);
122 /* Place the symbol into the free nodes list if possible */
123 if (FreeNodeCount < MAX_FREE_NODES) {
124 /* Remember this node for later */
125 E->Left = FreeExprNodes;
128 /* Free the memory */
136 /*****************************************************************************/
138 /*****************************************************************************/
142 static ExprNode* Expr0 (void);
146 int IsByteRange (long Val)
147 /* Return true if this is a byte value */
149 return (Val & ~0xFFL) == 0;
154 int IsWordRange (long Val)
155 /* Return true if this is a word value */
157 return (Val & ~0xFFFFL) == 0;
162 int IsFarRange (long Val)
163 /* Return true if this is a far (24 bit) value */
165 return (Val & ~0xFFFFFFL) == 0;
170 static int IsEasyConst (const ExprNode* E, long* Val)
171 /* Do some light checking if the given node is a constant. Don't care if E is
172 * a complex expression. If E is a constant, return true and place its value
173 * into Val, provided that Val is not NULL.
176 /* Resolve symbols, follow symbol chains */
177 while (E->Op == EXPR_SYMBOL) {
178 E = SymResolve (E->V.Sym);
180 /* Could not resolve */
185 /* Symbols resolved, check for a literal */
186 if (E->Op == EXPR_LITERAL) {
193 /* Not found to be a const according to our tests */
199 static ExprNode* LoByte (ExprNode* Operand)
200 /* Return the low byte of the given expression */
205 /* Special handling for const expressions */
206 if (IsEasyConst (Operand, &Val)) {
208 Expr = GenLiteralExpr (Val & 0xFF);
210 /* Extract byte #0 */
211 Expr = NewExprNode (EXPR_BYTE0);
212 Expr->Left = Operand;
219 static ExprNode* HiByte (ExprNode* Operand)
220 /* Return the high byte of the given expression */
225 /* Special handling for const expressions */
226 if (IsEasyConst (Operand, &Val)) {
228 Expr = GenLiteralExpr ((Val >> 8) & 0xFF);
230 /* Extract byte #1 */
231 Expr = NewExprNode (EXPR_BYTE1);
232 Expr->Left = Operand;
239 static ExprNode* BankByte (ExprNode* Operand)
240 /* Return the bank byte of the given expression */
245 /* Special handling for const expressions */
246 if (IsEasyConst (Operand, &Val)) {
248 Expr = GenLiteralExpr ((Val >> 16) & 0xFF);
250 /* Extract byte #2 */
251 Expr = NewExprNode (EXPR_BYTE2);
252 Expr->Left = Operand;
259 static ExprNode* LoWord (ExprNode* Operand)
260 /* Return the low word of the given expression */
265 /* Special handling for const expressions */
266 if (IsEasyConst (Operand, &Val)) {
268 Expr = GenLiteralExpr (Val & 0xFFFF);
270 /* Extract word #0 */
271 Expr = NewExprNode (EXPR_WORD0);
272 Expr->Left = Operand;
279 static ExprNode* HiWord (ExprNode* Operand)
280 /* Return the high word of the given expression */
285 /* Special handling for const expressions */
286 if (IsEasyConst (Operand, &Val)) {
288 Expr = GenLiteralExpr ((Val >> 16) & 0xFFFF);
290 /* Extract word #1 */
291 Expr = NewExprNode (EXPR_WORD1);
292 Expr->Left = Operand;
299 static ExprNode* Symbol (SymEntry* S)
300 /* Reference a symbol and return an expression for it */
303 /* Some weird error happened before */
304 return GenLiteralExpr (0);
306 /* Mark the symbol as referenced */
308 /* Create symbol node */
309 return GenSymExpr (S);
315 static ExprNode* FuncBankByte (void)
316 /* Handle the .BANKBYTE builtin function */
318 return BankByte (Expression ());
323 static ExprNode* FuncBlank (void)
324 /* Handle the .BLANK builtin function */
328 /* Assume no tokens if the closing brace follows (this is not correct in
329 * all cases, since the token may be the closing brace, but this will
330 * give a syntax error anyway and may not be handled by .BLANK.
332 if (Tok != TOK_RPAREN) {
333 /* Skip any tokens */
335 while (!TokIsSep (Tok)) {
336 if (Tok == TOK_LPAREN) {
338 } else if (Tok == TOK_RPAREN) {
350 return GenLiteralExpr (Result);
355 static ExprNode* FuncConst (void)
356 /* Handle the .CONST builtin function */
358 /* Read an expression */
359 ExprNode* Expr = Expression ();
361 /* Check the constness of the expression */
362 ExprNode* Result = GenLiteralExpr (IsConstExpr (Expr, 0));
364 /* Free the expression */
373 static ExprNode* FuncDefined (void)
374 /* Handle the .DEFINED builtin function */
376 /* Parse the symbol name and search for the symbol */
377 SymEntry* Sym = ParseScopedSymName (SYM_FIND_EXISTING);
379 /* Check if the symbol is defined */
380 return GenLiteralExpr (Sym != 0 && SymIsDef (Sym));
385 static ExprNode* FuncHiByte (void)
386 /* Handle the .HIBYTE builtin function */
388 return HiByte (Expression ());
393 static ExprNode* FuncHiWord (void)
394 /* Handle the .HIWORD builtin function */
396 return HiWord (Expression ());
401 static ExprNode* FuncLoByte (void)
402 /* Handle the .LOBYTE builtin function */
404 return LoByte (Expression ());
409 static ExprNode* FuncLoWord (void)
410 /* Handle the .LOWORD builtin function */
412 return LoWord (Expression ());
417 static ExprNode* DoMatch (enum TC EqualityLevel)
418 /* Handle the .MATCH and .XMATCH builtin functions */
426 /* A list of tokens follows. Read this list and remember it building a
427 * single linked list of tokens including attributes. The list is
428 * either enclosed in curly braces, or terminated by a comma.
430 if (Tok == TOK_LCURLY) {
436 while (Tok != Term) {
438 /* We may not end-of-line of end-of-file here */
439 if (TokIsSep (Tok)) {
440 Error ("Unexpected end of line");
441 return GenLiteralExpr (0);
444 /* Get a node with this token */
445 Node = NewTokNode ();
447 /* Insert the node into the list */
459 /* Skip the terminator token*/
462 /* If the token list was enclosed in curly braces, we expect a comma */
463 if (Term == TOK_RCURLY) {
467 /* Read the second list which is optionally enclosed in curly braces and
468 * terminated by the right parenthesis. Compare each token against the
469 * one in the first list.
471 if (Tok == TOK_LCURLY) {
479 while (Tok != Term) {
481 /* We may not end-of-line of end-of-file here */
482 if (TokIsSep (Tok)) {
483 Error ("Unexpected end of line");
484 return GenLiteralExpr (0);
487 /* Compare the tokens if the result is not already known */
490 /* The second list is larger than the first one */
492 } else if (TokCmp (Node) < EqualityLevel) {
493 /* Tokens do not match */
498 /* Next token in first list */
503 /* Next token in current list */
507 /* If the token list was enclosed in curly braces, eat the closing brace */
508 if (Term == TOK_RCURLY) {
512 /* Check if there are remaining tokens in the first list */
517 /* Free the token list */
524 /* Done, return the result */
525 return GenLiteralExpr (Result);
530 static ExprNode* FuncMatch (void)
531 /* Handle the .MATCH function */
533 return DoMatch (tcSameToken);
538 static ExprNode* FuncReferenced (void)
539 /* Handle the .REFERENCED builtin function */
541 /* Parse the symbol name and search for the symbol */
542 SymEntry* Sym = ParseScopedSymName (SYM_FIND_EXISTING);
544 /* Check if the symbol is referenced */
545 return GenLiteralExpr (Sym != 0 && SymIsRef (Sym));
550 static ExprNode* FuncSizeOf (void)
551 /* Handle the .SIZEOF function */
553 StrBuf ScopeName = AUTO_STRBUF_INITIALIZER;
554 char Name[sizeof (SVal)];
562 /* Assume an error */
565 /* Check for a cheap local which needs special handling */
566 if (Tok == TOK_LOCAL_IDENT) {
568 /* Cheap local symbol */
569 Sym = SymFindLocal (SymLast, SVal, SYM_FIND_EXISTING);
571 Error ("Unknown symbol or scope: `%s'", SVal);
573 SizeSym = GetSizeOfSymbol (Sym);
576 /* Remember and skip SVal, terminate ScopeName so it is empty */
579 SB_Terminate (&ScopeName);
583 /* Parse the scope and the name */
584 SymTable* ParentScope = ParseScopedIdent (Name, &ScopeName);
586 /* Check if the parent scope is valid */
587 if (ParentScope == 0) {
589 DoneStrBuf (&ScopeName);
590 return GenLiteralExpr (0);
593 /* If ScopeName is empty, no explicit scope was specified. We have to
594 * search upper scope levels in this case.
596 NoScope = SB_IsEmpty (&ScopeName);
598 /* First search for a scope with the given name */
600 Scope = SymFindAnyScope (ParentScope, Name);
602 Scope = SymFindScope (ParentScope, Name, SYM_FIND_EXISTING);
605 /* If we did find a scope with the name, read the symbol defining the
606 * size, otherwise search for a symbol entry with the name and scope.
609 /* Yep, it's a scope */
610 SizeSym = GetSizeOfScope (Scope);
613 Sym = SymFindAny (ParentScope, Name);
615 Sym = SymFind (ParentScope, Name, SYM_FIND_EXISTING);
618 /* If we found the symbol retrieve the size, otherwise complain */
620 SizeSym = GetSizeOfSymbol (Sym);
622 Error ("Unknown symbol or scope: `%s%s'",
623 SB_GetConstBuf (&ScopeName), Name);
628 /* Check if we have a size */
629 if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
630 Error ("Size of `%s%s' is unknown", SB_GetConstBuf (&ScopeName), Name);
634 /* Free the scope name */
635 DoneStrBuf (&ScopeName);
637 /* Return the size */
638 return GenLiteralExpr (Size);
643 static ExprNode* FuncStrAt (void)
644 /* Handle the .STRAT function */
646 char Str [sizeof(SVal)];
650 /* String constant expected */
651 if (Tok != TOK_STRCON) {
652 Error ("String constant expected");
658 /* Remember the string and skip it */
662 /* Comma must follow */
665 /* Expression expected */
666 Index = ConstExpression ();
668 /* Must be a valid index */
669 if (Index >= (long) strlen (Str)) {
670 Error ("Range error");
671 return GenLiteralExpr (0);
674 /* Get the char, handle as unsigned. Be sure to translate it into
675 * the target character set.
677 C = TgtTranslateChar (Str [(size_t)Index]);
679 /* Return the char expression */
680 return GenLiteralExpr (C);
685 static ExprNode* FuncStrLen (void)
686 /* Handle the .STRLEN function */
690 /* String constant expected */
691 if (Tok != TOK_STRCON) {
693 Error ("String constant expected");
694 /* Smart error recovery */
695 if (Tok != TOK_RPAREN) {
702 /* Get the length of the string */
705 /* Skip the string */
709 /* Return the length */
710 return GenLiteralExpr (Len);
715 static ExprNode* FuncTCount (void)
716 /* Handle the .TCOUNT function */
718 /* We have a list of tokens that ends with the closing paren. Skip
719 * the tokens, handling nested braces and count them.
723 while (Parens != 0 || Tok != TOK_RPAREN) {
725 /* Check for end of line or end of input. Since the calling function
726 * will check for the closing paren, we don't need to print an error
727 * here, just bail out.
729 if (TokIsSep (Tok)) {
736 /* Keep track of the nesting level */
738 case TOK_LPAREN: ++Parens; break;
739 case TOK_RPAREN: --Parens; break;
747 /* Return the number of tokens */
748 return GenLiteralExpr (Count);
753 static ExprNode* FuncXMatch (void)
754 /* Handle the .XMATCH function */
756 return DoMatch (tcIdentical);
761 static ExprNode* Function (ExprNode* (*F) (void))
762 /* Handle builtin functions */
766 /* Skip the keyword */
769 /* Expression must be enclosed in braces */
770 if (Tok != TOK_LPAREN) {
771 Error ("'(' expected");
773 return GenLiteralExpr (0);
777 /* Call the function itself */
780 /* Closing brace must follow */
783 /* Return the result of the actual function */
789 static ExprNode* Factor (void)
798 N = GenLiteralExpr (IVal);
803 N = GenLiteralExpr (TgtTranslateChar (IVal));
809 N = Symbol (ParseScopedSymName (SYM_ALLOC_NEW));
812 case TOK_LOCAL_IDENT:
813 N = Symbol (SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW));
825 if (IsEasyConst (L, &Val)) {
827 N = GenLiteralExpr (-Val);
829 N = NewExprNode (EXPR_UNARY_MINUS);
837 if (IsEasyConst (L, &Val)) {
839 N = GenLiteralExpr (~Val);
841 N = NewExprNode (EXPR_NOT);
854 N = LoByte (Factor ());
859 N = HiByte (Factor ());
864 N = BankByte (Factor ());
874 N = Function (FuncBankByte);
878 N = Function (FuncBlank);
882 N = Function (FuncConst);
886 N = GenLiteralExpr (CPUIsets[CPU]);
891 N = Function (FuncDefined);
895 N = Function (FuncHiByte);
899 N = Function (FuncHiWord);
903 N = Function (FuncLoByte);
907 N = Function (FuncLoWord);
911 N = Function (FuncMatch);
915 N = Function (FuncReferenced);
919 N = Function (FuncSizeOf);
923 N = Function (FuncStrAt);
927 N = Function (FuncStrLen);
931 N = Function (FuncTCount);
935 N = GenLiteralExpr (time (0));
940 N = GenLiteralExpr (VERSION);
945 N = Function (FuncXMatch);
949 if (LooseCharTerm && Tok == TOK_STRCON && strlen(SVal) == 1) {
950 /* A character constant */
951 N = GenLiteralExpr (TgtTranslateChar (SVal[0]));
953 N = GenLiteralExpr (0); /* Dummy */
954 Error ("Syntax error");
964 static ExprNode* Term (void)
966 /* Read left hand side */
967 ExprNode* Root = Factor ();
969 /* Handle multiplicative operations */
970 while (Tok == TOK_MUL || Tok == TOK_DIV || Tok == TOK_MOD ||
971 Tok == TOK_AND || Tok == TOK_XOR || Tok == TOK_SHL ||
974 long LVal, RVal, Val;
978 /* Remember the token and skip it */
982 /* Move root to left side and read the right side */
986 /* If both expressions are constant, we can evaluate the term */
987 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
996 Error ("Division by zero");
1005 Error ("Modulo operation with zero");
1021 Val = shl_l (LVal, RVal);
1025 Val = shr_l (LVal, RVal);
1029 Internal ("Invalid token");
1032 /* Generate a literal expression and delete the old left and
1037 Root = GenLiteralExpr (Val);
1041 /* Generate an expression tree */
1044 case TOK_MUL: Op = EXPR_MUL; break;
1045 case TOK_DIV: Op = EXPR_DIV; break;
1046 case TOK_MOD: Op = EXPR_MOD; break;
1047 case TOK_AND: Op = EXPR_AND; break;
1048 case TOK_XOR: Op = EXPR_XOR; break;
1049 case TOK_SHL: Op = EXPR_SHL; break;
1050 case TOK_SHR: Op = EXPR_SHR; break;
1051 default: Internal ("Invalid token");
1053 Root = NewExprNode (Op);
1055 Root->Right = Right;
1061 /* Return the expression tree we've created */
1067 static ExprNode* SimpleExpr (void)
1069 /* Read left hand side */
1070 ExprNode* Root = Term ();
1072 /* Handle additive operations */
1073 while (Tok == TOK_PLUS || Tok == TOK_MINUS || Tok == TOK_OR) {
1075 long LVal, RVal, Val;
1079 /* Remember the token and skip it */
1083 /* Move root to left side and read the right side */
1087 /* If both expressions are constant, we can evaluate the term */
1088 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1091 case TOK_PLUS: Val = LVal + RVal; break;
1092 case TOK_MINUS: Val = LVal - RVal; break;
1093 case TOK_OR: Val = LVal | RVal; break;
1094 default: Internal ("Invalid token");
1097 /* Generate a literal expression and delete the old left and
1102 Root = GenLiteralExpr (Val);
1106 /* Generate an expression tree */
1109 case TOK_PLUS: Op = EXPR_PLUS; break;
1110 case TOK_MINUS: Op = EXPR_MINUS; break;
1111 case TOK_OR: Op = EXPR_OR; break;
1112 default: Internal ("Invalid token");
1114 Root = NewExprNode (Op);
1116 Root->Right = Right;
1121 /* Return the expression tree we've created */
1127 static ExprNode* BoolExpr (void)
1128 /* Evaluate a boolean expression */
1130 /* Read left hand side */
1131 ExprNode* Root = SimpleExpr ();
1133 /* Handle booleans */
1134 while (Tok == TOK_EQ || Tok == TOK_NE || Tok == TOK_LT ||
1135 Tok == TOK_GT || Tok == TOK_LE || Tok == TOK_GE) {
1137 long LVal, RVal, Val;
1141 /* Remember the token and skip it */
1145 /* Move root to left side and read the right side */
1147 Right = SimpleExpr ();
1149 /* If both expressions are constant, we can evaluate the term */
1150 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1153 case TOK_EQ: Val = (LVal == RVal); break;
1154 case TOK_NE: Val = (LVal != RVal); break;
1155 case TOK_LT: Val = (LVal < RVal); break;
1156 case TOK_GT: Val = (LVal > RVal); break;
1157 case TOK_LE: Val = (LVal <= RVal); break;
1158 case TOK_GE: Val = (LVal >= RVal); break;
1159 default: Internal ("Invalid token");
1162 /* Generate a literal expression and delete the old left and
1167 Root = GenLiteralExpr (Val);
1171 /* Generate an expression tree */
1174 case TOK_EQ: Op = EXPR_EQ; break;
1175 case TOK_NE: Op = EXPR_NE; break;
1176 case TOK_LT: Op = EXPR_LT; break;
1177 case TOK_GT: Op = EXPR_GT; break;
1178 case TOK_LE: Op = EXPR_LE; break;
1179 case TOK_GE: Op = EXPR_GE; break;
1180 default: Internal ("Invalid token");
1182 Root = NewExprNode (Op);
1184 Root->Right = Right;
1189 /* Return the expression tree we've created */
1195 static ExprNode* Expr2 (void)
1196 /* Boolean operators: AND and XOR */
1198 /* Read left hand side */
1199 ExprNode* Root = BoolExpr ();
1201 /* Handle booleans */
1202 while (Tok == TOK_BOOLAND || Tok == TOK_BOOLXOR) {
1204 long LVal, RVal, Val;
1208 /* Remember the token and skip it */
1212 /* Move root to left side and read the right side */
1214 Right = BoolExpr ();
1216 /* If both expressions are constant, we can evaluate the term */
1217 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1220 case TOK_BOOLAND: Val = ((LVal != 0) && (RVal != 0)); break;
1221 case TOK_BOOLXOR: Val = ((LVal != 0) ^ (RVal != 0)); break;
1222 default: Internal ("Invalid token");
1225 /* Generate a literal expression and delete the old left and
1230 Root = GenLiteralExpr (Val);
1234 /* Generate an expression tree */
1237 case TOK_BOOLAND: Op = EXPR_BOOLAND; break;
1238 case TOK_BOOLXOR: Op = EXPR_BOOLXOR; break;
1239 default: Internal ("Invalid token");
1241 Root = NewExprNode (Op);
1243 Root->Right = Right;
1248 /* Return the expression tree we've created */
1254 static ExprNode* Expr1 (void)
1255 /* Boolean operators: OR */
1257 /* Read left hand side */
1258 ExprNode* Root = Expr2 ();
1260 /* Handle booleans */
1261 while (Tok == TOK_BOOLOR) {
1263 long LVal, RVal, Val;
1267 /* Remember the token and skip it */
1271 /* Move root to left side and read the right side */
1275 /* If both expressions are constant, we can evaluate the term */
1276 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1279 case TOK_BOOLOR: Val = ((LVal != 0) || (RVal != 0)); break;
1280 default: Internal ("Invalid token");
1283 /* Generate a literal expression and delete the old left and
1288 Root = GenLiteralExpr (Val);
1292 /* Generate an expression tree */
1295 case TOK_BOOLOR: Op = EXPR_BOOLOR; break;
1296 default: Internal ("Invalid token");
1298 Root = NewExprNode (Op);
1300 Root->Right = Right;
1305 /* Return the expression tree we've created */
1311 static ExprNode* Expr0 (void)
1312 /* Boolean operators: NOT */
1316 /* Handle booleans */
1317 if (Tok == TOK_BOOLNOT) {
1322 /* Skip the operator token */
1325 /* Read the argument */
1328 /* If the argument is const, evaluate it directly */
1329 if (IsEasyConst (Left, &Val)) {
1331 Root = GenLiteralExpr (!Val);
1333 Root = NewExprNode (EXPR_BOOLNOT);
1339 /* Read left hand side */
1344 /* Return the expression tree we've created */
1350 ExprNode* Expression (void)
1351 /* Evaluate an expression, build the expression tree on the heap and return
1352 * a pointer to the root of the tree.
1360 long ConstExpression (void)
1361 /* Parse an expression. Check if the expression is const, and print an error
1362 * message if not. Return the value of the expression, or a dummy, if it is
1368 /* Read the expression */
1369 ExprNode* Expr = Expression ();
1371 /* Study the expression */
1374 StudyExpr (Expr, &D);
1376 /* Check if the expression is constant */
1377 if (ED_IsConst (&D)) {
1380 Error ("Constant expression expected");
1384 /* Free the expression tree and allocated memory for D */
1388 /* Return the value */
1394 void FreeExpr (ExprNode* Root)
1395 /* Free the expression, Root is pointing to. */
1398 FreeExpr (Root->Left);
1399 FreeExpr (Root->Right);
1400 FreeExprNode (Root);
1406 ExprNode* SimplifyExpr (ExprNode* Expr, const ExprDesc* D)
1407 /* Try to simplify the given expression tree */
1409 if (Expr->Op != EXPR_LITERAL && ED_IsConst (D)) {
1410 /* No external references */
1412 Expr = GenLiteralExpr (D->Val);
1419 ExprNode* GenLiteralExpr (long Val)
1420 /* Return an expression tree that encodes the given literal value */
1422 ExprNode* Expr = NewExprNode (EXPR_LITERAL);
1429 ExprNode* GenSymExpr (SymEntry* Sym)
1430 /* Return an expression node that encodes the given symbol */
1432 ExprNode* Expr = NewExprNode (EXPR_SYMBOL);
1434 SymAddExprRef (Sym, Expr);
1440 static ExprNode* GenSectionExpr (unsigned SegNum)
1441 /* Return an expression node for the given section */
1443 ExprNode* Expr = NewExprNode (EXPR_SECTION);
1444 Expr->V.SegNum = SegNum;
1450 ExprNode* GenAddExpr (ExprNode* Left, ExprNode* Right)
1451 /* Generate an addition from the two operands */
1454 if (IsEasyConst (Left, &Val) && Val == 0) {
1457 } else if (IsEasyConst (Right, &Val) && Val == 0) {
1461 ExprNode* Root = NewExprNode (EXPR_PLUS);
1463 Root->Right = Right;
1470 ExprNode* GenCurrentPC (void)
1471 /* Return the current program counter as expression */
1476 /* Create SegmentBase + Offset */
1477 Root = GenAddExpr (GenSectionExpr (GetCurrentSegNum ()),
1478 GenLiteralExpr (GetPC ()));
1480 /* Absolute mode, just return PC value */
1481 Root = GenLiteralExpr (GetPC ());
1489 ExprNode* GenSwapExpr (ExprNode* Expr)
1490 /* Return an extended expression with lo and hi bytes swapped */
1492 ExprNode* N = NewExprNode (EXPR_SWAP);
1499 ExprNode* GenBranchExpr (unsigned Offs)
1500 /* Return an expression that encodes the difference between current PC plus
1501 * offset and the target expression (that is, Expression() - (*+Offs) ).
1508 /* Read Expression() */
1511 /* If the expression is a cheap constant, generate a simpler tree */
1512 if (IsEasyConst (N, &Val)) {
1514 /* Free the constant expression tree */
1517 /* Generate the final expression:
1519 * Val - ((Seg + PC) + Offs)
1520 * Val - Seg - PC - Offs
1521 * (Val - PC - Offs) - Seg
1523 Root = GenLiteralExpr (Val - GetPC () - Offs);
1526 Root = NewExprNode (EXPR_MINUS);
1528 Root->Right = GenSectionExpr (GetCurrentSegNum ());
1533 /* Generate the expression:
1535 * N - ((Seg + PC) + Offs)
1536 * N - Seg - PC - Offs
1537 * N - (PC + Offs) - Seg
1539 Root = NewExprNode (EXPR_MINUS);
1541 Root->Right = GenLiteralExpr (GetPC () + Offs);
1544 Root = NewExprNode (EXPR_MINUS);
1546 Root->Right = GenSectionExpr (GetCurrentSegNum ());
1550 /* Return the result */
1556 ExprNode* GenULabelExpr (unsigned Num)
1557 /* Return an expression for an unnamed label with the given index */
1559 ExprNode* Node = NewExprNode (EXPR_ULABEL);
1562 /* Return the new node */
1568 ExprNode* GenByteExpr (ExprNode* Expr)
1569 /* Force the given expression into a byte and return the result */
1571 /* Use the low byte operator to force the expression into byte size */
1572 return LoByte (Expr);
1577 ExprNode* GenWordExpr (ExprNode* Expr)
1578 /* Force the given expression into a word and return the result. */
1580 /* Use the low byte operator to force the expression into word size */
1581 return LoWord (Expr);
1586 ExprNode* GenNE (ExprNode* Expr, long Val)
1587 /* Generate an expression that compares Expr and Val for inequality */
1589 /* Generate a compare node */
1590 ExprNode* Root = NewExprNode (EXPR_NE);
1592 Root->Right = GenLiteralExpr (Val);
1594 /* Return the result */
1600 int IsConstExpr (ExprNode* Expr, long* Val)
1601 /* Return true if the given expression is a constant expression, that is, one
1602 * with no references to external symbols. If Val is not NULL and the
1603 * expression is constant, the constant value is stored here.
1608 /* Study the expression */
1611 StudyExpr (Expr, &D);
1613 /* Check if the expression is constant */
1614 IsConst = ED_IsConst (&D);
1615 if (IsConst && Val != 0) {
1619 /* Delete allocated memory and return the result */
1626 ExprNode* CloneExpr (ExprNode* Expr)
1627 /* Clone the given expression tree. The function will simply clone symbol
1628 * nodes, it will not resolve them.
1633 /* Accept NULL pointers */
1638 /* Clone the node */
1642 Clone = GenLiteralExpr (Expr->V.Val);
1646 Clone = GenULabelExpr (Expr->V.Val);
1650 Clone = GenSymExpr (Expr->V.Sym);
1654 Clone = GenSectionExpr (Expr->V.SegNum);
1658 /* Generate a new node */
1659 Clone = NewExprNode (Expr->Op);
1660 /* Clone the tree nodes */
1661 Clone->Left = CloneExpr (Expr->Left);
1662 Clone->Right = CloneExpr (Expr->Right);
1672 void WriteExpr (ExprNode* Expr)
1673 /* Write the given expression to the object file */
1675 /* Null expressions are encoded by a type byte of zero */
1677 ObjWrite8 (EXPR_NULL);
1681 /* If the is a leafnode, write the expression attribute, otherwise
1682 * write the expression operands.
1687 ObjWrite8 (EXPR_LITERAL);
1688 ObjWrite32 (Expr->V.Val);
1692 if (SymIsImport (Expr->V.Sym)) {
1693 ObjWrite8 (EXPR_SYMBOL);
1694 ObjWriteVar (GetSymIndex (Expr->V.Sym));
1696 WriteExpr (GetSymExpr (Expr->V.Sym));
1701 ObjWrite8 (EXPR_SECTION);
1702 ObjWrite8 (Expr->V.SegNum);
1706 WriteExpr (ULabResolve (Expr->V.Val));
1710 /* Not a leaf node */
1711 ObjWrite8 (Expr->Op);
1712 WriteExpr (Expr->Left);
1713 WriteExpr (Expr->Right);