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_BAND },
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 { ".ENDIF", TOK_ENDIF },
158 { ".ENDMAC", TOK_ENDMACRO },
159 { ".ENDMACRO", TOK_ENDMACRO },
160 { ".ENDPROC", TOK_ENDPROC },
161 { ".ENDREP", TOK_ENDREP },
162 { ".ENDREPEAT", TOK_ENDREP },
163 { ".ENDSTRUCT", TOK_ENDSTRUCT },
164 { ".ERROR", TOK_ERROR },
165 { ".EXITMAC", TOK_EXITMACRO },
166 { ".EXITMACRO", TOK_EXITMACRO },
167 { ".EXPORT", TOK_EXPORT },
168 { ".EXPORTZP", TOK_EXPORTZP },
169 { ".FARADDR", TOK_FARADDR },
170 { ".FEATURE", TOK_FEATURE },
171 { ".FILEOPT", TOK_FILEOPT },
172 { ".FOPT", TOK_FILEOPT },
173 { ".FORCEIMPORT", TOK_FORCEIMPORT },
174 { ".FORCEWORD", TOK_FORCEWORD },
175 { ".GLOBAL", TOK_GLOBAL },
176 { ".GLOBALZP", TOK_GLOBALZP },
180 { ".IFBLANK", TOK_IFBLANK },
181 { ".IFCONST", TOK_IFCONST },
182 { ".IFDEF", TOK_IFDEF },
183 { ".IFNBLANK", TOK_IFNBLANK },
184 { ".IFNCONST", TOK_IFNCONST },
185 { ".IFNDEF", TOK_IFNDEF },
186 { ".IFNREF", TOK_IFNREF },
187 { ".IFP02", TOK_IFP02 },
188 { ".IFP816", TOK_IFP816 },
189 { ".IFPC02", TOK_IFPC02 },
190 { ".IFPSC02", TOK_IFPSC02 },
191 { ".IFREF", TOK_IFREF },
192 { ".IMPORT", TOK_IMPORT },
193 { ".IMPORTZP", TOK_IMPORTZP },
194 { ".INCBIN", TOK_INCBIN },
195 { ".INCLUDE", TOK_INCLUDE },
196 { ".LEFT", TOK_LEFT },
197 { ".LINECONT", TOK_LINECONT },
198 { ".LIST", TOK_LIST },
199 { ".LISTBYTES", TOK_LISTBYTES },
200 { ".LOCAL", TOK_LOCAL },
201 { ".LOCALCHAR", TOK_LOCALCHAR },
202 { ".MAC", TOK_MACRO },
203 { ".MACPACK", TOK_MACPACK },
204 { ".MACRO", TOK_MACRO },
205 { ".MATCH", TOK_MATCH },
208 { ".NOT", TOK_BNOT },
209 { ".NULL", TOK_NULL },
214 { ".P816", TOK_P816 },
215 { ".PAGELEN", TOK_PAGELENGTH },
216 { ".PAGELENGTH", TOK_PAGELENGTH },
217 { ".PARAMCOUNT", TOK_PARAMCOUNT },
218 { ".PC02", TOK_PC02 },
219 { ".POPSEG", TOK_POPSEG },
220 { ".PROC", TOK_PROC },
221 { ".PSC02", TOK_PSC02 },
222 { ".PUSHSEG", TOK_PUSHSEG },
223 { ".REF", TOK_REFERENCED },
224 { ".REFERENCED", TOK_REFERENCED },
225 { ".RELOC", TOK_RELOC },
226 { ".REPEAT", TOK_REPEAT },
228 { ".RIGHT", TOK_RIGHT },
229 { ".RODATA", TOK_RODATA },
230 { ".SEGMENT", TOK_SEGMENT },
231 { ".SETCPU", TOK_SETCPU },
234 { ".SMART", TOK_SMART },
235 { ".STRAT", TOK_STRAT },
236 { ".STRING", TOK_STRING },
237 { ".STRLEN", TOK_STRLEN },
238 { ".STRUCT", TOK_STRUCT },
239 { ".SUNPLUS", TOK_SUNPLUS },
241 { ".TCOUNT", TOK_TCOUNT },
242 { ".TIME", TOK_TIME },
243 { ".UNION", TOK_UNION },
244 { ".VERSION", TOK_VERSION },
245 { ".WARNING", TOK_WARNING },
246 { ".WORD", TOK_WORD },
247 { ".XMATCH", TOK_XMATCH },
248 { ".XOR", TOK_BXOR },
249 { ".ZEROPAGE", TOK_ZEROPAGE },
254 /*****************************************************************************/
256 /*****************************************************************************/
260 static void NextChar (void);
261 /* Read the next character from the input file */
265 /*****************************************************************************/
266 /* Character classification functions */
267 /*****************************************************************************/
271 static int IsIdChar (int C)
272 /* Return true if the character is a valid character for an identifier */
274 return IsAlNum (C) ||
276 (C == '@' && AtInIdents) ||
277 (C == '$' && DollarInIdents);
282 static int IsIdStart (int C)
283 /* Return true if the character may start an identifier */
285 return IsAlpha (C) || C == '_';
290 /*****************************************************************************/
292 /*****************************************************************************/
296 void NewInputFile (const char* Name)
297 /* Open a new input file */
302 /* First try to open the file */
303 F = fopen (Name, "r");
308 /* Error (fatal error if this is the main file) */
310 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
313 /* We are on include level. Search for the file in the include
316 PathName = FindInclude (Name);
317 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
318 /* Not found or cannot open, print an error and bail out */
319 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
322 /* Free the allocated memory */
327 /* check again if we do now have an open file */
332 /* Stat the file and remember the values */
334 if (fstat (fileno (F), &Buf) != 0) {
335 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
338 /* Add the file to the input file table and remember the index */
339 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
341 /* Create a new state variable and initialize it */
342 I = xmalloc (sizeof (*I));
346 I->Pos.Name = FileIdx;
351 /* Use the new file */
363 void DoneInputFile (void)
364 /* Close the current input file */
368 /* Restore the old token */
372 /* Save a pointer to the current struct, then set it back */
376 /* Cleanup the current stuff */
384 void NewInputData (char* Data, int Malloced)
385 /* Add a chunk of input data to the input stream */
389 /* Create a new state variable and initialize it */
390 I = xmalloc (sizeof (*I));
393 I->Malloced = Malloced;
397 /* Use the new data */
407 static void DoneInputData (void)
408 /* End the current input data stream */
412 /* Restore the old token */
416 /* Save a pointer to the current struct, then set it back */
420 /* Cleanup the current stuff */
429 static unsigned DigitVal (unsigned char C)
430 /* Convert a digit into it's numerical representation */
435 return toupper (C) - 'A' + 10;
441 static void NextChar (void)
442 /* Read the next character from the input file */
444 /* If we have an input data structure, read from there */
449 /* End of input data, will set to last file char */
455 /* Check for end of line, read the next line if needed */
456 while (IFile->Line [IFile->Pos.Col] == '\0') {
458 /* End of current line reached, read next line */
459 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
460 /* End of file. Add an empty line to the listing. This is a
461 * small hack needed to keep the PC output in sync.
463 NewListingLine ("", IFile->Pos.Name, ICount);
472 /* Remember the new line for the listing */
473 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
477 /* Return the next character from the file */
478 C = IFile->Line [IFile->Pos.Col++];
485 void LocaseSVal (void)
486 /* Make SVal lower case */
490 SVal [I] = tolower (SVal [I]);
497 void UpcaseSVal (void)
498 /* Make SVal upper case */
502 SVal [I] = toupper (SVal [I]);
509 static int CmpDotKeyword (const void* K1, const void* K2)
510 /* Compare function for the dot keyword search */
512 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
517 static unsigned char FindDotKeyword (void)
518 /* Find the dot keyword in SVal. Return the corresponding token if found,
519 * return TOK_NONE if not found.
522 static const struct DotKeyword K = { SVal, 0 };
523 struct DotKeyword* R;
525 /* If we aren't in ignore case mode, we have to uppercase the keyword */
530 /* Search for the keyword */
531 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
532 sizeof (DotKeywords [0]), CmpDotKeyword);
542 static void ReadIdent (unsigned Index)
543 /* Read an identifier from the current input position into Ident. Filling SVal
544 * starts at Index with the current character in C. It is assumed that any
545 * characters already filled in are ok, and the character in C is checked.
548 /* Read the identifier */
550 if (Index < MAX_STR_LEN) {
554 } while (IsIdChar (C));
557 /* If we should ignore case, convert the identifier to upper case */
565 static unsigned ReadStringConst (int StringTerm)
566 /* Read a string constant into SVal. Check for maximum string length and all
567 * other stuff. The length of the string is returned.
572 /* Skip the leading string terminator */
575 /* Read the string */
578 if (C == StringTerm) {
581 if (C == '\n' || C == EOF) {
582 Error ("Newline in string constant");
586 /* Check for string length, print an error message once */
587 if (I == MAX_STR_LEN) {
588 Error ("Maximum string size exceeded");
589 } else if (I < MAX_STR_LEN) {
594 /* Skip the character */
598 /* Skip the trailing terminator */
601 /* Terminate the string */
602 if (I >= MAX_STR_LEN) {
607 /* Return the length of the string */
613 void NextRawTok (void)
614 /* Read the next raw token from the input stream */
616 /* If we've a forced end of assembly, don't read further */
623 /* Check if we have tokens from another input source */
624 if (InputFromStack ()) {
629 /* Skip whitespace, remember if we had some */
630 if ((WS = IsBlank (C)) != 0) {
633 } while (IsBlank (C));
636 /* If we're reading from the file, update the location from where the
637 * next token will be read. If we're reading from input data, keep the
644 /* Hex number or PC symbol? */
648 /* Hex digit must follow or DollarIsPC must be enabled */
654 Error ("Hexadecimal digit expected");
658 /* Read the number */
660 while (IsXDigit (C)) {
661 if (IVal & 0xF0000000) {
662 Error ("Overflow in hexadecimal number");
665 IVal = (IVal << 4) + DigitVal (C);
669 /* This is an integer constant */
678 /* 0 or 1 must follow */
680 Error ("Binary digit expected");
683 /* Read the number */
685 while (IsBDigit (C)) {
686 if (IVal & 0x80000000) {
687 Error ("Overflow in binary number");
690 IVal = (IVal << 1) + DigitVal (C);
694 /* This is an integer constant */
699 /* Decimal number? */
702 /* Read the number */
704 while (IsDigit (C)) {
705 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
706 Error ("Overflow in decimal number");
709 IVal = (IVal * 10) + DigitVal (C);
713 /* This is an integer constant */
718 /* Control command? */
721 /* Remember and skip the dot */
724 /* Check if it's just a dot */
725 if (!IsIdStart (C)) {
732 /* Read the remainder of the identifier */
736 /* Dot keyword, search for it */
737 Tok = FindDotKeyword ();
738 if (Tok == TOK_NONE) {
740 if (LeadingDotInIdents) {
741 /* An identifier with a dot */
744 /* Invalid pseudo instruction */
745 Error ("`%s' is not a recognized control command", SVal);
755 if (C == LocalStart) {
757 /* Read the identifier */
760 /* Start character alone is not enough */
761 if (SVal [1] == '\0') {
762 Error ("Invalid cheap local symbol");
772 /* Identifier or keyword? */
775 /* Read the identifier */
778 /* Check for special names */
779 if (SVal[1] == '\0') {
780 switch (toupper (SVal [0])) {
785 Tok = TOK_OVERRIDE_ABS;
794 Tok = TOK_OVERRIDE_FAR;
815 Tok = TOK_OVERRIDE_ZP;
827 /* Search for an opcode */
828 IVal = FindInstruction (SVal);
830 /* This is a mnemonic */
832 } else if (IsDefine (SVal)) {
833 /* This is a define style macro - expand it */
843 /* Ok, let's do the switch */
937 while (C != '\n' && C != EOF) {
972 } else if (C == '<') {
975 } else if (C == '>') {
998 } else if (C == '>') {
1012 /* Hack: If we allow ' as terminating character for strings, read
1013 * the following stuff as a string, and check for a one character
1016 if (LooseStringTerm) {
1017 if (ReadStringConst ('\'') == 1) {
1024 /* Always a character constant */
1026 if (C == '\n' || C == EOF) {
1027 Error ("Illegal character constant");
1034 Error ("Illegal character constant");
1042 ReadStringConst ('\"');
1047 /* Line continuation? */
1051 /* Handle as white space */
1065 /* Check if we have any open .IFs in this file */
1067 /* Check if we have any open token lists in this file */
1070 /* If this was an include file, then close it and handle like a
1071 * separator. Do not close the main file, but return EOF.
1082 /* If we go here, we could not identify the current character. Skip it
1085 Error ("Invalid input character: 0x%02X", C & 0xFF);
1092 int TokHasSVal (enum Token Tok)
1093 /* Return true if the given token has an attached SVal */
1095 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1100 int TokHasIVal (enum Token Tok)
1101 /* Return true if the given token has an attached IVal */
1103 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1108 int GetSubKey (const char** Keys, unsigned Count)
1109 /* Search for a subkey in a table of keywords. The current token must be an
1110 * identifier and all keys must be in upper case. The identifier will be
1111 * uppercased in the process. The function returns the index of the keyword,
1112 * or -1 if the keyword was not found.
1117 /* Must have an identifier */
1118 PRECONDITION (Tok == TOK_IDENT);
1120 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1125 /* Do a linear search (a binary search is not worth the effort) */
1126 for (I = 0; I < Count; ++I) {
1127 if (strcmp (SVal, Keys [I]) == 0) {
1139 unsigned ParseAddrSize (void)
1140 /* Check if the next token is a keyword that denotes an address size specifier.
1141 * If so, return the corresponding address size constant, otherwise output an
1142 * error message and return ADDR_SIZE_DEFAULT.
1145 static const char* Keys[] = {
1146 "DIRECT", "ZEROPAGE", "ZP",
1147 "ABSOLUTE", "ABS", "NEAR",
1151 /* Check for an identifier */
1152 if (Tok != TOK_IDENT) {
1153 Error ("Address size specifier expected");
1154 return ADDR_SIZE_DEFAULT;
1157 /* Search for the attribute */
1158 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1161 case 2: return ADDR_SIZE_FAR;
1164 case 5: return ADDR_SIZE_ABS;
1165 case 6: return ADDR_SIZE_FAR;
1167 Error ("Address size specifier expected");
1168 return ADDR_SIZE_DEFAULT;
1174 void InitScanner (const char* InFile)
1175 /* Initialize the scanner, open the given input file */
1177 /* Open the input file */
1178 NewInputFile (InFile);
1183 void DoneScanner (void)
1184 /* Release scanner resources */