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. Note: The length of the input line may
82 * not exceed 255+1, since the column is stored in the file position struct
83 * as a character. Increasing this value means changing the FilePos struct,
84 * and the read and write routines in the assembler and linker.
86 typedef struct InputFile_ InputFile;
88 FILE* F; /* Input file descriptor */
89 FilePos Pos; /* Position in file */
90 enum Token Tok; /* Last token */
91 int C; /* Last character */
92 char Line[256]; /* The current input line */
93 InputFile* Next; /* Linked list of input files */
96 /* Struct to handle textual input data */
97 typedef struct InputData_ InputData;
99 char* Data; /* Pointer to the data */
100 const char* Pos; /* Pointer to current position */
101 int Malloced; /* Memory was malloced */
102 enum Token Tok; /* Last token */
103 int C; /* Last character */
104 InputData* Next; /* Linked list of input data */
107 /* Current input variables */
108 static InputFile* IFile = 0; /* Current input file */
109 static InputData* IData = 0; /* Current input memory data */
110 static unsigned ICount = 0; /* Count of input files */
111 static int C = 0; /* Current input character */
113 /* Force end of assembly */
116 /* List of dot keywords with the corresponding tokens */
118 const char* Key; /* MUST be first field */
123 { ".ADDR", TOK_ADDR },
124 { ".ALIGN", TOK_ALIGN },
125 { ".AND", TOK_BOOLAND },
126 { ".ASCIIZ", TOK_ASCIIZ },
127 { ".ASSERT", TOK_ASSERT },
128 { ".AUTOIMPORT", TOK_AUTOIMPORT },
129 { ".BANKBYTE", TOK_BANKBYTE },
130 { ".BITAND", TOK_AND },
131 { ".BITNOT", TOK_NOT },
132 { ".BITOR", TOK_OR },
133 { ".BITXOR", TOK_XOR },
134 { ".BLANK", TOK_BLANK },
136 { ".BYT", TOK_BYTE },
137 { ".BYTE", TOK_BYTE },
138 { ".CASE", TOK_CASE },
139 { ".CHARMAP", TOK_CHARMAP },
140 { ".CODE", TOK_CODE },
141 { ".CONCAT", TOK_CONCAT },
142 { ".CONDES", TOK_CONDES },
143 { ".CONST", TOK_CONST },
144 { ".CONSTRUCTOR", TOK_CONSTRUCTOR },
146 { ".DATA", TOK_DATA },
148 { ".DBYT", TOK_DBYT },
149 { ".DEBUGINFO", TOK_DEBUGINFO },
150 { ".DEF", TOK_DEFINED },
151 { ".DEFINE", TOK_DEFINE },
152 { ".DEFINED", TOK_DEFINED },
153 { ".DESTRUCTOR", TOK_DESTRUCTOR },
154 { ".DWORD", TOK_DWORD },
155 { ".ELSE", TOK_ELSE },
156 { ".ELSEIF", TOK_ELSEIF },
158 { ".ENDENUM", TOK_ENDENUM },
159 { ".ENDIF", TOK_ENDIF },
160 { ".ENDMAC", TOK_ENDMACRO },
161 { ".ENDMACRO", TOK_ENDMACRO },
162 { ".ENDPROC", TOK_ENDPROC },
163 { ".ENDREP", TOK_ENDREP },
164 { ".ENDREPEAT", TOK_ENDREP },
165 { ".ENDSCOPE", TOK_ENDSCOPE },
166 { ".ENDSTRUCT", TOK_ENDSTRUCT },
167 { ".ENDUNION", TOK_ENDUNION },
168 { ".ENUM", TOK_ENUM },
169 { ".ERROR", TOK_ERROR },
170 { ".EXITMAC", TOK_EXITMACRO },
171 { ".EXITMACRO", TOK_EXITMACRO },
172 { ".EXPORT", TOK_EXPORT },
173 { ".EXPORTZP", TOK_EXPORTZP },
174 { ".FARADDR", TOK_FARADDR },
175 { ".FEATURE", TOK_FEATURE },
176 { ".FILEOPT", TOK_FILEOPT },
177 { ".FOPT", TOK_FILEOPT },
178 { ".FORCEIMPORT", TOK_FORCEIMPORT },
179 { ".FORCEWORD", TOK_FORCEWORD },
180 { ".GLOBAL", TOK_GLOBAL },
181 { ".GLOBALZP", TOK_GLOBALZP },
182 { ".HIBYTE", TOK_HIBYTE },
183 { ".HIWORD", TOK_HIWORD },
187 { ".IFBLANK", TOK_IFBLANK },
188 { ".IFCONST", TOK_IFCONST },
189 { ".IFDEF", TOK_IFDEF },
190 { ".IFNBLANK", TOK_IFNBLANK },
191 { ".IFNCONST", TOK_IFNCONST },
192 { ".IFNDEF", TOK_IFNDEF },
193 { ".IFNREF", TOK_IFNREF },
194 { ".IFP02", TOK_IFP02 },
195 { ".IFP816", TOK_IFP816 },
196 { ".IFPC02", TOK_IFPC02 },
197 { ".IFPSC02", TOK_IFPSC02 },
198 { ".IFREF", TOK_IFREF },
199 { ".IMPORT", TOK_IMPORT },
200 { ".IMPORTZP", TOK_IMPORTZP },
201 { ".INCBIN", TOK_INCBIN },
202 { ".INCLUDE", TOK_INCLUDE },
203 { ".INTERRUPTOR", TOK_INTERRUPTOR },
204 { ".LEFT", TOK_LEFT },
205 { ".LINECONT", TOK_LINECONT },
206 { ".LIST", TOK_LIST },
207 { ".LISTBYTES", TOK_LISTBYTES },
208 { ".LOBYTE", TOK_LOBYTE },
209 { ".LOCAL", TOK_LOCAL },
210 { ".LOCALCHAR", TOK_LOCALCHAR },
211 { ".LOWORD", TOK_LOWORD },
212 { ".MAC", TOK_MACRO },
213 { ".MACPACK", TOK_MACPACK },
214 { ".MACRO", TOK_MACRO },
215 { ".MATCH", TOK_MATCH },
218 { ".NOT", TOK_BOOLNOT },
219 { ".NULL", TOK_NULL },
220 { ".OR", TOK_BOOLOR },
224 { ".P816", TOK_P816 },
225 { ".PAGELEN", TOK_PAGELENGTH },
226 { ".PAGELENGTH", TOK_PAGELENGTH },
227 { ".PARAMCOUNT", TOK_PARAMCOUNT },
228 { ".PC02", TOK_PC02 },
229 { ".POPSEG", TOK_POPSEG },
230 { ".PROC", TOK_PROC },
231 { ".PSC02", TOK_PSC02 },
232 { ".PUSHSEG", TOK_PUSHSEG },
233 { ".REF", TOK_REFERENCED },
234 { ".REFERENCED", TOK_REFERENCED },
235 { ".RELOC", TOK_RELOC },
236 { ".REPEAT", TOK_REPEAT },
238 { ".RIGHT", TOK_RIGHT },
239 { ".RODATA", TOK_RODATA },
240 { ".SCOPE", TOK_SCOPE },
241 { ".SEGMENT", TOK_SEGMENT },
242 { ".SETCPU", TOK_SETCPU },
245 { ".SIZEOF", TOK_SIZEOF },
246 { ".SMART", TOK_SMART },
247 { ".STRAT", TOK_STRAT },
248 { ".STRING", TOK_STRING },
249 { ".STRLEN", TOK_STRLEN },
250 { ".STRUCT", TOK_STRUCT },
251 { ".SUNPLUS", TOK_SUNPLUS },
253 { ".TCOUNT", TOK_TCOUNT },
254 { ".TIME", TOK_TIME },
255 { ".UNION", TOK_UNION },
256 { ".VERSION", TOK_VERSION },
257 { ".WARNING", TOK_WARNING },
258 { ".WORD", TOK_WORD },
259 { ".XMATCH", TOK_XMATCH },
260 { ".XOR", TOK_BOOLXOR },
261 { ".ZEROPAGE", TOK_ZEROPAGE },
266 /*****************************************************************************/
268 /*****************************************************************************/
272 static void NextChar (void);
273 /* Read the next character from the input file */
277 /*****************************************************************************/
278 /* Character classification functions */
279 /*****************************************************************************/
283 static int IsIdChar (int C)
284 /* Return true if the character is a valid character for an identifier */
286 return IsAlNum (C) ||
288 (C == '@' && AtInIdents) ||
289 (C == '$' && DollarInIdents);
294 static int IsIdStart (int C)
295 /* Return true if the character may start an identifier */
297 return IsAlpha (C) || C == '_';
302 /*****************************************************************************/
304 /*****************************************************************************/
308 void NewInputFile (const char* Name)
309 /* Open a new input file */
314 /* First try to open the file */
315 F = fopen (Name, "r");
320 /* Error (fatal error if this is the main file) */
322 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
325 /* We are on include level. Search for the file in the include
328 PathName = FindInclude (Name);
329 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
330 /* Not found or cannot open, print an error and bail out */
331 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
334 /* Free the allocated memory */
339 /* check again if we do now have an open file */
344 /* Stat the file and remember the values */
346 if (fstat (fileno (F), &Buf) != 0) {
347 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
350 /* Add the file to the input file table and remember the index */
351 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
353 /* Create a new state variable and initialize it */
354 I = xmalloc (sizeof (*I));
358 I->Pos.Name = FileIdx;
363 /* Use the new file */
375 void DoneInputFile (void)
376 /* Close the current input file */
380 /* Restore the old token */
384 /* Save a pointer to the current struct, then set it back */
388 /* Cleanup the current stuff */
396 void NewInputData (char* Data, int Malloced)
397 /* Add a chunk of input data to the input stream */
401 /* Create a new state variable and initialize it */
402 I = xmalloc (sizeof (*I));
405 I->Malloced = Malloced;
409 /* Use the new data */
419 static void DoneInputData (void)
420 /* End the current input data stream */
424 /* Restore the old token */
428 /* Save a pointer to the current struct, then set it back */
432 /* Cleanup the current stuff */
441 static unsigned DigitVal (unsigned char C)
442 /* Convert a digit into it's numerical representation */
447 return toupper (C) - 'A' + 10;
453 static void NextChar (void)
454 /* Read the next character from the input file */
456 /* If we have an input data structure, read from there */
461 /* End of input data, will set to last file char */
467 /* Check for end of line, read the next line if needed */
468 while (IFile->Line [IFile->Pos.Col] == '\0') {
470 unsigned Len, Removed;
472 /* End of current line reached, read next line */
473 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
474 /* End of file. Add an empty line to the listing. This is a
475 * small hack needed to keep the PC output in sync.
477 NewListingLine ("", IFile->Pos.Name, ICount);
482 /* For better handling of files with unusual line endings (DOS
483 * files that are accidently translated on Unix for example),
484 * first remove all whitespace at the end, then add a single
487 Len = strlen (IFile->Line);
489 while (Len > 0 && IsSpace (IFile->Line[Len-1])) {
494 IFile->Line[Len+0] = '\n';
495 IFile->Line[Len+1] = '\0';
502 /* Remember the new line for the listing */
503 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
507 /* Return the next character from the file */
508 C = IFile->Line [IFile->Pos.Col++];
515 void LocaseSVal (void)
516 /* Make SVal lower case */
520 SVal [I] = tolower (SVal [I]);
527 void UpcaseSVal (void)
528 /* Make SVal upper case */
532 SVal [I] = toupper (SVal [I]);
539 static int CmpDotKeyword (const void* K1, const void* K2)
540 /* Compare function for the dot keyword search */
542 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
547 static unsigned char FindDotKeyword (void)
548 /* Find the dot keyword in SVal. Return the corresponding token if found,
549 * return TOK_NONE if not found.
552 static const struct DotKeyword K = { SVal, 0 };
553 struct DotKeyword* R;
555 /* If we aren't in ignore case mode, we have to uppercase the keyword */
560 /* Search for the keyword */
561 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
562 sizeof (DotKeywords [0]), CmpDotKeyword);
572 static void ReadIdent (unsigned Index)
573 /* Read an identifier from the current input position into Ident. Filling SVal
574 * starts at Index with the current character in C. It is assumed that any
575 * characters already filled in are ok, and the character in C is checked.
578 /* Read the identifier */
580 if (Index < MAX_STR_LEN) {
584 } while (IsIdChar (C));
587 /* If we should ignore case, convert the identifier to upper case */
595 static unsigned ReadStringConst (int StringTerm)
596 /* Read a string constant into SVal. Check for maximum string length and all
597 * other stuff. The length of the string is returned.
602 /* Skip the leading string terminator */
605 /* Read the string */
608 if (C == StringTerm) {
611 if (C == '\n' || C == EOF) {
612 Error ("Newline in string constant");
616 /* Check for string length, print an error message once */
617 if (I == MAX_STR_LEN) {
618 Error ("Maximum string size exceeded");
619 } else if (I < MAX_STR_LEN) {
624 /* Skip the character */
628 /* Skip the trailing terminator */
631 /* Terminate the string */
632 if (I >= MAX_STR_LEN) {
637 /* Return the length of the string */
643 static int Sweet16Reg (const char* Ident)
644 /* Check if the given identifier is a sweet16 register. Return -1 if this is
645 * not the case, return the register number otherwise.
651 if (Ident[0] != 'r' && Ident[0] != 'R') {
654 if (!IsDigit (Ident[1])) {
658 if (sscanf (Ident+1, "%u%c", &RegNum, &Check) != 1 || RegNum > 15) {
659 /* Invalid register */
663 /* The register number is valid */
669 void NextRawTok (void)
670 /* Read the next raw token from the input stream */
672 /* If we've a forced end of assembly, don't read further */
679 /* Check if we have tokens from another input source */
680 if (InputFromStack ()) {
685 /* Skip whitespace, remember if we had some */
686 if ((WS = IsBlank (C)) != 0) {
689 } while (IsBlank (C));
692 /* If we're reading from the file, update the location from where the
693 * next token will be read. If we're reading from input data, keep the
700 /* Hex number or PC symbol? */
704 /* Hex digit must follow or DollarIsPC must be enabled */
710 Error ("Hexadecimal digit expected");
714 /* Read the number */
716 while (IsXDigit (C)) {
717 if (IVal & 0xF0000000) {
718 Error ("Overflow in hexadecimal number");
721 IVal = (IVal << 4) + DigitVal (C);
725 /* This is an integer constant */
734 /* 0 or 1 must follow */
736 Error ("Binary digit expected");
739 /* Read the number */
741 while (IsBDigit (C)) {
742 if (IVal & 0x80000000) {
743 Error ("Overflow in binary number");
746 IVal = (IVal << 1) + DigitVal (C);
750 /* This is an integer constant */
755 /* Decimal number? */
758 /* Read the number */
760 while (IsDigit (C)) {
761 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
762 Error ("Overflow in decimal number");
765 IVal = (IVal * 10) + DigitVal (C);
769 /* This is an integer constant */
774 /* Control command? */
777 /* Remember and skip the dot */
780 /* Check if it's just a dot */
781 if (!IsIdStart (C)) {
788 /* Read the remainder of the identifier */
792 /* Dot keyword, search for it */
793 Tok = FindDotKeyword ();
794 if (Tok == TOK_NONE) {
797 if (!LeadingDotInIdents) {
798 /* Invalid pseudo instruction */
799 Error ("`%s' is not a recognized control command", SVal);
803 /* An identifier with a dot. Check if it's a define style
806 if (IsDefine (SVal)) {
807 /* This is a define style macro - expand it */
812 /* Just an identifier with a dot */
820 /* Indirect op for sweet16 cpu. Must check this before checking for local
821 * symbols, because these may also use the '@' symbol.
823 if (CPU == CPU_SWEET16 && C == '@') {
830 if (C == LocalStart) {
832 /* Read the identifier */
835 /* Start character alone is not enough */
836 if (SVal [1] == '\0') {
837 Error ("Invalid cheap local symbol");
841 /* A local identifier */
842 Tok = TOK_LOCAL_IDENT;
847 /* Identifier or keyword? */
850 /* Read the identifier */
853 /* Check for special names. Bail out if we have identified the type of
854 * the token. Go on if the token is an identifier.
856 if (SVal[1] == '\0') {
857 switch (toupper (SVal [0])) {
862 Tok = TOK_OVERRIDE_ABS;
871 Tok = TOK_OVERRIDE_FAR;
891 Tok = TOK_OVERRIDE_ZP;
900 } else if (CPU == CPU_SWEET16 && (IVal = Sweet16Reg (SVal)) >= 0) {
902 /* A sweet16 register number in sweet16 mode */
908 /* Check for define style macro */
909 if (IsDefine (SVal)) {
910 /* Macro - expand it */
920 /* Ok, let's do the switch */
1014 while (C != '\n' && C != EOF) {
1059 } else if (C == '<') {
1062 } else if (C == '>') {
1085 } else if (C == '>') {
1099 /* Hack: If we allow ' as terminating character for strings, read
1100 * the following stuff as a string, and check for a one character
1103 if (LooseStringTerm) {
1104 if (ReadStringConst ('\'') == 1) {
1111 /* Always a character constant */
1113 if (C == EOF || IsControl (C)) {
1114 Error ("Illegal character constant");
1121 if (!MissingCharTerm) {
1122 Error ("Illegal character constant");
1131 ReadStringConst ('\"');
1136 /* Line continuation? */
1140 /* Handle as white space */
1154 /* Check if we have any open .IFs in this file */
1156 /* Check if we have any open token lists in this file */
1159 /* If this was an include file, then close it and handle like a
1160 * separator. Do not close the main file, but return EOF.
1171 /* If we go here, we could not identify the current character. Skip it
1174 Error ("Invalid input character: 0x%02X", C & 0xFF);
1181 int TokHasSVal (enum Token Tok)
1182 /* Return true if the given token has an attached SVal */
1184 return (Tok == TOK_IDENT || TOK_LOCAL_IDENT || Tok == TOK_STRCON);
1189 int TokHasIVal (enum Token Tok)
1190 /* Return true if the given token has an attached IVal */
1192 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_REG);
1197 int GetSubKey (const char** Keys, unsigned Count)
1198 /* Search for a subkey in a table of keywords. The current token must be an
1199 * identifier and all keys must be in upper case. The identifier will be
1200 * uppercased in the process. The function returns the index of the keyword,
1201 * or -1 if the keyword was not found.
1206 /* Must have an identifier */
1207 PRECONDITION (Tok == TOK_IDENT);
1209 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1214 /* Do a linear search (a binary search is not worth the effort) */
1215 for (I = 0; I < Count; ++I) {
1216 if (strcmp (SVal, Keys [I]) == 0) {
1228 unsigned char ParseAddrSize (void)
1229 /* Check if the next token is a keyword that denotes an address size specifier.
1230 * If so, return the corresponding address size constant, otherwise output an
1231 * error message and return ADDR_SIZE_DEFAULT.
1234 static const char* Keys[] = {
1235 "DIRECT", "ZEROPAGE", "ZP",
1236 "ABSOLUTE", "ABS", "NEAR",
1241 /* Check for an identifier */
1242 if (Tok != TOK_IDENT) {
1243 Error ("Address size specifier expected");
1244 return ADDR_SIZE_DEFAULT;
1247 /* Search for the attribute */
1248 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1251 case 2: return ADDR_SIZE_ZP;
1254 case 5: return ADDR_SIZE_ABS;
1255 case 6: return ADDR_SIZE_FAR;
1257 case 8: return ADDR_SIZE_LONG;
1259 Error ("Address size specifier expected");
1260 return ADDR_SIZE_DEFAULT;
1266 void InitScanner (const char* InFile)
1267 /* Initialize the scanner, open the given input file */
1269 /* Open the input file */
1270 NewInputFile (InFile);
1275 void DoneScanner (void)
1276 /* Release scanner resources */