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