1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2002 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@musoftware.de */
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 */
65 /*****************************************************************************/
67 /*****************************************************************************/
71 enum Token Tok = TOK_NONE; /* Current token */
72 int WS; /* Flag: Whitespace before token */
73 long IVal; /* Integer token attribute */
74 char SVal [MAX_STR_LEN+1]; /* String token attribute */
76 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
80 /* Struct to handle include files. Note: The length of the input line may
81 * not exceed 255+1, since the column is stored in the file position struct
82 * as a character. Increasing this value means changing the FilePos struct,
83 * and the read and write routines in the assembler and linker.
85 typedef struct InputFile_ InputFile;
87 FILE* F; /* Input file descriptor */
88 FilePos Pos; /* Position in file */
89 enum Token Tok; /* Last token */
90 int C; /* Last character */
91 char Line[256]; /* The current input line */
92 InputFile* Next; /* Linked list of input files */
95 /* Struct to handle textual input data */
96 typedef struct InputData_ InputData;
98 const char* Data; /* Pointer to the data */
99 const char* Pos; /* Pointer to current position */
100 int Malloced; /* Memory was malloced */
101 enum Token Tok; /* Last token */
102 int C; /* Last character */
103 InputData* Next; /* Linked list of input data */
106 /* Current input variables */
107 static InputFile* IFile = 0; /* Current input file */
108 static InputData* IData = 0; /* Current input memory data */
109 static unsigned ICount = 0; /* Count of input files */
110 static int C = 0; /* Current input character */
112 /* Force end of assembly */
115 /* List of dot keywords with the corresponding tokens */
117 const char* Key; /* MUST be first field */
122 { ".ADDR", TOK_ADDR },
123 { ".ALIGN", TOK_ALIGN },
124 { ".AND", TOK_BAND },
125 { ".ASCIIZ", TOK_ASCIIZ },
126 { ".AUTOIMPORT", TOK_AUTOIMPORT },
127 { ".BITAND", TOK_AND },
128 { ".BITNOT", TOK_NOT },
129 { ".BITOR", TOK_OR },
130 { ".BITXOR", TOK_XOR },
131 { ".BLANK", TOK_BLANK },
133 { ".BYT", TOK_BYTE },
134 { ".BYTE", TOK_BYTE },
135 { ".CASE", TOK_CASE },
136 { ".CHARMAP", TOK_CHARMAP },
137 { ".CODE", TOK_CODE },
138 { ".CONCAT", TOK_CONCAT },
139 { ".CONDES", TOK_CONDES },
140 { ".CONST", TOK_CONST },
141 { ".CONSTRUCTOR", TOK_CONSTRUCTOR },
143 { ".DATA", TOK_DATA },
145 { ".DBYT", TOK_DBYT },
146 { ".DEBUGINFO", TOK_DEBUGINFO },
147 { ".DEF", TOK_DEFINED },
148 { ".DEFINE", TOK_DEFINE },
149 { ".DEFINED", TOK_DEFINED },
150 { ".DESTRUCTOR", TOK_DESTRUCTOR },
151 { ".DWORD", TOK_DWORD },
152 { ".ELSE", TOK_ELSE },
153 { ".ELSEIF", TOK_ELSEIF },
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 { ".ERROR", TOK_ERROR },
162 { ".EXITMAC", TOK_EXITMACRO },
163 { ".EXITMACRO", TOK_EXITMACRO },
164 { ".EXPORT", TOK_EXPORT },
165 { ".EXPORTZP", TOK_EXPORTZP },
166 { ".FARADDR", TOK_FARADDR },
167 { ".FEATURE", TOK_FEATURE },
168 { ".FILEOPT", TOK_FILEOPT },
169 { ".FOPT", TOK_FILEOPT },
170 { ".FORCEWORD", TOK_FORCEWORD },
171 { ".GLOBAL", TOK_GLOBAL },
172 { ".GLOBALZP", TOK_GLOBALZP },
176 { ".IFBLANK", TOK_IFBLANK },
177 { ".IFCONST", TOK_IFCONST },
178 { ".IFDEF", TOK_IFDEF },
179 { ".IFNBLANK", TOK_IFNBLANK },
180 { ".IFNCONST", TOK_IFNCONST },
181 { ".IFNDEF", TOK_IFNDEF },
182 { ".IFNREF", TOK_IFNREF },
183 { ".IFP02", TOK_IFP02 },
184 { ".IFP816", TOK_IFP816 },
185 { ".IFPC02", TOK_IFPC02 },
186 { ".IFREF", TOK_IFREF },
187 { ".IMPORT", TOK_IMPORT },
188 { ".IMPORTZP", TOK_IMPORTZP },
189 { ".INCBIN", TOK_INCBIN },
190 { ".INCLUDE", TOK_INCLUDE },
191 { ".LEFT", TOK_LEFT },
192 { ".LINECONT", TOK_LINECONT },
193 { ".LIST", TOK_LIST },
194 { ".LISTBYTES", TOK_LISTBYTES },
195 { ".LOCAL", TOK_LOCAL },
196 { ".LOCALCHAR", TOK_LOCALCHAR },
197 { ".MAC", TOK_MACRO },
198 { ".MACPACK", TOK_MACPACK },
199 { ".MACRO", TOK_MACRO },
200 { ".MATCH", TOK_MATCH },
203 { ".NOT", TOK_BNOT },
204 { ".NULL", TOK_NULL },
209 { ".P816", TOK_P816 },
210 { ".PAGELEN", TOK_PAGELENGTH },
211 { ".PAGELENGTH", TOK_PAGELENGTH },
212 { ".PARAMCOUNT", TOK_PARAMCOUNT },
213 { ".PC02", TOK_PC02 },
214 { ".PROC", TOK_PROC },
215 { ".REF", TOK_REFERENCED },
216 { ".REFERENCED", TOK_REFERENCED },
217 { ".RELOC", TOK_RELOC },
218 { ".REPEAT", TOK_REPEAT },
220 { ".RIGHT", TOK_RIGHT },
221 { ".RODATA", TOK_RODATA },
222 { ".SEGMENT", TOK_SEGMENT },
225 { ".SMART", TOK_SMART },
226 { ".STRAT", TOK_STRAT },
227 { ".STRING", TOK_STRING },
228 { ".STRLEN", TOK_STRLEN },
229 { ".SUNPLUS", TOK_SUNPLUS },
230 { ".TCOUNT", TOK_TCOUNT },
231 { ".TIME", TOK_TIME },
232 { ".WARNING", TOK_WARNING },
233 { ".WORD", TOK_WORD },
234 { ".XMATCH", TOK_XMATCH },
235 { ".XOR", TOK_BXOR },
236 { ".ZEROPAGE", TOK_ZEROPAGE },
241 /*****************************************************************************/
243 /*****************************************************************************/
247 static void NextChar (void);
248 /* Read the next character from the input file */
252 /*****************************************************************************/
253 /* Character classification functions */
254 /*****************************************************************************/
258 static int IsIdChar (int C)
259 /* Return true if the character is a valid character for an identifier */
261 return IsAlNum (C) ||
263 (C == '@' && AtInIdents) ||
264 (C == '$' && DollarInIdents);
269 static int IsIdStart (int C)
270 /* Return true if the character may start an identifier */
272 return IsAlpha (C) || C == '_';
277 /*****************************************************************************/
279 /*****************************************************************************/
283 void NewInputFile (const char* Name)
284 /* Open a new input file */
289 /* First try to open the file */
290 F = fopen (Name, "r");
295 /* Error (fatal error if this is the main file) */
297 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
300 /* We are on include level. Search for the file in the include
303 PathName = FindInclude (Name);
304 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
305 /* Not found or cannot open, print an error and bail out */
306 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
309 /* Free the allocated memory */
314 /* check again if we do now have an open file */
319 /* Stat the file and remember the values */
321 if (fstat (fileno (F), &Buf) != 0) {
322 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
325 /* Add the file to the input file table and remember the index */
326 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
328 /* Create a new state variable and initialize it */
329 I = xmalloc (sizeof (*I));
333 I->Pos.Name = FileIdx;
338 /* Use the new file */
350 void DoneInputFile (void)
351 /* Close the current input file */
355 /* Restore the old token */
359 /* Save a pointer to the current struct, then set it back */
363 /* Cleanup the current stuff */
371 void NewInputData (const char* Data, int Malloced)
372 /* Add a chunk of input data to the input stream */
376 /* Create a new state variable and initialize it */
377 I = xmalloc (sizeof (*I));
380 I->Malloced = Malloced;
384 /* Use the new data */
394 static void DoneInputData (void)
395 /* End the current input data stream */
399 /* Restore the old token */
403 /* Save a pointer to the current struct, then set it back */
407 /* Cleanup the current stuff */
416 static unsigned DigitVal (unsigned char C)
417 /* Convert a digit into it's numerical representation */
422 return toupper (C) - 'A' + 10;
428 static void NextChar (void)
429 /* Read the next character from the input file */
431 /* If we have an input data structure, read from there */
436 /* End of input data, will set to last file char */
442 /* Check for end of line, read the next line if needed */
443 while (IFile->Line [IFile->Pos.Col] == '\0') {
445 /* End of current line reached, read next line */
446 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
447 /* End of file. Add an empty line to the listing. This is a
448 * small hack needed to keep the PC output in sync.
450 NewListingLine ("", IFile->Pos.Name, ICount);
459 /* Remember the new line for the listing */
460 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
464 /* Return the next character from the file */
465 C = IFile->Line [IFile->Pos.Col++];
472 void LocaseSVal (void)
473 /* Make SVal lower case */
477 SVal [I] = tolower (SVal [I]);
484 void UpcaseSVal (void)
485 /* Make SVal upper case */
489 SVal [I] = toupper (SVal [I]);
496 static int CmpDotKeyword (const void* K1, const void* K2)
497 /* Compare function for the dot keyword search */
499 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
504 static unsigned char FindDotKeyword (void)
505 /* Find the dot keyword in SVal. Return the corresponding token if found,
506 * return TOK_NONE if not found.
509 static const struct DotKeyword K = { SVal, 0 };
510 struct DotKeyword* R;
512 /* If we aren't in ignore case mode, we have to uppercase the keyword */
517 /* Search for the keyword */
518 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
519 sizeof (DotKeywords [0]), CmpDotKeyword);
529 static void ReadIdent (unsigned Index)
530 /* Read an identifier from the current input position into Ident. Filling SVal
531 * starts at Index with the current character in C. It is assumed that any
532 * characters already filled in are ok, and the character in C is checked.
535 /* Read the identifier */
537 if (Index < MAX_STR_LEN) {
541 } while (IsIdChar (C));
544 /* If we should ignore case, convert the identifier to upper case */
552 static unsigned ReadStringConst (int StringTerm)
553 /* Read a string constant into SVal. Check for maximum string length and all
554 * other stuff. The length of the string is returned.
559 /* Skip the leading string terminator */
562 /* Read the string */
565 if (C == StringTerm) {
568 if (C == '\n' || C == EOF) {
569 Error (ERR_NEWLINE_IN_STRING);
573 /* Check for string length, print an error message once */
574 if (I == MAX_STR_LEN) {
575 Error (ERR_STRING_TOO_LONG);
576 } else if (I < MAX_STR_LEN) {
581 /* Skip the character */
585 /* Skip the trailing terminator */
588 /* Terminate the string */
589 if (I >= MAX_STR_LEN) {
594 /* Return the length of the string */
600 void NextRawTok (void)
601 /* Read the next raw token from the input stream */
603 /* If we've a forced end of assembly, don't read further */
610 /* Check if we have tokens from another input source */
611 if (InputFromStack ()) {
616 /* Skip whitespace, remember if we had some */
617 if ((WS = IsBlank (C)) != 0) {
620 } while (IsBlank (C));
623 /* If we're reading from the file, update the location from where the
624 * next token will be read. If we're reading from input data, keep the
631 /* Hex number or PC symbol? */
635 /* Hex digit must follow or DollarIsPC must be enabled */
641 Error (ERR_HEX_DIGIT_EXPECTED);
645 /* Read the number */
647 while (IsXDigit (C)) {
648 if (IVal & 0xF0000000) {
649 Error (ERR_NUM_OVERFLOW);
652 IVal = (IVal << 4) + DigitVal (C);
656 /* This is an integer constant */
665 /* 0 or 1 must follow */
667 Error (ERR_01_EXPECTED);
670 /* Read the number */
672 while (IsBDigit (C)) {
673 if (IVal & 0x80000000) {
674 Error (ERR_NUM_OVERFLOW);
677 IVal = (IVal << 1) + DigitVal (C);
681 /* This is an integer constant */
686 /* Decimal number? */
689 /* Read the number */
691 while (IsDigit (C)) {
692 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
693 Error (ERR_NUM_OVERFLOW);
696 IVal = (IVal * 10) + DigitVal (C);
700 /* This is an integer constant */
705 /* Control command? */
708 /* Remember and skip the dot */
712 /* Check if it's just a dot */
713 if (!IsIdStart (C)) {
720 /* Read the remainder of the identifier */
723 /* Dot keyword, search for it */
724 Tok = FindDotKeyword ();
725 if (Tok == TOK_NONE) {
727 if (LeadingDotInIdents) {
728 /* An identifier with a dot */
731 /* Invalid pseudo instruction */
732 Error (ERR_PSEUDO_EXPECTED);
742 if (C == LocalStart) {
744 /* Read the identifier */
747 /* Start character alone is not enough */
748 if (SVal [1] == '\0') {
749 Error (ERR_IDENT_EXPECTED);
759 /* Identifier or keyword? */
762 /* Read the identifier */
765 /* Check for special names */
766 if (SVal [1] == '\0') {
767 switch (toupper (SVal [0])) {
791 /* Search for an opcode */
792 IVal = FindInstruction (SVal);
794 /* This is a mnemonic */
796 } else if (IsDefine (SVal)) {
797 /* This is a define style macro - expand it */
807 /* Ok, let's do the switch */
896 while (C != '\n' && C != EOF) {
931 } else if (C == '<') {
934 } else if (C == '>') {
957 } else if (C == '>') {
971 /* Hack: If we allow ' as terminating character for strings, read
972 * the following stuff as a string, and check for a one character
975 if (LooseStringTerm) {
976 if (ReadStringConst ('\'') == 1) {
983 /* Always a character constant */
985 if (C == '\n' || C == EOF) {
986 Error (ERR_ILLEGAL_CHARCON);
993 Error (ERR_ILLEGAL_CHARCON);
1001 ReadStringConst ('\"');
1006 /* Line continuation? */
1010 /* Handle as white space */
1024 /* Check if we have any open .IFs in this file */
1026 /* Check if we have any open token lists in this file */
1029 /* If this was an include file, then close it and handle like a
1030 * separator. Do not close the main file, but return EOF.
1041 /* If we go here, we could not identify the current character. Skip it
1044 Error (ERR_INVALID_CHAR, C & 0xFF);
1051 int TokHasSVal (enum Token Tok)
1052 /* Return true if the given token has an attached SVal */
1054 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1059 int TokHasIVal (enum Token Tok)
1060 /* Return true if the given token has an attached IVal */
1062 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1067 int GetSubKey (const char** Keys, unsigned Count)
1068 /* Search for a subkey in a table of keywords. The current token must be an
1069 * identifier and all keys must be in upper case. The identifier will be
1070 * uppercased in the process. The function returns the index of the keyword,
1071 * or -1 if the keyword was not found.
1076 /* Must have an identifier */
1077 PRECONDITION (Tok == TOK_IDENT);
1079 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1084 /* Do a linear search (a binary search is not worth the effort) */
1085 for (I = 0; I < Count; ++I) {
1086 if (strcmp (SVal, Keys [I]) == 0) {
1098 void InitScanner (const char* InFile)
1099 /* Initialize the scanner, open the given input file */
1101 /* Open the input file */
1102 NewInputFile (InFile);
1107 void DoneScanner (void)
1108 /* Release scanner resources */