1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2005 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 },
182 { ".IDENT", TOK_MAKEIDENT },
184 { ".IFBLANK", TOK_IFBLANK },
185 { ".IFCONST", TOK_IFCONST },
186 { ".IFDEF", TOK_IFDEF },
187 { ".IFNBLANK", TOK_IFNBLANK },
188 { ".IFNCONST", TOK_IFNCONST },
189 { ".IFNDEF", TOK_IFNDEF },
190 { ".IFNREF", TOK_IFNREF },
191 { ".IFP02", TOK_IFP02 },
192 { ".IFP816", TOK_IFP816 },
193 { ".IFPC02", TOK_IFPC02 },
194 { ".IFPSC02", TOK_IFPSC02 },
195 { ".IFREF", TOK_IFREF },
196 { ".IMPORT", TOK_IMPORT },
197 { ".IMPORTZP", TOK_IMPORTZP },
198 { ".INCBIN", TOK_INCBIN },
199 { ".INCLUDE", TOK_INCLUDE },
200 { ".INTERRUPTOR", TOK_INTERRUPTOR },
201 { ".LEFT", TOK_LEFT },
202 { ".LINECONT", TOK_LINECONT },
203 { ".LIST", TOK_LIST },
204 { ".LISTBYTES", TOK_LISTBYTES },
205 { ".LOBYTE", TOK_LOBYTE },
206 { ".LOCAL", TOK_LOCAL },
207 { ".LOCALCHAR", TOK_LOCALCHAR },
208 { ".LOWORD", TOK_LOWORD },
209 { ".MAC", TOK_MACRO },
210 { ".MACPACK", TOK_MACPACK },
211 { ".MACRO", TOK_MACRO },
212 { ".MATCH", TOK_MATCH },
215 { ".NOT", TOK_BOOLNOT },
216 { ".NULL", TOK_NULL },
217 { ".OR", TOK_BOOLOR },
221 { ".P816", TOK_P816 },
222 { ".PAGELEN", TOK_PAGELENGTH },
223 { ".PAGELENGTH", TOK_PAGELENGTH },
224 { ".PARAMCOUNT", TOK_PARAMCOUNT },
225 { ".PC02", TOK_PC02 },
226 { ".POPSEG", TOK_POPSEG },
227 { ".PROC", TOK_PROC },
228 { ".PSC02", TOK_PSC02 },
229 { ".PUSHSEG", TOK_PUSHSEG },
230 { ".REF", TOK_REFERENCED },
231 { ".REFERENCED", TOK_REFERENCED },
232 { ".RELOC", TOK_RELOC },
233 { ".REPEAT", TOK_REPEAT },
235 { ".RIGHT", TOK_RIGHT },
236 { ".RODATA", TOK_RODATA },
237 { ".SCOPE", TOK_SCOPE },
238 { ".SEGMENT", TOK_SEGMENT },
239 { ".SETCPU", TOK_SETCPU },
242 { ".SIZEOF", TOK_SIZEOF },
243 { ".SMART", TOK_SMART },
244 { ".SPRINTF", TOK_SPRINTF },
245 { ".STRAT", TOK_STRAT },
246 { ".STRING", TOK_STRING },
247 { ".STRLEN", TOK_STRLEN },
248 { ".STRUCT", TOK_STRUCT },
249 { ".SUNPLUS", TOK_SUNPLUS },
251 { ".TCOUNT", TOK_TCOUNT },
252 { ".TIME", TOK_TIME },
253 { ".UNION", TOK_UNION },
254 { ".VERSION", TOK_VERSION },
255 { ".WARNING", TOK_WARNING },
256 { ".WORD", TOK_WORD },
257 { ".XMATCH", TOK_XMATCH },
258 { ".XOR", TOK_BOOLXOR },
259 { ".ZEROPAGE", TOK_ZEROPAGE },
264 /*****************************************************************************/
266 /*****************************************************************************/
270 static void NextChar (void);
271 /* Read the next character from the input file */
275 /*****************************************************************************/
276 /* Character classification functions */
277 /*****************************************************************************/
282 /* Return true if the character is a valid character for an identifier */
284 return IsAlNum (C) ||
286 (C == '@' && AtInIdents) ||
287 (C == '$' && DollarInIdents);
292 int IsIdStart (int C)
293 /* Return true if the character may start an identifier */
295 return IsAlpha (C) || C == '_';
300 /*****************************************************************************/
302 /*****************************************************************************/
306 void NewInputFile (const char* Name)
307 /* Open a new input file */
312 /* First try to open the file */
313 F = fopen (Name, "r");
318 /* Error (fatal error if this is the main file) */
320 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
323 /* We are on include level. Search for the file in the include
326 PathName = FindInclude (Name);
327 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
328 /* Not found or cannot open, print an error and bail out */
329 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
332 /* Free the allocated memory */
337 /* check again if we do now have an open file */
342 /* Stat the file and remember the values */
344 if (fstat (fileno (F), &Buf) != 0) {
345 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
348 /* Add the file to the input file table and remember the index */
349 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
351 /* Create a new state variable and initialize it */
352 I = xmalloc (sizeof (*I));
356 I->Pos.Name = FileIdx;
361 /* Use the new file */
373 void DoneInputFile (void)
374 /* Close the current input file */
378 /* Restore the old token */
382 /* Save a pointer to the current struct, then set it back */
386 /* Cleanup the current stuff */
394 void NewInputData (char* Data, int Malloced)
395 /* Add a chunk of input data to the input stream */
399 /* Create a new state variable and initialize it */
400 I = xmalloc (sizeof (*I));
403 I->Malloced = Malloced;
407 /* Use the new data */
417 static void DoneInputData (void)
418 /* End the current input data stream */
422 /* Restore the old token */
426 /* Save a pointer to the current struct, then set it back */
430 /* Cleanup the current stuff */
439 static unsigned DigitVal (unsigned char C)
440 /* Convert a digit into it's numerical representation */
445 return toupper (C) - 'A' + 10;
451 static void NextChar (void)
452 /* Read the next character from the input file */
454 /* If we have an input data structure, read from there */
459 /* End of input data, will set to last file char */
465 /* Check for end of line, read the next line if needed */
466 while (IFile->Line [IFile->Pos.Col] == '\0') {
468 unsigned Len, Removed;
470 /* End of current line reached, read next line */
471 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
472 /* End of file. Add an empty line to the listing. This is a
473 * small hack needed to keep the PC output in sync.
475 NewListingLine ("", IFile->Pos.Name, ICount);
480 /* For better handling of files with unusual line endings (DOS
481 * files that are accidently translated on Unix for example),
482 * first remove all whitespace at the end, then add a single
485 Len = strlen (IFile->Line);
487 while (Len > 0 && IsSpace (IFile->Line[Len-1])) {
492 IFile->Line[Len+0] = '\n';
493 IFile->Line[Len+1] = '\0';
500 /* Remember the new line for the listing */
501 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
505 /* Return the next character from the file */
506 C = IFile->Line [IFile->Pos.Col++];
513 void LocaseSVal (void)
514 /* Make SVal lower case */
518 SVal [I] = tolower (SVal [I]);
525 void UpcaseSVal (void)
526 /* Make SVal upper case */
530 SVal [I] = toupper (SVal [I]);
537 static int CmpDotKeyword (const void* K1, const void* K2)
538 /* Compare function for the dot keyword search */
540 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
545 static unsigned char FindDotKeyword (void)
546 /* Find the dot keyword in SVal. Return the corresponding token if found,
547 * return TOK_NONE if not found.
550 static const struct DotKeyword K = { SVal, 0 };
551 struct DotKeyword* R;
553 /* If we aren't in ignore case mode, we have to uppercase the keyword */
558 /* Search for the keyword */
559 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
560 sizeof (DotKeywords [0]), CmpDotKeyword);
570 static void ReadIdent (unsigned Index)
571 /* Read an identifier from the current input position into Ident. Filling SVal
572 * starts at Index with the current character in C. It is assumed that any
573 * characters already filled in are ok, and the character in C is checked.
576 /* Read the identifier */
578 if (Index < MAX_STR_LEN) {
582 } while (IsIdChar (C));
585 /* If we should ignore case, convert the identifier to upper case */
593 static unsigned ReadStringConst (int StringTerm)
594 /* Read a string constant into SVal. Check for maximum string length and all
595 * other stuff. The length of the string is returned.
600 /* Skip the leading string terminator */
603 /* Read the string */
606 if (C == StringTerm) {
609 if (C == '\n' || C == EOF) {
610 Error ("Newline in string constant");
614 /* Check for string length, print an error message once */
615 if (I == MAX_STR_LEN) {
616 Error ("Maximum string size exceeded");
617 } else if (I < MAX_STR_LEN) {
622 /* Skip the character */
626 /* Skip the trailing terminator */
629 /* Terminate the string */
630 if (I >= MAX_STR_LEN) {
635 /* Return the length of the string */
641 static int Sweet16Reg (const char* Ident)
642 /* Check if the given identifier is a sweet16 register. Return -1 if this is
643 * not the case, return the register number otherwise.
649 if (Ident[0] != 'r' && Ident[0] != 'R') {
652 if (!IsDigit (Ident[1])) {
656 if (sscanf (Ident+1, "%u%c", &RegNum, &Check) != 1 || RegNum > 15) {
657 /* Invalid register */
661 /* The register number is valid */
667 void NextRawTok (void)
668 /* Read the next raw token from the input stream */
670 /* If we've a forced end of assembly, don't read further */
677 /* Check if we have tokens from another input source */
678 if (InputFromStack ()) {
683 /* Skip whitespace, remember if we had some */
684 if ((WS = IsBlank (C)) != 0) {
687 } while (IsBlank (C));
690 /* If we're reading from the file, update the location from where the
691 * next token will be read. If we're reading from input data, keep the
698 /* Hex number or PC symbol? */
702 /* Hex digit must follow or DollarIsPC must be enabled */
708 Error ("Hexadecimal digit expected");
712 /* Read the number */
714 while (IsXDigit (C)) {
715 if (IVal & 0xF0000000) {
716 Error ("Overflow in hexadecimal number");
719 IVal = (IVal << 4) + DigitVal (C);
723 /* This is an integer constant */
732 /* 0 or 1 must follow */
734 Error ("Binary digit expected");
737 /* Read the number */
739 while (IsBDigit (C)) {
740 if (IVal & 0x80000000) {
741 Error ("Overflow in binary number");
744 IVal = (IVal << 1) + DigitVal (C);
748 /* This is an integer constant */
763 /* Ignore leading zeros */
768 /* Read the number into Buf counting the digits */
770 while (IsXDigit (C)) {
772 /* Buf is big enough to allow any decimal and hex number to
773 * overflow, so ignore excess digits here, they will be detected
774 * when we convert the value.
776 if (Digits < sizeof (Buf)) {
783 /* Allow zilog/intel style hex numbers with a 'h' suffix */
784 if (C == 'h' || C == 'H') {
787 Max = 0xFFFFFFFFUL / 16;
790 Max = 0xFFFFFFFFUL / 10;
793 /* Convert the number using the given base */
795 for (I = 0; I < Digits; ++I) {
797 Error ("Number out of range");
801 DVal = DigitVal (Buf[I]);
803 Error ("Invalid digits in number");
807 IVal = (IVal * Base) + DVal;
810 /* This is an integer constant */
815 /* Control command? */
818 /* Remember and skip the dot */
821 /* Check if it's just a dot */
822 if (!IsIdStart (C)) {
829 /* Read the remainder of the identifier */
833 /* Dot keyword, search for it */
834 Tok = FindDotKeyword ();
835 if (Tok == TOK_NONE) {
838 if (!LeadingDotInIdents) {
839 /* Invalid pseudo instruction */
840 Error ("`%s' is not a recognized control command", SVal);
844 /* An identifier with a dot. Check if it's a define style
847 if (IsDefine (SVal)) {
848 /* This is a define style macro - expand it */
853 /* Just an identifier with a dot */
861 /* Indirect op for sweet16 cpu. Must check this before checking for local
862 * symbols, because these may also use the '@' symbol.
864 if (CPU == CPU_SWEET16 && C == '@') {
871 if (C == LocalStart) {
873 /* Read the identifier */
876 /* Start character alone is not enough */
877 if (SVal [1] == '\0') {
878 Error ("Invalid cheap local symbol");
882 /* A local identifier */
883 Tok = TOK_LOCAL_IDENT;
888 /* Identifier or keyword? */
891 /* Read the identifier */
894 /* Check for special names. Bail out if we have identified the type of
895 * the token. Go on if the token is an identifier.
897 if (SVal[1] == '\0') {
898 switch (toupper (SVal [0])) {
903 Tok = TOK_OVERRIDE_ABS;
912 Tok = TOK_OVERRIDE_FAR;
932 Tok = TOK_OVERRIDE_ZP;
941 } else if (CPU == CPU_SWEET16 && (IVal = Sweet16Reg (SVal)) >= 0) {
943 /* A sweet16 register number in sweet16 mode */
949 /* Check for define style macro */
950 if (IsDefine (SVal)) {
951 /* Macro - expand it */
961 /* Ok, let's do the switch */
1016 Tok = TOK_NAMESPACE;
1055 while (C != '\n' && C != EOF) {
1100 } else if (C == '<') {
1103 } else if (C == '>') {
1126 } else if (C == '>') {
1140 /* Hack: If we allow ' as terminating character for strings, read
1141 * the following stuff as a string, and check for a one character
1144 if (LooseStringTerm) {
1145 if (ReadStringConst ('\'') == 1) {
1152 /* Always a character constant */
1154 if (C == EOF || IsControl (C)) {
1155 Error ("Illegal character constant");
1162 if (!MissingCharTerm) {
1163 Error ("Illegal character constant");
1172 ReadStringConst ('\"');
1177 /* Line continuation? */
1181 /* Handle as white space */
1195 /* Check if we have any open .IFs in this file */
1197 /* Check if we have any open token lists in this file */
1200 /* If this was an include file, then close it and handle like a
1201 * separator. Do not close the main file, but return EOF.
1212 /* If we go here, we could not identify the current character. Skip it
1215 Error ("Invalid input character: 0x%02X", C & 0xFF);
1222 int TokHasSVal (enum Token Tok)
1223 /* Return true if the given token has an attached SVal */
1225 return (Tok == TOK_IDENT || TOK_LOCAL_IDENT || Tok == TOK_STRCON);
1230 int TokHasIVal (enum Token Tok)
1231 /* Return true if the given token has an attached IVal */
1233 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_REG);
1238 int GetSubKey (const char** Keys, unsigned Count)
1239 /* Search for a subkey in a table of keywords. The current token must be an
1240 * identifier and all keys must be in upper case. The identifier will be
1241 * uppercased in the process. The function returns the index of the keyword,
1242 * or -1 if the keyword was not found.
1247 /* Must have an identifier */
1248 PRECONDITION (Tok == TOK_IDENT);
1250 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1255 /* Do a linear search (a binary search is not worth the effort) */
1256 for (I = 0; I < Count; ++I) {
1257 if (strcmp (SVal, Keys [I]) == 0) {
1269 unsigned char ParseAddrSize (void)
1270 /* Check if the next token is a keyword that denotes an address size specifier.
1271 * If so, return the corresponding address size constant, otherwise output an
1272 * error message and return ADDR_SIZE_DEFAULT.
1275 static const char* Keys[] = {
1276 "DIRECT", "ZEROPAGE", "ZP",
1277 "ABSOLUTE", "ABS", "NEAR",
1282 /* Check for an identifier */
1283 if (Tok != TOK_IDENT) {
1284 Error ("Address size specifier expected");
1285 return ADDR_SIZE_DEFAULT;
1288 /* Search for the attribute */
1289 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1292 case 2: return ADDR_SIZE_ZP;
1295 case 5: return ADDR_SIZE_ABS;
1296 case 6: return ADDR_SIZE_FAR;
1298 case 8: return ADDR_SIZE_LONG;
1300 Error ("Address size specifier expected");
1301 return ADDR_SIZE_DEFAULT;
1307 void InitScanner (const char* InFile)
1308 /* Initialize the scanner, open the given input file */
1310 /* Open the input file */
1311 NewInputFile (InFile);
1316 void DoneScanner (void)
1317 /* Release scanner resources */