1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2004 Ullrich von Bassewitz */
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 */
66 /*****************************************************************************/
68 /*****************************************************************************/
72 enum Token Tok = TOK_NONE; /* Current token */
73 int WS; /* Flag: Whitespace before token */
74 long IVal; /* Integer token attribute */
75 char SVal[MAX_STR_LEN+1]; /* String token attribute */
77 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
81 /* Struct to handle include files. */
82 typedef struct InputFile InputFile;
84 FILE* F; /* Input file descriptor */
85 FilePos Pos; /* Position in file */
86 enum Token Tok; /* Last token */
87 int C; /* Last character */
88 char Line[256]; /* The current input line */
89 InputFile* Next; /* Linked list of input files */
92 /* Struct to handle textual input data */
93 typedef struct InputData InputData;
95 char* Data; /* Pointer to the data */
96 const char* Pos; /* Pointer to current position */
97 int Malloced; /* Memory was malloced */
98 enum Token Tok; /* Last token */
99 int C; /* Last character */
100 InputData* Next; /* Linked list of input data */
103 /* Current input variables */
104 static InputFile* IFile = 0; /* Current input file */
105 static InputData* IData = 0; /* Current input memory data */
106 static unsigned ICount = 0; /* Count of input files */
107 static int C = 0; /* Current input character */
109 /* Force end of assembly */
112 /* List of dot keywords with the corresponding tokens */
114 const char* Key; /* MUST be first field */
119 { ".ADDR", TOK_ADDR },
120 { ".ALIGN", TOK_ALIGN },
121 { ".AND", TOK_BOOLAND },
122 { ".ASCIIZ", TOK_ASCIIZ },
123 { ".ASSERT", TOK_ASSERT },
124 { ".AUTOIMPORT", TOK_AUTOIMPORT },
125 { ".BANKBYTE", TOK_BANKBYTE },
126 { ".BITAND", TOK_AND },
127 { ".BITNOT", TOK_NOT },
128 { ".BITOR", TOK_OR },
129 { ".BITXOR", TOK_XOR },
130 { ".BLANK", TOK_BLANK },
132 { ".BYT", TOK_BYTE },
133 { ".BYTE", TOK_BYTE },
134 { ".CASE", TOK_CASE },
135 { ".CHARMAP", TOK_CHARMAP },
136 { ".CODE", TOK_CODE },
137 { ".CONCAT", TOK_CONCAT },
138 { ".CONDES", TOK_CONDES },
139 { ".CONST", TOK_CONST },
140 { ".CONSTRUCTOR", TOK_CONSTRUCTOR },
142 { ".DATA", TOK_DATA },
144 { ".DBYT", TOK_DBYT },
145 { ".DEBUGINFO", TOK_DEBUGINFO },
146 { ".DEF", TOK_DEFINED },
147 { ".DEFINE", TOK_DEFINE },
148 { ".DEFINED", TOK_DEFINED },
149 { ".DESTRUCTOR", TOK_DESTRUCTOR },
150 { ".DWORD", TOK_DWORD },
151 { ".ELSE", TOK_ELSE },
152 { ".ELSEIF", TOK_ELSEIF },
154 { ".ENDENUM", TOK_ENDENUM },
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 { ".ENDSCOPE", TOK_ENDSCOPE },
162 { ".ENDSTRUCT", TOK_ENDSTRUCT },
163 { ".ENDUNION", TOK_ENDUNION },
164 { ".ENUM", TOK_ENUM },
165 { ".ERROR", TOK_ERROR },
166 { ".EXITMAC", TOK_EXITMACRO },
167 { ".EXITMACRO", TOK_EXITMACRO },
168 { ".EXPORT", TOK_EXPORT },
169 { ".EXPORTZP", TOK_EXPORTZP },
170 { ".FARADDR", TOK_FARADDR },
171 { ".FEATURE", TOK_FEATURE },
172 { ".FILEOPT", TOK_FILEOPT },
173 { ".FOPT", TOK_FILEOPT },
174 { ".FORCEIMPORT", TOK_FORCEIMPORT },
175 { ".FORCEWORD", TOK_FORCEWORD },
176 { ".GLOBAL", TOK_GLOBAL },
177 { ".GLOBALZP", TOK_GLOBALZP },
178 { ".HIBYTE", TOK_HIBYTE },
179 { ".HIWORD", TOK_HIWORD },
183 { ".IFBLANK", TOK_IFBLANK },
184 { ".IFCONST", TOK_IFCONST },
185 { ".IFDEF", TOK_IFDEF },
186 { ".IFNBLANK", TOK_IFNBLANK },
187 { ".IFNCONST", TOK_IFNCONST },
188 { ".IFNDEF", TOK_IFNDEF },
189 { ".IFNREF", TOK_IFNREF },
190 { ".IFP02", TOK_IFP02 },
191 { ".IFP816", TOK_IFP816 },
192 { ".IFPC02", TOK_IFPC02 },
193 { ".IFPSC02", TOK_IFPSC02 },
194 { ".IFREF", TOK_IFREF },
195 { ".IMPORT", TOK_IMPORT },
196 { ".IMPORTZP", TOK_IMPORTZP },
197 { ".INCBIN", TOK_INCBIN },
198 { ".INCLUDE", TOK_INCLUDE },
199 { ".INTERRUPTOR", TOK_INTERRUPTOR },
200 { ".LEFT", TOK_LEFT },
201 { ".LINECONT", TOK_LINECONT },
202 { ".LIST", TOK_LIST },
203 { ".LISTBYTES", TOK_LISTBYTES },
204 { ".LOBYTE", TOK_LOBYTE },
205 { ".LOCAL", TOK_LOCAL },
206 { ".LOCALCHAR", TOK_LOCALCHAR },
207 { ".LOWORD", TOK_LOWORD },
208 { ".MAC", TOK_MACRO },
209 { ".MACPACK", TOK_MACPACK },
210 { ".MACRO", TOK_MACRO },
211 { ".MATCH", TOK_MATCH },
214 { ".NOT", TOK_BOOLNOT },
215 { ".NULL", TOK_NULL },
216 { ".OR", TOK_BOOLOR },
220 { ".P816", TOK_P816 },
221 { ".PAGELEN", TOK_PAGELENGTH },
222 { ".PAGELENGTH", TOK_PAGELENGTH },
223 { ".PARAMCOUNT", TOK_PARAMCOUNT },
224 { ".PC02", TOK_PC02 },
225 { ".POPSEG", TOK_POPSEG },
226 { ".PROC", TOK_PROC },
227 { ".PSC02", TOK_PSC02 },
228 { ".PUSHSEG", TOK_PUSHSEG },
229 { ".REF", TOK_REFERENCED },
230 { ".REFERENCED", TOK_REFERENCED },
231 { ".RELOC", TOK_RELOC },
232 { ".REPEAT", TOK_REPEAT },
234 { ".RIGHT", TOK_RIGHT },
235 { ".RODATA", TOK_RODATA },
236 { ".SCOPE", TOK_SCOPE },
237 { ".SEGMENT", TOK_SEGMENT },
238 { ".SETCPU", TOK_SETCPU },
241 { ".SIZEOF", TOK_SIZEOF },
242 { ".SMART", TOK_SMART },
243 { ".STRAT", TOK_STRAT },
244 { ".STRING", TOK_STRING },
245 { ".STRLEN", TOK_STRLEN },
246 { ".STRUCT", TOK_STRUCT },
247 { ".SUNPLUS", TOK_SUNPLUS },
249 { ".TCOUNT", TOK_TCOUNT },
250 { ".TIME", TOK_TIME },
251 { ".UNION", TOK_UNION },
252 { ".VERSION", TOK_VERSION },
253 { ".WARNING", TOK_WARNING },
254 { ".WORD", TOK_WORD },
255 { ".XMATCH", TOK_XMATCH },
256 { ".XOR", TOK_BOOLXOR },
257 { ".ZEROPAGE", TOK_ZEROPAGE },
262 /*****************************************************************************/
264 /*****************************************************************************/
268 static void NextChar (void);
269 /* Read the next character from the input file */
273 /*****************************************************************************/
274 /* Character classification functions */
275 /*****************************************************************************/
279 static int IsIdChar (int C)
280 /* Return true if the character is a valid character for an identifier */
282 return IsAlNum (C) ||
284 (C == '@' && AtInIdents) ||
285 (C == '$' && DollarInIdents);
290 static int IsIdStart (int C)
291 /* Return true if the character may start an identifier */
293 return IsAlpha (C) || C == '_';
298 /*****************************************************************************/
300 /*****************************************************************************/
304 void NewInputFile (const char* Name)
305 /* Open a new input file */
310 /* First try to open the file */
311 F = fopen (Name, "r");
316 /* Error (fatal error if this is the main file) */
318 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
321 /* We are on include level. Search for the file in the include
324 PathName = FindInclude (Name);
325 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
326 /* Not found or cannot open, print an error and bail out */
327 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
330 /* Free the allocated memory */
335 /* check again if we do now have an open file */
340 /* Stat the file and remember the values */
342 if (fstat (fileno (F), &Buf) != 0) {
343 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
346 /* Add the file to the input file table and remember the index */
347 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
349 /* Create a new state variable and initialize it */
350 I = xmalloc (sizeof (*I));
354 I->Pos.Name = FileIdx;
359 /* Use the new file */
371 void DoneInputFile (void)
372 /* Close the current input file */
376 /* Restore the old token */
380 /* Save a pointer to the current struct, then set it back */
384 /* Cleanup the current stuff */
392 void NewInputData (char* Data, int Malloced)
393 /* Add a chunk of input data to the input stream */
397 /* Create a new state variable and initialize it */
398 I = xmalloc (sizeof (*I));
401 I->Malloced = Malloced;
405 /* Use the new data */
415 static void DoneInputData (void)
416 /* End the current input data stream */
420 /* Restore the old token */
424 /* Save a pointer to the current struct, then set it back */
428 /* Cleanup the current stuff */
437 static unsigned DigitVal (unsigned char C)
438 /* Convert a digit into it's numerical representation */
443 return toupper (C) - 'A' + 10;
449 static void NextChar (void)
450 /* Read the next character from the input file */
452 /* If we have an input data structure, read from there */
457 /* End of input data, will set to last file char */
463 /* Check for end of line, read the next line if needed */
464 while (IFile->Line [IFile->Pos.Col] == '\0') {
466 unsigned Len, Removed;
468 /* End of current line reached, read next line */
469 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
470 /* End of file. Add an empty line to the listing. This is a
471 * small hack needed to keep the PC output in sync.
473 NewListingLine ("", IFile->Pos.Name, ICount);
478 /* For better handling of files with unusual line endings (DOS
479 * files that are accidently translated on Unix for example),
480 * first remove all whitespace at the end, then add a single
483 Len = strlen (IFile->Line);
485 while (Len > 0 && IsSpace (IFile->Line[Len-1])) {
490 IFile->Line[Len+0] = '\n';
491 IFile->Line[Len+1] = '\0';
498 /* Remember the new line for the listing */
499 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
503 /* Return the next character from the file */
504 C = IFile->Line [IFile->Pos.Col++];
511 void LocaseSVal (void)
512 /* Make SVal lower case */
516 SVal [I] = tolower (SVal [I]);
523 void UpcaseSVal (void)
524 /* Make SVal upper case */
528 SVal [I] = toupper (SVal [I]);
535 static int CmpDotKeyword (const void* K1, const void* K2)
536 /* Compare function for the dot keyword search */
538 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
543 static unsigned char FindDotKeyword (void)
544 /* Find the dot keyword in SVal. Return the corresponding token if found,
545 * return TOK_NONE if not found.
548 static const struct DotKeyword K = { SVal, 0 };
549 struct DotKeyword* R;
551 /* If we aren't in ignore case mode, we have to uppercase the keyword */
556 /* Search for the keyword */
557 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
558 sizeof (DotKeywords [0]), CmpDotKeyword);
568 static void ReadIdent (unsigned Index)
569 /* Read an identifier from the current input position into Ident. Filling SVal
570 * starts at Index with the current character in C. It is assumed that any
571 * characters already filled in are ok, and the character in C is checked.
574 /* Read the identifier */
576 if (Index < MAX_STR_LEN) {
580 } while (IsIdChar (C));
583 /* If we should ignore case, convert the identifier to upper case */
591 static unsigned ReadStringConst (int StringTerm)
592 /* Read a string constant into SVal. Check for maximum string length and all
593 * other stuff. The length of the string is returned.
598 /* Skip the leading string terminator */
601 /* Read the string */
604 if (C == StringTerm) {
607 if (C == '\n' || C == EOF) {
608 Error ("Newline in string constant");
612 /* Check for string length, print an error message once */
613 if (I == MAX_STR_LEN) {
614 Error ("Maximum string size exceeded");
615 } else if (I < MAX_STR_LEN) {
620 /* Skip the character */
624 /* Skip the trailing terminator */
627 /* Terminate the string */
628 if (I >= MAX_STR_LEN) {
633 /* Return the length of the string */
639 static int Sweet16Reg (const char* Ident)
640 /* Check if the given identifier is a sweet16 register. Return -1 if this is
641 * not the case, return the register number otherwise.
647 if (Ident[0] != 'r' && Ident[0] != 'R') {
650 if (!IsDigit (Ident[1])) {
654 if (sscanf (Ident+1, "%u%c", &RegNum, &Check) != 1 || RegNum > 15) {
655 /* Invalid register */
659 /* The register number is valid */
665 void NextRawTok (void)
666 /* Read the next raw token from the input stream */
668 /* If we've a forced end of assembly, don't read further */
675 /* Check if we have tokens from another input source */
676 if (InputFromStack ()) {
681 /* Skip whitespace, remember if we had some */
682 if ((WS = IsBlank (C)) != 0) {
685 } while (IsBlank (C));
688 /* If we're reading from the file, update the location from where the
689 * next token will be read. If we're reading from input data, keep the
696 /* Hex number or PC symbol? */
700 /* Hex digit must follow or DollarIsPC must be enabled */
706 Error ("Hexadecimal digit expected");
710 /* Read the number */
712 while (IsXDigit (C)) {
713 if (IVal & 0xF0000000) {
714 Error ("Overflow in hexadecimal number");
717 IVal = (IVal << 4) + DigitVal (C);
721 /* This is an integer constant */
730 /* 0 or 1 must follow */
732 Error ("Binary digit expected");
735 /* Read the number */
737 while (IsBDigit (C)) {
738 if (IVal & 0x80000000) {
739 Error ("Overflow in binary number");
742 IVal = (IVal << 1) + DigitVal (C);
746 /* This is an integer constant */
761 /* Ignore leading zeros */
766 /* Read the number into Buf counting the digits */
768 while (IsXDigit (C)) {
770 /* Buf is big enough to allow any decimal and hex number to
771 * overflow, so ignore excess digits here, they will be detected
772 * when we convert the value.
774 if (Digits < sizeof (Buf)) {
781 /* Allow zilog/intel style hex numbers with a 'h' suffix */
782 if (C == 'h' || C == 'H') {
785 Max = 0xFFFFFFFFUL / 16;
788 Max = 0xFFFFFFFFUL / 10;
791 /* Convert the number using the given base */
793 for (I = 0; I < Digits; ++I) {
795 Error ("Number out of range");
799 DVal = DigitVal (Buf[I]);
801 Error ("Invalid digits in number");
805 IVal = (IVal * Base) + DVal;
808 /* This is an integer constant */
813 /* Control command? */
816 /* Remember and skip the dot */
819 /* Check if it's just a dot */
820 if (!IsIdStart (C)) {
827 /* Read the remainder of the identifier */
831 /* Dot keyword, search for it */
832 Tok = FindDotKeyword ();
833 if (Tok == TOK_NONE) {
836 if (!LeadingDotInIdents) {
837 /* Invalid pseudo instruction */
838 Error ("`%s' is not a recognized control command", SVal);
842 /* An identifier with a dot. Check if it's a define style
845 if (IsDefine (SVal)) {
846 /* This is a define style macro - expand it */
851 /* Just an identifier with a dot */
859 /* Indirect op for sweet16 cpu. Must check this before checking for local
860 * symbols, because these may also use the '@' symbol.
862 if (CPU == CPU_SWEET16 && C == '@') {
869 if (C == LocalStart) {
871 /* Read the identifier */
874 /* Start character alone is not enough */
875 if (SVal [1] == '\0') {
876 Error ("Invalid cheap local symbol");
880 /* A local identifier */
881 Tok = TOK_LOCAL_IDENT;
886 /* Identifier or keyword? */
889 /* Read the identifier */
892 /* Check for special names. Bail out if we have identified the type of
893 * the token. Go on if the token is an identifier.
895 if (SVal[1] == '\0') {
896 switch (toupper (SVal [0])) {
901 Tok = TOK_OVERRIDE_ABS;
910 Tok = TOK_OVERRIDE_FAR;
930 Tok = TOK_OVERRIDE_ZP;
939 } else if (CPU == CPU_SWEET16 && (IVal = Sweet16Reg (SVal)) >= 0) {
941 /* A sweet16 register number in sweet16 mode */
947 /* Check for define style macro */
948 if (IsDefine (SVal)) {
949 /* Macro - expand it */
959 /* Ok, let's do the switch */
1014 Tok = TOK_NAMESPACE;
1053 while (C != '\n' && C != EOF) {
1098 } else if (C == '<') {
1101 } else if (C == '>') {
1124 } else if (C == '>') {
1138 /* Hack: If we allow ' as terminating character for strings, read
1139 * the following stuff as a string, and check for a one character
1142 if (LooseStringTerm) {
1143 if (ReadStringConst ('\'') == 1) {
1150 /* Always a character constant */
1152 if (C == EOF || IsControl (C)) {
1153 Error ("Illegal character constant");
1160 if (!MissingCharTerm) {
1161 Error ("Illegal character constant");
1170 ReadStringConst ('\"');
1175 /* Line continuation? */
1179 /* Handle as white space */
1193 /* Check if we have any open .IFs in this file */
1195 /* Check if we have any open token lists in this file */
1198 /* If this was an include file, then close it and handle like a
1199 * separator. Do not close the main file, but return EOF.
1210 /* If we go here, we could not identify the current character. Skip it
1213 Error ("Invalid input character: 0x%02X", C & 0xFF);
1220 int TokHasSVal (enum Token Tok)
1221 /* Return true if the given token has an attached SVal */
1223 return (Tok == TOK_IDENT || TOK_LOCAL_IDENT || Tok == TOK_STRCON);
1228 int TokHasIVal (enum Token Tok)
1229 /* Return true if the given token has an attached IVal */
1231 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_REG);
1236 int GetSubKey (const char** Keys, unsigned Count)
1237 /* Search for a subkey in a table of keywords. The current token must be an
1238 * identifier and all keys must be in upper case. The identifier will be
1239 * uppercased in the process. The function returns the index of the keyword,
1240 * or -1 if the keyword was not found.
1245 /* Must have an identifier */
1246 PRECONDITION (Tok == TOK_IDENT);
1248 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1253 /* Do a linear search (a binary search is not worth the effort) */
1254 for (I = 0; I < Count; ++I) {
1255 if (strcmp (SVal, Keys [I]) == 0) {
1267 unsigned char ParseAddrSize (void)
1268 /* Check if the next token is a keyword that denotes an address size specifier.
1269 * If so, return the corresponding address size constant, otherwise output an
1270 * error message and return ADDR_SIZE_DEFAULT.
1273 static const char* Keys[] = {
1274 "DIRECT", "ZEROPAGE", "ZP",
1275 "ABSOLUTE", "ABS", "NEAR",
1280 /* Check for an identifier */
1281 if (Tok != TOK_IDENT) {
1282 Error ("Address size specifier expected");
1283 return ADDR_SIZE_DEFAULT;
1286 /* Search for the attribute */
1287 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1290 case 2: return ADDR_SIZE_ZP;
1293 case 5: return ADDR_SIZE_ABS;
1294 case 6: return ADDR_SIZE_FAR;
1296 case 8: return ADDR_SIZE_LONG;
1298 Error ("Address size specifier expected");
1299 return ADDR_SIZE_DEFAULT;
1305 void InitScanner (const char* InFile)
1306 /* Initialize the scanner, open the given input file */
1308 /* Open the input file */
1309 NewInputFile (InFile);
1314 void DoneScanner (void)
1315 /* Release scanner resources */