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 { ".SMART", TOK_SMART },
240 { ".STRAT", TOK_STRAT },
241 { ".STRING", TOK_STRING },
242 { ".STRLEN", TOK_STRLEN },
243 { ".STRUCT", TOK_STRUCT },
244 { ".SUNPLUS", TOK_SUNPLUS },
246 { ".TCOUNT", TOK_TCOUNT },
247 { ".TIME", TOK_TIME },
248 { ".UNION", TOK_UNION },
249 { ".VERSION", TOK_VERSION },
250 { ".WARNING", TOK_WARNING },
251 { ".WORD", TOK_WORD },
252 { ".XMATCH", TOK_XMATCH },
253 { ".XOR", TOK_BOOLXOR },
254 { ".ZEROPAGE", TOK_ZEROPAGE },
259 /*****************************************************************************/
261 /*****************************************************************************/
265 static void NextChar (void);
266 /* Read the next character from the input file */
270 /*****************************************************************************/
271 /* Character classification functions */
272 /*****************************************************************************/
276 static int IsIdChar (int C)
277 /* Return true if the character is a valid character for an identifier */
279 return IsAlNum (C) ||
281 (C == '@' && AtInIdents) ||
282 (C == '$' && DollarInIdents);
287 static int IsIdStart (int C)
288 /* Return true if the character may start an identifier */
290 return IsAlpha (C) || C == '_';
295 /*****************************************************************************/
297 /*****************************************************************************/
301 void NewInputFile (const char* Name)
302 /* Open a new input file */
307 /* First try to open the file */
308 F = fopen (Name, "r");
313 /* Error (fatal error if this is the main file) */
315 Fatal ("Cannot open input file `%s': %s", Name, strerror (errno));
318 /* We are on include level. Search for the file in the include
321 PathName = FindInclude (Name);
322 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
323 /* Not found or cannot open, print an error and bail out */
324 Error ("Cannot open include file `%s': %s", Name, strerror (errno));
327 /* Free the allocated memory */
332 /* check again if we do now have an open file */
337 /* Stat the file and remember the values */
339 if (fstat (fileno (F), &Buf) != 0) {
340 Fatal ("Cannot stat input file `%s': %s", Name, strerror (errno));
343 /* Add the file to the input file table and remember the index */
344 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
346 /* Create a new state variable and initialize it */
347 I = xmalloc (sizeof (*I));
351 I->Pos.Name = FileIdx;
356 /* Use the new file */
368 void DoneInputFile (void)
369 /* Close the current input file */
373 /* Restore the old token */
377 /* Save a pointer to the current struct, then set it back */
381 /* Cleanup the current stuff */
389 void NewInputData (char* Data, int Malloced)
390 /* Add a chunk of input data to the input stream */
394 /* Create a new state variable and initialize it */
395 I = xmalloc (sizeof (*I));
398 I->Malloced = Malloced;
402 /* Use the new data */
412 static void DoneInputData (void)
413 /* End the current input data stream */
417 /* Restore the old token */
421 /* Save a pointer to the current struct, then set it back */
425 /* Cleanup the current stuff */
434 static unsigned DigitVal (unsigned char C)
435 /* Convert a digit into it's numerical representation */
440 return toupper (C) - 'A' + 10;
446 static void NextChar (void)
447 /* Read the next character from the input file */
449 /* If we have an input data structure, read from there */
454 /* End of input data, will set to last file char */
460 /* Check for end of line, read the next line if needed */
461 while (IFile->Line [IFile->Pos.Col] == '\0') {
463 /* End of current line reached, read next line */
464 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
465 /* End of file. Add an empty line to the listing. This is a
466 * small hack needed to keep the PC output in sync.
468 NewListingLine ("", IFile->Pos.Name, ICount);
477 /* Remember the new line for the listing */
478 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
482 /* Return the next character from the file */
483 C = IFile->Line [IFile->Pos.Col++];
490 void LocaseSVal (void)
491 /* Make SVal lower case */
495 SVal [I] = tolower (SVal [I]);
502 void UpcaseSVal (void)
503 /* Make SVal upper case */
507 SVal [I] = toupper (SVal [I]);
514 static int CmpDotKeyword (const void* K1, const void* K2)
515 /* Compare function for the dot keyword search */
517 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
522 static unsigned char FindDotKeyword (void)
523 /* Find the dot keyword in SVal. Return the corresponding token if found,
524 * return TOK_NONE if not found.
527 static const struct DotKeyword K = { SVal, 0 };
528 struct DotKeyword* R;
530 /* If we aren't in ignore case mode, we have to uppercase the keyword */
535 /* Search for the keyword */
536 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
537 sizeof (DotKeywords [0]), CmpDotKeyword);
547 static void ReadIdent (unsigned Index)
548 /* Read an identifier from the current input position into Ident. Filling SVal
549 * starts at Index with the current character in C. It is assumed that any
550 * characters already filled in are ok, and the character in C is checked.
553 /* Read the identifier */
555 if (Index < MAX_STR_LEN) {
559 } while (IsIdChar (C));
562 /* If we should ignore case, convert the identifier to upper case */
570 static unsigned ReadStringConst (int StringTerm)
571 /* Read a string constant into SVal. Check for maximum string length and all
572 * other stuff. The length of the string is returned.
577 /* Skip the leading string terminator */
580 /* Read the string */
583 if (C == StringTerm) {
586 if (C == '\n' || C == EOF) {
587 Error ("Newline in string constant");
591 /* Check for string length, print an error message once */
592 if (I == MAX_STR_LEN) {
593 Error ("Maximum string size exceeded");
594 } else if (I < MAX_STR_LEN) {
599 /* Skip the character */
603 /* Skip the trailing terminator */
606 /* Terminate the string */
607 if (I >= MAX_STR_LEN) {
612 /* Return the length of the string */
618 void NextRawTok (void)
619 /* Read the next raw token from the input stream */
621 /* If we've a forced end of assembly, don't read further */
628 /* Check if we have tokens from another input source */
629 if (InputFromStack ()) {
634 /* Skip whitespace, remember if we had some */
635 if ((WS = IsBlank (C)) != 0) {
638 } while (IsBlank (C));
641 /* If we're reading from the file, update the location from where the
642 * next token will be read. If we're reading from input data, keep the
649 /* Hex number or PC symbol? */
653 /* Hex digit must follow or DollarIsPC must be enabled */
659 Error ("Hexadecimal digit expected");
663 /* Read the number */
665 while (IsXDigit (C)) {
666 if (IVal & 0xF0000000) {
667 Error ("Overflow in hexadecimal number");
670 IVal = (IVal << 4) + DigitVal (C);
674 /* This is an integer constant */
683 /* 0 or 1 must follow */
685 Error ("Binary digit expected");
688 /* Read the number */
690 while (IsBDigit (C)) {
691 if (IVal & 0x80000000) {
692 Error ("Overflow in binary number");
695 IVal = (IVal << 1) + DigitVal (C);
699 /* This is an integer constant */
704 /* Decimal number? */
707 /* Read the number */
709 while (IsDigit (C)) {
710 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
711 Error ("Overflow in decimal number");
714 IVal = (IVal * 10) + DigitVal (C);
718 /* This is an integer constant */
723 /* Control command? */
726 /* Remember and skip the dot */
729 /* Check if it's just a dot */
730 if (!IsIdStart (C)) {
737 /* Read the remainder of the identifier */
741 /* Dot keyword, search for it */
742 Tok = FindDotKeyword ();
743 if (Tok == TOK_NONE) {
745 if (LeadingDotInIdents) {
746 /* An identifier with a dot */
749 /* Invalid pseudo instruction */
750 Error ("`%s' is not a recognized control command", SVal);
760 if (C == LocalStart) {
762 /* Read the identifier */
765 /* Start character alone is not enough */
766 if (SVal [1] == '\0') {
767 Error ("Invalid cheap local symbol");
777 /* Identifier or keyword? */
780 /* Read the identifier */
783 /* Check for special names */
784 if (SVal[1] == '\0') {
785 switch (toupper (SVal [0])) {
790 Tok = TOK_OVERRIDE_ABS;
799 Tok = TOK_OVERRIDE_FAR;
820 Tok = TOK_OVERRIDE_ZP;
832 /* Search for an opcode */
833 IVal = FindInstruction (SVal);
835 /* This is a mnemonic */
837 } else if (IsDefine (SVal)) {
838 /* This is a define style macro - expand it */
848 /* Ok, let's do the switch */
942 while (C != '\n' && C != EOF) {
977 } else if (C == '<') {
980 } else if (C == '>') {
1003 } else if (C == '>') {
1017 /* Hack: If we allow ' as terminating character for strings, read
1018 * the following stuff as a string, and check for a one character
1021 if (LooseStringTerm) {
1022 if (ReadStringConst ('\'') == 1) {
1029 /* Always a character constant */
1031 if (C == '\n' || C == EOF) {
1032 Error ("Illegal character constant");
1039 Error ("Illegal character constant");
1047 ReadStringConst ('\"');
1052 /* Line continuation? */
1056 /* Handle as white space */
1070 /* Check if we have any open .IFs in this file */
1072 /* Check if we have any open token lists in this file */
1075 /* If this was an include file, then close it and handle like a
1076 * separator. Do not close the main file, but return EOF.
1087 /* If we go here, we could not identify the current character. Skip it
1090 Error ("Invalid input character: 0x%02X", C & 0xFF);
1097 int TokHasSVal (enum Token Tok)
1098 /* Return true if the given token has an attached SVal */
1100 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1105 int TokHasIVal (enum Token Tok)
1106 /* Return true if the given token has an attached IVal */
1108 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1113 int GetSubKey (const char** Keys, unsigned Count)
1114 /* Search for a subkey in a table of keywords. The current token must be an
1115 * identifier and all keys must be in upper case. The identifier will be
1116 * uppercased in the process. The function returns the index of the keyword,
1117 * or -1 if the keyword was not found.
1122 /* Must have an identifier */
1123 PRECONDITION (Tok == TOK_IDENT);
1125 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1130 /* Do a linear search (a binary search is not worth the effort) */
1131 for (I = 0; I < Count; ++I) {
1132 if (strcmp (SVal, Keys [I]) == 0) {
1144 unsigned char ParseAddrSize (void)
1145 /* Check if the next token is a keyword that denotes an address size specifier.
1146 * If so, return the corresponding address size constant, otherwise output an
1147 * error message and return ADDR_SIZE_DEFAULT.
1150 static const char* Keys[] = {
1151 "DIRECT", "ZEROPAGE", "ZP",
1152 "ABSOLUTE", "ABS", "NEAR",
1156 /* Check for an identifier */
1157 if (Tok != TOK_IDENT) {
1158 Error ("Address size specifier expected");
1159 return ADDR_SIZE_DEFAULT;
1162 /* Search for the attribute */
1163 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
1166 case 2: return ADDR_SIZE_ZP;
1169 case 5: return ADDR_SIZE_ABS;
1170 case 6: return ADDR_SIZE_FAR;
1172 Error ("Address size specifier expected");
1173 return ADDR_SIZE_DEFAULT;
1179 void InitScanner (const char* InFile)
1180 /* Initialize the scanner, open the given input file */
1182 /* Open the input file */
1183 NewInputFile (InFile);
1188 void DoneScanner (void)
1189 /* Release scanner resources */