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