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