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