]> git.sur5r.net Git - cc65/blobdiff - src/ca65/expr.c
New .FEATURE org_per_seg. If enabled, .org/.reloc do only influence the
[cc65] / src / ca65 / expr.c
index 02ae88a3670670741590bb84fce341f1567a9348..fc64f29c7e879fd0a14d38057cb0aa919dbb64c0 100644 (file)
@@ -6,8 +6,8 @@
 /*                                                                           */
 /*                                                                           */
 /*                                                                           */
-/* (C) 1998-2003 Ullrich von Bassewitz                                       */
-/*               Römerstrasse 52                                             */
+/* (C) 1998-2007 Ullrich von Bassewitz                                       */
+/*               Roemerstrasse 52                                            */
 /*               D-70794 Filderstadt                                         */
 /* EMail:        uz@cc65.org                                                 */
 /*                                                                           */
@@ -41,6 +41,8 @@
 #include "cpu.h"
 #include "exprdefs.h"
 #include "print.h"
+#include "shift.h"
+#include "strbuf.h"
 #include "tgttrans.h"
 #include "version.h"
 #include "xmalloc.h"
@@ -53,6 +55,8 @@
 #include "nexttok.h"
 #include "objfile.h"
 #include "segment.h"
+#include "sizeof.h"
+#include "studyexpr.h"
 #include "symbol.h"
 #include "symtab.h"
 #include "toklist.h"
  * using the Left link.
  */
 #define        MAX_FREE_NODES  64
-static ExprNode*       FreeExprNodes = 0;
-static unsigned                FreeNodeCount = 0;
+static ExprNode*       FreeExprNodes = 0;
+static unsigned                FreeNodeCount = 0;
 
 
 
 /*****************************************************************************/
-/*                                 Helpers                                  */
+/*                                 Helpers                                  */
 /*****************************************************************************/
 
 
@@ -150,51 +154,223 @@ int IsByteRange (long Val)
 int IsWordRange (long Val)
 /* Return true if this is a word value */
 {
-    return (Val & ~0xFFFF) == 0;
+    return (Val & ~0xFFFFL) == 0;
 }
 
 
 
