1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2000 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 /*****************************************************************************/
43 #include "../common/fname.h"
44 #include "../common/xmalloc.h"
60 /*****************************************************************************/
62 /*****************************************************************************/
66 enum Token Tok = TOK_NONE; /* Current token */
67 int WS; /* Flag: Whitespace before token */
68 long IVal; /* Integer token attribute */
69 char SVal [MAX_STR_LEN+1]; /* String token attribute */
71 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
75 /* Struct to handle include files. Note: The length of the input line may
76 * not exceed 255+1, since the column is stored in the file position struct
77 * as a character. Increasing this value means changing the FilePos struct,
78 * and the read and write routines in the assembler and linker.
80 typedef struct InputFile_ InputFile;
82 FILE* F; /* Input file descriptor */
83 FilePos Pos; /* Position in file */
84 enum Token Tok; /* Last token */
85 int C; /* Last character */
86 char Line[256]; /* The current input line */
87 InputFile* Next; /* Linked list of input files */
90 /* Struct to handle textual input data */
91 typedef struct InputData_ InputData;
93 const char* Data; /* Pointer to the data */
94 const char* Pos; /* Pointer to current position */
95 int Malloced; /* Memory was malloced */
96 enum Token Tok; /* Last token */
97 int C; /* Last character */
98 InputData* Next; /* Linked list of input data */
101 /* List of input files */
103 unsigned long MTime; /* Time of last modification */
104 unsigned long Size; /* Size of file */
105 const char* Name; /* Name of file */
106 } Files [MAX_INPUT_FILES];
107 static unsigned FileCount = 0;
109 /* Current input variables */
110 static InputFile* IFile = 0; /* Current input file */
111 static InputData* IData = 0; /* Current input memory data */
112 static unsigned ICount = 0; /* Count of input files */
113 static int C = 0; /* Current input character */
115 /* Force end of assembly */
118 /* List of dot keywords with the corresponding tokens */
120 const char* Key; /* MUST be first field */
125 { "ADDR", TOK_ADDR },
126 { "ALIGN", TOK_ALIGN },
128 { "ASCIIZ", TOK_ASCIIZ },
129 { "AUTOIMPORT", TOK_AUTOIMPORT },
130 { "BITAND", TOK_AND },
131 { "BITNOT", TOK_NOT },
133 { "BITXOR", TOK_XOR },
134 { "BLANK", TOK_BLANK },
136 { "BYTE", TOK_BYTE },
137 { "CASE", TOK_CASE },
138 { "CODE", TOK_CODE },
139 { "CONCAT", TOK_CONCAT },
140 { "CONST", TOK_CONST },
142 { "DATA", TOK_DATA },
143 { "DBYT", TOK_DBYT },
144 { "DEBUGINFO", TOK_DEBUGINFO },
145 { "DEF", TOK_DEFINED },
146 { "DEFINE", TOK_DEFINE },
147 { "DEFINED", TOK_DEFINED },
148 { "DWORD", TOK_DWORD },
149 { "ELSE", TOK_ELSE },
150 { "ELSEIF", TOK_ELSEIF },
152 { "ENDIF", TOK_ENDIF },
153 { "ENDMAC", TOK_ENDMACRO },
154 { "ENDMACRO", TOK_ENDMACRO },
155 { "ENDPROC", TOK_ENDPROC },
156 { "ENDREP", TOK_ENDREP },
157 { "ENDREPEAT", TOK_ENDREP },
158 { "ERROR", TOK_ERROR },
159 { "EXITMAC", TOK_EXITMACRO },
160 { "EXITMACRO", TOK_EXITMACRO },
161 { "EXPORT", TOK_EXPORT },
162 { "EXPORTZP", TOK_EXPORTZP },
163 { "FARADDR", TOK_FARADDR },
164 { "FEATURE", TOK_FEATURE },
165 { "FILEOPT", TOK_FILEOPT },
166 { "FOPT", TOK_FILEOPT },
167 { "GLOBAL", TOK_GLOBAL },
168 { "GLOBALZP", TOK_GLOBALZP },
172 { "IFBLANK", TOK_IFBLANK },
173 { "IFCONST", TOK_IFCONST },
174 { "IFDEF", TOK_IFDEF },
175 { "IFNBLANK", TOK_IFNBLANK },
176 { "IFNCONST", TOK_IFNCONST },
177 { "IFNDEF", TOK_IFNDEF },
178 { "IFNREF", TOK_IFNREF },
179 { "IFP02", TOK_IFP02 },
180 { "IFP816", TOK_IFP816 },
181 { "IFPC02", TOK_IFPC02 },
182 { "IFREF", TOK_IFREF },
183 { "IMPORT", TOK_IMPORT },
184 { "IMPORTZP", TOK_IMPORTZP },
185 { "INCBIN", TOK_INCBIN },
186 { "INCLUDE", TOK_INCLUDE },
187 { "LEFT", TOK_LEFT },
188 { "LINECONT", TOK_LINECONT },
189 { "LIST", TOK_LIST },
190 { "LISTBYTES", TOK_LISTBYTES },
191 { "LOCAL", TOK_LOCAL },
192 { "LOCALCHAR", TOK_LOCALCHAR },
193 { "MAC", TOK_MACRO },
194 { "MACPACK", TOK_MACPACK },
195 { "MACRO", TOK_MACRO },
196 { "MATCH", TOK_MATCH },
200 { "NULL", TOK_NULL },
205 { "P816", TOK_P816 },
206 { "PAGELEN", TOK_PAGELENGTH },
207 { "PAGELENGTH", TOK_PAGELENGTH },
208 { "PARAMCOUNT", TOK_PARAMCOUNT },
209 { "PC02", TOK_PC02 },
210 { "PROC", TOK_PROC },
211 { "REF", TOK_REFERENCED },
212 { "REFERENCED", TOK_REFERENCED },
213 { "RELOC", TOK_RELOC },
214 { "REPEAT", TOK_REPEAT },
216 { "RIGHT", TOK_RIGHT },
217 { "RODATA", TOK_RODATA },
218 { "SEGMENT", TOK_SEGMENT },
221 { "SMART", TOK_SMART },
222 { "STRAT", TOK_STRAT },
223 { "STRING", TOK_STRING },
224 { "STRLEN", TOK_STRLEN },
225 { "SUNPLUS", TOK_SUNPLUS },
226 { "TCOUNT", TOK_TCOUNT },
227 { "WORD", TOK_WORD },
228 { "XMATCH", TOK_XMATCH },
230 { "ZEROPAGE", TOK_ZEROPAGE },
235 /*****************************************************************************/
237 /*****************************************************************************/
241 static void NextChar (void);
242 /* Read the next character from the input file */
246 /*****************************************************************************/
247 /* Character classification functions */
248 /*****************************************************************************/
252 static int IsBlank (int C)
253 /* Return true if the character is a blank or tab */
255 return (C == ' ' || C == '\t');
260 static int IsDigit (int C)
261 /* Return true if the character is a digit */
268 static int IsXDigit (int C)
269 /* Return true if the character is a hexadecimal digit */
276 static int IsDDigit (int C)
277 /* Return true if the character is a dual digit */
279 return (C == '0' || C == '1');
284 static int IsIdChar (int C)
285 /* Return true if the character is a valid character for an identifier */
287 return isalnum (C) ||
289 (C == '@' && AtInIdents) ||
290 (C == '$' && DollarInIdents);
295 static int IsIdStart (int C)
296 /* Return true if the character may start an identifier */
298 return isalpha (C) || C == '_';
303 /*****************************************************************************/
305 /*****************************************************************************/
309 const char* GetFileName (unsigned char Name)
310 /* Get the name of a file where the name index is known */
312 PRECONDITION (Name <= FileCount);
314 /* Name was defined outside any file scope, use the name of the first
315 * file instead. Errors are then reported with a file position of
316 * line zero in the first file.
318 if (FileCount == 0) {
319 /* No files defined until now */
320 return "(outside file scope)";
322 return Files [0].Name;
325 return Files [Name-1].Name;
331 void NewInputFile (const char* Name)
332 /* Open a new input file */
337 /* Check for nested include overflow */
338 if (FileCount >= MAX_INPUT_FILES) {
339 Fatal (FAT_MAX_INPUT_FILES);
342 /* First try to open the file */
343 F = fopen (Name, "r");
348 /* Error (fatal error if this is the main file) */
350 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
353 /* We are on include level. Search for the file in the include
356 PathName = FindInclude (Name);
357 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
358 /* Not found or cannot open, print an error and bail out */
359 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
362 /* Free the allocated memory */
367 /* check again if we do now have an open file */
370 /* Stat the file and remember the values */
372 if (fstat (fileno (F), &Buf) != 0) {
373 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
375 Files [FileCount].MTime = Buf.st_mtime;
376 Files [FileCount].Size = Buf.st_size;
377 Files [FileCount].Name = xstrdup (Name);
380 /* Create a new state variable and initialize it */
381 I = xmalloc (sizeof (*I));
385 I->Pos.Name = FileCount;
390 /* Use the new file */
402 void DoneInputFile (void)
403 /* Close the current input file */
407 /* Restore the old token */
411 /* Save a pointer to the current struct, then set it back */
415 /* Cleanup the current stuff */
423 void NewInputData (const char* Data, int Malloced)
424 /* Add a chunk of input data to the input stream */
428 /* Create a new state variable and initialize it */
429 I = xmalloc (sizeof (*I));
432 I->Malloced = Malloced;
436 /* Use the new data */
446 static void DoneInputData (void)
447 /* End the current input data stream */
451 /* Restore the old token */
455 /* Save a pointer to the current struct, then set it back */
459 /* Cleanup the current stuff */
468 static unsigned DigitVal (unsigned char C)
469 /* Convert a digit into it's numerical representation */
474 return toupper (C) - 'A' + 10;
480 static void NextChar (void)
481 /* Read the next character from the input file */
483 /* If we have an input data structure, read from there */
488 /* End of input data, will set to last file char */
494 /* Check for end of line, read the next line if needed */
495 while (IFile->Line [IFile->Pos.Col] == '\0') {
497 /* End of current line reached, read next line */
498 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
499 /* End of file. Add an empty line to the listing. This is a
500 * small hack needed to keep the PC output in sync.
502 NewListingLine ("", IFile->Pos.Name, ICount);
511 /* Remember the new line for the listing */
512 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
516 /* Return the next character from the file */
517 C = IFile->Line [IFile->Pos.Col++];
524 void UpcaseSVal (void)
525 /* Make SVal upper case */
529 SVal [I] = toupper (SVal [I]);
536 static int CmpDotKeyword (const void* K1, const void* K2)
537 /* Compare function for the dot keyword search */
539 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
544 static unsigned char FindDotKeyword (void)
545 /* Find the dot keyword in SVal. Return the corresponding token if found,
546 * return TOK_NONE if not found.
549 static const struct DotKeyword K = { SVal, 0 };
550 struct DotKeyword* R;
552 /* If we aren't in ignore case mode, we have to uppercase the keyword */
557 /* Search for the keyword */
558 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
559 sizeof (DotKeywords [0]), CmpDotKeyword);
569 static void ReadIdent (void)
570 /* Read an identifier from the current input position into Ident. It is
571 * assumed that the first character has already been checked.
574 /* Read the identifier */
577 if (I < MAX_STR_LEN) {
581 } while (IsIdChar (C));
584 /* If we should ignore case, convert the identifier to upper case */
592 static unsigned ReadStringConst (int StringTerm)
593 /* Read a string constant into SVal. Check for maximum string length and all
594 * other stuff. The length of the string is returned.
599 /* Skip the leading string terminator */
602 /* Read the string */
605 if (C == StringTerm) {
608 if (C == '\n' || C == EOF) {
609 Error (ERR_NEWLINE_IN_STRING);
613 /* Check for string length, print an error message once */
614 if (I == MAX_STR_LEN) {
615 Error (ERR_STRING_TOO_LONG);
616 } else if (I < MAX_STR_LEN) {
621 /* Skip the character */
625 /* Skip the trailing terminator */
628 /* Terminate the string */
629 if (I >= MAX_STR_LEN) {
634 /* Return the length of the string */
640 void NextRawTok (void)
641 /* Read the next raw token from the input stream */
643 /* If we've a forced end of assembly, don't read further */
650 /* Check if we have tokens from another input source */
651 if (InputFromStack ()) {
656 /* Skip whitespace, remember if we had some */
657 if ((WS = IsBlank (C)) != 0) {
660 } while (IsBlank (C));
663 /* If we're reading from the file, update the location from where the
664 * next token will be read. If we're reading from input data, keep the
671 /* Hex number or PC symbol? */
675 /* Hex digit must follow or DollarIsPC must be enabled */
681 Error (ERR_HEX_DIGIT_EXPECTED);
685 /* Read the number */
687 while (IsXDigit (C)) {
688 if (IVal & 0xF0000000) {
689 Error (ERR_NUM_OVERFLOW);
692 IVal = (IVal << 4) + DigitVal (C);
696 /* This is an integer constant */
705 /* 0 or 1 must follow */
707 Error (ERR_01_EXPECTED);
710 /* Read the number */
712 while (IsDDigit (C)) {
713 if (IVal & 0x80000000) {
714 Error (ERR_NUM_OVERFLOW);
717 IVal = (IVal << 1) + DigitVal (C);
721 /* This is an integer constant */
726 /* Decimal number? */
729 /* Read the number */
731 while (IsDigit (C)) {
732 if (IVal > (0xFFFFFFFF / 10)) {
733 Error (ERR_NUM_OVERFLOW);
736 IVal = (IVal * 10) + DigitVal (C);
740 /* This is an integer constant */
745 /* Control command? */
750 if (!IsIdStart (C)) {
751 Error (ERR_PSEUDO_EXPECTED);
752 /* Try to read an identifier */
756 /* Read the identifier */
759 /* Search the keyword */
760 Tok = FindDotKeyword ();
761 if (Tok == TOK_NONE) {
763 Error (ERR_PSEUDO_EXPECTED);
770 if (C == LocalStart) {
772 /* Read the identifier */
775 /* Start character alone is not enough */
776 if (SVal [1] == '\0') {
777 Error (ERR_IDENT_EXPECTED);
787 /* Identifier or keyword? */
790 /* Read the identifier */
793 /* Check for special names */
794 if (SVal [1] == '\0') {
795 switch (toupper (SVal [0])) {
819 /* Search for an opcode */
820 IVal = FindInstruction (SVal);
822 /* This is a mnemonic */
824 } else if (IsDefine (SVal)) {
825 /* This is a define style macro - expand it */
835 /* Ok, let's do the switch */
924 while (C != '\n' && C != EOF) {
959 } else if (C == '<') {
962 } else if (C == '>') {
985 } else if (C == '>') {
999 /* Hack: If we allow ' as terminating character for strings, read
1000 * the following stuff as a string, and check for a one character
1003 if (LooseStringTerm) {
1004 if (ReadStringConst ('\'') == 1) {
1011 /* Always a character constant */
1013 if (C == '\n' || C == EOF) {
1014 Error (ERR_ILLEGAL_CHARCON);
1021 Error (ERR_ILLEGAL_CHARCON);
1029 ReadStringConst ('\"');
1034 /* Line continuation? */
1038 /* Handle as white space */
1052 /* Check if we have any open .IFs in this file */
1054 /* Check if we have any open token lists in this file */
1057 /* If this was an include file, then close it and handle like a
1058 * separator. Do not close the main file, but return EOF.
1069 /* If we go here, we could not identify the current character. Skip it
1072 Error (ERR_INVALID_CHAR, C & 0xFF);
1079 int TokHasSVal (enum Token Tok)
1080 /* Return true if the given token has an attached SVal */
1082 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1087 int TokHasIVal (enum Token Tok)
1088 /* Return true if the given token has an attached IVal */
1090 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1095 int GetSubKey (const char** Keys, unsigned Count)
1096 /* Search for a subkey in a table of keywords. The current token must be an
1097 * identifier and all keys must be in upper case. The identifier will be
1098 * uppercased in the process. The function returns the index of the keyword,
1099 * or -1 if the keyword was not found.
1104 /* Must have an identifier */
1105 PRECONDITION (Tok == TOK_IDENT);
1107 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1112 /* Do a linear search (a binary search is not worth the effort) */
1113 for (I = 0; I < Count; ++I) {
1114 if (strcmp (SVal, Keys [I]) == 0) {
1126 void WriteFiles (void)
1127 /* Write the list of input files to the object file */
1131 /* Tell the obj file module that we're about to start the file list */
1134 /* Write the file count */
1135 ObjWrite8 (FileCount);
1137 /* Write the file data */
1138 for (I = 0; I < FileCount; ++I) {
1139 ObjWrite32 (Files [I].MTime);
1140 ObjWrite32 (Files [I].Size);
1141 ObjWriteStr (Files [I].Name);
1144 /* Done writing files */
1150 void InitScanner (const char* InFile)
1151 /* Initialize the scanner, open the given input file */
1153 /* Open the input file */
1154 NewInputFile (InFile);
1159 void DoneScanner (void)
1160 /* Release scanner resources */