1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2002 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@musoftware.de */
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 const 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 { ".FORCEWORD", TOK_FORCEWORD },
171 { ".GLOBAL", TOK_GLOBAL },
172 { ".GLOBALZP", TOK_GLOBALZP },
176 { ".IFBLANK", TOK_IFBLANK },
177 { ".IFCONST", TOK_IFCONST },
178 { ".IFDEF", TOK_IFDEF },
179 { ".IFNBLANK", TOK_IFNBLANK },
180 { ".IFNCONST", TOK_IFNCONST },
181 { ".IFNDEF", TOK_IFNDEF },
182 { ".IFNREF", TOK_IFNREF },
183 { ".IFP02", TOK_IFP02 },
184 { ".IFP816", TOK_IFP816 },
185 { ".IFPC02", TOK_IFPC02 },
186 { ".IFREF", TOK_IFREF },
187 { ".IMPORT", TOK_IMPORT },
188 { ".IMPORTZP", TOK_IMPORTZP },
189 { ".INCBIN", TOK_INCBIN },
190 { ".INCLUDE", TOK_INCLUDE },
191 { ".LEFT", TOK_LEFT },
192 { ".LINECONT", TOK_LINECONT },
193 { ".LIST", TOK_LIST },
194 { ".LISTBYTES", TOK_LISTBYTES },
195 { ".LOCAL", TOK_LOCAL },
196 { ".LOCALCHAR", TOK_LOCALCHAR },
197 { ".MAC", TOK_MACRO },
198 { ".MACPACK", TOK_MACPACK },
199 { ".MACRO", TOK_MACRO },
200 { ".MATCH", TOK_MATCH },
203 { ".NOT", TOK_BNOT },
204 { ".NULL", TOK_NULL },
209 { ".P816", TOK_P816 },
210 { ".PAGELEN", TOK_PAGELENGTH },
211 { ".PAGELENGTH", TOK_PAGELENGTH },
212 { ".PARAMCOUNT", TOK_PARAMCOUNT },
213 { ".PC02", TOK_PC02 },
214 { ".PROC", TOK_PROC },
215 { ".REF", TOK_REFERENCED },
216 { ".REFERENCED", TOK_REFERENCED },
217 { ".RELOC", TOK_RELOC },
218 { ".REPEAT", TOK_REPEAT },
220 { ".RIGHT", TOK_RIGHT },
221 { ".RODATA", TOK_RODATA },
222 { ".SEGMENT", TOK_SEGMENT },
225 { ".SMART", TOK_SMART },
226 { ".STRAT", TOK_STRAT },
227 { ".STRING", TOK_STRING },
228 { ".STRLEN", TOK_STRLEN },
229 { ".SUNPLUS", TOK_SUNPLUS },
230 { ".TCOUNT", TOK_TCOUNT },
231 { ".WARNING", TOK_WARNING },
232 { ".WORD", TOK_WORD },
233 { ".XMATCH", TOK_XMATCH },
234 { ".XOR", TOK_BXOR },
235 { ".ZEROPAGE", TOK_ZEROPAGE },
240 /*****************************************************************************/
242 /*****************************************************************************/
246 static void NextChar (void);
247 /* Read the next character from the input file */
251 /*****************************************************************************/
252 /* Character classification functions */
253 /*****************************************************************************/
257 static int IsIdChar (int C)
258 /* Return true if the character is a valid character for an identifier */
260 return IsAlNum (C) ||
262 (C == '@' && AtInIdents) ||
263 (C == '$' && DollarInIdents);
268 static int IsIdStart (int C)
269 /* Return true if the character may start an identifier */
271 return IsAlpha (C) || C == '_';
276 /*****************************************************************************/
278 /*****************************************************************************/
282 void NewInputFile (const char* Name)
283 /* Open a new input file */
288 /* First try to open the file */
289 F = fopen (Name, "r");
294 /* Error (fatal error if this is the main file) */
296 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
299 /* We are on include level. Search for the file in the include
302 PathName = FindInclude (Name);
303 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
304 /* Not found or cannot open, print an error and bail out */
305 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
308 /* Free the allocated memory */
313 /* check again if we do now have an open file */
318 /* Stat the file and remember the values */
320 if (fstat (fileno (F), &Buf) != 0) {
321 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
324 /* Add the file to the input file table and remember the index */
325 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
327 /* Create a new state variable and initialize it */
328 I = xmalloc (sizeof (*I));
332 I->Pos.Name = FileIdx;
337 /* Use the new file */
349 void DoneInputFile (void)
350 /* Close the current input file */
354 /* Restore the old token */
358 /* Save a pointer to the current struct, then set it back */
362 /* Cleanup the current stuff */
370 void NewInputData (const char* Data, int Malloced)
371 /* Add a chunk of input data to the input stream */
375 /* Create a new state variable and initialize it */
376 I = xmalloc (sizeof (*I));
379 I->Malloced = Malloced;
383 /* Use the new data */
393 static void DoneInputData (void)
394 /* End the current input data stream */
398 /* Restore the old token */
402 /* Save a pointer to the current struct, then set it back */
406 /* Cleanup the current stuff */
415 static unsigned DigitVal (unsigned char C)
416 /* Convert a digit into it's numerical representation */
421 return toupper (C) - 'A' + 10;
427 static void NextChar (void)
428 /* Read the next character from the input file */
430 /* If we have an input data structure, read from there */
435 /* End of input data, will set to last file char */
441 /* Check for end of line, read the next line if needed */
442 while (IFile->Line [IFile->Pos.Col] == '\0') {
444 /* End of current line reached, read next line */
445 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
446 /* End of file. Add an empty line to the listing. This is a
447 * small hack needed to keep the PC output in sync.
449 NewListingLine ("", IFile->Pos.Name, ICount);
458 /* Remember the new line for the listing */
459 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
463 /* Return the next character from the file */
464 C = IFile->Line [IFile->Pos.Col++];
471 void LocaseSVal (void)
472 /* Make SVal lower case */
476 SVal [I] = tolower (SVal [I]);
483 void UpcaseSVal (void)
484 /* Make SVal upper case */
488 SVal [I] = toupper (SVal [I]);
495 static int CmpDotKeyword (const void* K1, const void* K2)
496 /* Compare function for the dot keyword search */
498 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
503 static unsigned char FindDotKeyword (void)
504 /* Find the dot keyword in SVal. Return the corresponding token if found,
505 * return TOK_NONE if not found.
508 static const struct DotKeyword K = { SVal, 0 };
509 struct DotKeyword* R;
511 /* If we aren't in ignore case mode, we have to uppercase the keyword */
516 /* Search for the keyword */
517 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
518 sizeof (DotKeywords [0]), CmpDotKeyword);
528 static void ReadIdent (unsigned Index)
529 /* Read an identifier from the current input position into Ident. Filling SVal
530 * starts at Index with the current character in C. It is assumed that any
531 * characters already filled in are ok, and the character in C is checked.
534 /* Read the identifier */
536 if (Index < MAX_STR_LEN) {
540 } while (IsIdChar (C));
543 /* If we should ignore case, convert the identifier to upper case */
551 static unsigned ReadStringConst (int StringTerm)
552 /* Read a string constant into SVal. Check for maximum string length and all
553 * other stuff. The length of the string is returned.
558 /* Skip the leading string terminator */
561 /* Read the string */
564 if (C == StringTerm) {
567 if (C == '\n' || C == EOF) {
568 Error (ERR_NEWLINE_IN_STRING);
572 /* Check for string length, print an error message once */
573 if (I == MAX_STR_LEN) {
574 Error (ERR_STRING_TOO_LONG);
575 } else if (I < MAX_STR_LEN) {
580 /* Skip the character */
584 /* Skip the trailing terminator */
587 /* Terminate the string */
588 if (I >= MAX_STR_LEN) {
593 /* Return the length of the string */
599 void NextRawTok (void)
600 /* Read the next raw token from the input stream */
602 /* If we've a forced end of assembly, don't read further */
609 /* Check if we have tokens from another input source */
610 if (InputFromStack ()) {
615 /* Skip whitespace, remember if we had some */
616 if ((WS = IsBlank (C)) != 0) {
619 } while (IsBlank (C));
622 /* If we're reading from the file, update the location from where the
623 * next token will be read. If we're reading from input data, keep the
630 /* Hex number or PC symbol? */
634 /* Hex digit must follow or DollarIsPC must be enabled */
640 Error (ERR_HEX_DIGIT_EXPECTED);
644 /* Read the number */
646 while (IsXDigit (C)) {
647 if (IVal & 0xF0000000) {
648 Error (ERR_NUM_OVERFLOW);
651 IVal = (IVal << 4) + DigitVal (C);
655 /* This is an integer constant */
664 /* 0 or 1 must follow */
666 Error (ERR_01_EXPECTED);
669 /* Read the number */
671 while (IsBDigit (C)) {
672 if (IVal & 0x80000000) {
673 Error (ERR_NUM_OVERFLOW);
676 IVal = (IVal << 1) + DigitVal (C);
680 /* This is an integer constant */
685 /* Decimal number? */
688 /* Read the number */
690 while (IsDigit (C)) {
691 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
692 Error (ERR_NUM_OVERFLOW);
695 IVal = (IVal * 10) + DigitVal (C);
699 /* This is an integer constant */
704 /* Control command? */
707 /* Remember and skip the dot */
711 /* Check if it's just a dot */
712 if (!IsIdStart (C)) {
719 /* Read the remainder of the identifier */
722 /* Dot keyword, search for it */
723 Tok = FindDotKeyword ();
724 if (Tok == TOK_NONE) {
726 if (LeadingDotInIdents) {
727 /* An identifier with a dot */
730 /* Invalid pseudo instruction */
731 Error (ERR_PSEUDO_EXPECTED);
741 if (C == LocalStart) {
743 /* Read the identifier */
746 /* Start character alone is not enough */
747 if (SVal [1] == '\0') {
748 Error (ERR_IDENT_EXPECTED);
758 /* Identifier or keyword? */
761 /* Read the identifier */
764 /* Check for special names */
765 if (SVal [1] == '\0') {
766 switch (toupper (SVal [0])) {
790 /* Search for an opcode */
791 IVal = FindInstruction (SVal);
793 /* This is a mnemonic */
795 } else if (IsDefine (SVal)) {
796 /* This is a define style macro - expand it */
806 /* Ok, let's do the switch */
895 while (C != '\n' && C != EOF) {
930 } else if (C == '<') {
933 } else if (C == '>') {
956 } else if (C == '>') {
970 /* Hack: If we allow ' as terminating character for strings, read
971 * the following stuff as a string, and check for a one character
974 if (LooseStringTerm) {
975 if (ReadStringConst ('\'') == 1) {
982 /* Always a character constant */
984 if (C == '\n' || C == EOF) {
985 Error (ERR_ILLEGAL_CHARCON);
992 Error (ERR_ILLEGAL_CHARCON);
1000 ReadStringConst ('\"');
1005 /* Line continuation? */
1009 /* Handle as white space */
1023 /* Check if we have any open .IFs in this file */
1025 /* Check if we have any open token lists in this file */
1028 /* If this was an include file, then close it and handle like a
1029 * separator. Do not close the main file, but return EOF.
1040 /* If we go here, we could not identify the current character. Skip it
1043 Error (ERR_INVALID_CHAR, C & 0xFF);
1050 int TokHasSVal (enum Token Tok)
1051 /* Return true if the given token has an attached SVal */
1053 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1058 int TokHasIVal (enum Token Tok)
1059 /* Return true if the given token has an attached IVal */
1061 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1066 int GetSubKey (const char** Keys, unsigned Count)
1067 /* Search for a subkey in a table of keywords. The current token must be an
1068 * identifier and all keys must be in upper case. The identifier will be
1069 * uppercased in the process. The function returns the index of the keyword,
1070 * or -1 if the keyword was not found.
1075 /* Must have an identifier */
1076 PRECONDITION (Tok == TOK_IDENT);
1078 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1083 /* Do a linear search (a binary search is not worth the effort) */
1084 for (I = 0; I < Count; ++I) {
1085 if (strcmp (SVal, Keys [I]) == 0) {
1097 void InitScanner (const char* InFile)
1098 /* Initialize the scanner, open the given input file */
1100 /* Open the input file */
1101 NewInputFile (InFile);
1106 void DoneScanner (void)
1107 /* Release scanner resources */