]> git.sur5r.net Git - cc65/blob - src/ca65/scanner.c
Implemented new .PUSHCPU and .POPCPU commands.
[cc65] / src / ca65 / scanner.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 scanner.c                                 */
4 /*                                                                           */
5 /*                  The scanner for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2010, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
12 /* EMail:         uz@cc65.org                                                */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <errno.h>
41 #include <sys/types.h>          /* EMX needs this */
42 #include <sys/stat.h>
43
44 /* common */
45 #include "addrsize.h"
46 #include "attrib.h"
47 #include "chartype.h"
48 #include "check.h"
49 #include "fname.h"
50 #include "xmalloc.h"
51
52 /* ca65 */
53 #include "condasm.h"
54 #include "error.h"
55 #include "filetab.h"
56 #include "global.h"
57 #include "incpath.h"
58 #include "instr.h"
59 #include "istack.h"
60 #include "listing.h"
61 #include "macro.h"
62 #include "toklist.h"
63 #include "scanner.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Data                                    */
69 /*****************************************************************************/
70
71
72
73 Token Tok = TOK_NONE;                   /* Current token */
74 int WS;                                 /* Flag: Whitespace before token */
75 long IVal;                              /* Integer token attribute */
76 StrBuf SVal = STATIC_STRBUF_INITIALIZER;/* String token attribute */
77
78 FilePos CurPos = { 0, 0, 0 };           /* Name and position in current file */
79
80
81
82 /* Struct to handle include files. */
83 typedef struct InputFile InputFile;
84 struct InputFile {
85     FILE*           F;                  /* Input file descriptor */
86     FilePos         Pos;                /* Position in file */
87     Token           Tok;                /* Last token */
88     int             C;                  /* Last character */
89     char            Line[256];          /* The current input line */
90     InputFile*      Next;               /* Linked list of input files */
91 };
92
93 /* Struct to handle textual input data */
94 typedef struct InputData InputData;
95 struct InputData {
96     char*           Text;               /* Pointer to the text data */
97     const char*     Pos;                /* Pointer to current position */
98     int             Malloced;           /* Memory was malloced */
99     Token           Tok;                /* Last token */
100     int             C;                  /* Last character */
101     InputData*      Next;               /* Linked list of input data */
102 };
103
104 /* Input source: Either file or data */
105 typedef struct CharSource CharSource;
106
107 /* Set of input functions */
108 typedef struct CharSourceFunctions CharSourceFunctions;
109 struct CharSourceFunctions {
110     void (*MarkStart) (CharSource*);    /* Mark the start pos of a token */
111     void (*NextChar) (CharSource*);     /* Read next char from input */
112     void (*Done) (CharSource*);         /* Close input source */
113 };
114
115 /* Input source: Either file or data */
116 struct CharSource {
117     CharSource*                 Next;   /* Linked list of char sources */
118     Token                       Tok;    /* Last token */
119     int                         C;      /* Last character */
120     const CharSourceFunctions*  Func;   /* Pointer to function table */
121     union {
122         InputFile               File;   /* File data */
123         InputData               Data;   /* Textual data */
124     }                           V;
125 };
126
127 /* Current input variables */
128 static CharSource* Source       = 0;    /* Current char source */
129 static unsigned     FCount      = 0;    /* Count of input files */
130 static int          C           = 0;    /* Current input character */
131
132 /* Force end of assembly */
133 int               ForcedEnd     = 0;
134
135 /* List of dot keywords with the corresponding tokens */
136 struct DotKeyword {
137     const char* Key;                    /* MUST be first field */
138     Token       Tok;
139 } DotKeywords [] = {
140     { ".A16",           TOK_A16         },
141     { ".A8",            TOK_A8          },
142     { ".ADDR",          TOK_ADDR        },
143     { ".ALIGN",         TOK_ALIGN       },
144     { ".AND",           TOK_BOOLAND     },
145     { ".ASCIIZ",        TOK_ASCIIZ      },
146     { ".ASSERT",        TOK_ASSERT      },
147     { ".AUTOIMPORT",    TOK_AUTOIMPORT  },
148     { ".BANKBYTE",      TOK_BANKBYTE    },
149     { ".BANKBYTES",     TOK_BANKBYTES   },
150     { ".BITAND",        TOK_AND         },
151     { ".BITNOT",        TOK_NOT         },
152     { ".BITOR",         TOK_OR          },
153     { ".BITXOR",        TOK_XOR         },
154     { ".BLANK",         TOK_BLANK       },
155     { ".BSS",           TOK_BSS         },
156     { ".BYT",           TOK_BYTE        },
157     { ".BYTE",          TOK_BYTE        },
158     { ".CASE",          TOK_CASE        },
159     { ".CHARMAP",       TOK_CHARMAP     },
160     { ".CODE",          TOK_CODE        },
161     { ".CONCAT",        TOK_CONCAT      },
162     { ".CONDES",        TOK_CONDES      },
163     { ".CONST",         TOK_CONST       },
164     { ".CONSTRUCTOR",   TOK_CONSTRUCTOR },
165     { ".CPU",           TOK_CPU         },
166     { ".DATA",          TOK_DATA        },
167     { ".DBG",           TOK_DBG         },
168     { ".DBYT",          TOK_DBYT        },
169     { ".DEBUGINFO",     TOK_DEBUGINFO   },
170     { ".DEF",           TOK_DEFINED     },
171     { ".DEFINE",        TOK_DEFINE      },
172     { ".DEFINED",       TOK_DEFINED     },
173     { ".DESTRUCTOR",    TOK_DESTRUCTOR  },
174     { ".DWORD",         TOK_DWORD       },
175     { ".ELSE",          TOK_ELSE        },
176     { ".ELSEIF",        TOK_ELSEIF      },
177     { ".END",           TOK_END         },
178     { ".ENDENUM",       TOK_ENDENUM     },
179     { ".ENDIF",         TOK_ENDIF       },
180     { ".ENDMAC",        TOK_ENDMACRO    },
181     { ".ENDMACRO",      TOK_ENDMACRO    },
182     { ".ENDPROC",       TOK_ENDPROC     },
183     { ".ENDREP",        TOK_ENDREP      },
184     { ".ENDREPEAT",     TOK_ENDREP      },
185     { ".ENDSCOPE",      TOK_ENDSCOPE    },
186     { ".ENDSTRUCT",     TOK_ENDSTRUCT   },
187     { ".ENDUNION",      TOK_ENDUNION    },
188     { ".ENUM",          TOK_ENUM        },
189     { ".ERROR",         TOK_ERROR       },
190     { ".EXITMAC",       TOK_EXITMACRO   },
191     { ".EXITMACRO",     TOK_EXITMACRO   },
192     { ".EXPORT",        TOK_EXPORT      },
193     { ".EXPORTZP",      TOK_EXPORTZP    },
194     { ".FARADDR",       TOK_FARADDR     },
195     { ".FEATURE",       TOK_FEATURE     },
196     { ".FILEOPT",       TOK_FILEOPT     },
197     { ".FOPT",          TOK_FILEOPT     },
198     { ".FORCEIMPORT",   TOK_FORCEIMPORT },
199     { ".FORCEWORD",     TOK_FORCEWORD   },
200     { ".GLOBAL",        TOK_GLOBAL      },
201     { ".GLOBALZP",      TOK_GLOBALZP    },
202     { ".HIBYTE",        TOK_HIBYTE      },
203     { ".HIBYTES",       TOK_HIBYTES     },
204     { ".HIWORD",        TOK_HIWORD      },
205     { ".I16",           TOK_I16         },
206     { ".I8",            TOK_I8          },
207     { ".IDENT",         TOK_MAKEIDENT   },
208     { ".IF",            TOK_IF          },
209     { ".IFBLANK",       TOK_IFBLANK     },
210     { ".IFCONST",       TOK_IFCONST     },
211     { ".IFDEF",         TOK_IFDEF       },
212     { ".IFNBLANK",      TOK_IFNBLANK    },
213     { ".IFNCONST",      TOK_IFNCONST    },
214     { ".IFNDEF",        TOK_IFNDEF      },
215     { ".IFNREF",        TOK_IFNREF      },
216     { ".IFP02",         TOK_IFP02       },
217     { ".IFP816",        TOK_IFP816      },
218     { ".IFPC02",        TOK_IFPC02      },
219     { ".IFPSC02",       TOK_IFPSC02     },
220     { ".IFREF",         TOK_IFREF       },
221     { ".IMPORT",        TOK_IMPORT      },
222     { ".IMPORTZP",      TOK_IMPORTZP    },
223     { ".INCBIN",        TOK_INCBIN      },
224     { ".INCLUDE",       TOK_INCLUDE     },
225     { ".INTERRUPTOR",   TOK_INTERRUPTOR },
226     { ".LEFT",          TOK_LEFT        },
227     { ".LINECONT",      TOK_LINECONT    },
228     { ".LIST",          TOK_LIST        },
229     { ".LISTBYTES",     TOK_LISTBYTES   },
230     { ".LOBYTE",        TOK_LOBYTE      },
231     { ".LOBYTES",       TOK_LOBYTES     },
232     { ".LOCAL",         TOK_LOCAL       },
233     { ".LOCALCHAR",     TOK_LOCALCHAR   },
234     { ".LOWORD",        TOK_LOWORD      },
235     { ".MAC",           TOK_MACRO       },
236     { ".MACPACK",       TOK_MACPACK     },
237     { ".MACRO",         TOK_MACRO       },
238     { ".MATCH",         TOK_MATCH       },
239     { ".MAX",           TOK_MAX         },
240     { ".MID",           TOK_MID         },
241     { ".MIN",           TOK_MIN         },
242     { ".MOD",           TOK_MOD         },
243     { ".NOT",           TOK_BOOLNOT     },
244     { ".NULL",          TOK_NULL        },
245     { ".OR",            TOK_BOOLOR      },
246     { ".ORG",           TOK_ORG         },
247     { ".OUT",           TOK_OUT         },
248     { ".P02",           TOK_P02         },
249     { ".P816",          TOK_P816        },
250     { ".PAGELEN",       TOK_PAGELENGTH  },
251     { ".PAGELENGTH",    TOK_PAGELENGTH  },
252     { ".PARAMCOUNT",    TOK_PARAMCOUNT  },
253     { ".PC02",          TOK_PC02        },
254     { ".POPCPU",        TOK_POPCPU      },
255     { ".POPSEG",        TOK_POPSEG      },
256     { ".PROC",          TOK_PROC        },
257     { ".PSC02",         TOK_PSC02       },
258     { ".PUSHCPU",       TOK_PUSHCPU     },
259     { ".PUSHSEG",       TOK_PUSHSEG     },
260     { ".REF",           TOK_REFERENCED  },
261     { ".REFERENCED",    TOK_REFERENCED  },
262     { ".RELOC",         TOK_RELOC       },
263     { ".REPEAT",        TOK_REPEAT      },
264     { ".RES",           TOK_RES         },
265     { ".RIGHT",         TOK_RIGHT       },
266     { ".RODATA",        TOK_RODATA      },
267     { ".SCOPE",         TOK_SCOPE       },
268     { ".SEGMENT",       TOK_SEGMENT     },
269     { ".SET",           TOK_SET         },
270     { ".SETCPU",        TOK_SETCPU      },
271     { ".SHL",           TOK_SHL         },
272     { ".SHR",           TOK_SHR         },
273     { ".SIZEOF",        TOK_SIZEOF      },
274     { ".SMART",         TOK_SMART       },
275     { ".SPRINTF",       TOK_SPRINTF     },
276     { ".STRAT",         TOK_STRAT       },
277     { ".STRING",        TOK_STRING      },
278     { ".STRLEN",        TOK_STRLEN      },
279     { ".STRUCT",        TOK_STRUCT      },
280     { ".SUNPLUS",       TOK_SUNPLUS     },
281     { ".TAG",           TOK_TAG         },
282     { ".TCOUNT",        TOK_TCOUNT      },
283     { ".TIME",          TOK_TIME        },
284     { ".UNION",         TOK_UNION       },
285     { ".VERSION",       TOK_VERSION     },
286     { ".WARNING",       TOK_WARNING     },
287     { ".WORD",          TOK_WORD        },
288     { ".XMATCH",        TOK_XMATCH      },
289     { ".XOR",           TOK_BOOLXOR     },
290     { ".ZEROPAGE",      TOK_ZEROPAGE    },
291 };
292
293
294
295 /*****************************************************************************/
296 /*                            CharSource functions                           */
297 /*****************************************************************************/
298
299
300
301 static void UseCharSource (CharSource* S)
302 /* Initialize a new input source and start to use it. */
303 {
304     /* Remember the current input char and token */
305     S->Tok      = Tok;
306     S->C        = C;
307
308     /* Use the new input source */
309     S->Next     = Source;
310     Source      = S;
311
312     /* Read the first character from the new file */
313     S->Func->NextChar (S);
314
315     /* Setup the next token so it will be skipped on the next call to
316      * NextRawTok().
317      */
318     Tok = TOK_SEP;
319 }
320
321
322
323 static void DoneCharSource (void)
324 /* Close the top level character source */
325 {
326     CharSource* S;
327
328     /* First, call the type specific function */
329     Source->Func->Done (Source);
330
331     /* Restore the old token */
332     Tok = Source->Tok;
333     C   = Source->C;
334
335     /* Remember the last stacked input source */
336     S = Source->Next;
337
338     /* Delete the top level one ... */
339     xfree (Source);
340
341     /* ... and use the one before */
342     Source = S;
343 }
344
345
346
347 /*****************************************************************************/
348 /*                            InputFile functions                            */
349 /*****************************************************************************/
350                                           
351
352
353 static void IFMarkStart (CharSource* S)
354 /* Mark the start of the next token */
355 {
356     CurPos = S->V.File.Pos;
357 }
358
359
360
361 static void IFNextChar (CharSource* S)
362 /* Read the next character from the input file */
363 {
364     /* Check for end of line, read the next line if needed */
365     while (S->V.File.Line [S->V.File.Pos.Col] == '\0') {
366
367         unsigned Len, Removed;
368
369         /* End of current line reached, read next line */
370         if (fgets (S->V.File.Line, sizeof (S->V.File.Line), S->V.File.F) == 0) {
371             /* End of file. Add an empty line to the listing. This is a
372              * small hack needed to keep the PC output in sync.
373              */
374             NewListingLine ("", S->V.File.Pos.Name, FCount);
375             C = EOF;
376             return;
377         }
378
379         /* For better handling of files with unusual line endings (DOS
380          * files that are accidently translated on Unix for example),
381          * first remove all whitespace at the end, then add a single
382          * newline.
383          */
384         Len = strlen (S->V.File.Line);
385         Removed = 0;
386         while (Len > 0 && IsSpace (S->V.File.Line[Len-1])) {
387             ++Removed;
388             --Len;
389         }
390         if (Removed) {
391             S->V.File.Line[Len+0] = '\n';
392             S->V.File.Line[Len+1] = '\0';
393         }
394
395         /* One more line */
396         S->V.File.Pos.Line++;
397         S->V.File.Pos.Col = 0;
398
399         /* Remember the new line for the listing */
400         NewListingLine (S->V.File.Line, S->V.File.Pos.Name, FCount);
401
402     }
403
404     /* Return the next character from the file */
405     C = S->V.File.Line [S->V.File.Pos.Col++];
406 }
407
408
409
410 void IFDone (CharSource* S)
411 /* Close the current input file */
412 {
413     /* We're at the end of an include file. Check if we have any
414      * open .IFs, or any open token lists in this file. This
415      * enforcement is artificial, using conditionals that start
416      * in one file and end in another are uncommon, and don't
417      * allowing these things will help finding errors.
418      */
419     CheckOpenIfs ();
420
421     /* Close the input file and decrement the file count. We will ignore
422      * errors here, since we were just reading from the file.
423      */
424     (void) fclose (S->V.File.F);
425     --FCount;
426 }
427
428
429
430 /* Set of input file handling functions */
431 static const CharSourceFunctions IFFunc = {
432     IFMarkStart,
433     IFNextChar,
434     IFDone
435 };
436
437
438
439 int NewInputFile (const char* Name)
440 /* Open a new input file. Returns true if the file could be successfully opened
441  * and false otherwise.
442  */
443 {
444     int RetCode = 0;            /* Return code. Assume an error. */
445     char* PathName = 0;
446
447     /* First try to open the file */
448     FILE* F = fopen (Name, "r");
449     if (F == 0) {
450
451         /* Error (fatal error if this is the main file) */
452         if (FCount == 0) {
453             Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
454         }
455
456         /* We are on include level. Search for the file in the include
457          * directories.
458          */
459         PathName = FindInclude (Name, INC_STD);
460         if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
461             /* Not found or cannot open, print an error and bail out */
462             Error ("Cannot open include file `%s': %s", Name, strerror (errno));
463             goto ExitPoint;
464         }
465
466         /* Use the path name from now on */
467         Name = PathName;
468     }
469
470     /* check again if we do now have an open file */
471     if (F != 0) {
472
473         StrBuf          NameBuf;
474         unsigned        FileIdx;
475         CharSource*     S;
476
477         /* Stat the file and remember the values. There a race condition here,
478          * since we cannot use fileno() (non standard identifier in standard
479          * header file), and therefore not fstat. When using stat with the
480          * file name, there's a risk that the file was deleted and recreated
481          * while it was open. Since mtime and size are only used to check
482          * if a file has changed in the debugger, we will ignore this problem
483          * here.
484          */
485         struct stat Buf;
486         if (stat (Name, &Buf) != 0) {
487             Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
488         }
489
490         /* Add the file to the input file table and remember the index */
491         FileIdx = AddFile (SB_InitFromString (&NameBuf, Name), Buf.st_size, Buf.st_mtime);
492
493         /* Create a new input source variable and initialize it */
494         S                   = xmalloc (sizeof (*S));
495         S->Func             = &IFFunc;
496         S->V.File.F         = F;
497         S->V.File.Pos.Line  = 0;
498         S->V.File.Pos.Col   = 0;
499         S->V.File.Pos.Name  = FileIdx;
500         S->V.File.Line[0]   = '\0';
501
502         /* Count active input files */
503         ++FCount;
504
505         /* Use this input source */
506         UseCharSource (S);
507     }
508
509     /* File successfully opened */
510     RetCode = 1;
511
512 ExitPoint:
513     /* Free an allocated name buffer */
514     xfree (PathName);
515
516     /* Return the success code */
517     return RetCode;
518 }
519
520
521
522 /*****************************************************************************/
523 /*                            InputData functions                            */
524 /*****************************************************************************/
525
526
527
528 static void IDMarkStart (CharSource* S attribute ((unused)))
529 /* Mark the start of the next token */
530 {
531     /* Nothing to do here */
532 }
533
534
535
536 static void IDNextChar (CharSource* S)
537 /* Read the next character from the input text */
538 {
539     C = *S->V.Data.Pos++;
540     if (C == '\0') {
541         /* End of input data */
542         --S->V.Data.Pos;
543         C = EOF;
544     }
545 }
546
547
548
549 void IDDone (CharSource* S)
550 /* Close the current input data */
551 {
552     /* Cleanup the current stuff */
553     if (S->V.Data.Malloced) {
554         xfree (S->V.Data.Text);
555     }
556 }
557
558
559
560 /* Set of input data handling functions */
561 static const CharSourceFunctions IDFunc = {
562     IDMarkStart,
563     IDNextChar,
564     IDDone
565 };
566
567
568
569 void NewInputData (char* Text, int Malloced)
570 /* Add a chunk of input data to the input stream */
571 {
572     CharSource* S;
573
574     /* Create a new input source variable and initialize it */
575     S                   = xmalloc (sizeof (*S));
576     S->Func             = &IDFunc;
577     S->V.Data.Text      = Text;
578     S->V.Data.Pos       = Text;
579     S->V.Data.Malloced  = Malloced;
580
581     /* Use this input source */
582     UseCharSource (S);
583 }
584
585
586
587 /*****************************************************************************/
588 /*                    Character classification functions                     */
589 /*****************************************************************************/
590
591
592
593 int IsIdChar (int C)
594 /* Return true if the character is a valid character for an identifier */
595 {
596     return IsAlNum (C)                  ||
597            (C == '_')                   ||
598            (C == '@' && AtInIdents)     ||
599            (C == '$' && DollarInIdents);
600 }
601
602
603
604 int IsIdStart (int C)
605 /* Return true if the character may start an identifier */
606 {
607     return IsAlpha (C) || C == '_';
608 }
609
610
611
612 /*****************************************************************************/
613 /*                                   Code                                    */
614 /*****************************************************************************/
615
616
617
618 static unsigned DigitVal (unsigned char C)
619 /* Convert a digit into it's numerical representation */
620 {
621     if (IsDigit (C)) {
622         return C - '0';
623     } else {
624         return toupper (C) - 'A' + 10;
625     }
626 }
627
628
629
630 static void NextChar (void)
631 /* Read the next character from the input file */
632 {
633     Source->Func->NextChar (Source);
634 }
635
636
637
638 void LocaseSVal (void)
639 /* Make SVal lower case */
640 {
641     SB_ToLower (&SVal);
642 }
643
644
645
646 void UpcaseSVal (void)
647 /* Make SVal upper case */
648 {
649     SB_ToUpper (&SVal);
650 }
651
652
653
654 static int CmpDotKeyword (const void* K1, const void* K2)
655 /* Compare function for the dot keyword search */
656 {
657     return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
658 }
659
660
661
662 static unsigned char FindDotKeyword (void)
663 /* Find the dot keyword in SVal. Return the corresponding token if found,
664  * return TOK_NONE if not found.
665  */
666 {
667     struct DotKeyword K;
668     struct DotKeyword* R;
669
670     /* Initialize K */
671     K.Key = SB_GetConstBuf (&SVal);
672     K.Tok = 0;
673
674     /* If we aren't in ignore case mode, we have to uppercase the keyword */
675     if (!IgnoreCase) {
676         UpcaseSVal ();
677     }
678
679     /* Search for the keyword */
680     R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
681                  sizeof (DotKeywords [0]), CmpDotKeyword);
682     if (R != 0) {
683         return R->Tok;
684     } else {
685         return TOK_NONE;
686     }
687 }
688
689
690
691 static void ReadIdent (void)
692 /* Read an identifier from the current input position into Ident. Filling SVal
693  * starts at the current position with the next character in C. It is assumed
694  * that any characters already filled in are ok, and the character in C is
695  * checked.
696  */
697 {
698     /* Read the identifier */
699     do {
700         SB_AppendChar (&SVal, C);
701         NextChar ();
702     } while (IsIdChar (C));
703     SB_Terminate (&SVal);
704
705     /* If we should ignore case, convert the identifier to upper case */
706     if (IgnoreCase) {
707         UpcaseSVal ();
708     }
709 }
710
711
712
713 static void ReadStringConst (int StringTerm)
714 /* Read a string constant into SVal. */
715 {
716     /* Skip the leading string terminator */
717     NextChar ();
718
719     /* Read the string */
720     while (1) {
721         if (C == StringTerm) {
722             break;
723         }
724         if (C == '\n' || C == EOF) {
725             Error ("Newline in string constant");
726             break;
727         }
728
729         /* Append the char to the string */
730         SB_AppendChar (&SVal, C);
731
732         /* Skip the character */
733         NextChar ();
734     }
735
736     /* Skip the trailing terminator */
737     NextChar ();
738
739     /* Terminate the string */
740     SB_Terminate (&SVal);
741 }
742
743
744
745 static int Sweet16Reg (const StrBuf* Id)
746 /* Check if the given identifier is a sweet16 register. Return -1 if this is
747  * not the case, return the register number otherwise.
748  */
749 {
750     unsigned RegNum;
751     char Check;
752
753     if (SB_GetLen (Id) < 2) {
754         return -1;
755     }
756     if (toupper (SB_AtUnchecked (Id, 0)) != 'R') {
757         return -1;
758     }
759     if (!IsDigit (SB_AtUnchecked (Id, 1))) {
760         return -1;
761     }
762
763     if (sscanf (SB_GetConstBuf (Id)+1, "%u%c", &RegNum, &Check) != 1 || RegNum > 15) {
764         /* Invalid register */
765         return -1;
766     }
767
768     /* The register number is valid */
769     return (int) RegNum;
770 }
771
772
773
774 void NextRawTok (void)
775 /* Read the next raw token from the input stream */
776 {
777     /* If we've a forced end of assembly, don't read further */
778     if (ForcedEnd) {
779         Tok = TOK_EOF;
780         return;
781     }
782
783 Restart:
784     /* Check if we have tokens from another input source */
785     if (InputFromStack ()) {
786         return;
787     }
788
789 Again:
790     /* Skip whitespace, remember if we had some */
791     if ((WS = IsBlank (C)) != 0) {
792         do {
793             NextChar ();
794         } while (IsBlank (C));
795     }
796
797     /* Mark the file position of the next token */
798     Source->Func->MarkStart (Source);
799
800     /* Clear the string attribute */
801     SB_Clear (&SVal);
802
803     /* Hex number or PC symbol? */
804     if (C == '$') {
805         NextChar ();
806
807         /* Hex digit must follow or DollarIsPC must be enabled */
808         if (!IsXDigit (C)) {
809             if (DollarIsPC) {
810                 Tok = TOK_PC;
811                 return;
812             } else {
813                 Error ("Hexadecimal digit expected");
814             }
815         }
816
817         /* Read the number */
818         IVal = 0;
819         while (IsXDigit (C)) {
820             if (IVal & 0xF0000000) {
821                 Error ("Overflow in hexadecimal number");
822                 IVal = 0;
823             }
824             IVal = (IVal << 4) + DigitVal (C);
825             NextChar ();
826         }
827
828         /* This is an integer constant */
829         Tok = TOK_INTCON;
830         return;
831     }
832
833     /* Binary number? */
834     if (C == '%') {
835         NextChar ();
836
837         /* 0 or 1 must follow */
838         if (!IsBDigit (C)) {
839             Error ("Binary digit expected");
840         }
841
842         /* Read the number */
843         IVal = 0;
844         while (IsBDigit (C)) {
845             if (IVal & 0x80000000) {
846                 Error ("Overflow in binary number");
847                 IVal = 0;
848             }
849             IVal = (IVal << 1) + DigitVal (C);
850             NextChar ();
851         }
852
853         /* This is an integer constant */
854         Tok = TOK_INTCON;
855         return;
856     }
857
858     /* Number? */
859     if (IsDigit (C)) {
860
861         char Buf[16];
862         unsigned Digits;
863         unsigned Base;
864         unsigned I;
865         long     Max;
866         unsigned DVal;
867
868         /* Ignore leading zeros */
869         while (C == '0') {
870             NextChar ();
871         }
872
873         /* Read the number into Buf counting the digits */
874         Digits = 0;
875         while (IsXDigit (C)) {
876
877             /* Buf is big enough to allow any decimal and hex number to
878              * overflow, so ignore excess digits here, they will be detected
879              * when we convert the value.
880              */
881             if (Digits < sizeof (Buf)) {
882                 Buf[Digits++] = C;
883             }
884
885             NextChar ();
886         }
887
888         /* Allow zilog/intel style hex numbers with a 'h' suffix */
889         if (C == 'h' || C == 'H') {
890             NextChar ();
891             Base = 16;
892             Max  = 0xFFFFFFFFUL / 16;
893         } else {
894             Base = 10;
895             Max  = 0xFFFFFFFFUL / 10;
896         }
897
898         /* Convert the number using the given base */
899         IVal = 0;
900         for (I = 0; I < Digits; ++I) {
901             if (IVal > Max) {
902                 Error ("Number out of range");
903                 IVal = 0;
904                 break;
905             }
906             DVal = DigitVal (Buf[I]);
907             if (DVal > Base) {
908                 Error ("Invalid digits in number");
909                 IVal = 0;
910                 break;
911             }
912             IVal = (IVal * Base) + DVal;
913         }
914
915         /* This is an integer constant */
916         Tok = TOK_INTCON;
917         return;
918     }
919
920     /* Control command? */
921     if (C == '.') {
922
923         /* Remember and skip the dot */
924         NextChar ();
925
926         /* Check if it's just a dot */
927         if (!IsIdStart (C)) {
928
929             /* Just a dot */
930             Tok = TOK_DOT;
931
932         } else {
933
934             /* Read the remainder of the identifier */
935             SB_AppendChar (&SVal, '.');
936             ReadIdent ();
937
938             /* Dot keyword, search for it */
939             Tok = FindDotKeyword ();
940             if (Tok == TOK_NONE) {
941
942                 /* Not found */
943                 if (!LeadingDotInIdents) {
944                     /* Invalid pseudo instruction */
945                     Error ("`%m%p' is not a recognized control command", &SVal);
946                     goto Again;
947                 }
948
949                 /* An identifier with a dot. Check if it's a define style
950                  * macro.
951                  */
952                 if (IsDefine (&SVal)) {
953                     /* This is a define style macro - expand it */
954                     MacExpandStart ();
955                     goto Restart;
956                 }
957
958                 /* Just an identifier with a dot */
959                 Tok = TOK_IDENT;
960             }
961
962         }
963         return;
964     }
965
966     /* Indirect op for sweet16 cpu. Must check this before checking for local
967      * symbols, because these may also use the '@' symbol.
968      */
969     if (CPU == CPU_SWEET16 && C == '@') {
970         NextChar ();
971         Tok = TOK_AT;
972         return;
973     }
974
975     /* Local symbol? */
976     if (C == LocalStart) {
977
978         /* Read the identifier. */
979         ReadIdent ();
980
981         /* Start character alone is not enough */
982         if (SB_GetLen (&SVal) == 1) {
983             Error ("Invalid cheap local symbol");
984             goto Again;
985         }
986
987         /* A local identifier */
988         Tok = TOK_LOCAL_IDENT;
989         return;
990     }
991
992
993     /* Identifier or keyword? */
994     if (IsIdStart (C)) {
995
996         /* Read the identifier */
997         ReadIdent ();
998
999         /* Check for special names. Bail out if we have identified the type of
1000          * the token. Go on if the token is an identifier.
1001          */
1002         if (SB_GetLen (&SVal) == 1) {
1003             switch (toupper (SB_AtUnchecked (&SVal, 0))) {
1004
1005                 case 'A':
1006                     if (C == ':') {
1007                         NextChar ();
1008                         Tok = TOK_OVERRIDE_ABS;
1009                     } else {
1010                         Tok = TOK_A;
1011                     }
1012                     return;
1013
1014                 case 'F':
1015                     if (C == ':') {
1016                         NextChar ();
1017                         Tok = TOK_OVERRIDE_FAR;
1018                         return;
1019                     }
1020                     break;
1021
1022                 case 'S':
1023                     if (CPU == CPU_65816) {
1024                         Tok = TOK_S;
1025                         return;
1026                     }
1027                     break;
1028
1029                 case 'X':
1030                     Tok = TOK_X;
1031                     return;
1032
1033                 case 'Y':
1034                     Tok = TOK_Y;
1035                     return;
1036
1037                 case 'Z':
1038                     if (C == ':') {
1039                         NextChar ();
1040                         Tok = TOK_OVERRIDE_ZP;
1041                         return;
1042                     }
1043                     break;
1044
1045                 default:
1046                     break;
1047             }
1048
1049         } else if (CPU == CPU_SWEET16 && (IVal = Sweet16Reg (&SVal)) >= 0) {
1050
1051             /* A sweet16 register number in sweet16 mode */
1052             Tok = TOK_REG;
1053             return;
1054
1055         }
1056
1057         /* Check for define style macro */
1058         if (IsDefine (&SVal)) {
1059             /* Macro - expand it */
1060             MacExpandStart ();
1061             goto Restart;
1062         } else {
1063             /* An identifier */
1064             Tok = TOK_IDENT;
1065         }
1066         return;
1067     }
1068
1069     /* Ok, let's do the switch */
1070 CharAgain:
1071     switch (C) {
1072
1073         case '+':
1074             NextChar ();
1075             Tok = TOK_PLUS;
1076             return;
1077
1078         case '-':
1079             NextChar ();
1080             Tok = TOK_MINUS;
1081             return;
1082
1083         case '/':
1084             NextChar ();
1085             if (C != '*') {
1086                 Tok = TOK_DIV;
1087             } else if (CComments) {
1088                 /* Remember the position, then skip the '*' */
1089                 FilePos Pos = CurPos;
1090                 NextChar ();
1091                 do {
1092                     while (C !=  '*') {
1093                         if (C == EOF) {
1094                             PError (&Pos, "Unterminated comment");
1095                             goto CharAgain;
1096                         }
1097                         NextChar ();
1098                     }
1099                     NextChar ();
1100                 } while (C != '/');
1101                 NextChar ();
1102                 goto Again;
1103             }
1104             return;
1105
1106         case '*':
1107             NextChar ();
1108             Tok = TOK_MUL;
1109             return;
1110
1111         case '^':
1112             NextChar ();
1113             Tok = TOK_XOR;
1114             return;
1115
1116         case '&':
1117             NextChar ();
1118             if (C == '&') {
1119                 NextChar ();
1120                 Tok = TOK_BOOLAND;
1121             } else {
1122                 Tok = TOK_AND;
1123             }
1124             return;
1125
1126         case '|':
1127             NextChar ();
1128             if (C == '|') {
1129                 NextChar ();
1130                 Tok = TOK_BOOLOR;
1131             } else {
1132                 Tok = TOK_OR;
1133             }
1134             return;
1135
1136         case ':':
1137             NextChar ();
1138             switch (C) {
1139
1140                 case ':':
1141                     NextChar ();
1142                     Tok = TOK_NAMESPACE;
1143                     break;
1144
1145                 case '-':
1146                     IVal = 0;
1147                     do {
1148                         --IVal;
1149                         NextChar ();
1150                     } while (C == '-');
1151                     Tok = TOK_ULABEL;
1152                     break;
1153
1154                 case '+':
1155                     IVal = 0;
1156                     do {
1157                         ++IVal;
1158                         NextChar ();
1159                     } while (C == '+');
1160                     Tok = TOK_ULABEL;
1161                     break;
1162
1163                 case '=':
1164                     NextChar ();
1165                     Tok = TOK_ASSIGN;
1166                     break;
1167
1168                 default:
1169                     Tok = TOK_COLON;
1170                     break;
1171             }
1172             return;
1173
1174         case ',':
1175             NextChar ();
1176             Tok = TOK_COMMA;
1177             return;
1178
1179         case ';':
1180             NextChar ();
1181             while (C != '\n' && C != EOF) {
1182                 NextChar ();
1183             }
1184             goto CharAgain;
1185
1186         case '#':
1187             NextChar ();
1188             Tok = TOK_HASH;
1189             return;
1190
1191         case '(':
1192             NextChar ();
1193             Tok = TOK_LPAREN;
1194             return;
1195
1196         case ')':
1197             NextChar ();
1198             Tok = TOK_RPAREN;
1199             return;
1200
1201         case '[':
1202             NextChar ();
1203             Tok = TOK_LBRACK;
1204             return;
1205
1206         case ']':
1207             NextChar ();
1208             Tok = TOK_RBRACK;
1209             return;
1210
1211         case '{':
1212             NextChar ();
1213             Tok = TOK_LCURLY;
1214             return;
1215
1216         case '}':
1217             NextChar ();
1218             Tok = TOK_RCURLY;
1219             return;
1220
1221         case '<':
1222             NextChar ();
1223             if (C == '=') {
1224                 NextChar ();
1225                 Tok = TOK_LE;
1226             } else if (C == '<') {
1227                 NextChar ();
1228                 Tok = TOK_SHL;
1229             } else if (C == '>') {
1230                 NextChar ();
1231                 Tok = TOK_NE;
1232             } else {
1233                 Tok = TOK_LT;
1234             }
1235             return;
1236
1237         case '=':
1238             NextChar ();
1239             Tok = TOK_EQ;
1240             return;
1241
1242         case '!':
1243             NextChar ();
1244             Tok = TOK_BOOLNOT;
1245             return;
1246
1247         case '>':
1248             NextChar ();
1249             if (C == '=') {
1250                 NextChar ();
1251                 Tok = TOK_GE;
1252             } else if (C == '>') {
1253                 NextChar ();
1254                 Tok = TOK_SHR;
1255             } else {
1256                 Tok = TOK_GT;
1257             }
1258             return;
1259
1260         case '~':
1261             NextChar ();
1262             Tok = TOK_NOT;
1263             return;
1264
1265         case '\'':
1266             /* Hack: If we allow ' as terminating character for strings, read
1267              * the following stuff as a string, and check for a one character
1268              * string later.
1269              */
1270             if (LooseStringTerm) {
1271                 ReadStringConst ('\'');
1272                 if (SB_GetLen (&SVal) == 1) {
1273                     IVal = SB_AtUnchecked (&SVal, 0);
1274                     Tok = TOK_CHARCON;
1275                 } else {
1276                     Tok = TOK_STRCON;
1277                 }
1278             } else {
1279                 /* Always a character constant */
1280                 NextChar ();
1281                 if (C == EOF || IsControl (C)) {
1282                     Error ("Illegal character constant");
1283                     goto CharAgain;
1284                 }
1285                 IVal = C;
1286                 Tok = TOK_CHARCON;
1287                 NextChar ();
1288                 if (C != '\'') {
1289                     if (!MissingCharTerm) {
1290                         Error ("Illegal character constant");
1291                     }
1292                 } else {
1293                     NextChar ();
1294                 }
1295             }
1296             return;
1297
1298         case '\"':
1299             ReadStringConst ('\"');
1300             Tok = TOK_STRCON;
1301             return;
1302
1303         case '\\':
1304             /* Line continuation? */
1305             if (LineCont) {
1306                 NextChar ();
1307                 if (C == '\n') {
1308                     /* Handle as white space */
1309                     NextChar ();
1310                     C = ' ';
1311                     goto Again;
1312                 }
1313             }
1314             break;
1315
1316         case '\n':
1317             NextChar ();
1318             Tok = TOK_SEP;
1319             return;
1320
1321         case EOF:
1322             CheckInputStack ();
1323             /* In case of the main file, do not close it, but return EOF. */
1324             if (Source && Source->Next) {
1325                 DoneCharSource ();
1326                 goto Again;
1327             } else {
1328                 Tok = TOK_EOF;
1329             }
1330             return;
1331     }
1332
1333     /* If we go here, we could not identify the current character. Skip it
1334      * and try again.
1335      */
1336     Error ("Invalid input character: 0x%02X", C & 0xFF);
1337     NextChar ();
1338     goto Again;
1339 }
1340
1341
1342
1343 int GetSubKey (const char** Keys, unsigned Count)
1344 /* Search for a subkey in a table of keywords. The current token must be an
1345  * identifier and all keys must be in upper case. The identifier will be
1346  * uppercased in the process. The function returns the index of the keyword,
1347  * or -1 if the keyword was not found.
1348  */
1349 {
1350     unsigned I;
1351
1352     /* Must have an identifier */
1353     PRECONDITION (Tok == TOK_IDENT);
1354
1355     /* If we aren't in ignore case mode, we have to uppercase the identifier */
1356     if (!IgnoreCase) {
1357         UpcaseSVal ();
1358     }
1359
1360     /* Do a linear search (a binary search is not worth the effort) */
1361     for (I = 0; I < Count; ++I) {
1362         if (SB_CompareStr (&SVal, Keys [I]) == 0) {
1363             /* Found it */
1364             return I;
1365         }
1366     }
1367
1368     /* Not found */
1369     return -1;
1370 }
1371
1372
1373
1374 unsigned char ParseAddrSize (void)
1375 /* Check if the next token is a keyword that denotes an address size specifier.
1376  * If so, return the corresponding address size constant, otherwise output an
1377  * error message and return ADDR_SIZE_DEFAULT.
1378  */
1379 {
1380     unsigned char AddrSize;
1381
1382     /* Check for an identifier */
1383     if (Tok != TOK_IDENT) {
1384         Error ("Address size specifier expected");
1385         return ADDR_SIZE_DEFAULT;
1386     }
1387
1388     /* Convert the attribute */
1389     AddrSize = AddrSizeFromStr (SB_GetConstBuf (&SVal));
1390     if (AddrSize == ADDR_SIZE_INVALID) {
1391         Error ("Address size specifier expected");
1392         AddrSize = ADDR_SIZE_DEFAULT;
1393     }
1394
1395     /* Done */
1396     return AddrSize;
1397 }
1398
1399
1400
1401 void InitScanner (const char* InFile)
1402 /* Initialize the scanner, open the given input file */
1403 {
1404     /* Open the input file */
1405     NewInputFile (InFile);
1406 }
1407
1408
1409
1410 void DoneScanner (void)
1411 /* Release scanner resources */
1412 {
1413     DoneCharSource ();
1414 }
1415
1416
1417