1 /*****************************************************************************/
5 /* Expression evaluation for the ca65 macroassembler */
9 /* (C) 1998-2012, Ullrich von Bassewitz */
10 /* Roemerstrasse 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 /*****************************************************************************/
60 #include "studyexpr.h"
68 /*****************************************************************************/
70 /*****************************************************************************/
74 /* Since all expressions are first packed into expression trees, and each
75 * expression tree node is allocated on the heap, we add some type of special
76 * purpose memory allocation here: Instead of freeing the nodes, we save some
77 * number of freed nodes for later and remember them in a single linked list
78 * using the Left link.
80 #define MAX_FREE_NODES 64
81 static ExprNode* FreeExprNodes = 0;
82 static unsigned FreeNodeCount = 0;
86 /*****************************************************************************/
88 /*****************************************************************************/
92 static ExprNode* NewExprNode (unsigned Op)
93 /* Create a new expression node */
97 /* Do we have some nodes in the list already? */
99 /* Use first node from list */
101 FreeExprNodes = N->Left;
104 /* Allocate fresh memory */
105 N = xmalloc (sizeof (ExprNode));
108 N->Left = N->Right = 0;
116 static void FreeExprNode (ExprNode* E)
120 if (E->Op == EXPR_SYMBOL) {
121 /* Remove the symbol reference */
122 SymDelExprRef (E->V.Sym, E);
124 /* Place the symbol into the free nodes list if possible */
125 if (FreeNodeCount < MAX_FREE_NODES) {
126 /* Remember this node for later */
127 E->Left = FreeExprNodes;
131 /* Free the memory */
139 /*****************************************************************************/
141 /*****************************************************************************/
145 static ExprNode* Expr0 (void);
149 int IsByteRange (long Val)
150 /* Return true if this is a byte value */
152 return (Val & ~0xFFL) == 0;
157 int IsWordRange (long Val)
158 /* Return true if this is a word value */
160 return (Val & ~0xFFFFL) == 0;
165 int IsFarRange (long Val)
166 /* Return true if this is a far (24 bit) value */
168 return (Val & ~0xFFFFFFL) == 0;
173 int IsEasyConst (const ExprNode* E, long* Val)
174 /* Do some light checking if the given node is a constant. Don't care if E is
175 * a complex expression. If E is a constant, return true and place its value
176 * into Val, provided that Val is not NULL.
179 /* Resolve symbols, follow symbol chains */
180 while (E->Op == EXPR_SYMBOL) {
181 E = SymResolve (E->V.Sym);
183 /* Could not resolve */
188 /* Symbols resolved, check for a literal */
189 if (E->Op == EXPR_LITERAL) {
196 /* Not found to be a const according to our tests */
202 static ExprNode* LoByte (ExprNode* Operand)
203 /* Return the low byte of the given expression */
208 /* Special handling for const expressions */
209 if (IsEasyConst (Operand, &Val)) {
211 Expr = GenLiteralExpr (Val & 0xFF);
213 /* Extract byte #0 */
214 Expr = NewExprNode (EXPR_BYTE0);
215 Expr->Left = Operand;
222 static ExprNode* HiByte (ExprNode* Operand)
223 /* Return the high byte of the given expression */
228 /* Special handling for const expressions */
229 if (IsEasyConst (Operand, &Val)) {
231 Expr = GenLiteralExpr ((Val >> 8) & 0xFF);
233 /* Extract byte #1 */
234 Expr = NewExprNode (EXPR_BYTE1);
235 Expr->Left = Operand;
242 static ExprNode* Bank (ExprNode* Operand)
243 /* Return the bank of the given segmented expression */
245 /* Generate the bank expression */
246 ExprNode* Expr = NewExprNode (EXPR_BANKRAW);
247 Expr->Left = Operand;
249 /* Return the result */
255 static ExprNode* BankByte (ExprNode* Operand)
256 /* Return the bank byte of the given expression */
261 /* Special handling for const expressions */
262 if (IsEasyConst (Operand, &Val)) {
264 Expr = GenLiteralExpr ((Val >> 16) & 0xFF);
266 /* Extract byte #2 */
267 Expr = NewExprNode (EXPR_BYTE2);
268 Expr->Left = Operand;
275 static ExprNode* LoWord (ExprNode* Operand)
276 /* Return the low word of the given expression */
281 /* Special handling for const expressions */
282 if (IsEasyConst (Operand, &Val)) {
284 Expr = GenLiteralExpr (Val & 0xFFFF);
286 /* Extract word #0 */
287 Expr = NewExprNode (EXPR_WORD0);
288 Expr->Left = Operand;
295 static ExprNode* HiWord (ExprNode* Operand)
296 /* Return the high word of the given expression */
301 /* Special handling for const expressions */
302 if (IsEasyConst (Operand, &Val)) {
304 Expr = GenLiteralExpr ((Val >> 16) & 0xFFFF);
306 /* Extract word #1 */
307 Expr = NewExprNode (EXPR_WORD1);
308 Expr->Left = Operand;
315 static ExprNode* Symbol (SymEntry* S)
316 /* Reference a symbol and return an expression for it */
319 /* Some weird error happened before */
320 return GenLiteralExpr (0);
322 /* Mark the symbol as referenced */
324 /* If the symbol is a variable, return just its value, otherwise
325 * return a reference to the symbol.
328 return CloneExpr (GetSymExpr (S));
330 /* Create symbol node */
331 return GenSymExpr (S);
338 ExprNode* FuncBank (void)
339 /* Handle the .BANK builtin function */
341 return Bank (Expression ());
346 ExprNode* FuncBankByte (void)
347 /* Handle the .BANKBYTE builtin function */
349 return BankByte (Expression ());
354 static ExprNode* FuncBlank (void)
355 /* Handle the .BLANK builtin function */
357 /* We have a list of tokens that ends with the closing paren. Skip
358 * the tokens, and count them. Allow optionally curly braces.
360 token_t Term = GetTokListTerm (TOK_RPAREN);
362 while (CurTok.Tok != Term) {
364 /* Check for end of line or end of input. Since the calling function
365 * will check for the closing paren, we don't need to print an error
366 * here, just bail out.
368 if (TokIsSep (CurTok.Tok)) {
379 /* If the list was enclosed in curly braces, skip the closing brace */
380 if (Term == TOK_RCURLY && CurTok.Tok == TOK_RCURLY) {
384 /* Return true if the list was empty */
385 return GenLiteralExpr (Count == 0);
390 static ExprNode* FuncConst (void)
391 /* Handle the .CONST builtin function */
393 /* Read an expression */
394 ExprNode* Expr = Expression ();
396 /* Check the constness of the expression */
397 ExprNode* Result = GenLiteralExpr (IsConstExpr (Expr, 0));
399 /* Free the expression */
408 static ExprNode* FuncDefined (void)
409 /* Handle the .DEFINED builtin function */
411 /* Parse the symbol name and search for the symbol */
412 SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING);
414 /* Check if the symbol is defined */
415 return GenLiteralExpr (Sym != 0 && SymIsDef (Sym));
420 ExprNode* FuncHiByte (void)
421 /* Handle the .HIBYTE builtin function */
423 return HiByte (Expression ());
428 static ExprNode* FuncHiWord (void)
429 /* Handle the .HIWORD builtin function */
431 return HiWord (Expression ());
436 ExprNode* FuncLoByte (void)
437 /* Handle the .LOBYTE builtin function */
439 return LoByte (Expression ());
444 static ExprNode* FuncLoWord (void)
445 /* Handle the .LOWORD builtin function */
447 return LoWord (Expression ());
452 static ExprNode* DoMatch (enum TC EqualityLevel)
453 /* Handle the .MATCH and .XMATCH builtin functions */
460 /* A list of tokens follows. Read this list and remember it building a
461 * single linked list of tokens including attributes. The list is
462 * either enclosed in curly braces, or terminated by a comma.
464 token_t Term = GetTokListTerm (TOK_COMMA);
465 while (CurTok.Tok != Term) {
467 /* We may not end-of-line of end-of-file here */
468 if (TokIsSep (CurTok.Tok)) {
469 Error ("Unexpected end of line");
470 return GenLiteral0 ();
473 /* Get a node with this token */
474 Node = NewTokNode ();
476 /* Insert the node into the list */
488 /* Skip the terminator token*/
491 /* If the token list was enclosed in curly braces, we expect a comma */
492 if (Term == TOK_RCURLY) {
496 /* Read the second list which is optionally enclosed in curly braces and
497 * terminated by the right parenthesis. Compare each token against the
498 * one in the first list.
500 Term = GetTokListTerm (TOK_RPAREN);
503 while (CurTok.Tok != Term) {
505 /* We may not end-of-line of end-of-file here */
506 if (TokIsSep (CurTok.Tok)) {
507 Error ("Unexpected end of line");
508 return GenLiteral0 ();
511 /* Compare the tokens if the result is not already known */
514 /* The second list is larger than the first one */
516 } else if (TokCmp (Node) < EqualityLevel) {
517 /* Tokens do not match */
522 /* Next token in first list */
527 /* Next token in current list */
531 /* If the token list was enclosed in curly braces, eat the closing brace */
532 if (Term == TOK_RCURLY) {
536 /* Check if there are remaining tokens in the first list */
541 /* Free the token list */
548 /* Done, return the result */
549 return GenLiteralExpr (Result);
554 static ExprNode* FuncMatch (void)
555 /* Handle the .MATCH function */
557 return DoMatch (tcSameToken);
562 static ExprNode* FuncMax (void)
563 /* Handle the .MAX function */
568 long LeftVal, RightVal;
570 /* Two arguments to the pseudo function */
571 Left = Expression ();
573 Right = Expression ();
575 /* Check if we can evaluate the value immediately */
576 if (IsEasyConst (Left, &LeftVal) && IsEasyConst (Right, &RightVal)) {
579 Expr = GenLiteralExpr ((LeftVal > RightVal)? LeftVal : RightVal);
581 /* Make an expression node */
582 Expr = NewExprNode (EXPR_MAX);
591 static ExprNode* FuncMin (void)
592 /* Handle the .MIN function */
597 long LeftVal, RightVal;
599 /* Two arguments to the pseudo function */
600 Left = Expression ();
602 Right = Expression ();
604 /* Check if we can evaluate the value immediately */
605 if (IsEasyConst (Left, &LeftVal) && IsEasyConst (Right, &RightVal)) {
608 Expr = GenLiteralExpr ((LeftVal < RightVal)? LeftVal : RightVal);
610 /* Make an expression node */
611 Expr = NewExprNode (EXPR_MIN);
620 static ExprNode* FuncReferenced (void)
621 /* Handle the .REFERENCED builtin function */
623 /* Parse the symbol name and search for the symbol */
624 SymEntry* Sym = ParseAnySymName (SYM_FIND_EXISTING);
626 /* Check if the symbol is referenced */
627 return GenLiteralExpr (Sym != 0 && SymIsRef (Sym));
632 static ExprNode* FuncSizeOf (void)
633 /* Handle the .SIZEOF function */
635 StrBuf ScopeName = STATIC_STRBUF_INITIALIZER;
636 StrBuf Name = STATIC_STRBUF_INITIALIZER;
644 /* Assume an error */
647 /* Check for a cheap local which needs special handling */
648 if (CurTok.Tok == TOK_LOCAL_IDENT) {
650 /* Cheap local symbol */
651 Sym = SymFindLocal (SymLast, &CurTok.SVal, SYM_FIND_EXISTING);
653 Error ("Unknown symbol or scope: `%m%p'", &CurTok.SVal);
655 SizeSym = GetSizeOfSymbol (Sym);
658 /* Remember and skip SVal, terminate ScopeName so it is empty */
659 SB_Copy (&Name, &CurTok.SVal);
661 SB_Terminate (&ScopeName);
665 /* Parse the scope and the name */
666 SymTable* ParentScope = ParseScopedIdent (&Name, &ScopeName);
668 /* Check if the parent scope is valid */
669 if (ParentScope == 0) {
671 SB_Done (&ScopeName);
673 return GenLiteral0 ();
676 /* If ScopeName is empty, no explicit scope was specified. We have to
677 * search upper scope levels in this case.
679 NoScope = SB_IsEmpty (&ScopeName);
681 /* First search for a scope with the given name */
683 Scope = SymFindAnyScope (ParentScope, &Name);
685 Scope = SymFindScope (ParentScope, &Name, SYM_FIND_EXISTING);
688 /* If we did find a scope with the name, read the symbol defining the
689 * size, otherwise search for a symbol entry with the name and scope.
692 /* Yep, it's a scope */
693 SizeSym = GetSizeOfScope (Scope);
696 Sym = SymFindAny (ParentScope, &Name);
698 Sym = SymFind (ParentScope, &Name, SYM_FIND_EXISTING);
701 /* If we found the symbol retrieve the size, otherwise complain */
703 SizeSym = GetSizeOfSymbol (Sym);
705 Error ("Unknown symbol or scope: `%m%p%m%p'",
711 /* Check if we have a size */
712 if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
713 Error ("Size of `%m%p%m%p' is unknown", &ScopeName, &Name);
717 /* Free the string buffers */
718 SB_Done (&ScopeName);
721 /* Return the size */
722 return GenLiteralExpr (Size);
727 static ExprNode* FuncStrAt (void)
728 /* Handle the .STRAT function */
730 StrBuf Str = STATIC_STRBUF_INITIALIZER;
734 /* String constant expected */
735 if (CurTok.Tok != TOK_STRCON) {
736 Error ("String constant expected");
741 /* Remember the string and skip it */
742 SB_Copy (&Str, &CurTok.SVal);
745 /* Comma must follow */
748 /* Expression expected */
749 Index = ConstExpression ();
751 /* Must be a valid index */
752 if (Index >= (long) SB_GetLen (&Str)) {
753 Error ("Range error");
757 /* Get the char, handle as unsigned. Be sure to translate it into
758 * the target character set.
760 C = TgtTranslateChar (SB_At (&Str, (unsigned)Index));
763 /* Free string buffer memory */
766 /* Return the char expression */
767 return GenLiteralExpr (C);
772 static ExprNode* FuncStrLen (void)
773 /* Handle the .STRLEN function */
777 /* String constant expected */
778 if (CurTok.Tok != TOK_STRCON) {
780 Error ("String constant expected");
781 /* Smart error recovery */
782 if (CurTok.Tok != TOK_RPAREN) {
789 /* Get the length of the string */
790 Len = SB_GetLen (&CurTok.SVal);
792 /* Skip the string */
796 /* Return the length */
797 return GenLiteralExpr (Len);
802 static ExprNode* FuncTCount (void)
803 /* Handle the .TCOUNT function */
805 /* We have a list of tokens that ends with the closing paren. Skip
806 * the tokens, and count them. Allow optionally curly braces.
808 token_t Term = GetTokListTerm (TOK_RPAREN);
810 while (CurTok.Tok != Term) {
812 /* Check for end of line or end of input. Since the calling function
813 * will check for the closing paren, we don't need to print an error
814 * here, just bail out.
816 if (TokIsSep (CurTok.Tok)) {
827 /* If the list was enclosed in curly braces, skip the closing brace */
828 if (Term == TOK_RCURLY && CurTok.Tok == TOK_RCURLY) {
832 /* Return the number of tokens */
833 return GenLiteralExpr (Count);
838 static ExprNode* FuncXMatch (void)
839 /* Handle the .XMATCH function */
841 return DoMatch (tcIdentical);
846 static ExprNode* Function (ExprNode* (*F) (void))
847 /* Handle builtin functions */
851 /* Skip the keyword */
854 /* Expression must be enclosed in braces */
855 if (CurTok.Tok != TOK_LPAREN) {
856 Error ("'(' expected");
858 return GenLiteral0 ();
862 /* Call the function itself */
865 /* Closing brace must follow */
868 /* Return the result of the actual function */
874 static ExprNode* Factor (void)
880 switch (CurTok.Tok) {
883 N = GenLiteralExpr (CurTok.IVal);
888 N = GenLiteralExpr (TgtTranslateChar (CurTok.IVal));
894 case TOK_LOCAL_IDENT:
895 N = Symbol (ParseAnySymName (SYM_ALLOC_NEW));
899 N = ULabRef (CurTok.IVal);
911 if (IsEasyConst (L, &Val)) {
913 N = GenLiteralExpr (-Val);
915 N = NewExprNode (EXPR_UNARY_MINUS);
923 if (IsEasyConst (L, &Val)) {
925 N = GenLiteralExpr (~Val);
927 N = NewExprNode (EXPR_NOT);
940 N = LoByte (Factor ());
945 N = HiByte (Factor ());
949 /* ^ means the bank byte of an expression */
951 N = BankByte (Factor ());
961 N = Function (FuncBank);
965 N = Function (FuncBankByte);
969 N = Function (FuncBlank);
973 N = Function (FuncConst);
977 N = GenLiteralExpr (CPUIsets[CPU]);
982 N = Function (FuncDefined);
986 N = Function (FuncHiByte);
990 N = Function (FuncHiWord);
994 N = Function (FuncLoByte);
998 N = Function (FuncLoWord);
1002 N = Function (FuncMatch);
1006 N = Function (FuncMax);
1010 N = Function (FuncMin);
1013 case TOK_REFERENCED:
1014 N = Function (FuncReferenced);
1018 N = Function (FuncSizeOf);
1022 N = Function (FuncStrAt);
1026 N = Function (FuncStrLen);
1030 N = Function (FuncTCount);
1034 N = GenLiteralExpr (time (0));
1039 N = GenLiteralExpr (GetVersionAsNumber ());
1044 N = Function (FuncXMatch);
1048 if (LooseCharTerm && CurTok.Tok == TOK_STRCON &&
1049 SB_GetLen (&CurTok.SVal) == 1) {
1050 /* A character constant */
1051 N = GenLiteralExpr (TgtTranslateChar (SB_At (&CurTok.SVal, 0)));
1053 N = GenLiteral0 (); /* Dummy */
1054 Error ("Syntax error");
1064 static ExprNode* Term (void)
1066 /* Read left hand side */
1067 ExprNode* Root = Factor ();
1069 /* Handle multiplicative operations */
1070 while (CurTok.Tok == TOK_MUL || CurTok.Tok == TOK_DIV ||
1071 CurTok.Tok == TOK_MOD || CurTok.Tok == TOK_AND ||
1072 CurTok.Tok == TOK_XOR || CurTok.Tok == TOK_SHL ||
1073 CurTok.Tok == TOK_SHR) {
1075 long LVal, RVal, Val;
1079 /* Remember the token and skip it */
1080 token_t T = CurTok.Tok;
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)) {
1097 Error ("Division by zero");
1106 Error ("Modulo operation with zero");
1122 Val = shl_l (LVal, RVal);
1126 Val = shr_l (LVal, RVal);
1130 Internal ("Invalid token");
1133 /* Generate a literal expression and delete the old left and
1138 Root = GenLiteralExpr (Val);
1142 /* Generate an expression tree */
1145 case TOK_MUL: Op = EXPR_MUL; break;
1146 case TOK_DIV: Op = EXPR_DIV; break;
1147 case TOK_MOD: Op = EXPR_MOD; break;
1148 case TOK_AND: Op = EXPR_AND; break;
1149 case TOK_XOR: Op = EXPR_XOR; break;
1150 case TOK_SHL: Op = EXPR_SHL; break;
1151 case TOK_SHR: Op = EXPR_SHR; break;
1152 default: Internal ("Invalid token");
1154 Root = NewExprNode (Op);
1156 Root->Right = Right;
1162 /* Return the expression tree we've created */
1168 static ExprNode* SimpleExpr (void)
1170 /* Read left hand side */
1171 ExprNode* Root = Term ();
1173 /* Handle additive operations */
1174 while (CurTok.Tok == TOK_PLUS ||
1175 CurTok.Tok == TOK_MINUS ||
1176 CurTok.Tok == TOK_OR) {
1178 long LVal, RVal, Val;
1182 /* Remember the token and skip it */
1183 token_t T = CurTok.Tok;
1186 /* Move root to left side and read the right side */
1190 /* If both expressions are constant, we can evaluate the term */
1191 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1194 case TOK_PLUS: Val = LVal + RVal; break;
1195 case TOK_MINUS: Val = LVal - RVal; break;
1196 case TOK_OR: Val = LVal | RVal; break;
1197 default: Internal ("Invalid token");
1200 /* Generate a literal expression and delete the old left and
1205 Root = GenLiteralExpr (Val);
1209 /* Generate an expression tree */
1212 case TOK_PLUS: Op = EXPR_PLUS; break;
1213 case TOK_MINUS: Op = EXPR_MINUS; break;
1214 case TOK_OR: Op = EXPR_OR; break;
1215 default: Internal ("Invalid token");
1217 Root = NewExprNode (Op);
1219 Root->Right = Right;
1224 /* Return the expression tree we've created */
1230 static ExprNode* BoolExpr (void)
1231 /* Evaluate a boolean expression */
1233 /* Read left hand side */
1234 ExprNode* Root = SimpleExpr ();
1236 /* Handle booleans */
1237 while (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_NE ||
1238 CurTok.Tok == TOK_LT || CurTok.Tok == TOK_GT ||
1239 CurTok.Tok == TOK_LE || CurTok.Tok == TOK_GE) {
1241 long LVal, RVal, Val;
1245 /* Remember the token and skip it */
1246 token_t T = CurTok.Tok;
1249 /* Move root to left side and read the right side */
1251 Right = SimpleExpr ();
1253 /* If both expressions are constant, we can evaluate the term */
1254 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1257 case TOK_EQ: Val = (LVal == RVal); break;
1258 case TOK_NE: Val = (LVal != RVal); break;
1259 case TOK_LT: Val = (LVal < RVal); break;
1260 case TOK_GT: Val = (LVal > RVal); break;
1261 case TOK_LE: Val = (LVal <= RVal); break;
1262 case TOK_GE: Val = (LVal >= RVal); break;
1263 default: Internal ("Invalid token");
1266 /* Generate a literal expression and delete the old left and
1271 Root = GenLiteralExpr (Val);
1275 /* Generate an expression tree */
1278 case TOK_EQ: Op = EXPR_EQ; break;
1279 case TOK_NE: Op = EXPR_NE; break;
1280 case TOK_LT: Op = EXPR_LT; break;
1281 case TOK_GT: Op = EXPR_GT; break;
1282 case TOK_LE: Op = EXPR_LE; break;
1283 case TOK_GE: Op = EXPR_GE; break;
1284 default: Internal ("Invalid token");
1286 Root = NewExprNode (Op);
1288 Root->Right = Right;
1293 /* Return the expression tree we've created */
1299 static ExprNode* Expr2 (void)
1300 /* Boolean operators: AND and XOR */
1302 /* Read left hand side */
1303 ExprNode* Root = BoolExpr ();
1305 /* Handle booleans */
1306 while (CurTok.Tok == TOK_BOOLAND || CurTok.Tok == TOK_BOOLXOR) {
1308 long LVal, RVal, Val;
1312 /* Remember the token and skip it */
1313 token_t T = CurTok.Tok;
1316 /* Move root to left side and read the right side */
1318 Right = BoolExpr ();
1320 /* If both expressions are constant, we can evaluate the term */
1321 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1324 case TOK_BOOLAND: Val = ((LVal != 0) && (RVal != 0)); break;
1325 case TOK_BOOLXOR: Val = ((LVal != 0) ^ (RVal != 0)); break;
1326 default: Internal ("Invalid token");
1329 /* Generate a literal expression and delete the old left and
1334 Root = GenLiteralExpr (Val);
1338 /* Generate an expression tree */
1341 case TOK_BOOLAND: Op = EXPR_BOOLAND; break;
1342 case TOK_BOOLXOR: Op = EXPR_BOOLXOR; break;
1343 default: Internal ("Invalid token");
1345 Root = NewExprNode (Op);
1347 Root->Right = Right;
1352 /* Return the expression tree we've created */
1358 static ExprNode* Expr1 (void)
1359 /* Boolean operators: OR */
1361 /* Read left hand side */
1362 ExprNode* Root = Expr2 ();
1364 /* Handle booleans */
1365 while (CurTok.Tok == TOK_BOOLOR) {
1367 long LVal, RVal, Val;
1371 /* Remember the token and skip it */
1372 token_t T = CurTok.Tok;
1375 /* Move root to left side and read the right side */
1379 /* If both expressions are constant, we can evaluate the term */
1380 if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
1383 case TOK_BOOLOR: Val = ((LVal != 0) || (RVal != 0)); break;
1384 default: Internal ("Invalid token");
1387 /* Generate a literal expression and delete the old left and
1392 Root = GenLiteralExpr (Val);
1396 /* Generate an expression tree */
1399 case TOK_BOOLOR: Op = EXPR_BOOLOR; break;
1400 default: Internal ("Invalid token");
1402 Root = NewExprNode (Op);
1404 Root->Right = Right;
1409 /* Return the expression tree we've created */
1415 static ExprNode* Expr0 (void)
1416 /* Boolean operators: NOT */
1420 /* Handle booleans */
1421 if (CurTok.Tok == TOK_BOOLNOT) {
1426 /* Skip the operator token */
1429 /* Read the argument */
1432 /* If the argument is const, evaluate it directly */
1433 if (IsEasyConst (Left, &Val)) {
1435 Root = GenLiteralExpr (!Val);
1437 Root = NewExprNode (EXPR_BOOLNOT);
1443 /* Read left hand side */
1448 /* Return the expression tree we've created */
1454 ExprNode* Expression (void)
1455 /* Evaluate an expression, build the expression tree on the heap and return
1456 * a pointer to the root of the tree.
1464 long ConstExpression (void)
1465 /* Parse an expression. Check if the expression is const, and print an error
1466 * message if not. Return the value of the expression, or a dummy, if it is
1472 /* Read the expression */
1473 ExprNode* Expr = Expression ();
1475 /* Study the expression */
1478 StudyExpr (Expr, &D);
1480 /* Check if the expression is constant */
1481 if (ED_IsConst (&D)) {
1484 Error ("Constant expression expected");
1488 /* Free the expression tree and allocated memory for D */
1492 /* Return the value */
1498 void FreeExpr (ExprNode* Root)
1499 /* Free the expression, Root is pointing to. */
1502 FreeExpr (Root->Left);
1503 FreeExpr (Root->Right);
1504 FreeExprNode (Root);
1510 ExprNode* SimplifyExpr (ExprNode* Expr, const ExprDesc* D)
1511 /* Try to simplify the given expression tree */
1513 if (Expr->Op != EXPR_LITERAL && ED_IsConst (D)) {
1514 /* No external references */
1516 Expr = GenLiteralExpr (D->Val);
1523 ExprNode* GenLiteralExpr (long Val)
1524 /* Return an expression tree that encodes the given literal value */
1526 ExprNode* Expr = NewExprNode (EXPR_LITERAL);
1533 ExprNode* GenLiteral0 (void)
1534 /* Return an expression tree that encodes the the number zero */
1536 return GenLiteralExpr (0);
1541 ExprNode* GenSymExpr (SymEntry* Sym)
1542 /* Return an expression node that encodes the given symbol */
1544 ExprNode* Expr = NewExprNode (EXPR_SYMBOL);
1546 SymAddExprRef (Sym, Expr);
1552 static ExprNode* GenSectionExpr (unsigned SecNum)
1553 /* Return an expression node for the given section */
1555 ExprNode* Expr = NewExprNode (EXPR_SECTION);
1556 Expr->V.SecNum = SecNum;
1562 static ExprNode* GenBankExpr (unsigned SecNum)
1563 /* Return an expression node for the given bank */
1565 ExprNode* Expr = NewExprNode (EXPR_BANK);
1566 Expr->V.SecNum = SecNum;
1572 ExprNode* GenAddExpr (ExprNode* Left, ExprNode* Right)
1573 /* Generate an addition from the two operands */
1576 if (IsEasyConst (Left, &Val) && Val == 0) {
1579 } else if (IsEasyConst (Right, &Val) && Val == 0) {
1583 ExprNode* Root = NewExprNode (EXPR_PLUS);
1585 Root->Right = Right;
1592 ExprNode* GenCurrentPC (void)
1593 /* Return the current program counter as expression */
1597 if (GetRelocMode ()) {
1598 /* Create SegmentBase + Offset */
1599 Root = GenAddExpr (GenSectionExpr (GetCurrentSegNum ()),
1600 GenLiteralExpr (GetPC ()));
1602 /* Absolute mode, just return PC value */
1603 Root = GenLiteralExpr (GetPC ());
1611 ExprNode* GenSwapExpr (ExprNode* Expr)
1612 /* Return an extended expression with lo and hi bytes swapped */
1614 ExprNode* N = NewExprNode (EXPR_SWAP);
1621 ExprNode* GenBranchExpr (unsigned Offs)
1622 /* Return an expression that encodes the difference between current PC plus
1623 * offset and the target expression (that is, Expression() - (*+Offs) ).
1630 /* Read Expression() */
1633 /* If the expression is a cheap constant, generate a simpler tree */
1634 if (IsEasyConst (N, &Val)) {
1636 /* Free the constant expression tree */
1639 /* Generate the final expression:
1641 * Val - ((Seg + PC) + Offs)
1642 * Val - Seg - PC - Offs
1643 * (Val - PC - Offs) - Seg
1645 Root = GenLiteralExpr (Val - GetPC () - Offs);
1646 if (GetRelocMode ()) {
1648 Root = NewExprNode (EXPR_MINUS);
1650 Root->Right = GenSectionExpr (GetCurrentSegNum ());
1655 /* Generate the expression:
1657 * N - ((Seg + PC) + Offs)
1658 * N - Seg - PC - Offs
1659 * N - (PC + Offs) - Seg
1661 Root = NewExprNode (EXPR_MINUS);
1663 Root->Right = GenLiteralExpr (GetPC () + Offs);
1664 if (GetRelocMode ()) {
1666 Root = NewExprNode (EXPR_MINUS);
1668 Root->Right = GenSectionExpr (GetCurrentSegNum ());
1672 /* Return the result */
1678 ExprNode* GenULabelExpr (unsigned Num)
1679 /* Return an expression for an unnamed label with the given index */
1681 ExprNode* Node = NewExprNode (EXPR_ULABEL);
1684 /* Return the new node */
1690 ExprNode* GenByteExpr (ExprNode* Expr)
1691 /* Force the given expression into a byte and return the result */
1693 /* Use the low byte operator to force the expression into byte size */
1694 return LoByte (Expr);
1699 ExprNode* GenWordExpr (ExprNode* Expr)
1700 /* Force the given expression into a word and return the result. */
1702 /* Use the low byte operator to force the expression into word size */
1703 return LoWord (Expr);
1708 ExprNode* GenNE (ExprNode* Expr, long Val)
1709 /* Generate an expression that compares Expr and Val for inequality */
1711 /* Generate a compare node */
1712 ExprNode* Root = NewExprNode (EXPR_NE);
1714 Root->Right = GenLiteralExpr (Val);
1716 /* Return the result */
1722 int IsConstExpr (ExprNode* Expr, long* Val)
1723 /* Return true if the given expression is a constant expression, that is, one
1724 * with no references to external symbols. If Val is not NULL and the
1725 * expression is constant, the constant value is stored here.
1730 /* Study the expression */
1733 StudyExpr (Expr, &D);
1735 /* Check if the expression is constant */
1736 IsConst = ED_IsConst (&D);
1737 if (IsConst && Val != 0) {
1741 /* Delete allocated memory and return the result */
1748 ExprNode* CloneExpr (ExprNode* Expr)
1749 /* Clone the given expression tree. The function will simply clone symbol
1750 * nodes, it will not resolve them.
1755 /* Accept NULL pointers */
1760 /* Clone the node */
1764 Clone = GenLiteralExpr (Expr->V.IVal);
1768 Clone = GenULabelExpr (Expr->V.IVal);
1772 Clone = GenSymExpr (Expr->V.Sym);
1776 Clone = GenSectionExpr (Expr->V.SecNum);
1780 Clone = GenBankExpr (Expr->V.SecNum);
1784 /* Generate a new node */
1785 Clone = NewExprNode (Expr->Op);
1786 /* Clone the tree nodes */
1787 Clone->Left = CloneExpr (Expr->Left);
1788 Clone->Right = CloneExpr (Expr->Right);
1798 ExprNode* FinalizeExpr (ExprNode* Expr, const Collection* LineInfos)
1799 /* Finalize an expression tree before it is written to the file. This will
1800 * replace EXPR_BANKRAW nodes by EXPR_BANK nodes, and replace constant
1801 * expressions by their result. The LineInfos are used when diagnosing errors.
1802 * Beware: The expression tree may get replaced in future versions, so don't
1803 * use Expr after calling this function.
1808 /* Check the type code */
1809 switch (EXPR_NODETYPE (Expr->Op)) {
1812 /* Nothing to do for leaf nodes */
1815 case EXPR_BINARYNODE:
1816 Expr->Left = FinalizeExpr (Expr->Left, LineInfos);
1817 Expr->Right = FinalizeExpr (Expr->Right, LineInfos);
1820 case EXPR_UNARYNODE:
1821 Expr->Left = FinalizeExpr (Expr->Left, LineInfos);
1823 /* Special handling for BANKRAW */
1824 if (Expr->Op == EXPR_BANKRAW) {
1826 /* Study the expression */
1828 StudyExpr (Expr->Left, &ED);
1830 /* The expression must be ok and must have exactly one segment
1833 if (ED.Flags & ED_TOO_COMPLEX) {
1835 "Cannot evaluate expression");
1836 } else if (ED.SecCount == 0) {
1838 ".BANK expects a segment reference");
1839 } else if (ED.SecCount > 1 || ED.SecRef[0].Count > 1) {
1841 "Too many segment references in argument to .BANK");
1845 FreeExpr (Expr->Left);
1846 Expr->Op = EXPR_BANK;
1848 Expr->V.SecNum = ED.SecRef[0].Ref;
1850 /* Mark the segment */
1851 S = CollAt (&SegmentList, Expr->V.SecNum);
1852 S->Flags |= SEG_FLAG_BANKREF;
1862 /* Return the (partial) tree */
1868 void WriteExpr (ExprNode* Expr)
1869 /* Write the given expression to the object file */
1871 /* Null expressions are encoded by a type byte of zero */
1873 ObjWrite8 (EXPR_NULL);
1877 /* If the is a leafnode, write the expression attribute, otherwise
1878 * write the expression operands.
1883 ObjWrite8 (EXPR_LITERAL);
1884 ObjWrite32 (Expr->V.IVal);
1888 if (SymIsImport (Expr->V.Sym)) {
1889 ObjWrite8 (EXPR_SYMBOL);
1890 ObjWriteVar (GetSymImportId (Expr->V.Sym));
1892 WriteExpr (GetSymExpr (Expr->V.Sym));
1897 ObjWrite8 (EXPR_SECTION);
1898 ObjWriteVar (Expr->V.SecNum);
1902 WriteExpr (ULabResolve (Expr->V.IVal));
1906 ObjWrite8 (EXPR_BANK);
1907 ObjWriteVar (Expr->V.SecNum);
1911 /* Not a leaf node */
1912 ObjWrite8 (Expr->Op);
1913 WriteExpr (Expr->Left);
1914 WriteExpr (Expr->Right);
1922 void ExprGuessedAddrSize (const ExprNode* Expr, unsigned char AddrSize)
1923 /* Mark the address size of the given expression tree as guessed. The address
1924 * size passed as argument is the one NOT used, because the actual address
1925 * size wasn't known. Example: Zero page addressing was not used because symbol
1926 * is undefined, and absolute addressing was available.
1927 * This function will actually parse the expression tree for undefined symbols,
1928 * and mark these symbols accordingly.
1931 /* Accept NULL expressions */
1936 /* Check the type code */
1937 switch (EXPR_NODETYPE (Expr->Op)) {
1940 if (Expr->Op == EXPR_SYMBOL) {
1941 if (!SymIsDef (Expr->V.Sym)) {
1942 /* Symbol is undefined, mark it */
1943 SymGuessedAddrSize (Expr->V.Sym, AddrSize);
1948 case EXPR_BINARYNODE:
1949 ExprGuessedAddrSize (Expr->Right, AddrSize);
1952 case EXPR_UNARYNODE:
1953 ExprGuessedAddrSize (Expr->Left, AddrSize);