1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2003 Ullrich von Bassewitz */
10 /* Römerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
41 #include <sys/types.h> /* EMX needs this */
65 /*****************************************************************************/
67 /*****************************************************************************/
71 enum Token Tok = TOK_NONE; /* Current token */
72 int WS; /* Flag: Whitespace before token */
73 long IVal; /* Integer token attribute */
74 char SVal [MAX_STR_LEN+1]; /* String token attribute */
76 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
80 /* Struct to handle include files. Note: The length of the input line may
81 * not exceed 255+1, since the column is stored in the file position struct
82 * as a character. Increasing this value means changing the FilePos struct,
83 * and the read and write routines in the assembler and linker.
85 typedef struct InputFile_ InputFile;
87 FILE* F; /* Input file descriptor */
88 FilePos Pos; /* Position in file */
89 enum Token Tok; /* Last token */
90 int C; /* Last character */
91 char Line[256]; /* The current input line */
92 InputFile* Next; /* Linked list of input files */
95 /* Struct to handle textual input data */
96 typedef struct InputData_ InputData;
98 char* Data; /* Pointer to the data */
99 const char* Pos; /* Pointer to current position */
100 int Malloced; /* Memory was malloced */
101 enum Token Tok; /* Last token */
102 int C; /* Last character */
103 InputData* Next; /* Linked list of input data */
106 /* Current input variables */
107 static InputFile* IFile = 0; /* Current input file */
108 static InputData* IData = 0; /* Current input memory data */
109 static unsigned ICount = 0; /* Count of input files */
110 static int C = 0; /* Current input character */
112 /* Force end of assembly */
115 /* List of dot keywords with the corresponding tokens */
117 const char* Key; /* MUST be first field */
122 { ".ADDR", TOK_ADDR },
123 { ".ALIGN", TOK_ALIGN },
124 { ".AND", TOK_BAND },
125 { ".ASCIIZ", TOK_ASCIIZ },
126 { ".AUTOIMPORT", TOK_AUTOIMPORT },
127 { ".BITAND", TOK_AND },
128 { ".BITNOT", TOK_NOT },
129 { ".BITOR", TOK_OR },
130 { ".BITXOR", TOK_XOR },
131 { ".BLANK", TOK_BLANK },
133 { ".BYT", TOK_BYTE },
134 { ".BYTE", TOK_BYTE },
135 { ".CASE", TOK_CASE },
136 { ".CHARMAP", TOK_CHARMAP },
137 { ".CODE", TOK_CODE },
138 { ".CONCAT", TOK_CONCAT },
139 { ".CONDES", TOK_CONDES },
140 { ".CONST", TOK_CONST },
141 { ".CONSTRUCTOR", TOK_CONSTRUCTOR },
143 { ".DATA", TOK_DATA },
145 { ".DBYT", TOK_DBYT },
146 { ".DEBUGINFO", TOK_DEBUGINFO },
147 { ".DEF", TOK_DEFINED },
148 { ".DEFINE", TOK_DEFINE },
149 { ".DEFINED", TOK_DEFINED },
150 { ".DESTRUCTOR", TOK_DESTRUCTOR },
151 { ".DWORD", TOK_DWORD },
152 { ".ELSE", TOK_ELSE },
153 { ".ELSEIF", TOK_ELSEIF },
155 { ".ENDIF", TOK_ENDIF },
156 { ".ENDMAC", TOK_ENDMACRO },
157 { ".ENDMACRO", TOK_ENDMACRO },
158 { ".ENDPROC", TOK_ENDPROC },
159 { ".ENDREP", TOK_ENDREP },
160 { ".ENDREPEAT", TOK_ENDREP },
161 { ".ERROR", TOK_ERROR },
162 { ".EXITMAC", TOK_EXITMACRO },
163 { ".EXITMACRO", TOK_EXITMACRO },
164 { ".EXPORT", TOK_EXPORT },
165 { ".EXPORTZP", TOK_EXPORTZP },
166 { ".FARADDR", TOK_FARADDR },
167 { ".FEATURE", TOK_FEATURE },
168 { ".FILEOPT", TOK_FILEOPT },
169 { ".FOPT", TOK_FILEOPT },
170 { ".FORCEIMPORT", TOK_FORCEIMPORT },
171 { ".FORCEWORD", TOK_FORCEWORD },
172 { ".GLOBAL", TOK_GLOBAL },
173 { ".GLOBALZP", TOK_GLOBALZP },
177 { ".IFBLANK", TOK_IFBLANK },
178 { ".IFCONST", TOK_IFCONST },
179 { ".IFDEF", TOK_IFDEF },
180 { ".IFNBLANK", TOK_IFNBLANK },
181 { ".IFNCONST", TOK_IFNCONST },
182 { ".IFNDEF", TOK_IFNDEF },
183 { ".IFNREF", TOK_IFNREF },
184 { ".IFP02", TOK_IFP02 },
185 { ".IFP816", TOK_IFP816 },
186 { ".IFPC02", TOK_IFPC02 },
187 { ".IFREF", TOK_IFREF },
188 { ".IMPORT", TOK_IMPORT },
189 { ".IMPORTZP", TOK_IMPORTZP },
190 { ".INCBIN", TOK_INCBIN },
191 { ".INCLUDE", TOK_INCLUDE },
192 { ".LEFT", TOK_LEFT },
193 { ".LINECONT", TOK_LINECONT },
194 { ".LIST", TOK_LIST },
195 { ".LISTBYTES", TOK_LISTBYTES },
196 { ".LOCAL", TOK_LOCAL },
197 { ".LOCALCHAR", TOK_LOCALCHAR },
198 { ".MAC", TOK_MACRO },
199 { ".MACPACK", TOK_MACPACK },
200 { ".MACRO", TOK_MACRO },
201 { ".MATCH", TOK_MATCH },
204 { ".NOT", TOK_BNOT },
205 { ".NULL", TOK_NULL },
210 { ".P816", TOK_P816 },
211 { ".PAGELEN", TOK_PAGELENGTH },
212 { ".PAGELENGTH", TOK_PAGELENGTH },
213 { ".PARAMCOUNT", TOK_PARAMCOUNT },
214 { ".PC02", TOK_PC02 },
215 { ".POPSEG", TOK_POPSEG },
216 { ".PROC", TOK_PROC },
217 { ".PUSHSEG", TOK_PUSHSEG },
218 { ".REF", TOK_REFERENCED },
219 { ".REFERENCED", TOK_REFERENCED },
220 { ".RELOC", TOK_RELOC },
221 { ".REPEAT", TOK_REPEAT },
223 { ".RIGHT", TOK_RIGHT },
224 { ".RODATA", TOK_RODATA },
225 { ".SEGMENT", TOK_SEGMENT },
228 { ".SMART", TOK_SMART },
229 { ".STRAT", TOK_STRAT },
230 { ".STRING", TOK_STRING },
231 { ".STRLEN", TOK_STRLEN },
232 { ".SUNPLUS", TOK_SUNPLUS },
233 { ".TCOUNT", TOK_TCOUNT },
234 { ".TIME", TOK_TIME },
235 { ".WARNING", TOK_WARNING },
236 { ".WORD", TOK_WORD },
237 { ".XMATCH", TOK_XMATCH },
238 { ".XOR", TOK_BXOR },
239 { ".ZEROPAGE", TOK_ZEROPAGE },
244 /*****************************************************************************/
246 /*****************************************************************************/
250 static void NextChar (void);
251 /* Read the next character from the input file */
255 /*****************************************************************************/
256 /* Character classification functions */
257 /*****************************************************************************/
261 static int IsIdChar (int C)
262 /* Return true if the character is a valid character for an identifier */
264 return IsAlNum (C) ||
266 (C == '@' && AtInIdents) ||
267 (C == '$' && DollarInIdents);
272 static int IsIdStart (int C)
273 /* Return true if the character may start an identifier */
275 return IsAlpha (C) || C == '_';
280 /*****************************************************************************/
282 /*****************************************************************************/
286 void NewInputFile (const char* Name)
287 /* Open a new input file */
292 /* First try to open the file */
293 F = fopen (Name, "r");
298 /* Error (fatal error if this is the main file) */
300 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
303 /* We are on include level. Search for the file in the include
306 PathName = FindInclude (Name);
307 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
308 /* Not found or cannot open, print an error and bail out */
309 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
312 /* Free the allocated memory */
317 /* check again if we do now have an open file */
322 /* Stat the file and remember the values */
324 if (fstat (fileno (F), &Buf) != 0) {
325 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
328 /* Add the file to the input file table and remember the index */
329 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
331 /* Create a new state variable and initialize it */
332 I = xmalloc (sizeof (*I));
336 I->Pos.Name = FileIdx;
341 /* Use the new file */
353 void DoneInputFile (void)
354 /* Close the current input file */
358 /* Restore the old token */
362 /* Save a pointer to the current struct, then set it back */
366 /* Cleanup the current stuff */
374 void NewInputData (char* Data, int Malloced)
375 /* Add a chunk of input data to the input stream */
379 /* Create a new state variable and initialize it */
380 I = xmalloc (sizeof (*I));
383 I->Malloced = Malloced;
387 /* Use the new data */
397 static void DoneInputData (void)
398 /* End the current input data stream */
402 /* Restore the old token */
406 /* Save a pointer to the current struct, then set it back */
410 /* Cleanup the current stuff */
419 static unsigned DigitVal (unsigned char C)
420 /* Convert a digit into it's numerical representation */
425 return toupper (C) - 'A' + 10;
431 static void NextChar (void)
432 /* Read the next character from the input file */
434 /* If we have an input data structure, read from there */
439 /* End of input data, will set to last file char */
445 /* Check for end of line, read the next line if needed */
446 while (IFile->Line [IFile->Pos.Col] == '\0') {
448 /* End of current line reached, read next line */
449 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
450 /* End of file. Add an empty line to the listing. This is a
451 * small hack needed to keep the PC output in sync.
453 NewListingLine ("", IFile->Pos.Name, ICount);
462 /* Remember the new line for the listing */
463 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
467 /* Return the next character from the file */
468 C = IFile->Line [IFile->Pos.Col++];
475 void LocaseSVal (void)
476 /* Make SVal lower case */
480 SVal [I] = tolower (SVal [I]);
487 void UpcaseSVal (void)
488 /* Make SVal upper case */
492 SVal [I] = toupper (SVal [I]);
499 static int CmpDotKeyword (const void* K1, const void* K2)
500 /* Compare function for the dot keyword search */
502 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
507 static unsigned char FindDotKeyword (void)
508 /* Find the dot keyword in SVal. Return the corresponding token if found,
509 * return TOK_NONE if not found.
512 static const struct DotKeyword K = { SVal, 0 };
513 struct DotKeyword* R;
515 /* If we aren't in ignore case mode, we have to uppercase the keyword */
520 /* Search for the keyword */
521 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
522 sizeof (DotKeywords [0]), CmpDotKeyword);
532 static void ReadIdent (unsigned Index)
533 /* Read an identifier from the current input position into Ident. Filling SVal
534 * starts at Index with the current character in C. It is assumed that any
535 * characters already filled in are ok, and the character in C is checked.
538 /* Read the identifier */
540 if (Index < MAX_STR_LEN) {
544 } while (IsIdChar (C));
547 /* If we should ignore case, convert the identifier to upper case */
555 static unsigned ReadStringConst (int StringTerm)
556 /* Read a string constant into SVal. Check for maximum string length and all
557 * other stuff. The length of the string is returned.
562 /* Skip the leading string terminator */
565 /* Read the string */
568 if (C == StringTerm) {
571 if (C == '\n' || C == EOF) {
572 Error (ERR_NEWLINE_IN_STRING);
576 /* Check for string length, print an error message once */
577 if (I == MAX_STR_LEN) {
578 Error (ERR_STRING_TOO_LONG);
579 } else if (I < MAX_STR_LEN) {
584 /* Skip the character */
588 /* Skip the trailing terminator */
591 /* Terminate the string */
592 if (I >= MAX_STR_LEN) {
597 /* Return the length of the string */
603 void NextRawTok (void)
604 /* Read the next raw token from the input stream */
606 /* If we've a forced end of assembly, don't read further */
613 /* Check if we have tokens from another input source */
614 if (InputFromStack ()) {
619 /* Skip whitespace, remember if we had some */
620 if ((WS = IsBlank (C)) != 0) {
623 } while (IsBlank (C));
626 /* If we're reading from the file, update the location from where the
627 * next token will be read. If we're reading from input data, keep the
634 /* Hex number or PC symbol? */
638 /* Hex digit must follow or DollarIsPC must be enabled */
644 Error (ERR_HEX_DIGIT_EXPECTED);
648 /* Read the number */
650 while (IsXDigit (C)) {
651 if (IVal & 0xF0000000) {
652 Error (ERR_NUM_OVERFLOW);
655 IVal = (IVal << 4) + DigitVal (C);
659 /* This is an integer constant */
668 /* 0 or 1 must follow */
670 Error (ERR_01_EXPECTED);
673 /* Read the number */
675 while (IsBDigit (C)) {
676 if (IVal & 0x80000000) {
677 Error (ERR_NUM_OVERFLOW);
680 IVal = (IVal << 1) + DigitVal (C);
684 /* This is an integer constant */
689 /* Decimal number? */
692 /* Read the number */
694 while (IsDigit (C)) {
695 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
696 Error (ERR_NUM_OVERFLOW);
699 IVal = (IVal * 10) + DigitVal (C);
703 /* This is an integer constant */
708 /* Control command? */
711 /* Remember and skip the dot */
715 /* Check if it's just a dot */
716 if (!IsIdStart (C)) {
723 /* Read the remainder of the identifier */
726 /* Dot keyword, search for it */
727 Tok = FindDotKeyword ();
728 if (Tok == TOK_NONE) {
730 if (LeadingDotInIdents) {
731 /* An identifier with a dot */
734 /* Invalid pseudo instruction */
735 Error (ERR_PSEUDO_EXPECTED);
745 if (C == LocalStart) {
747 /* Read the identifier */
750 /* Start character alone is not enough */
751 if (SVal [1] == '\0') {
752 Error (ERR_IDENT_EXPECTED);
762 /* Identifier or keyword? */
765 /* Read the identifier */
768 /* Check for special names */
769 if (SVal [1] == '\0') {
770 switch (toupper (SVal [0])) {
794 /* Search for an opcode */
795 IVal = FindInstruction (SVal);
797 /* This is a mnemonic */
799 } else if (IsDefine (SVal)) {
800 /* This is a define style macro - expand it */
810 /* Ok, let's do the switch */
899 while (C != '\n' && C != EOF) {
934 } else if (C == '<') {
937 } else if (C == '>') {
960 } else if (C == '>') {
974 /* Hack: If we allow ' as terminating character for strings, read
975 * the following stuff as a string, and check for a one character
978 if (LooseStringTerm) {
979 if (ReadStringConst ('\'') == 1) {
986 /* Always a character constant */
988 if (C == '\n' || C == EOF) {
989 Error (ERR_ILLEGAL_CHARCON);
996 Error (ERR_ILLEGAL_CHARCON);
1004 ReadStringConst ('\"');
1009 /* Line continuation? */
1013 /* Handle as white space */
1027 /* Check if we have any open .IFs in this file */
1029 /* Check if we have any open token lists in this file */
1032 /* If this was an include file, then close it and handle like a
1033 * separator. Do not close the main file, but return EOF.
1044 /* If we go here, we could not identify the current character. Skip it
1047 Error (ERR_INVALID_CHAR, C & 0xFF);
1054 int TokHasSVal (enum Token Tok)
1055 /* Return true if the given token has an attached SVal */
1057 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1062 int TokHasIVal (enum Token Tok)
1063 /* Return true if the given token has an attached IVal */
1065 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1070 int GetSubKey (const char** Keys, unsigned Count)
1071 /* Search for a subkey in a table of keywords. The current token must be an
1072 * identifier and all keys must be in upper case. The identifier will be
1073 * uppercased in the process. The function returns the index of the keyword,
1074 * or -1 if the keyword was not found.
1079 /* Must have an identifier */
1080 PRECONDITION (Tok == TOK_IDENT);
1082 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1087 /* Do a linear search (a binary search is not worth the effort) */
1088 for (I = 0; I < Count; ++I) {
1089 if (strcmp (SVal, Keys [I]) == 0) {
1101 void InitScanner (const char* InFile)
1102 /* Initialize the scanner, open the given input file */
1104 /* Open the input file */
1105 NewInputFile (InFile);
1110 void DoneScanner (void)
1111 /* Release scanner resources */