-static int FuncBlank (void)
+int IsFarRange (long Val)
+/* Return true if this is a far (24 bit) value */
+{
+    return (Val & ~0xFFFFFFL) == 0;
+}
+
+
+
+static int IsEasyConst (const ExprNode* E, long* Val)
+/* Do some light checking if the given node is a constant. Don't care if E is
+ * a complex expression. If E is a constant, return true and place its value
+ * into Val, provided that Val is not NULL.
+ */
+{
+    /* Resolve symbols, follow symbol chains */
+    while (E->Op == EXPR_SYMBOL) {
+        E = SymResolve (E->V.Sym);
+        if (E == 0) {
+            /* Could not resolve */
+            return 0;
+        }
+    }
+
+    /* Symbols resolved, check for a literal */
+    if (E->Op == EXPR_LITERAL) {
+        if (Val) {
+            *Val = E->V.Val;
+        }
+        return 1;
+    }
+
+    /* Not found to be a const according to our tests */
+    return 0;
+}
+
+
+
+static ExprNode* LoByte (ExprNode* Operand)
+/* Return the low byte of the given expression */
+{
+    ExprNode* Expr;
+    long      Val;
+
+    /* Special handling for const expressions */
+    if (IsEasyConst (Operand, &Val)) {
+        FreeExpr (Operand);
+        Expr = GenLiteralExpr (Val & 0xFF);
+    } else {
+        /* Extract byte #0 */
+        Expr = NewExprNode (EXPR_BYTE0);
+        Expr->Left = Operand;
+    }
+    return Expr;
+}
+
+
+
+static ExprNode* HiByte (ExprNode* Operand)
+/* Return the high byte of the given expression */
+{
+    ExprNode* Expr;
+    long      Val;
+
+    /* Special handling for const expressions */
+    if (IsEasyConst (Operand, &Val)) {
+        FreeExpr (Operand);
+        Expr = GenLiteralExpr ((Val >> 8) & 0xFF);
+    } else {
+        /* Extract byte #1 */
+        Expr = NewExprNode (EXPR_BYTE1);
+        Expr->Left = Operand;
+    }
+    return Expr;
+}
+
+
+
+static ExprNode* BankByte (ExprNode* Operand)
+/* Return the bank byte of the given expression */
+{
+    ExprNode* Expr;
+    long      Val;
+
+    /* Special handling for const expressions */
+    if (IsEasyConst (Operand, &Val)) {
+        FreeExpr (Operand);
+        Expr = GenLiteralExpr ((Val >> 16) & 0xFF);
+    } else {
+        /* Extract byte #2 */
+        Expr = NewExprNode (EXPR_BYTE2);
+        Expr->Left = Operand;
+    }
+    return Expr;
+}
+
+
+
+static ExprNode* LoWord (ExprNode* Operand)
+/* Return the low word of the given expression */
+{
+    ExprNode* Expr;
+    long      Val;
+
+    /* Special handling for const expressions */
+    if (IsEasyConst (Operand, &Val)) {
+        FreeExpr (Operand);
+        Expr = GenLiteralExpr (Val & 0xFFFF);
+    } else {
+        /* Extract word #0 */
+        Expr = NewExprNode (EXPR_WORD0);
+        Expr->Left = Operand;
+    }
+    return Expr;
+}
+
+
+
+static ExprNode* HiWord (ExprNode* Operand)
+/* Return the high word of the given expression */
+{
+    ExprNode* Expr;
+    long      Val;
+
+    /* Special handling for const expressions */
+    if (IsEasyConst (Operand, &Val)) {
+        FreeExpr (Operand);
+        Expr = GenLiteralExpr ((Val >> 16) & 0xFFFF);
+    } else {
+        /* Extract word #1 */
+        Expr = NewExprNode (EXPR_WORD1);
+        Expr->Left = Operand;
+    }
+    return Expr;
+}
+
+
+
+static ExprNode* Symbol (SymEntry* S)
+/* Reference a symbol and return an expression for it */
+{
+    if (S == 0) {
+        /* Some weird error happened before */
+        return GenLiteralExpr (0);
+    } else {
+        /* Mark the symbol as referenced */
+        SymRef (S);
+        /* If the symbol is a variable, return just its value, otherwise
+         * return a reference to the symbol.
+         */
+        if (SymIsVar (S)) {
+            return CloneExpr (GetSymExpr (S));
+        } else {
+            /* Create symbol node */
+            return GenSymExpr (S);
+        }
+    }
+}
+
+
+
+static ExprNode* FuncBankByte (void)
+/* Handle the .BANKBYTE builtin function */
+{
+    return BankByte (Expression ());
+}
+
+
+
+static ExprNode* FuncBlank (void)
 /* Handle the .BLANK builtin function */
 {
-    /* Assume no tokens if the closing brace follows (this is not correct in
-     * all cases, since the token may be the closing brace, but this will
-     * give a syntax error anyway and may not be handled by .BLANK.
+    /* We have a list of tokens that ends with the closing paren. Skip
+     * the tokens, and count them. Allow optionally curly braces.
      */
-    if (Tok == TOK_RPAREN) {
-       /* No tokens */
-       return 1;
-    } else {
-       /* Skip any tokens */
-       int Braces = 0;
-       while (!TokIsSep (Tok)) {
-           if (Tok == TOK_LPAREN) {
-               ++Braces;
-           } else if (Tok == TOK_RPAREN) {
-               if (Braces == 0) {
-                   /* Done */
-                   break;
-               } else {
-                   --Braces;
-               }
-           }
-           NextTok ();
+    enum Token Term = GetTokListTerm (TOK_RPAREN);
+    unsigned Count = 0;
+    while (Tok != Term) {
+
+       /* Check for end of line or end of input. Since the calling function
+        * will check for the closing paren, we don't need to print an error
+        * here, just bail out.
+        */
+       if (TokIsSep (Tok)) {
+           break;
        }
-       return 0;
+
+       /* One more token */
+       ++Count;
+
+       /* Skip the token */
+       NextTok ();
+    }
+
+    /* If the list was enclosed in curly braces, skip the closing brace */
+    if (Term == TOK_RCURLY && Tok == TOK_RCURLY) {
+        NextTok ();
     }
+
+    /* Return true if the list was empty */
+    return GenLiteralExpr (Count == 0);
 }
 
 
 
-static int FuncConst (void)
+static ExprNode* FuncConst (void)
 /* Handle the .CONST builtin function */
 {
     /* Read an expression */
     ExprNode* Expr = Expression ();
 
     /* Check the constness of the expression */
-    int Result = IsConstExpr (Expr);
+    ExprNode* Result = GenLiteralExpr (IsConstExpr (Expr, 0));
 
     /* Free the expression */
     FreeExpr (Expr);
@@ -205,36 +381,69 @@ static int FuncConst (void)
 
 
 
-static int FuncDefined (void)
+static ExprNode* FuncDefined (void)
 /* Handle the .DEFINED builtin function */
 {
     /* Parse the symbol name and search for the symbol */
     SymEntry* Sym = ParseScopedSymName (SYM_FIND_EXISTING);
 
     /* Check if the symbol is defined */
-    return (Sym != 0 && SymIsDef (Sym));
+    return GenLiteralExpr (Sym != 0 && SymIsDef (Sym));
+}
+
+
+
+static ExprNode* FuncHiByte (void)
+/* Handle the .HIBYTE builtin function */
+{
+    return HiByte (Expression ());
 }
 
 
 
-static int DoMatch (enum TC EqualityLevel)
+static ExprNode* FuncHiWord (void)
+/* Handle the .HIWORD builtin function */
+{
+    return HiWord (Expression ());
+}
+
+
+
+static ExprNode* FuncLoByte (void)
+/* Handle the .LOBYTE builtin function */
+{
+    return LoByte (Expression ());
+}
+
+
+
+static ExprNode* FuncLoWord (void)
+/* Handle the .LOWORD builtin function */
+{
+    return LoWord (Expression ());
+}
+
+
+
+static ExprNode* DoMatch (enum TC EqualityLevel)
 /* Handle the .MATCH and .XMATCH builtin functions */
 {
     int Result;
     TokNode* Root = 0;
     TokNode* Last = 0;
-    TokNode* Node = 0;
+    TokNode* Node;
 
     /* A list of tokens follows. Read this list and remember it building a
      * single linked list of tokens including attributes. The list is
-     * terminated by a comma.
+     * either enclosed in curly braces, or terminated by a comma.
      */
-    while (Tok != TOK_COMMA) {
+    enum Token Term = GetTokListTerm (TOK_COMMA);
+    while (Tok != Term) {
 
        /* We may not end-of-line of end-of-file here */
        if (TokIsSep (Tok)) {
-           Error (ERR_UNEXPECTED_EOL);
-           return 0;
+           Error ("Unexpected end of line");
+           return GenLiteral0 ();
        }
 
        /* Get a node with this token */
@@ -252,23 +461,30 @@ static int DoMatch (enum TC EqualityLevel)
        NextTok ();
     }
 
-    /* Skip the comma */
+    /* Skip the terminator token*/
     NextTok ();
 
-    /* Read the second list which is terminated by the right parenthesis and
-     * compare each token against the one in the first list.
+    /* If the token list was enclosed in curly braces, we expect a comma */
+    if (Term == TOK_RCURLY) {
+        ConsumeComma ();
+    }
+
+    /* Read the second list which is optionally enclosed in curly braces and
+     * terminated by the right parenthesis. Compare each token against the
+     * one in the first list.
      */
+    Term = GetTokListTerm (TOK_RPAREN);
     Result = 1;
     Node = Root;
-    while (Tok != TOK_RPAREN) {
+    while (Tok != Term) {
 
        /* We may not end-of-line of end-of-file here */
        if (TokIsSep (Tok)) {
-           Error (ERR_UNEXPECTED_EOL);
-           return 0;
+           Error ("Unexpected end of line");
+           return GenLiteral0 ();
        }
 
-       /* Compare the tokens if the result is not already known */
+               /* Compare the tokens if the result is not already known */
        if (Result != 0) {
            if (Node == 0) {
                /* The second list is larger than the first one */
@@ -288,6 +504,11 @@ static int DoMatch (enum TC EqualityLevel)
        NextTok ();
     }
 
+    /* If the token list was enclosed in curly braces, eat the closing brace */
+    if (Term == TOK_RCURLY) {
+        NextTok ();
+    }
+
     /* Check if there are remaining tokens in the first list */
     if (Node != 0) {
        Result = 0;
@@ -301,12 +522,12 @@ static int DoMatch (enum TC EqualityLevel)
     }
 
     /* Done, return the result */
-    return Result;
+    return GenLiteralExpr (Result);
 }
 
 
 
-static int FuncMatch (void)
+static ExprNode* FuncMatch (void)
 /* Handle the .MATCH function */
 {
     return DoMatch (tcSameToken);
@@ -314,30 +535,123 @@ static int FuncMatch (void)
 
 
 
-static int FuncReferenced (void)
+static ExprNode* FuncReferenced (void)
 /* Handle the .REFERENCED builtin function */
 {
     /* Parse the symbol name and search for the symbol */
     SymEntry* Sym = ParseScopedSymName (SYM_FIND_EXISTING);
 
     /* Check if the symbol is referenced */
-    return (Sym != 0 && SymIsRef (Sym));
+    return GenLiteralExpr (Sym != 0 && SymIsRef (Sym));
+}
+
+
+
+static ExprNode* FuncSizeOf (void)
+/* Handle the .SIZEOF function */
+{
+    StrBuf    ScopeName = AUTO_STRBUF_INITIALIZER;
+    char      Name[sizeof (SVal)];
+    SymTable* Scope;
+    SymEntry* Sym;
+    SymEntry* SizeSym;
+    long      Size;
+    int       NoScope;
+
+
+    /* Assume an error */
+    SizeSym = 0;
+
+    /* Check for a cheap local which needs special handling */
+    if (Tok == TOK_LOCAL_IDENT) {
+
+        /* Cheap local symbol */
+        Sym = SymFindLocal (SymLast, SVal, SYM_FIND_EXISTING);
+        if (Sym == 0) {
+            Error ("Unknown symbol or scope: `%s'", SVal);
+        } else {
+            SizeSym = GetSizeOfSymbol (Sym);
+        }
+
+        /* Remember and skip SVal, terminate ScopeName so it is empty */
+        strcpy (Name, SVal);
+        NextTok ();
+        SB_Terminate (&ScopeName);
+
+    } else {
+
+        /* Parse the scope and the name */
+        SymTable* ParentScope = ParseScopedIdent (Name, &ScopeName);
+
+        /* Check if the parent scope is valid */
+        if (ParentScope == 0) {
+            /* No such scope */
+            DoneStrBuf (&ScopeName);
+            return GenLiteral0 ();
+        }
+
+        /* If ScopeName is empty, no explicit scope was specified. We have to
+         * search upper scope levels in this case.
+         */
+        NoScope = SB_IsEmpty (&ScopeName);
+
+        /* First search for a scope with the given name */
+        if (NoScope) {
+            Scope = SymFindAnyScope (ParentScope, Name);
+        } else {
+            Scope = SymFindScope (ParentScope, Name, SYM_FIND_EXISTING);
+        }
+
+        /* If we did find a scope with the name, read the symbol defining the
+         * size, otherwise search for a symbol entry with the name and scope.
+         */
+        if (Scope) {
+            /* Yep, it's a scope */
+            SizeSym = GetSizeOfScope (Scope);
+        } else {
+            if (NoScope) {
+                Sym = SymFindAny (ParentScope, Name);
+            } else {
+                Sym = SymFind (ParentScope, Name, SYM_FIND_EXISTING);
+            }
+
+            /* If we found the symbol retrieve the size, otherwise complain */
+            if (Sym) {
+                SizeSym = GetSizeOfSymbol (Sym);
+            } else {
+                Error ("Unknown symbol or scope: `%s%s'",
+                       SB_GetConstBuf (&ScopeName), Name);
+            }
+        }
+    }
+
+    /* Check if we have a size */
+    if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
+        Error ("Size of `%s%s' is unknown", SB_GetConstBuf (&ScopeName), Name);
+        Size = 0;
+    }
+
+    /* Free the scope name */
+    DoneStrBuf (&ScopeName);
+
+    /* Return the size */
+    return GenLiteralExpr (Size);
 }
 
 
 
-static int FuncStrAt (void)
+static ExprNode* FuncStrAt (void)
 /* Handle the .STRAT function */
 {
     char Str [sizeof(SVal)];
     long Index;
+    unsigned char C;
 
     /* String constant expected */
     if (Tok != TOK_STRCON) {
-       Error (ERR_STRCON_EXPECTED);
+       Error ("String constant expected");
        NextTok ();
-               return 0;
-
+               return GenLiteral0 ();
     }
 
     /* Remember the string and skip it */
@@ -352,56 +666,60 @@ static int FuncStrAt (void)
 
     /* Must be a valid index */
     if (Index >= (long) strlen (Str)) {
-       Error (ERR_RANGE);
-       return 0;
+       Error ("Range error");
+       return GenLiteral0 ();
     }
 
-    /* Return the char, handle as unsigned. Be sure to translate it into
+    /* Get the char, handle as unsigned. Be sure to translate it into
      * the target character set.
      */
-    return (unsigned char) TgtTranslateChar (Str [(size_t)Index]);
+    C = TgtTranslateChar (Str [(size_t)Index]);
+
+    /* Return the char expression */
+    return GenLiteralExpr (C);
 }
 
 
 
-static int FuncStrLen (void)
+static ExprNode* FuncStrLen (void)
 /* Handle the .STRLEN function */
 {
+    int Len;
+
     /* String constant expected */
     if (Tok != TOK_STRCON) {
 
-       Error (ERR_STRCON_EXPECTED);
+       Error ("String constant expected");
        /* Smart error recovery */
        if (Tok != TOK_RPAREN) {
            NextTok ();
        }
-               return 0;
+               Len = 0;
 
     } else {
 
         /* Get the length of the string */
-       int Len = strlen (SVal);
+       Len = strlen (SVal);
 
        /* Skip the string */
        NextTok ();
-
-       /* Return the length */
-       return Len;
-
     }
+
+    /* Return the length */
+    return GenLiteralExpr (Len);
 }
 
 
 
-static int FuncTCount (void)
+static ExprNode* FuncTCount (void)
 /* Handle the .TCOUNT function */
 {
     /* We have a list of tokens that ends with the closing paren. Skip
-     * the tokens, handling nested braces and count them.
+     * the tokens, and count them. Allow optionally curly braces.
      */
-    int      Count  = 0;
-    unsigned Parens = 0;
-    while (Parens != 0 || Tok != TOK_RPAREN) {
+    enum Token Term = GetTokListTerm (TOK_RPAREN);
+    int Count = 0;
+    while (Tok != Term) {
 
        /* Check for end of line or end of input. Since the calling function
         * will check for the closing paren, we don't need to print an error
@@ -414,24 +732,22 @@ static int FuncTCount (void)
        /* One more token */
        ++Count;
 
-       /* Keep track of the nesting level */
-       switch (Tok) {
-           case TOK_LPAREN:    ++Parens;       break;
-           case TOK_RPAREN:    --Parens;       break;
-           default:                            break;
-       }
-
        /* Skip the token */
        NextTok ();
     }
 
+    /* If the list was enclosed in curly braces, skip the closing brace */
+    if (Term == TOK_RCURLY && Tok == TOK_RCURLY) {
+        NextTok ();
+    }
+
     /* Return the number of tokens */
-    return Count;
+    return GenLiteralExpr (Count);
 }
 
 
 
-static int FuncXMatch (void)
+static ExprNode* FuncXMatch (void)
 /* Handle the .XMATCH function */
 {
     return DoMatch (tcIdentical);
@@ -439,38 +755,39 @@ static int FuncXMatch (void)
 
 
 
-static ExprNode* Function (int (*F) (void))
+static ExprNode* Function (ExprNode* (*F) (void))
 /* Handle builtin functions */
 {
-    long Result;
+    ExprNode* E;
 
     /* Skip the keyword */
     NextTok ();
 
     /* Expression must be enclosed in braces */
     if (Tok != TOK_LPAREN) {
-       Error (ERR_LPAREN_EXPECTED);
+       Error ("'(' expected");
        SkipUntilSep ();
-       return GenLiteralExpr (0);
+       return GenLiteral0 ();
     }
     NextTok ();
 
     /* Call the function itself */
-    Result = F ();
+    E = F ();
 
     /* Closing brace must follow */
     ConsumeRParen ();
 
-    /* Return an expression node with the boolean code */
-    return GenLiteralExpr (Result);
+    /* Return the result of the actual function */
+    return E;
 }
 
 
 
 static ExprNode* Factor (void)
 {
+    ExprNode* L;
     ExprNode* N;
-    SymEntry* S;
+    long      Val;
 
     switch (Tok) {
 
@@ -486,34 +803,46 @@ static ExprNode* Factor (void)
 
        case TOK_NAMESPACE:
        case TOK_IDENT:
-           /* Search for the symbol */
-           S = ParseScopedSymName (SYM_ALLOC_NEW);
-           if (S == 0) {
-               /* Some weird error happened before */
-               N = GenLiteralExpr (0);
-           } else {
-               /* Mark the symbol as referenced */
-               SymRef (S);
-               /* Create symbol node */
-               N = GenSymExpr (S);
-           }
+            N = Symbol (ParseScopedSymName (SYM_ALLOC_NEW));
            break;
 
+        case TOK_LOCAL_IDENT:
+            N = Symbol (SymFindLocal (SymLast, SVal, SYM_ALLOC_NEW));
+            NextTok ();
+            break;
+
        case TOK_ULABEL:
            N = ULabRef (IVal);
            NextTok ();
            break;
 
+        case TOK_PLUS:
+            NextTok ();
+            N = Factor ();
+            break;
+
        case TOK_MINUS:
            NextTok ();
-           N = NewExprNode (EXPR_UNARY_MINUS);
-                   N->Left = Factor ();
+            L = Factor ();
+            if (IsEasyConst (L, &Val)) {
+                FreeExpr (L);
+                N = GenLiteralExpr (-Val);
+            } else {
+                N = NewExprNode (EXPR_UNARY_MINUS);
+                       N->Left = L;
+            }
            break;
 
        case TOK_NOT:
            NextTok ();
-           N = NewExprNode (EXPR_NOT);
-           N->Left = Factor ();
+            L = Factor ();
+            if (IsEasyConst (L, &Val)) {
+                FreeExpr (L);
+                N = GenLiteralExpr (~Val);
+            } else {
+                N = NewExprNode (EXPR_NOT);
+                N->Left = L;
+            }
            break;
 
        case TOK_STAR:
@@ -524,22 +853,29 @@ static ExprNode* Factor (void)
 
        case TOK_LT:
            NextTok ();
-           N = NewExprNode (EXPR_BYTE0);
-           N->Left = Factor ();
+            N = LoByte (Factor ());
            break;
 
        case TOK_GT:
            NextTok ();
-           N = NewExprNode (EXPR_BYTE1);
-           N->Left = Factor ();
+            N = HiByte (Factor ());
            break;
 
+        case TOK_BANK:
+            NextTok ();
+            N = BankByte (Factor ());
+            break;
+
        case TOK_LPAREN:
            NextTok ();
            N = Expr0 ();
                    ConsumeRParen ();
            break;
 
+        case TOK_BANKBYTE:
+            N = Function (FuncBankByte);
+            break;
+
         case TOK_BLANK:
            N = Function (FuncBlank);
            break;
@@ -557,6 +893,22 @@ static ExprNode* Factor (void)
            N = Function (FuncDefined);
            break;
 
+        case TOK_HIBYTE:
+            N = Function (FuncHiByte);
+            break;
+
+        case TOK_HIWORD:
+            N = Function (FuncHiWord);
+            break;
+
+        case TOK_LOBYTE:
+            N = Function (FuncLoByte);
+            break;
+
+        case TOK_LOWORD:
+            N = Function (FuncLoWord);
+            break;
+
        case TOK_MATCH:
            N = Function (FuncMatch);
            break;
@@ -565,6 +917,10 @@ static ExprNode* Factor (void)
            N = Function (FuncReferenced);
            break;
 
+        case TOK_SIZEOF:
+            N = Function (FuncSizeOf);
+            break;
+
        case TOK_STRAT:
            N = Function (FuncStrAt);
            break;
@@ -587,7 +943,6 @@ static ExprNode* Factor (void)
             NextTok ();
             break;
 
-
        case TOK_XMATCH:
            N = Function (FuncXMatch);
            break;
@@ -597,8 +952,8 @@ static ExprNode* Factor (void)
                /* A character constant */
                N = GenLiteralExpr (TgtTranslateChar (SVal[0]));
            } else {
-               N = GenLiteralExpr (0); /* Dummy */
-               Error (ERR_SYNTAX);
+               N = GenLiteral0 ();     /* Dummy */
+               Error ("Syntax error");
            }
            NextTok ();
            break;
@@ -618,25 +973,90 @@ static ExprNode* Term (void)
           Tok == TOK_AND || Tok == TOK_XOR || Tok == TOK_SHL ||
           Tok == TOK_SHR) {
 
-       /* Create the new node */
-       ExprNode* Left = Root;
-       switch (Tok) {
-                   case TOK_MUL:       Root = NewExprNode (EXPR_MUL);  break;
-                   case TOK_DIV:       Root = NewExprNode (EXPR_DIV);  break;
-                   case TOK_MOD:       Root = NewExprNode (EXPR_MOD);  break;
-                   case TOK_AND:       Root = NewExprNode (EXPR_AND);  break;
-                   case TOK_XOR:       Root = NewExprNode (EXPR_XOR);  break;
-                   case TOK_SHL:       Root = NewExprNode (EXPR_SHL);  break;
-                   case TOK_SHR:       Root = NewExprNode (EXPR_SHR);  break;
-           default:            Internal ("Invalid token");
-       }
-       Root->Left = Left;
-
-        /* Skip the operator token */
-       NextTok ();
+        long LVal, RVal, Val;
+        ExprNode* Left;
+        ExprNode* Right;
+
+        /* Remember the token and skip it */
+        enum Token T = Tok;
+        NextTok ();
+
+        /* Move root to left side and read the right side */
+        Left  = Root;
+        Right = Factor ();
+
+        /* If both expressions are constant, we can evaluate the term */
+        if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
+
+            switch (T) {
+                case TOK_MUL:
+                    Val = LVal * RVal;
+                    break;
+
+                case TOK_DIV:
+                    if (RVal == 0) {
+                        Error ("Division by zero");
+                        Val = 1;
+                    } else {
+                        Val = LVal / RVal;
+                    }
+                    break;
+
+                case TOK_MOD:
+                    if (RVal == 0) {
+                        Error ("Modulo operation with zero");
+                        Val = 1;
+                    } else {
+                        Val = LVal % RVal;
+                    }
+                    break;
+
+                case TOK_AND:
+                    Val = LVal & RVal;
+                    break;
+
+                case TOK_XOR:
+                    Val = LVal ^ RVal;
+                    break;
+
+                case TOK_SHL:
+                    Val = shl_l (LVal, RVal);
+                    break;
+
+                case TOK_SHR:
+                    Val = shr_l (LVal, RVal);
+                    break;
+
+                default:
+                    Internal ("Invalid token");
+            }
+
+            /* Generate a literal expression and delete the old left and
+             * right sides.
+             */
+            FreeExpr (Left);
+            FreeExpr (Right);
+            Root = GenLiteralExpr (Val);
+
+        } else {
+
+            /* Generate an expression tree */
+            unsigned char Op;
+            switch (T) {
+                case TOK_MUL:   Op = EXPR_MUL; break;
+                case TOK_DIV:   Op = EXPR_DIV;  break;
+                case TOK_MOD:   Op = EXPR_MOD;  break;
+                case TOK_AND:   Op = EXPR_AND;  break;
+                case TOK_XOR:   Op = EXPR_XOR;  break;
+                case TOK_SHL:   Op = EXPR_SHL;  break;
+                case TOK_SHR:   Op = EXPR_SHR;  break;
+                default:               Internal ("Invalid token");
+            }
+            Root        = NewExprNode (Op);
+            Root->Left  = Left;
+            Root->Right = Right;
 
-       /* Parse the right hand side */
-       Root->Right = Factor ();
+        }
 
     }
 
@@ -654,22 +1074,50 @@ static ExprNode* SimpleExpr (void)
     /* Handle additive operations */
     while (Tok == TOK_PLUS || Tok == TOK_MINUS || Tok == TOK_OR) {
 
-       /* Create the new node */
-       ExprNode* Left = Root;
-       switch (Tok) {
-                   case TOK_PLUS:      Root = NewExprNode (EXPR_PLUS);         break;
-                   case TOK_MINUS:     Root = NewExprNode (EXPR_MINUS);        break;
-                   case TOK_OR:        Root = NewExprNode (EXPR_OR);           break;
-           default:            Internal ("Invalid token");
-       }
-       Root->Left = Left;
-
-        /* Skip the operator token */
-       NextTok ();
-
-       /* Parse the right hand side */
-       Root->Right = Term ();
+        long LVal, RVal, Val;
+        ExprNode* Left;
+        ExprNode* Right;
+
+        /* Remember the token and skip it */
+        enum Token T = Tok;
+        NextTok ();
+
+        /* Move root to left side and read the right side */
+        Left  = Root;
+        Right = Term ();
+
+        /* If both expressions are constant, we can evaluate the term */
+        if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
+
+            switch (T) {
+                case TOK_PLUS:  Val = LVal + RVal;      break;
+                case TOK_MINUS: Val = LVal - RVal;      break;
+                case TOK_OR:    Val = LVal | RVal;      break;
+                default:        Internal ("Invalid token");
+            }
+
+            /* Generate a literal expression and delete the old left and
+             * right sides.
+             */
+            FreeExpr (Left);
+            FreeExpr (Right);
+            Root = GenLiteralExpr (Val);
+
+        } else {
+
+            /* Generate an expression tree */
+            unsigned char Op;
+            switch (T) {
+                case TOK_PLUS:  Op = EXPR_PLUS;  break;
+                case TOK_MINUS: Op = EXPR_MINUS; break;
+                case TOK_OR:    Op = EXPR_OR;    break;
+                default:               Internal ("Invalid token");
+            }
+            Root        = NewExprNode (Op);
+            Root->Left  = Left;
+            Root->Right = Right;
 
+        }
     }
 
     /* Return the expression tree we've created */
@@ -688,25 +1136,56 @@ static ExprNode* BoolExpr (void)
     while (Tok == TOK_EQ || Tok == TOK_NE || Tok == TOK_LT ||
           Tok == TOK_GT || Tok == TOK_LE || Tok == TOK_GE) {
 
-       /* Create the new node */
-       ExprNode* Left = Root;
-       switch (Tok) {
-                   case TOK_EQ:        Root = NewExprNode (EXPR_EQ);   break;
-                   case TOK_NE:        Root = NewExprNode (EXPR_NE);   break;
-                   case TOK_LT:        Root = NewExprNode (EXPR_LT);   break;
-                   case TOK_GT:        Root = NewExprNode (EXPR_GT);   break;
-                   case TOK_LE:        Root = NewExprNode (EXPR_LE);   break;
-                   case TOK_GE:        Root = NewExprNode (EXPR_GE);   break;
-           default:            Internal ("Invalid token");
-       }
-       Root->Left = Left;
-
-        /* Skip the operator token */
-       NextTok ();
-
-       /* Parse the right hand side */
-       Root->Right = SimpleExpr ();
+        long LVal, RVal, Val;
+        ExprNode* Left;
+        ExprNode* Right;
+
+        /* Remember the token and skip it */
+        enum Token T = Tok;
+        NextTok ();
+
+        /* Move root to left side and read the right side */
+        Left  = Root;
+        Right = SimpleExpr ();
+
+        /* If both expressions are constant, we can evaluate the term */
+        if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
+
+            switch (T) {
+                case TOK_EQ:    Val = (LVal == RVal);   break;
+                case TOK_NE:    Val = (LVal != RVal);   break;
+                case TOK_LT:    Val = (LVal < RVal);    break;
+                case TOK_GT:    Val = (LVal > RVal);    break;
+                case TOK_LE:    Val = (LVal <= RVal);   break;
+                case TOK_GE:    Val = (LVal >= RVal);   break;
+                default:        Internal ("Invalid token");
+            }
+
+            /* Generate a literal expression and delete the old left and
+             * right sides.
+             */
+            FreeExpr (Left);
+            FreeExpr (Right);
+            Root = GenLiteralExpr (Val);
+
+        } else {
+
+            /* Generate an expression tree */
+            unsigned char Op;
+            switch (T) {
+                case TOK_EQ:    Op = EXPR_EQ;   break;
+                case TOK_NE:    Op = EXPR_NE;   break;
+                case TOK_LT:    Op = EXPR_LT;   break;
+                case TOK_GT:    Op = EXPR_GT;   break;
+                case TOK_LE:    Op = EXPR_LE;   break;
+                case TOK_GE:    Op = EXPR_GE;   break;
+                default:               Internal ("Invalid token");
+            }
+            Root        = NewExprNode (Op);
+            Root->Left  = Left;
+            Root->Right = Right;
 
+        }
     }
 
     /* Return the expression tree we've created */
@@ -722,23 +1201,50 @@ static ExprNode* Expr2 (void)
     ExprNode* Root = BoolExpr ();
 
     /* Handle booleans */
-    while (Tok == TOK_BAND || Tok == TOK_BXOR) {
-
-       /* Create the new node */
-       ExprNode* Left = Root;
-       switch (Tok) {
-                   case TOK_BAND:      Root = NewExprNode (EXPR_BAND); break;
-                   case TOK_BXOR:      Root = NewExprNode (EXPR_BXOR); break;
-           default:            Internal ("Invalid token");
-       }
-       Root->Left = Left;
-
-        /* Skip the operator token */
-       NextTok ();
-
-       /* Parse the right hand side */
-       Root->Right = BoolExpr ();
+    while (Tok == TOK_BOOLAND || Tok == TOK_BOOLXOR) {
+
+        long LVal, RVal, Val;
+        ExprNode* Left;
+        ExprNode* Right;
+
+        /* Remember the token and skip it */
+        enum Token T = Tok;
+        NextTok ();
+
+        /* Move root to left side and read the right side */
+        Left  = Root;
+        Right = BoolExpr ();
+
+        /* If both expressions are constant, we can evaluate the term */
+        if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
+
+            switch (T) {
+                case TOK_BOOLAND:   Val = ((LVal != 0) && (RVal != 0)); break;
+                case TOK_BOOLXOR:   Val = ((LVal != 0) ^  (RVal != 0)); break;
+                default:        Internal ("Invalid token");
+            }
+
+            /* Generate a literal expression and delete the old left and
+             * right sides.
+             */
+            FreeExpr (Left);
+            FreeExpr (Right);
+            Root = GenLiteralExpr (Val);
+
+        } else {
+
+            /* Generate an expression tree */
+            unsigned char Op;
+            switch (T) {
+                case TOK_BOOLAND:   Op = EXPR_BOOLAND; break;
+                case TOK_BOOLXOR:   Op = EXPR_BOOLXOR; break;
+                default:                   Internal ("Invalid token");
+            }
+            Root        = NewExprNode (Op);
+            Root->Left  = Left;
+            Root->Right = Right;
 
+        }
     }
 
     /* Return the expression tree we've created */
@@ -754,22 +1260,48 @@ static ExprNode* Expr1 (void)
     ExprNode* Root = Expr2 ();
 
     /* Handle booleans */
-    while (Tok == TOK_BOR) {
-
-       /* Create the new node */
-       ExprNode* Left = Root;
-       switch (Tok) {
-                   case TOK_BOR:       Root = NewExprNode (EXPR_BOR);  break;
-           default:            Internal ("Invalid token");
-       }
-       Root->Left = Left;
-
-        /* Skip the operator token */
-       NextTok ();
-
-       /* Parse the right hand side */
-       Root->Right = Expr2 ();
+    while (Tok == TOK_BOOLOR) {
+
+        long LVal, RVal, Val;
+        ExprNode* Left;
+        ExprNode* Right;
+
+        /* Remember the token and skip it */
+        enum Token T = Tok;
+        NextTok ();
+
+        /* Move root to left side and read the right side */
+        Left  = Root;
+        Right = Expr2 ();
+
+        /* If both expressions are constant, we can evaluate the term */
+        if (IsEasyConst (Left, &LVal) && IsEasyConst (Right, &RVal)) {
+
+            switch (T) {
+                case TOK_BOOLOR:    Val = ((LVal != 0) || (RVal != 0)); break;
+                default:        Internal ("Invalid token");
+            }
+
+            /* Generate a literal expression and delete the old left and
+             * right sides.
+             */
+            FreeExpr (Left);
+            FreeExpr (Right);
+            Root = GenLiteralExpr (Val);
+
+        } else {
+
+            /* Generate an expression tree */
+            unsigned char Op;
+            switch (T) {
+                case TOK_BOOLOR:    Op = EXPR_BOOLOR;  break;
+                default:                   Internal ("Invalid token");
+            }
+            Root        = NewExprNode (Op);
+            Root->Left  = Left;
+            Root->Right = Right;
 
+        }
     }
 
     /* Return the expression tree we've created */
@@ -784,16 +1316,25 @@ static ExprNode* Expr0 (void)
     ExprNode* Root;
 
     /* Handle booleans */
-    if (Tok == TOK_BNOT) {
+    if (Tok == TOK_BOOLNOT) {
 
-       /* Create the new node */
-        Root = NewExprNode (EXPR_BNOT);
+        long Val;
+        ExprNode* Left;
 
         /* Skip the operator token */
        NextTok ();
 
-       /* Parse the left hand side, allow more BNOTs */
-       Root->Left = Expr0 ();
+        /* Read the argument */
+        Left = Expr0 ();
+
+        /* If the argument is const, evaluate it directly */
+        if (IsEasyConst (Left, &Val)) {
+            FreeExpr (Left);
+            Root = GenLiteralExpr (!Val);
+        } else {
+            Root = NewExprNode (EXPR_BOOLNOT);
+            Root->Left = Left;
+        }
 
     } else {
 
@@ -808,32 +1349,12 @@ static ExprNode* Expr0 (void)
 
 
 
-static ExprNode* SimplifyExpr (ExprNode* Root)
-/* Try to simplify the given expression tree */
-{
-    if (Root) {
-               Root->Left  = SimplifyExpr (Root->Left);
-       Root->Right = SimplifyExpr (Root->Right);
-       if (IsConstExpr (Root)) {
-           /* The complete expression is constant */
-           Root->V.Val = GetExprVal (Root);
-           Root->Op = EXPR_LITERAL;
-           FreeExpr (Root->Left);
-           FreeExpr (Root->Right);
-           Root->Left = Root->Right = 0;
-               }
-    }
-    return Root;
-}
-
-
-
 ExprNode* Expression (void)
 /* Evaluate an expression, build the expression tree on the heap and return
  * a pointer to the root of the tree.
  */
 {
-    return SimplifyExpr (Expr0 ());
+    return Expr0 ();
 }
 
 
@@ -846,21 +1367,27 @@ long ConstExpression (void)
 {
     long Val;
 
-    /* Read the expression, and call finalize (exception here, since we
-     * expect a const).
-     */
-    ExprNode* Expr = FinalizeExpr (Expression ());
+    /* Read the expression */
+    ExprNode* Expr = Expression ();
 
-    /* Get the value */
-    if (IsConstExpr (Expr)) {
-       Val = GetExprVal (Expr);
+    /* Study the expression */
+    ExprDesc D;
+    ED_Init (&D);
+    StudyExpr (Expr, &D);
+
+    /* Check if the expression is constant */
+    if (ED_IsConst (&D)) {
+        Val = D.Val;
     } else {
-       Error (ERR_CONSTEXPR_EXPECTED);
+       Error ("Constant expression expected");
        Val = 0;
     }
 
-    /* Free the expression tree and return the value */
+    /* Free the expression tree and allocated memory for D */
     FreeExpr (Expr);
+    ED_Done (&D);
+
+    /* Return the value */
     return Val;
 }
 
@@ -878,6 +1405,19 @@ void FreeExpr (ExprNode* Root)
 
 
 
+ExprNode* SimplifyExpr (ExprNode* Expr, const ExprDesc* D)
+/* Try to simplify the given expression tree */
+{
+    if (Expr->Op != EXPR_LITERAL && ED_IsConst (D)) {
+        /* No external references */
+        FreeExpr (Expr);
+        Expr = GenLiteralExpr (D->Val);
+    }
+    return Expr;
+}
+
+
+
 ExprNode* GenLiteralExpr (long Val)
 /* Return an expression tree that encodes the given literal value */
 {
@@ -888,6 +1428,14 @@ ExprNode* GenLiteralExpr (long Val)
 
 
 
+ExprNode* GenLiteral0 (void)
+/* Return an expression tree that encodes the the number zero */
+{
+    return GenLiteralExpr (0);
+}
+
+
+
 ExprNode* GenSymExpr (SymEntry* Sym)
 /* Return an expression node that encodes the given symbol */
 {
@@ -909,16 +1457,35 @@ static ExprNode* GenSectionExpr (unsigned SegNum)
 
 
 
+ExprNode* GenAddExpr (ExprNode* Left, ExprNode* Right)
+/* Generate an addition from the two operands */
+{
+    long Val;
+    if (IsEasyConst (Left, &Val) && Val == 0) {
+        FreeExpr (Left);
+        return Right;
+    } else if (IsEasyConst (Right, &Val) && Val == 0) {
+        FreeExpr (Right);
+        return Left;
+    } else {
+        ExprNode* Root = NewExprNode (EXPR_PLUS);
+        Root->Left = Left;
+        Root->Right = Right;
+        return Root;
+    }
+}
+
+
+
 ExprNode* GenCurrentPC (void)
 /* Return the current program counter as expression */
 {
     ExprNode* Root;
 
-    if (RelocMode) {
+    if (GetRelocMode ()) {
        /* Create SegmentBase + Offset */
-       Root = NewExprNode (EXPR_PLUS);
-       Root->Left  = GenSectionExpr (GetCurrentSegNum ());
-       Root->Right = GenLiteralExpr (GetPC ());
+               Root = GenAddExpr (GenSectionExpr (GetCurrentSegNum ()),
+                           GenLiteralExpr (GetPC ()));
     } else {
        /* Absolute mode, just return PC value */
        Root = GenLiteralExpr (GetPC ());
@@ -946,23 +1513,52 @@ ExprNode* GenBranchExpr (unsigned Offs)
 {
     ExprNode* N;
     ExprNode* Root;
+    long      Val;
+
+    /* Read Expression() */
+    N = Expression ();
+
+    /* If the expression is a cheap constant, generate a simpler tree */
+    if (IsEasyConst (N, &Val)) {
+
+        /* Free the constant expression tree */
+        FreeExpr (N);
+
+        /* Generate the final expression:
+         * Val - (* + Offs)
+         * Val - ((Seg + PC) + Offs)
+         * Val - Seg - PC - Offs
+         * (Val - PC - Offs) - Seg
+         */
+        Root = GenLiteralExpr (Val - GetPC () - Offs);
+        if (GetRelocMode ()) {
+            N = Root;
+            Root = NewExprNode (EXPR_MINUS);
+            Root->Left  = N;
+            Root->Right = GenSectionExpr (GetCurrentSegNum ());
+        }
 
-    /* Create *+Offs */
-    if (RelocMode) {
-       N = NewExprNode (EXPR_PLUS);
-       N->Left  = GenSectionExpr (GetCurrentSegNum ());
-       N->Right = GenLiteralExpr (GetPC () + Offs);
     } else {
-       N = GenLiteralExpr (GetPC () + Offs);
-    }
 
-    /* Create the root node */
-    Root = NewExprNode (EXPR_MINUS);
-    Root->Left = Expression ();
-    Root->Right = N;
+        /* Generate the expression:
+         * N - (* + Offs)
+         * N - ((Seg + PC) + Offs)
+         * N - Seg - PC - Offs
+         * N - (PC + Offs) - Seg
+         */
+        Root = NewExprNode (EXPR_MINUS);
+        Root->Left  = N;
+        Root->Right = GenLiteralExpr (GetPC () + Offs);
+        if (GetRelocMode ()) {
+            N = Root;
+            Root = NewExprNode (EXPR_MINUS);
+            Root->Left  = N;
+            Root->Right = GenSectionExpr (GetCurrentSegNum ());
+        }
+    }
 
     /* Return the result */
-    return SimplifyExpr (Root);
+    return Root;
 }
 
 
@@ -983,11 +1579,7 @@ ExprNode* GenByteExpr (ExprNode* Expr)
 /* Force the given expression into a byte and return the result */
 {
     /* Use the low byte operator to force the expression into byte size */
-    ExprNode* Root = NewExprNode (EXPR_BYTE0);
-    Root->Left  = Expr;
-
-    /* Return the result */
-    return Root;
+    return LoByte (Expr);
 }
 
 
@@ -995,13 +1587,8 @@ ExprNode* GenByteExpr (ExprNode* Expr)
 ExprNode* GenWordExpr (ExprNode* Expr)
 /* Force the given expression into a word and return the result. */
 {
-    /* AND the expression by $FFFF to force it into word size */
-    ExprNode* Root = NewExprNode (EXPR_AND);
-    Root->Left  = Expr;
-    Root->Right        = GenLiteralExpr (0xFFFF);
-
-    /* Return the result */
-    return Root;
+    /* Use the low byte operator to force the expression into word size */
+    return LoWord (Expr);
 }
 
 
@@ -1020,457 +1607,28 @@ ExprNode* GenNE (ExprNode* Expr, long Val)
 
 
 
-int IsConstExpr (ExprNode* Root)
+int IsConstExpr (ExprNode* Expr, long* Val)
 /* Return true if the given expression is a constant expression, that is, one
- * with no references to external symbols.
- */
-{
-    int Const;
-    SymEntry* Sym;
-
-    if (EXPR_IS_LEAF (Root->Op)) {
-       switch (Root->Op) {
-
-           case EXPR_LITERAL:
-               return 1;
-
-           case EXPR_SYMBOL:
-               Sym = Root->V.Sym;
-               if (SymHasUserMark (Sym)) {
-                   if (Verbosity > 0) {
-                       DumpExpr (Root);
-                   }
-                   PError (GetSymPos (Sym), ERR_CIRCULAR_REFERENCE);
-                   Const = 0;
-               } else {
-                   SymMarkUser (Sym);
-                   Const = SymIsConst (Sym);
-                   SymUnmarkUser (Sym);
-               }
-               return Const;
-
-           default:
-               return 0;
-
-       }
-    } else if (EXPR_IS_UNARY (Root->Op)) {
-
-       return IsConstExpr (Root->Left);
-
-    } else {
-
-       /* We must handle shortcut boolean expressions here */
-       switch (Root->Op) {
-
-           case EXPR_BAND:
-               if (IsConstExpr (Root->Left)) {
-                   /* lhs is const, if it is zero, don't eval right */
-                   if (GetExprVal (Root->Left) == 0) {
-                       return 1;
-                   } else {
-                       return IsConstExpr (Root->Right);
-                   }
-               } else {
-                   /* lhs not const --> tree not const */
-                   return 0;
-               }
-               break;
-
-           case EXPR_BOR:
-               if (IsConstExpr (Root->Left)) {
-                   /* lhs is const, if it is not zero, don't eval right */
-                   if (GetExprVal (Root->Left) != 0) {
-                       return 1;
-                   } else {
-                       return IsConstExpr (Root->Right);
-                   }
-               } else {
-                   /* lhs not const --> tree not const */
-                   return 0;
-               }
-               break;
-
-           default:
-               /* All others are handled normal */
-               return IsConstExpr (Root->Left) && IsConstExpr (Root->Right);
-       }
-    }
-}
-
-
-
-static void CheckByteExpr (const ExprNode* N, int* IsByte)
-/* Internal routine that is recursively called to check if there is a zeropage
- * symbol in the expression tree.
- */
-{
-    if (N) {
-       switch (N->Op & EXPR_TYPEMASK) {
-
-           case EXPR_LEAFNODE:
-               switch (N->Op) {
-
-                   case EXPR_SYMBOL:
-                       if (SymIsZP (N->V.Sym)) {
-                           *IsByte = 1;
-                       } else if (SymHasExpr (N->V.Sym)) {
-                           /* Check if this expression is a byte expression */
-                           *IsByte = IsByteExpr (GetSymExpr (N->V.Sym));
-                       }
-                       break;
-
-                   case EXPR_SECTION:
-                       if (GetSegAddrSize (N->V.SegNum) == ADDR_SIZE_ZP) {
-                           *IsByte = 1;
-                       }
-                       break;
-
-               }
-               break;
-
-           case EXPR_UNARYNODE:
-               CheckByteExpr (N->Left, IsByte);
-               break;
-
-           case EXPR_BINARYNODE:
-               CheckByteExpr (N->Left, IsByte);
-               CheckByteExpr (N->Right, IsByte);
-               break;
-
-           default:
-               Internal ("Unknown expression op: %02X", N->Op);
-       }
-    }
-}
-
-
-
-int IsByteExpr (ExprNode* Root)
-/* Return true if this is a byte expression */
-{
-    int IsByte;
-
-    if (IsConstExpr (Root)) {
-       if (Root->Op != EXPR_LITERAL) {
-           SimplifyExpr (Root);
-       }
-               return IsByteRange (GetExprVal (Root));
-    } else if (Root->Op == EXPR_BYTE0 || Root->Op == EXPR_BYTE1 ||
-              Root->Op == EXPR_BYTE2 || Root->Op == EXPR_BYTE3) {
-       /* Symbol forced to have byte range */
-               IsByte = 1;
-    } else {
-       /* We have undefined symbols in the expression. Assume that the
-        * expression is a byte expression if there is at least one symbol
-        * declared as zeropage in it. Being wrong here is not a very big
-        * problem since the linker knows about all symbols and detects
-        * error like mixing absolute and zeropage labels.
-        */
-       IsByte = 0;
-       CheckByteExpr (Root, &IsByte);
-    }
-    return IsByte;
-}
-
-
-
-long GetExprVal (ExprNode* Expr)
-/* Get the value of a constant expression */
-{
-    long Right, Left;
-
-    switch (Expr->Op) {
-
-               case EXPR_LITERAL:
-           return Expr->V.Val;
-
-               case EXPR_SYMBOL:
-           return GetSymVal (Expr->V.Sym);
-
-               case EXPR_PLUS:
-           return GetExprVal (Expr->Left) + GetExprVal (Expr->Right);
-
-               case EXPR_MINUS:
-           return GetExprVal (Expr->Left) - GetExprVal (Expr->Right);
-
-               case EXPR_MUL:
-           return GetExprVal (Expr->Left) * GetExprVal (Expr->Right);
-
-               case EXPR_DIV:
-           Left  = GetExprVal (Expr->Left);
-           Right = GetExprVal (Expr->Right);
-           if (Right == 0) {
-               Error (ERR_DIV_BY_ZERO);
-               return 0;
-           }
-           return Left / Right;
-
-               case EXPR_MOD:
-           Left  = GetExprVal (Expr->Left);
-           Right = GetExprVal (Expr->Right);
-           if (Right == 0) {
-               Error (ERR_MOD_BY_ZERO);
-               return 0;
-           }
-           return Left % Right;
-
-               case EXPR_OR:
-                   return GetExprVal (Expr->Left) | GetExprVal (Expr->Right);
-
-               case EXPR_XOR:
-                   return GetExprVal (Expr->Left) ^ GetExprVal (Expr->Right);
-
-               case EXPR_AND:
-                   return GetExprVal (Expr->Left) & GetExprVal (Expr->Right);
-
-               case EXPR_SHL:
-                   return GetExprVal (Expr->Left) << GetExprVal (Expr->Right);
-
-               case EXPR_SHR:
-                   return GetExprVal (Expr->Left) >> GetExprVal (Expr->Right);
-
-               case EXPR_EQ:
-                   return (GetExprVal (Expr->Left) == GetExprVal (Expr->Right));
-
-               case EXPR_NE:
-                   return (GetExprVal (Expr->Left) != GetExprVal (Expr->Right));
-
-               case EXPR_LT:
-           return (GetExprVal (Expr->Left) < GetExprVal (Expr->Right));
-
-               case EXPR_GT:
-           return (GetExprVal (Expr->Left) > GetExprVal (Expr->Right));
-
-               case EXPR_LE:
-           return (GetExprVal (Expr->Left) <= GetExprVal (Expr->Right));
-
-               case EXPR_GE:
-           return (GetExprVal (Expr->Left) >= GetExprVal (Expr->Right));
-
-               case EXPR_UNARY_MINUS:
-           return -GetExprVal (Expr->Left);
-
-               case EXPR_NOT:
-           return ~GetExprVal (Expr->Left);
-
-               case EXPR_BYTE0:
-           return GetExprVal (Expr->Left) & 0xFF;
-
-               case EXPR_BYTE1:
-           return (GetExprVal (Expr->Left) >> 8) & 0xFF;
-
-               case EXPR_BYTE2:
-           return (GetExprVal (Expr->Left) >> 16) & 0xFF;
-
-               case EXPR_BYTE3:
-           return (GetExprVal (Expr->Left) >> 24) & 0xFF;
-
-        case EXPR_SWAP:
-           Left = GetExprVal (Expr->Left);
-           return ((Left >> 8) & 0x00FF) | ((Left << 8) & 0xFF00);
-
-       case EXPR_BAND:
-           return GetExprVal (Expr->Left) && GetExprVal (Expr->Right);
-
-       case EXPR_BOR:
-           return GetExprVal (Expr->Left) || GetExprVal (Expr->Right);
-
-       case EXPR_BXOR:
-           return (GetExprVal (Expr->Left) != 0) ^ (GetExprVal (Expr->Right) != 0);
-
-       case EXPR_BNOT:
-                   return !GetExprVal (Expr->Left);
-
-       case EXPR_ULABEL:
-           Internal ("GetExprVal called for EXPR_ULABEL");
-           /* NOTREACHED */
-           return 0;
-
-        default:
-           Internal ("Unknown Op type: %u", Expr->Op);
-           /* NOTREACHED */
-           return 0;
-    }
-}
-
-
-
-static ExprNode* RemoveSyms (ExprNode* Expr, int MustClone)
-/* Remove resolved symbols from the tree by cloning symbol expressions */
-{
-    /* Accept NULL pointers */
-    if (Expr == 0) {
-       return 0;
-    }
-
-    /* Special node handling */
-    switch (Expr->Op) {
-
-       case EXPR_SYMBOL:
-           if (SymHasExpr (Expr->V.Sym)) {
-               /* The symbol has an expression tree */
-               SymEntry* Sym = Expr->V.Sym;
-               if (SymHasUserMark (Sym)) {
-                   /* Circular definition */
-                   if (Verbosity) {
-                       DumpExpr (Expr);
-                   }
-                   PError (GetSymPos (Sym), ERR_CIRCULAR_REFERENCE);
-                   return GenLiteralExpr (0);          /* Return a dummy value */
-               }
-               SymMarkUser (Sym);
-               Expr = RemoveSyms (GetSymExpr (Sym), 1);
-               SymUnmarkUser (Sym);
-               return Expr;
-           } else if (SymIsConst (Expr->V.Sym)) {
-               /* The symbol is a constant */
-               return GenLiteralExpr (GetSymVal (Expr->V.Sym));
-           }
-           break;
-
-       case EXPR_ULABEL:
-           if (ULabCanResolve ()) {
-               ExprNode* NewExpr = ULabResolve (Expr->V.Val);
-               FreeExpr (Expr);
-               Expr = NewExpr;
-           }
-           break;
-
-    }
-
-    /* Clone the current node if needed */
-    if (MustClone) {
-
-               ExprNode* Clone;
-
-       /* Clone the expression tree */
-       switch (Expr->Op) {
-
-           case EXPR_LITERAL:
-                Clone = GenLiteralExpr (Expr->V.Val);
-                break;
-
-           case EXPR_ULABEL:
-                Clone = GenULabelExpr (Expr->V.Val);
-                break;
-
-           case EXPR_SYMBOL:
-                Clone = GenSymExpr (Expr->V.Sym);
-                break;
-
-           case EXPR_SECTION:
-                Clone = GenSectionExpr (Expr->V.SegNum);
-                break;
-
-            default:
-                Clone = NewExprNode (Expr->Op);
-                Clone->Left  = RemoveSyms (Expr->Left, 1);
-                Clone->Right = RemoveSyms (Expr->Right, 1);
-                break;
-
-       }
-
-       /* Done */
-       return Clone;
-
-    } else {
-
-       /* Nothing to clone */
-               Expr->Left  = RemoveSyms (Expr->Left, 0);
-       Expr->Right = RemoveSyms (Expr->Right, 0);
-
-       /* Done */
-       return Expr;
-    }
-}
-
-
-
-static ExprNode* ConstExtract (ExprNode* Expr, long* Val, int Sign)
-/* Extract and evaluate all constant factors in an subtree that has only
- * additions and subtractions.
+ * with no references to external symbols. If Val is not NULL and the
+ * expression is constant, the constant value is stored here.
  */
 {
-    if (Expr->Op == EXPR_LITERAL) {
-       if (Sign < 0) {
-           *Val -= Expr->V.Val;
-       } else {
-           *Val += Expr->V.Val;
-       }
-               FreeExprNode (Expr);
-       return 0;
-    }
+    int IsConst;
 
-    if (Expr->Op == EXPR_PLUS || Expr->Op == EXPR_MINUS) {
-       ExprNode* Left;
-       ExprNode* Right;
-       Left = ConstExtract (Expr->Left, Val, Sign);
-       if (Expr->Op == EXPR_MINUS) {
-           Sign = -Sign;
-       }
-       Right = ConstExtract (Expr->Right, Val, Sign);
-       if (Left == 0 && Right == 0) {
-           FreeExprNode (Expr);
-           return 0;
-       } else if (Left == 0) {
-           FreeExprNode (Expr);
-           return Right;
-       } else if (Right == 0) {
-           FreeExprNode (Expr);
-           return Left;
-       } else {
-           /* Check for SEG - SEG which is now possible */
-           if (Left->Op == EXPR_SECTION && Right->Op == EXPR_SECTION &&
-               Left->V.SegNum == Right->V.SegNum) {
-               /* SEG - SEG, remove it completely */
-               FreeExprNode (Left);
-               FreeExprNode (Right);
-               FreeExprNode (Expr);
-               return 0;
-           } else {
-               Expr->Left  = Left;
-               Expr->Right = Right;
-               return Expr;
-           }
-       }
-    }
+    /* Study the expression */
+    ExprDesc D;
+    ED_Init (&D);
+    StudyExpr (Expr, &D);
 
-    /* Some other sort of node, finalize the terms */
-    if (Expr->Left) {
-       Expr->Left = FinalizeExpr (Expr->Left);
+    /* Check if the expression is constant */
+    IsConst = ED_IsConst (&D);
+    if (IsConst && Val != 0) {
+        *Val = D.Val;
     }
-    if (Expr->Right) {
-       Expr->Right = FinalizeExpr (Expr->Right);
-    }
-
-    return Expr;
-}
-
-
-
-ExprNode* FinalizeExpr (ExprNode* Expr)
-/* Resolve any symbols by cloning the symbol expression tree instead of the
- * symbol reference, then try to simplify the expression as much as possible.
- * This function must only be called if all symbols are resolved (no undefined
- * symbol errors).
- */
-{
-    long Val = 0;
-    ExprNode* N;
 
-    Expr = RemoveSyms (Expr, 0);
-    Expr = ConstExtract (Expr, &Val, 1);
-    if (Expr == 0) {
-       /* Reduced to a literal value */
-       Expr = GenLiteralExpr (Val);
-    } else if (Val) {
-       /* Extracted a value */
-       N = NewExprNode (EXPR_PLUS);
-       N->Left = Expr;
-       N->Right = GenLiteralExpr (Val);
-       Expr = N;
-    }
-    return Expr;
+    /* Delete allocated memory and return the result */
+    ED_Done (&D);
+    return IsConst;
 }
 
 
@@ -1526,38 +1684,41 @@ void WriteExpr (ExprNode* Expr)
 {
     /* Null expressions are encoded by a type byte of zero */
     if (Expr == 0) {
-       ObjWrite8 (0);
+       ObjWrite8 (EXPR_NULL);
        return;
     }
 
-    /* Write the expression code */
-    ObjWrite8 (Expr->Op);
-
     /* If the is a leafnode, write the expression attribute, otherwise
      * write the expression operands.
      */
     switch (Expr->Op) {
 
         case EXPR_LITERAL:
-           ObjWrite32 (Expr->V.Val);
-           break;
+            ObjWrite8 (EXPR_LITERAL);
+           ObjWrite32 (Expr->V.Val);
+           break;
 
         case EXPR_SYMBOL:
-           /* Maybe we should use a code here? */
-           CHECK (SymIsImport (Expr->V.Sym));  /* Safety */
-           ObjWriteVar (GetSymIndex (Expr->V.Sym));
+           if (SymIsImport (Expr->V.Sym)) {
+                ObjWrite8 (EXPR_SYMBOL);
+                ObjWriteVar (GetSymIndex (Expr->V.Sym));
+            } else {
+                WriteExpr (GetSymExpr (Expr->V.Sym));
+            }
            break;
 
         case EXPR_SECTION:
+            ObjWrite8 (EXPR_SECTION);
            ObjWrite8 (Expr->V.SegNum);
            break;
 
        case EXPR_ULABEL:
-           Internal ("WriteExpr: Cannot write EXPR_ULABEL nodes");
+            WriteExpr (ULabResolve (Expr->V.Val));
            break;
 
         default:
            /* Not a leaf node */
+            ObjWrite8 (Expr->Op);
            WriteExpr (Expr->Left);
            WriteExpr (Expr->Right);
            break;
@@ -1567,4 +1728,41 @@ void WriteExpr (ExprNode* Expr)
 
 
 
+void ExprGuessedAddrSize (const ExprNode* Expr, unsigned char AddrSize)
+/* Mark the address size of the given expression tree as guessed. The address
+ * size passed as argument is the one NOT used, because the actual address
+ * size wasn't known. Example: Zero page addressing was not used because symbol
+ * is undefined, and absolute addressing was available.
+ * This function will actually parse the expression tree for undefined symbols,
+ * and mark these symbols accordingly.
+ */
+{
+    /* Accept NULL expressions */
+    if (Expr == 0) {
+        return;
+    }
+
+    /* Check the type code */
+    switch (Expr->Op & EXPR_TYPEMASK) {
+
+        case EXPR_LEAFNODE:
+            if (Expr->Op == EXPR_SYMBOL) {
+                if (!SymIsDef (Expr->V.Sym)) {
+                    /* Symbol is undefined, mark it */
+                    SymGuessedAddrSize (Expr->V.Sym, AddrSize);
+                }
+            }
+            return;
+
+        case EXPR_BINARYNODE:
+            ExprGuessedAddrSize (Expr->Right, AddrSize);
+            /* FALLTHROUGH */
+
+        case EXPR_UNARYNODE:
+            ExprGuessedAddrSize (Expr->Left, AddrSize);
+            break;
+    }
+}
+
+