]> git.sur5r.net Git - cc65/blob - src/ca65/scanner.c
More lineinfo usage.
[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     /* Generate line info for the current token */
817     GenLineInfo (LI_SLOT_ASM, &CurTok.Pos);
818
819     /* Hex number or PC symbol? */
820     if (C == '$') {
821         NextChar ();
822
823         /* Hex digit must follow or DollarIsPC must be enabled */
824         if (!IsXDigit (C)) {
825             if (DollarIsPC) {
826                 CurTok.Tok = TOK_PC;
827                 return;
828             } else {
829                 Error ("Hexadecimal digit expected");
830             }
831         }
832
833         /* Read the number */
834         CurTok.IVal = 0;
835         while (IsXDigit (C)) {
836             if (CurTok.IVal & 0xF0000000) {
837                 Error ("Overflow in hexadecimal number");
838                 CurTok.IVal = 0;
839             }
840             CurTok.IVal = (CurTok.IVal << 4) + DigitVal (C);
841             NextChar ();
842         }
843
844         /* This is an integer constant */
845         CurTok.Tok = TOK_INTCON;
846         return;
847     }
848
849     /* Binary number? */
850     if (C == '%') {
851         NextChar ();
852
853         /* 0 or 1 must follow */
854         if (!IsBDigit (C)) {
855             Error ("Binary digit expected");
856         }
857
858         /* Read the number */
859         CurTok.IVal = 0;
860         while (IsBDigit (C)) {
861             if (CurTok.IVal & 0x80000000) {
862                 Error ("Overflow in binary number");
863                 CurTok.IVal = 0;
864             }
865             CurTok.IVal = (CurTok.IVal << 1) + DigitVal (C);
866             NextChar ();
867         }
868
869         /* This is an integer constant */
870         CurTok.Tok = TOK_INTCON;
871         return;
872     }
873
874     /* Number? */
875     if (IsDigit (C)) {
876
877         char Buf[16];
878         unsigned Digits;
879         unsigned Base;
880         unsigned I;
881         long     Max;
882         unsigned DVal;
883
884         /* Ignore leading zeros */
885         while (C == '0') {
886             NextChar ();
887         }
888
889         /* Read the number into Buf counting the digits */
890         Digits = 0;
891         while (IsXDigit (C)) {
892
893             /* Buf is big enough to allow any decimal and hex number to
894              * overflow, so ignore excess digits here, they will be detected
895              * when we convert the value.
896              */
897             if (Digits < sizeof (Buf)) {
898                 Buf[Digits++] = C;
899             }
900
901             NextChar ();
902         }
903
904         /* Allow zilog/intel style hex numbers with a 'h' suffix */
905         if (C == 'h' || C == 'H') {
906             NextChar ();
907             Base = 16;
908             Max  = 0xFFFFFFFFUL / 16;
909         } else {
910             Base = 10;
911             Max  = 0xFFFFFFFFUL / 10;
912         }
913
914         /* Convert the number using the given base */
915         CurTok.IVal = 0;
916         for (I = 0; I < Digits; ++I) {
917             if (CurTok.IVal > Max) {
918                 Error ("Number out of range");
919                 CurTok.IVal = 0;
920                 break;
921             }
922             DVal = DigitVal (Buf[I]);
923             if (DVal > Base) {
924                 Error ("Invalid digits in number");
925                 CurTok.IVal = 0;
926                 break;
927             }
928             CurTok.IVal = (CurTok.IVal * Base) + DVal;
929         }
930
931         /* This is an integer constant */
932         CurTok.Tok = TOK_INTCON;
933         return;
934     }
935
936     /* Control command? */
937     if (C == '.') {
938
939         /* Remember and skip the dot */
940         NextChar ();
941
942         /* Check if it's just a dot */
943         if (!IsIdStart (C)) {
944
945             /* Just a dot */
946             CurTok.Tok = TOK_DOT;
947
948         } else {
949
950             /* Read the remainder of the identifier */
951             SB_AppendChar (&CurTok.SVal, '.');
952             ReadIdent ();
953
954             /* Dot keyword, search for it */
955             CurTok.Tok = FindDotKeyword ();
956             if (CurTok.Tok == TOK_NONE) {
957
958                 /* Not found */
959                 if (!LeadingDotInIdents) {
960                     /* Invalid pseudo instruction */
961                     Error ("`%m%p' is not a recognized control command", &CurTok.SVal);
962                     goto Again;
963                 }
964
965                 /* An identifier with a dot. Check if it's a define style
966                  * macro.
967                  */
968                 if (IsDefine (&CurTok.SVal)) {
969                     /* This is a define style macro - expand it */
970                     MacExpandStart ();
971                     goto Restart;
972                 }
973
974                 /* Just an identifier with a dot */
975                 CurTok.Tok = TOK_IDENT;
976             }
977
978         }
979         return;
980     }
981
982     /* Indirect op for sweet16 cpu. Must check this before checking for local
983      * symbols, because these may also use the '@' symbol.
984      */
985     if (CPU == CPU_SWEET16 && C == '@') {
986         NextChar ();
987         CurTok.Tok = TOK_AT;
988         return;
989     }
990
991     /* Local symbol? */
992     if (C == LocalStart) {
993
994         /* Read the identifier. */
995         ReadIdent ();
996
997         /* Start character alone is not enough */
998         if (SB_GetLen (&CurTok.SVal) == 1) {
999             Error ("Invalid cheap local symbol");
1000             goto Again;
1001         }
1002
1003         /* A local identifier */
1004         CurTok.Tok = TOK_LOCAL_IDENT;
1005         return;
1006     }
1007
1008
1009     /* Identifier or keyword? */
1010     if (IsIdStart (C)) {
1011
1012         /* Read the identifier */
1013         ReadIdent ();
1014
1015         /* Check for special names. Bail out if we have identified the type of
1016          * the token. Go on if the token is an identifier.
1017          */
1018         if (SB_GetLen (&CurTok.SVal) == 1) {
1019             switch (toupper (SB_AtUnchecked (&CurTok.SVal, 0))) {
1020
1021                 case 'A':
1022                     if (C == ':') {
1023                         NextChar ();
1024                         CurTok.Tok = TOK_OVERRIDE_ABS;
1025                     } else {
1026                         CurTok.Tok = TOK_A;
1027                     }
1028                     return;
1029
1030                 case 'F':
1031                     if (C == ':') {
1032                         NextChar ();
1033                         CurTok.Tok = TOK_OVERRIDE_FAR;
1034                         return;
1035                     }
1036                     break;
1037
1038                 case 'S':
1039                     if (CPU == CPU_65816) {
1040                         CurTok.Tok = TOK_S;
1041                         return;
1042                     }
1043                     break;
1044
1045                 case 'X':
1046                     CurTok.Tok = TOK_X;
1047                     return;
1048
1049                 case 'Y':
1050                     CurTok.Tok = TOK_Y;
1051                     return;
1052
1053                 case 'Z':
1054                     if (C == ':') {
1055                         NextChar ();
1056                         CurTok.Tok = TOK_OVERRIDE_ZP;
1057                         return;
1058                     }
1059                     break;
1060
1061                 default:
1062                     break;
1063             }
1064
1065         } else if (CPU == CPU_SWEET16 &&
1066                   (CurTok.IVal = Sweet16Reg (&CurTok.SVal)) >= 0) {
1067
1068             /* A sweet16 register number in sweet16 mode */
1069             CurTok.Tok = TOK_REG;
1070             return;
1071
1072         }
1073
1074         /* Check for define style macro */
1075         if (IsDefine (&CurTok.SVal)) {
1076             /* Macro - expand it */
1077             MacExpandStart ();
1078             goto Restart;
1079         } else {
1080             /* An identifier */
1081             CurTok.Tok = TOK_IDENT;
1082         }
1083         return;
1084     }
1085
1086     /* Ok, let's do the switch */
1087 CharAgain:
1088     switch (C) {
1089
1090         case '+':
1091             NextChar ();
1092             CurTok.Tok = TOK_PLUS;
1093             return;
1094
1095         case '-':
1096             NextChar ();
1097             CurTok.Tok = TOK_MINUS;
1098             return;
1099
1100         case '/':
1101             NextChar ();
1102             if (C != '*') {
1103                 CurTok.Tok = TOK_DIV;
1104             } else if (CComments) {
1105                 /* Remember the position, then skip the '*' */
1106                 FilePos Pos = CurTok.Pos;
1107                 NextChar ();
1108                 do {
1109                     while (C !=  '*') {
1110                         if (C == EOF) {
1111                             PError (&Pos, "Unterminated comment");
1112                             goto CharAgain;
1113                         }
1114                         NextChar ();
1115                     }
1116                     NextChar ();
1117                 } while (C != '/');
1118                 NextChar ();
1119                 goto Again;
1120             }
1121             return;
1122
1123         case '*':
1124             NextChar ();
1125             CurTok.Tok = TOK_MUL;
1126             return;
1127
1128         case '^':
1129             NextChar ();
1130             CurTok.Tok = TOK_XOR;
1131             return;
1132
1133         case '&':
1134             NextChar ();
1135             if (C == '&') {
1136                 NextChar ();
1137                 CurTok.Tok = TOK_BOOLAND;
1138             } else {
1139                 CurTok.Tok = TOK_AND;
1140             }
1141             return;
1142
1143         case '|':
1144             NextChar ();
1145             if (C == '|') {
1146                 NextChar ();
1147                 CurTok.Tok = TOK_BOOLOR;
1148             } else {
1149                 CurTok.Tok = TOK_OR;
1150             }
1151             return;
1152
1153         case ':':
1154             NextChar ();
1155             switch (C) {
1156
1157                 case ':':
1158                     NextChar ();
1159                     CurTok.Tok = TOK_NAMESPACE;
1160                     break;
1161
1162                 case '-':
1163                     CurTok.IVal = 0;
1164                     do {
1165                         --CurTok.IVal;
1166                         NextChar ();
1167                     } while (C == '-');
1168                     CurTok.Tok = TOK_ULABEL;
1169                     break;
1170
1171                 case '+':
1172                     CurTok.IVal = 0;
1173                     do {
1174                         ++CurTok.IVal;
1175                         NextChar ();
1176                     } while (C == '+');
1177                     CurTok.Tok = TOK_ULABEL;
1178                     break;
1179
1180                 case '=':
1181                     NextChar ();
1182                     CurTok.Tok = TOK_ASSIGN;
1183                     break;
1184
1185                 default:
1186                     CurTok.Tok = TOK_COLON;
1187                     break;
1188             }
1189             return;
1190
1191         case ',':
1192             NextChar ();
1193             CurTok.Tok = TOK_COMMA;
1194             return;
1195
1196         case ';':
1197             NextChar ();
1198             while (C != '\n' && C != EOF) {
1199                 NextChar ();
1200             }
1201             goto CharAgain;
1202
1203         case '#':
1204             NextChar ();
1205             CurTok.Tok = TOK_HASH;
1206             return;
1207
1208         case '(':
1209             NextChar ();
1210             CurTok.Tok = TOK_LPAREN;
1211             return;
1212
1213         case ')':
1214             NextChar ();
1215             CurTok.Tok = TOK_RPAREN;
1216             return;
1217
1218         case '[':
1219             NextChar ();
1220             CurTok.Tok = TOK_LBRACK;
1221             return;
1222
1223         case ']':
1224             NextChar ();
1225             CurTok.Tok = TOK_RBRACK;
1226             return;
1227
1228         case '{':
1229             NextChar ();
1230             CurTok.Tok = TOK_LCURLY;
1231             return;
1232
1233         case '}':
1234             NextChar ();
1235             CurTok.Tok = TOK_RCURLY;
1236             return;
1237
1238         case '<':
1239             NextChar ();
1240             if (C == '=') {
1241                 NextChar ();
1242                 CurTok.Tok = TOK_LE;
1243             } else if (C == '<') {
1244                 NextChar ();
1245                 CurTok.Tok = TOK_SHL;
1246             } else if (C == '>') {
1247                 NextChar ();
1248                 CurTok.Tok = TOK_NE;
1249             } else {
1250                 CurTok.Tok = TOK_LT;
1251             }
1252             return;
1253
1254         case '=':
1255             NextChar ();
1256             CurTok.Tok = TOK_EQ;
1257             return;
1258
1259         case '!':
1260             NextChar ();
1261             CurTok.Tok = TOK_BOOLNOT;
1262             return;
1263
1264         case '>':
1265             NextChar ();
1266             if (C == '=') {
1267                 NextChar ();
1268                 CurTok.Tok = TOK_GE;
1269             } else if (C == '>') {
1270                 NextChar ();
1271                 CurTok.Tok = TOK_SHR;
1272             } else {
1273                 CurTok.Tok = TOK_GT;
1274             }
1275             return;
1276
1277         case '~':
1278             NextChar ();
1279             CurTok.Tok = TOK_NOT;
1280             return;
1281
1282         case '\'':
1283             /* Hack: If we allow ' as terminating character for strings, read
1284              * the following stuff as a string, and check for a one character
1285              * string later.
1286              */
1287             if (LooseStringTerm) {
1288                 ReadStringConst ('\'');
1289                 if (SB_GetLen (&CurTok.SVal) == 1) {
1290                     CurTok.IVal = SB_AtUnchecked (&CurTok.SVal, 0);
1291                     CurTok.Tok = TOK_CHARCON;
1292                 } else {
1293                     CurTok.Tok = TOK_STRCON;
1294                 }
1295             } else {
1296                 /* Always a character constant */
1297                 NextChar ();
1298                 if (C == EOF || IsControl (C)) {
1299                     Error ("Illegal character constant");
1300                     goto CharAgain;
1301                 }
1302                 CurTok.IVal = C;
1303                 CurTok.Tok = TOK_CHARCON;
1304                 NextChar ();
1305                 if (C != '\'') {
1306                     if (!MissingCharTerm) {
1307                         Error ("Illegal character constant");
1308                     }
1309                 } else {
1310                     NextChar ();
1311                 }
1312             }
1313             return;
1314
1315         case '\"':
1316             ReadStringConst ('\"');
1317             CurTok.Tok = TOK_STRCON;
1318             return;
1319
1320         case '\\':
1321             /* Line continuation? */
1322             if (LineCont) {
1323                 NextChar ();
1324                 if (C == '\n') {
1325                     /* Handle as white space */
1326                     NextChar ();
1327                     C = ' ';
1328                     goto Again;
1329                 }
1330             }
1331             break;
1332
1333         case '\n':
1334             NextChar ();
1335             CurTok.Tok = TOK_SEP;
1336             return;
1337
1338         case EOF:
1339             CheckInputStack ();
1340             /* In case of the main file, do not close it, but return EOF. */
1341             if (Source && Source->Next) {
1342                 DoneCharSource ();
1343                 goto Again;
1344             } else {
1345                 CurTok.Tok = TOK_EOF;
1346             }
1347             return;
1348     }
1349
1350     /* If we go here, we could not identify the current character. Skip it
1351      * and try again.
1352      */
1353     Error ("Invalid input character: 0x%02X", C & 0xFF);
1354     NextChar ();
1355     goto Again;
1356 }
1357
1358
1359
1360 int GetSubKey (const char** Keys, unsigned Count)
1361 /* Search for a subkey in a table of keywords. The current token must be an
1362  * identifier and all keys must be in upper case. The identifier will be
1363  * uppercased in the process. The function returns the index of the keyword,
1364  * or -1 if the keyword was not found.
1365  */
1366 {
1367     unsigned I;
1368
1369     /* Must have an identifier */
1370     PRECONDITION (CurTok.Tok == TOK_IDENT);
1371
1372     /* If we aren't in ignore case mode, we have to uppercase the identifier */
1373     if (!IgnoreCase) {
1374         UpcaseSVal ();
1375     }
1376
1377     /* Do a linear search (a binary search is not worth the effort) */
1378     for (I = 0; I < Count; ++I) {
1379         if (SB_CompareStr (&CurTok.SVal, Keys [I]) == 0) {
1380             /* Found it */
1381             return I;
1382         }
1383     }
1384
1385     /* Not found */
1386     return -1;
1387 }
1388
1389
1390
1391 unsigned char ParseAddrSize (void)
1392 /* Check if the next token is a keyword that denotes an address size specifier.
1393  * If so, return the corresponding address size constant, otherwise output an
1394  * error message and return ADDR_SIZE_DEFAULT.
1395  */
1396 {
1397     unsigned char AddrSize;
1398
1399     /* Check for an identifier */
1400     if (CurTok.Tok != TOK_IDENT) {
1401         Error ("Address size specifier expected");
1402         return ADDR_SIZE_DEFAULT;
1403     }
1404
1405     /* Convert the attribute */
1406     AddrSize = AddrSizeFromStr (SB_GetConstBuf (&CurTok.SVal));
1407     if (AddrSize == ADDR_SIZE_INVALID) {
1408         Error ("Address size specifier expected");
1409         AddrSize = ADDR_SIZE_DEFAULT;
1410     }
1411
1412     /* Done */
1413     return AddrSize;
1414 }
1415
1416
1417
1418 void InitScanner (const char* InFile)
1419 /* Initialize the scanner, open the given input file */
1420 {
1421     /* Open the input file */
1422     NewInputFile (InFile);
1423 }
1424
1425
1426
1427 void DoneScanner (void)
1428 /* Release scanner resources */
1429 {
1430     DoneCharSource ();
1431 }
1432
1433
1434
1435