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 },
240 { ".SETCPU", TOK_SETCPU },
243 { ".SIZEOF", TOK_SIZEOF },
244 { ".SMART", TOK_SMART },
245 { ".SPRINTF", TOK_SPRINTF },
246 { ".STRAT", TOK_STRAT },
247 { ".STRING", TOK_STRING },
248 { ".STRLEN", TOK_STRLEN },
249 { ".STRUCT", TOK_STRUCT },
250 { ".SUNPLUS", TOK_SUNPLUS },
252 { ".TCOUNT", TOK_TCOUNT },
253 { ".TIME", TOK_TIME },
254 { ".UNION", TOK_UNION },
255 { ".VERSION", TOK_VERSION },
256 { ".WARNING", TOK_WARNING },
257 { ".WORD", TOK_WORD },
258 { ".XMATCH", TOK_XMATCH },
259 { ".XOR", TOK_BOOLXOR },
260 { ".ZEROPAGE", TOK_ZEROPAGE },
265 /*****************************************************************************/
267 /*****************************************************************************/
271 static void NextChar (void);
272 /* Read the next character from the input file */
276 /*****************************************************************************/
277 /* Character classification functions */
278 /*****************************************************************************/
283 /* Return true if the character is a valid character for an identifier */
285 return IsAlNum (C) ||
287 (C == '@' && AtInIdents) ||
288 (C == '$' && DollarInIdents);
293 int IsIdStart (int C)
294 /* Return true if the character may start an identifier */
296 return IsAlpha (C) || C == '_';
301 /*****************************************************************************/
303 /*****************************************************************************/
307 void NewInputFile (const char* Name)
308 /* Open a new input file */
313 /* First try to open the file */
314 F = fopen (Name, "r");
319 /* Error (fatal error if this is the main file) */
321 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
324 /* We are on include level. Search for the file in the include
327 PathName = FindInclude (Name);
328 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
329 /* Not found or cannot open, print an error and bail out */
330 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
333 /* Free the allocated memory */
338 /* check again if we do now have an open file */
343 /* Stat the file and remember the values */
345 if (fstat (fileno (F), &Buf) != 0) {
346 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
349 /* Add the file to the input file table and remember the index */
350 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
352 /* Create a new state variable and initialize it */
353 I = xmalloc (sizeof (*I));
357 I->Pos.Name = FileIdx;
362 /* Use the new file */
367 /* Setup the next token and character so it will be skipped on the
368 * next call to NextRawTok().
378 void DoneInputFile (void)
379 /* Close the current input file */
383 /* Restore the old token */
387 /* Save a pointer to the current struct, then set it back */
391 /* Cleanup the current stuff */
399 void NewInputData (char* Data, int Malloced)
400 /* Add a chunk of input data to the input stream */
404 /* Create a new state variable and initialize it */
405 I = xmalloc (sizeof (*I));
408 I->Malloced = Malloced;
412 /* Use the new data */
416 /* Setup the next token and character so it will be skipped on the
417 * next call to NextRawTok().
425 static void DoneInputData (void)
426 /* End the current input data stream */
430 /* Restore the old token */
434 /* Save a pointer to the current struct, then set it back */
438 /* Cleanup the current stuff */
447 static unsigned DigitVal (unsigned char C)
448 /* Convert a digit into it's numerical representation */
453 return toupper (C) - 'A' + 10;
459 static void NextChar (void)
460 /* Read the next character from the input file */
462 /* If we have an input data structure, read from there */
467 /* End of input data */
473 /* Check for end of line, read the next line if needed */
474 while (IFile->Line [IFile->Pos.Col] == '\0') {
476 unsigned Len, Removed;
478 /* End of current line reached, read next line */
479 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
480 /* End of file. Add an empty line to the listing. This is a
481 * small hack needed to keep the PC output in sync.
483 NewListingLine ("", IFile->Pos.Name, ICount);
488 /* For better handling of files with unusual line endings (DOS
489 * files that are accidently translated on Unix for example),
490 * first remove all whitespace at the end, then add a single
493 Len = strlen (IFile->Line);
495 while (Len > 0 && IsSpace (IFile->Line[Len-1])) {
500 IFile->Line[Len+0] = '\n';
501 IFile->Line[Len+1] = '\0';
508 /* Remember the new line for the listing */
509 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
513 /* Return the next character from the file */
514 C = IFile->Line [IFile->Pos.Col++];
521 void LocaseSVal (void)
522 /* Make SVal lower case */
526 SVal [I] = tolower (SVal [I]);
533 void UpcaseSVal (void)
534 /* Make SVal upper case */
538 SVal [I] = toupper (SVal [I]);
545 static int CmpDotKeyword (const void* K1, const void* K2)
546 /* Compare function for the dot keyword search */
548 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
553 static unsigned char FindDotKeyword (void)
554 /* Find the dot keyword in SVal. Return the corresponding token if found,
555 * return TOK_NONE if not found.
558 static const struct DotKeyword K = { SVal, 0 };
559 struct DotKeyword* R;
561 /* If we aren't in ignore case mode, we have to uppercase the keyword */
566 /* Search for the keyword */
567 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
568 sizeof (DotKeywords [0]), CmpDotKeyword);
578 static void ReadIdent (unsigned Index)
579 /* Read an identifier from the current input position into Ident. Filling SVal
580 * starts at Index with the current character in C. It is assumed that any
581 * characters already filled in are ok, and the character in C is checked.
584 /* Read the identifier */
586 if (Index < MAX_STR_LEN) {
590 } while (IsIdChar (C));
593 /* If we should ignore case, convert the identifier to upper case */
601 static unsigned ReadStringConst (int StringTerm)
602 /* Read a string constant into SVal. Check for maximum string length and all
603 * other stuff. The length of the string is returned.
608 /* Skip the leading string terminator */
611 /* Read the string */
614 if (C == StringTerm) {
617 if (C == '\n' || C == EOF) {
618 Error ("Newline in string constant");
622 /* Check for string length, print an error message once */
623 if (I == MAX_STR_LEN) {
624 Error ("Maximum string size exceeded");
625 } else if (I < MAX_STR_LEN) {
630 /* Skip the character */
634 /* Skip the trailing terminator */
637 /* Terminate the string */
638 if (I >= MAX_STR_LEN) {
643 /* Return the length of the string */
649 static int Sweet16Reg (const char* Ident)
650 /* Check if the given identifier is a sweet16 register. Return -1 if this is
651 * not the case, return the register number otherwise.
657 if (Ident[0] != 'r' && Ident[0] != 'R') {
660 if (!IsDigit (Ident[1])) {
664 if (sscanf (Ident+1, "%u%c", &RegNum, &Check) != 1 || RegNum > 15) {
665 /* Invalid register */
669 /* The register number is valid */
675 void NextRawTok (void)
676 /* Read the next raw token from the input stream */
678 /* If we've a forced end of assembly, don't read further */
685 /* Check if we have tokens from another input source */
686 if (InputFromStack ()) {
691 /* Skip whitespace, remember if we had some */
692 if ((WS = IsBlank (C)) != 0) {
695 } while (IsBlank (C));
698 /* If we're reading from the file, update the location from where the
699 * next token will be read. If we're reading from input data, keep the
706 /* Hex number or PC symbol? */
710 /* Hex digit must follow or DollarIsPC must be enabled */
716 Error ("Hexadecimal digit expected");
720 /* Read the number */
722 while (IsXDigit (C)) {
723 if (IVal & 0xF0000000) {
724 Error ("Overflow in hexadecimal number");
727 IVal = (IVal << 4) + DigitVal (C);
731 /* This is an integer constant */
740 /* 0 or 1 must follow */
742 Error ("Binary digit expected");
745 /* Read the number */
747 while (IsBDigit (C)) {
748 if (IVal & 0x80000000) {
749 Error ("Overflow in binary number");
752 IVal = (IVal << 1) + DigitVal (C);
756 /* This is an integer constant */
771 /* Ignore leading zeros */
776 /* Read the number into Buf counting the digits */
778 while (IsXDigit (C)) {
780 /* Buf is big enough to allow any decimal and hex number to
781 * overflow, so ignore excess digits here, they will be detected
782 * when we convert the value.
784 if (Digits < sizeof (Buf)) {
791 /* Allow zilog/intel style hex numbers with a 'h' suffix */
792 if (C == 'h' || C == 'H') {
795 Max = 0xFFFFFFFFUL / 16;
798 Max = 0xFFFFFFFFUL / 10;
801 /* Convert the number using the given base */
803 for (I = 0; I < Digits; ++I) {
805 Error ("Number out of range");
809 DVal = DigitVal (Buf[I]);
811 Error ("Invalid digits in number");
815 IVal = (IVal * Base) + DVal;
818 /* This is an integer constant */
823 /* Control command? */
826 /* Remember and skip the dot */
829 /* Check if it's just a dot */
830 if (!IsIdStart (C)) {
837 /* Read the remainder of the identifier */
841 /* Dot keyword, search for it */
842 Tok = FindDotKeyword ();
843 if (Tok == TOK_NONE) {
846 if (!LeadingDotInIdents) {
847 /* Invalid pseudo instruction */
848 Error ("`%s' is not a recognized control command", SVal);
852 /* An identifier with a dot. Check if it's a define style
855 if (IsDefine (SVal)) {
856 /* This is a define style macro - expand it */
861 /* Just an identifier with a dot */
869 /* Indirect op for sweet16 cpu. Must check this before checking for local
870 * symbols, because these may also use the '@' symbol.
872 if (CPU == CPU_SWEET16 && C == '@') {
879 if (C == LocalStart) {
881 /* Read the identifier */
884 /* Start character alone is not enough */
885 if (SVal [1] == '\0') {
886 Error ("Invalid cheap local symbol");
890 /* A local identifier */
891 Tok = TOK_LOCAL_IDENT;
896 /* Identifier or keyword? */
899 /* Read the identifier */
902 /* Check for special names. Bail out if we have identified the type of
903 * the token. Go on if the token is an identifier.
905 if (SVal[1] == '\0') {
906 switch (toupper (SVal [0])) {
911 Tok = TOK_OVERRIDE_ABS;
920 Tok = TOK_OVERRIDE_FAR;
940 Tok = TOK_OVERRIDE_ZP;
949 } else if (CPU == CPU_SWEET16 && (IVal = Sweet16Reg (SVal)) >= 0) {
951 /* A sweet16 register number in sweet16 mode */
957 /* Check for define style macro */
958 if (IsDefine (SVal)) {
959 /* Macro - expand it */
969 /* Ok, let's do the switch */
1024 Tok = TOK_NAMESPACE;
1063 while (C != '\n' && C != EOF) {
1108 } else if (C == '<') {
1111 } else if (C == '>') {
1134 } else if (C == '>') {
1148 /* Hack: If we allow ' as terminating character for strings, read
1149 * the following stuff as a string, and check for a one character
1152 if (LooseStringTerm) {
1153 if (ReadStringConst ('\'') == 1) {
1160 /* Always a character constant */
1162 if (C == EOF || IsControl (C)) {
1163 Error ("Illegal character constant");
1170 if (!MissingCharTerm) {
1171 Error ("Illegal character constant");
1180 ReadStringConst ('\"');
1185 /* Line continuation? */
1189 /* Handle as white space */
1203 /* Check if we have any open .IFs in this file */
1205 /* Check if we have any open token lists in this file */
1208 /* If this was an include file, then close it and read the next
1209 * token. When an include file is opened, the last token of the
1210 * old file is not skipped, to prevent the lookahead to read
1211 * the next line of the old input file. So we do effectively
1212 * skip the last token in the old file (the file name of the
1213 * include statement).
1214 * In case of the main file, do not close it, but return EOF.
1217 /* Input came from internal data */
1220 } else if (ICount > 1) {
1230 /* If we go here, we could not identify the current character. Skip it
1233 Error ("Invalid input character: 0x%02X", C & 0xFF);
1240 int TokHasSVal (enum Token Tok)
1241 /* Return true if the given token has an attached SVal */
1243 return (Tok == TOK_IDENT || TOK_LOCAL_IDENT || Tok == TOK_STRCON);
1248 int TokHasIVal (enum Token Tok)
1249 /* Return true if the given token has an attached IVal */
1251 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_REG);
1256 int GetSubKey (const char** Keys, unsigned Count)
1257 /* Search for a subkey in a table of keywords. The current token must be an
1258 * identifier and all keys must be in upper case. The identifier will be
1259 * uppercased in the process. The function returns the index of the keyword,
1260 * or -1 if the keyword was not found.
1265 /* Must have an identifier */
1266 PRECONDITION (Tok == TOK_IDENT);
1268 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1273 /* Do a linear search (a binary search is not worth the effort) */
1274 for (I = 0; I < Count; ++I) {
1275 if (strcmp (SVal, Keys [I]) == 0) {
1287 unsigned char ParseAddrSize (void)
1288 /* Check if the next token is a keyword that denotes an address size specifier.
1289 * If so, return the corresponding address size constant, otherwise output an
1290 * error message and return ADDR_SIZE_DEFAULT.
1293 static const char* Keys[] = {
1294 "DIRECT", "ZEROPAGE", "ZP",
1295 "ABSOLUTE", "ABS", "NEAR",
1300 /* Check for an identifier */
1301 if (Tok != TOK_IDENT) {
1302 Error ("Address size specifier expected");
1303 return ADDR_SIZE_DEFAULT;
1306 /* Search for the attribute */
1307 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1310 case 2: return ADDR_SIZE_ZP;
1313 case 5: return ADDR_SIZE_ABS;
1314 case 6: return ADDR_SIZE_FAR;
1316 case 8: return ADDR_SIZE_LONG;
1318 Error ("Address size specifier expected");
1319 return ADDR_SIZE_DEFAULT;
1325 void InitScanner (const char* InFile)
1326 /* Initialize the scanner, open the given input file */
1328 /* Open the input file */
1329 NewInputFile (InFile);
1334 void DoneScanner (void)
1335 /* Release scanner resources */