1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2003 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 { ".BITAND", TOK_AND },
130 { ".BITNOT", TOK_NOT },
131 { ".BITOR", TOK_OR },
132 { ".BITXOR", TOK_XOR },
133 { ".BLANK", TOK_BLANK },
135 { ".BYT", TOK_BYTE },
136 { ".BYTE", TOK_BYTE },
137 { ".CASE", TOK_CASE },
138 { ".CHARMAP", TOK_CHARMAP },
139 { ".CODE", TOK_CODE },
140 { ".CONCAT", TOK_CONCAT },
141 { ".CONDES", TOK_CONDES },
142 { ".CONST", TOK_CONST },
143 { ".CONSTRUCTOR", TOK_CONSTRUCTOR },
145 { ".DATA", TOK_DATA },
147 { ".DBYT", TOK_DBYT },
148 { ".DEBUGINFO", TOK_DEBUGINFO },
149 { ".DEF", TOK_DEFINED },
150 { ".DEFINE", TOK_DEFINE },
151 { ".DEFINED", TOK_DEFINED },
152 { ".DESTRUCTOR", TOK_DESTRUCTOR },
153 { ".DWORD", TOK_DWORD },
154 { ".ELSE", TOK_ELSE },
155 { ".ELSEIF", TOK_ELSEIF },
157 { ".ENDENUM", TOK_ENDENUM },
158 { ".ENDIF", TOK_ENDIF },
159 { ".ENDMAC", TOK_ENDMACRO },
160 { ".ENDMACRO", TOK_ENDMACRO },
161 { ".ENDPROC", TOK_ENDPROC },
162 { ".ENDREP", TOK_ENDREP },
163 { ".ENDREPEAT", TOK_ENDREP },
164 { ".ENDSCOPE", TOK_ENDSCOPE },
165 { ".ENDSTRUCT", TOK_ENDSTRUCT },
166 { ".ENDUNION", TOK_ENDUNION },
167 { ".ENUM", TOK_ENUM },
168 { ".ERROR", TOK_ERROR },
169 { ".EXITMAC", TOK_EXITMACRO },
170 { ".EXITMACRO", TOK_EXITMACRO },
171 { ".EXPORT", TOK_EXPORT },
172 { ".EXPORTZP", TOK_EXPORTZP },
173 { ".FARADDR", TOK_FARADDR },
174 { ".FEATURE", TOK_FEATURE },
175 { ".FILEOPT", TOK_FILEOPT },
176 { ".FOPT", TOK_FILEOPT },
177 { ".FORCEIMPORT", TOK_FORCEIMPORT },
178 { ".FORCEWORD", TOK_FORCEWORD },
179 { ".GLOBAL", TOK_GLOBAL },
180 { ".GLOBALZP", TOK_GLOBALZP },
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 { ".LEFT", TOK_LEFT },
201 { ".LINECONT", TOK_LINECONT },
202 { ".LIST", TOK_LIST },
203 { ".LISTBYTES", TOK_LISTBYTES },
204 { ".LOCAL", TOK_LOCAL },
205 { ".LOCALCHAR", TOK_LOCALCHAR },
206 { ".MAC", TOK_MACRO },
207 { ".MACPACK", TOK_MACPACK },
208 { ".MACRO", TOK_MACRO },
209 { ".MATCH", TOK_MATCH },
212 { ".NOT", TOK_BOOLNOT },
213 { ".NULL", TOK_NULL },
214 { ".OR", TOK_BOOLOR },
218 { ".P816", TOK_P816 },
219 { ".PAGELEN", TOK_PAGELENGTH },
220 { ".PAGELENGTH", TOK_PAGELENGTH },
221 { ".PARAMCOUNT", TOK_PARAMCOUNT },
222 { ".PC02", TOK_PC02 },
223 { ".POPSEG", TOK_POPSEG },
224 { ".PROC", TOK_PROC },
225 { ".PSC02", TOK_PSC02 },
226 { ".PUSHSEG", TOK_PUSHSEG },
227 { ".REF", TOK_REFERENCED },
228 { ".REFERENCED", TOK_REFERENCED },
229 { ".RELOC", TOK_RELOC },
230 { ".REPEAT", TOK_REPEAT },
232 { ".RIGHT", TOK_RIGHT },
233 { ".RODATA", TOK_RODATA },
234 { ".SCOPE", TOK_SCOPE },
235 { ".SEGMENT", TOK_SEGMENT },
236 { ".SETCPU", TOK_SETCPU },
239 { ".SIZEOF", TOK_SIZEOF },
240 { ".SMART", TOK_SMART },
241 { ".STRAT", TOK_STRAT },
242 { ".STRING", TOK_STRING },
243 { ".STRLEN", TOK_STRLEN },
244 { ".STRUCT", TOK_STRUCT },
245 { ".SUNPLUS", TOK_SUNPLUS },
247 { ".TCOUNT", TOK_TCOUNT },
248 { ".TIME", TOK_TIME },
249 { ".UNION", TOK_UNION },
250 { ".VERSION", TOK_VERSION },
251 { ".WARNING", TOK_WARNING },
252 { ".WORD", TOK_WORD },
253 { ".XMATCH", TOK_XMATCH },
254 { ".XOR", TOK_BOOLXOR },
255 { ".ZEROPAGE", TOK_ZEROPAGE },
260 /*****************************************************************************/
262 /*****************************************************************************/
266 static void NextChar (void);
267 /* Read the next character from the input file */
271 /*****************************************************************************/
272 /* Character classification functions */
273 /*****************************************************************************/
277 static int IsIdChar (int C)
278 /* Return true if the character is a valid character for an identifier */
280 return IsAlNum (C) ||
282 (C == '@' && AtInIdents) ||
283 (C == '$' && DollarInIdents);
288 static int IsIdStart (int C)
289 /* Return true if the character may start an identifier */
291 return IsAlpha (C) || C == '_';
296 /*****************************************************************************/
298 /*****************************************************************************/
302 void NewInputFile (const char* Name)
303 /* Open a new input file */
308 /* First try to open the file */
309 F = fopen (Name, "r");
314 /* Error (fatal error if this is the main file) */
316 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
319 /* We are on include level. Search for the file in the include
322 PathName = FindInclude (Name);
323 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
324 /* Not found or cannot open, print an error and bail out */
325 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
328 /* Free the allocated memory */
333 /* check again if we do now have an open file */
338 /* Stat the file and remember the values */
340 if (fstat (fileno (F), &Buf) != 0) {
341 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
344 /* Add the file to the input file table and remember the index */
345 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
347 /* Create a new state variable and initialize it */
348 I = xmalloc (sizeof (*I));
352 I->Pos.Name = FileIdx;
357 /* Use the new file */
369 void DoneInputFile (void)
370 /* Close the current input file */
374 /* Restore the old token */
378 /* Save a pointer to the current struct, then set it back */
382 /* Cleanup the current stuff */
390 void NewInputData (char* Data, int Malloced)
391 /* Add a chunk of input data to the input stream */
395 /* Create a new state variable and initialize it */
396 I = xmalloc (sizeof (*I));
399 I->Malloced = Malloced;
403 /* Use the new data */
413 static void DoneInputData (void)
414 /* End the current input data stream */
418 /* Restore the old token */
422 /* Save a pointer to the current struct, then set it back */
426 /* Cleanup the current stuff */
435 static unsigned DigitVal (unsigned char C)
436 /* Convert a digit into it's numerical representation */
441 return toupper (C) - 'A' + 10;
447 static void NextChar (void)
448 /* Read the next character from the input file */
450 /* If we have an input data structure, read from there */
455 /* End of input data, will set to last file char */
461 /* Check for end of line, read the next line if needed */
462 while (IFile->Line [IFile->Pos.Col] == '\0') {
464 /* End of current line reached, read next line */
465 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
466 /* End of file. Add an empty line to the listing. This is a
467 * small hack needed to keep the PC output in sync.
469 NewListingLine ("", IFile->Pos.Name, ICount);
478 /* Remember the new line for the listing */
479 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
483 /* Return the next character from the file */
484 C = IFile->Line [IFile->Pos.Col++];
491 void LocaseSVal (void)
492 /* Make SVal lower case */
496 SVal [I] = tolower (SVal [I]);
503 void UpcaseSVal (void)
504 /* Make SVal upper case */
508 SVal [I] = toupper (SVal [I]);
515 static int CmpDotKeyword (const void* K1, const void* K2)
516 /* Compare function for the dot keyword search */
518 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
523 static unsigned char FindDotKeyword (void)
524 /* Find the dot keyword in SVal. Return the corresponding token if found,
525 * return TOK_NONE if not found.
528 static const struct DotKeyword K = { SVal, 0 };
529 struct DotKeyword* R;
531 /* If we aren't in ignore case mode, we have to uppercase the keyword */
536 /* Search for the keyword */
537 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
538 sizeof (DotKeywords [0]), CmpDotKeyword);
548 static void ReadIdent (unsigned Index)
549 /* Read an identifier from the current input position into Ident. Filling SVal
550 * starts at Index with the current character in C. It is assumed that any
551 * characters already filled in are ok, and the character in C is checked.
554 /* Read the identifier */
556 if (Index < MAX_STR_LEN) {
560 } while (IsIdChar (C));
563 /* If we should ignore case, convert the identifier to upper case */
571 static unsigned ReadStringConst (int StringTerm)
572 /* Read a string constant into SVal. Check for maximum string length and all
573 * other stuff. The length of the string is returned.
578 /* Skip the leading string terminator */
581 /* Read the string */
584 if (C == StringTerm) {
587 if (C == '\n' || C == EOF) {
588 Error ("Newline in string constant");
592 /* Check for string length, print an error message once */
593 if (I == MAX_STR_LEN) {
594 Error ("Maximum string size exceeded");
595 } else if (I < MAX_STR_LEN) {
600 /* Skip the character */
604 /* Skip the trailing terminator */
607 /* Terminate the string */
608 if (I >= MAX_STR_LEN) {
613 /* Return the length of the string */
619 void NextRawTok (void)
620 /* Read the next raw token from the input stream */
622 /* If we've a forced end of assembly, don't read further */
629 /* Check if we have tokens from another input source */
630 if (InputFromStack ()) {
635 /* Skip whitespace, remember if we had some */
636 if ((WS = IsBlank (C)) != 0) {
639 } while (IsBlank (C));
642 /* If we're reading from the file, update the location from where the
643 * next token will be read. If we're reading from input data, keep the
650 /* Hex number or PC symbol? */
654 /* Hex digit must follow or DollarIsPC must be enabled */
660 Error ("Hexadecimal digit expected");
664 /* Read the number */
666 while (IsXDigit (C)) {
667 if (IVal & 0xF0000000) {
668 Error ("Overflow in hexadecimal number");
671 IVal = (IVal << 4) + DigitVal (C);
675 /* This is an integer constant */
684 /* 0 or 1 must follow */
686 Error ("Binary digit expected");
689 /* Read the number */
691 while (IsBDigit (C)) {
692 if (IVal & 0x80000000) {
693 Error ("Overflow in binary number");
696 IVal = (IVal << 1) + DigitVal (C);
700 /* This is an integer constant */
705 /* Decimal number? */
708 /* Read the number */
710 while (IsDigit (C)) {
711 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
712 Error ("Overflow in decimal number");
715 IVal = (IVal * 10) + DigitVal (C);
719 /* This is an integer constant */
724 /* Control command? */
727 /* Remember and skip the dot */
730 /* Check if it's just a dot */
731 if (!IsIdStart (C)) {
738 /* Read the remainder of the identifier */
742 /* Dot keyword, search for it */
743 Tok = FindDotKeyword ();
744 if (Tok == TOK_NONE) {
746 if (LeadingDotInIdents) {
747 /* An identifier with a dot */
750 /* Invalid pseudo instruction */
751 Error ("`%s' is not a recognized control command", SVal);
761 if (C == LocalStart) {
763 /* Read the identifier */
766 /* Start character alone is not enough */
767 if (SVal [1] == '\0') {
768 Error ("Invalid cheap local symbol");
772 /* A local identifier */
773 Tok = TOK_LOCAL_IDENT;
778 /* Identifier or keyword? */
781 /* Read the identifier */
784 /* Check for special names */
785 if (SVal[1] == '\0') {
786 switch (toupper (SVal [0])) {
791 Tok = TOK_OVERRIDE_ABS;
800 Tok = TOK_OVERRIDE_FAR;
821 Tok = TOK_OVERRIDE_ZP;
833 /* Search for an opcode */
834 IVal = FindInstruction (SVal);
836 /* This is a mnemonic */
838 } else if (IsDefine (SVal)) {
839 /* This is a define style macro - expand it */
849 /* Ok, let's do the switch */
943 while (C != '\n' && C != EOF) {
978 } else if (C == '<') {
981 } else if (C == '>') {
1004 } else if (C == '>') {
1018 /* Hack: If we allow ' as terminating character for strings, read
1019 * the following stuff as a string, and check for a one character
1022 if (LooseStringTerm) {
1023 if (ReadStringConst ('\'') == 1) {
1030 /* Always a character constant */
1032 if (C == '\n' || C == EOF) {
1033 Error ("Illegal character constant");
1040 Error ("Illegal character constant");
1048 ReadStringConst ('\"');
1053 /* Line continuation? */
1057 /* Handle as white space */
1071 /* Check if we have any open .IFs in this file */
1073 /* Check if we have any open token lists in this file */
1076 /* If this was an include file, then close it and handle like a
1077 * separator. Do not close the main file, but return EOF.
1088 /* If we go here, we could not identify the current character. Skip it
1091 Error ("Invalid input character: 0x%02X", C & 0xFF);
1098 int TokHasSVal (enum Token Tok)
1099 /* Return true if the given token has an attached SVal */
1101 return (Tok == TOK_IDENT || TOK_LOCAL_IDENT || Tok == TOK_STRCON);
1106 int TokHasIVal (enum Token Tok)
1107 /* Return true if the given token has an attached IVal */
1109 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1114 int GetSubKey (const char** Keys, unsigned Count)
1115 /* Search for a subkey in a table of keywords. The current token must be an
1116 * identifier and all keys must be in upper case. The identifier will be
1117 * uppercased in the process. The function returns the index of the keyword,
1118 * or -1 if the keyword was not found.
1123 /* Must have an identifier */
1124 PRECONDITION (Tok == TOK_IDENT);
1126 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1131 /* Do a linear search (a binary search is not worth the effort) */
1132 for (I = 0; I < Count; ++I) {
1133 if (strcmp (SVal, Keys [I]) == 0) {
1145 unsigned char ParseAddrSize (void)
1146 /* Check if the next token is a keyword that denotes an address size specifier.
1147 * If so, return the corresponding address size constant, otherwise output an
1148 * error message and return ADDR_SIZE_DEFAULT.
1151 static const char* Keys[] = {
1152 "DIRECT", "ZEROPAGE", "ZP",
1153 "ABSOLUTE", "ABS", "NEAR",
1158 /* Check for an identifier */
1159 if (Tok != TOK_IDENT) {
1160 Error ("Address size specifier expected");
1161 return ADDR_SIZE_DEFAULT;
1164 /* Search for the attribute */
1165 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1168 case 2: return ADDR_SIZE_ZP;
1171 case 5: return ADDR_SIZE_ABS;
1172 case 6: return ADDR_SIZE_FAR;
1174 case 8: return ADDR_SIZE_LONG;
1176 Error ("Address size specifier expected");
1177 return ADDR_SIZE_DEFAULT;
1183 void InitScanner (const char* InFile)
1184 /* Initialize the scanner, open the given input file */
1186 /* Open the input file */
1187 NewInputFile (InFile);
1192 void DoneScanner (void)
1193 /* Release scanner resources */