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 /*****************************************************************************/
62 /*****************************************************************************/
64 /*****************************************************************************/
68 enum Token Tok = TOK_NONE; /* Current token */
69 int WS; /* Flag: Whitespace before token */
70 long IVal; /* Integer token attribute */
71 char SVal [MAX_STR_LEN+1]; /* String token attribute */
73 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
77 /* Struct to handle include files. Note: The length of the input line may
78 * not exceed 255+1, since the column is stored in the file position struct
79 * as a character. Increasing this value means changing the FilePos struct,
80 * and the read and write routines in the assembler and linker.
82 typedef struct InputFile_ InputFile;
84 FILE* F; /* Input file descriptor */
85 FilePos Pos; /* Position in file */
86 enum Token Tok; /* Last token */
87 int C; /* Last character */
88 char Line[256]; /* The current input line */
89 InputFile* Next; /* Linked list of input files */
92 /* Struct to handle textual input data */
93 typedef struct InputData_ InputData;
95 const char* Data; /* Pointer to the data */
96 const char* Pos; /* Pointer to current position */
97 int Malloced; /* Memory was malloced */
98 enum Token Tok; /* Last token */
99 int C; /* Last character */
100 InputData* Next; /* Linked list of input data */
103 /* List of input files */
105 unsigned long MTime; /* Time of last modification */
106 unsigned long Size; /* Size of file */
107 const char* Name; /* Name of file */
108 } Files [MAX_INPUT_FILES];
109 static unsigned FileCount = 0;
111 /* Current input variables */
112 static InputFile* IFile = 0; /* Current input file */
113 static InputData* IData = 0; /* Current input memory data */
114 static unsigned ICount = 0; /* Count of input files */
115 static int C = 0; /* Current input character */
117 /* Force end of assembly */
120 /* List of dot keywords with the corresponding tokens */
122 const char* Key; /* MUST be first field */
127 { "ADDR", TOK_ADDR },
128 { "ALIGN", TOK_ALIGN },
130 { "ASCIIZ", TOK_ASCIIZ },
131 { "AUTOIMPORT", TOK_AUTOIMPORT },
132 { "BITAND", TOK_AND },
133 { "BITNOT", TOK_NOT },
135 { "BITXOR", TOK_XOR },
136 { "BLANK", TOK_BLANK },
138 { "BYTE", TOK_BYTE },
139 { "CASE", TOK_CASE },
140 { "CODE", TOK_CODE },
141 { "CONCAT", TOK_CONCAT },
142 { "CONST", TOK_CONST },
144 { "DATA", TOK_DATA },
145 { "DBYT", TOK_DBYT },
146 { "DEBUGINFO", TOK_DEBUGINFO },
147 { "DEF", TOK_DEFINED },
148 { "DEFINE", TOK_DEFINE },
149 { "DEFINED", TOK_DEFINED },
150 { "DWORD", TOK_DWORD },
151 { "ELSE", TOK_ELSE },
152 { "ELSEIF", TOK_ELSEIF },
154 { "ENDIF", TOK_ENDIF },
155 { "ENDMAC", TOK_ENDMACRO },
156 { "ENDMACRO", TOK_ENDMACRO },
157 { "ENDPROC", TOK_ENDPROC },
158 { "ENDREP", TOK_ENDREP },
159 { "ENDREPEAT", TOK_ENDREP },
160 { "ERROR", TOK_ERROR },
161 { "EXITMAC", TOK_EXITMACRO },
162 { "EXITMACRO", TOK_EXITMACRO },
163 { "EXPORT", TOK_EXPORT },
164 { "EXPORTZP", TOK_EXPORTZP },
165 { "FARADDR", TOK_FARADDR },
166 { "FEATURE", TOK_FEATURE },
167 { "FILEOPT", TOK_FILEOPT },
168 { "FOPT", TOK_FILEOPT },
169 { "FORCEWORD", TOK_FORCEWORD },
170 { "GLOBAL", TOK_GLOBAL },
171 { "GLOBALZP", TOK_GLOBALZP },
175 { "IFBLANK", TOK_IFBLANK },
176 { "IFCONST", TOK_IFCONST },
177 { "IFDEF", TOK_IFDEF },
178 { "IFNBLANK", TOK_IFNBLANK },
179 { "IFNCONST", TOK_IFNCONST },
180 { "IFNDEF", TOK_IFNDEF },
181 { "IFNREF", TOK_IFNREF },
182 { "IFP02", TOK_IFP02 },
183 { "IFP816", TOK_IFP816 },
184 { "IFPC02", TOK_IFPC02 },
185 { "IFREF", TOK_IFREF },
186 { "IMPORT", TOK_IMPORT },
187 { "IMPORTZP", TOK_IMPORTZP },
188 { "INCBIN", TOK_INCBIN },
189 { "INCLUDE", TOK_INCLUDE },
190 { "LEFT", TOK_LEFT },
191 { "LINECONT", TOK_LINECONT },
192 { "LIST", TOK_LIST },
193 { "LISTBYTES", TOK_LISTBYTES },
194 { "LOCAL", TOK_LOCAL },
195 { "LOCALCHAR", TOK_LOCALCHAR },
196 { "MAC", TOK_MACRO },
197 { "MACPACK", TOK_MACPACK },
198 { "MACRO", TOK_MACRO },
199 { "MATCH", TOK_MATCH },
203 { "NULL", TOK_NULL },
208 { "P816", TOK_P816 },
209 { "PAGELEN", TOK_PAGELENGTH },
210 { "PAGELENGTH", TOK_PAGELENGTH },
211 { "PARAMCOUNT", TOK_PARAMCOUNT },
212 { "PC02", TOK_PC02 },
213 { "PROC", TOK_PROC },
214 { "REF", TOK_REFERENCED },
215 { "REFERENCED", TOK_REFERENCED },
216 { "RELOC", TOK_RELOC },
217 { "REPEAT", TOK_REPEAT },
219 { "RIGHT", TOK_RIGHT },
220 { "RODATA", TOK_RODATA },
221 { "SEGMENT", TOK_SEGMENT },
224 { "SMART", TOK_SMART },
225 { "STRAT", TOK_STRAT },
226 { "STRING", TOK_STRING },
227 { "STRLEN", TOK_STRLEN },
228 { "SUNPLUS", TOK_SUNPLUS },
229 { "TCOUNT", TOK_TCOUNT },
230 { "WARNING", TOK_WARNING },
231 { "WORD", TOK_WORD },
232 { "XMATCH", TOK_XMATCH },
234 { "ZEROPAGE", TOK_ZEROPAGE },
239 /*****************************************************************************/
241 /*****************************************************************************/
245 static void NextChar (void);
246 /* Read the next character from the input file */
250 /*****************************************************************************/
251 /* Character classification functions */
252 /*****************************************************************************/
256 static int IsBlank (int C)
257 /* Return true if the character is a blank or tab */
259 return (C == ' ' || C == '\t');
264 static int IsDigit (int C)
265 /* Return true if the character is a digit */
272 static int IsXDigit (int C)
273 /* Return true if the character is a hexadecimal digit */
280 static int IsDDigit (int C)
281 /* Return true if the character is a dual digit */
283 return (C == '0' || C == '1');
288 static int IsIdChar (int C)
289 /* Return true if the character is a valid character for an identifier */
291 return isalnum (C) ||
293 (C == '@' && AtInIdents) ||
294 (C == '$' && DollarInIdents);
299 static int IsIdStart (int C)
300 /* Return true if the character may start an identifier */
302 return isalpha (C) || C == '_';
307 /*****************************************************************************/
309 /*****************************************************************************/
313 const char* GetFileName (unsigned char Name)
314 /* Get the name of a file where the name index is known */
316 PRECONDITION (Name <= FileCount);
318 /* Name was defined outside any file scope, use the name of the first
319 * file instead. Errors are then reported with a file position of
320 * line zero in the first file.
322 if (FileCount == 0) {
323 /* No files defined until now */
324 return "(outside file scope)";
326 return Files [0].Name;
329 return Files [Name-1].Name;
335 void NewInputFile (const char* Name)
336 /* Open a new input file */
341 /* Check for nested include overflow */
342 if (FileCount >= MAX_INPUT_FILES) {
343 Fatal (FAT_MAX_INPUT_FILES);
346 /* First try to open the file */
347 F = fopen (Name, "r");
352 /* Error (fatal error if this is the main file) */
354 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
357 /* We are on include level. Search for the file in the include
360 PathName = FindInclude (Name);
361 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
362 /* Not found or cannot open, print an error and bail out */
363 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
366 /* Free the allocated memory */
371 /* check again if we do now have an open file */
374 /* Stat the file and remember the values */
376 if (fstat (fileno (F), &Buf) != 0) {
377 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
379 Files [FileCount].MTime = Buf.st_mtime;
380 Files [FileCount].Size = Buf.st_size;
381 Files [FileCount].Name = xstrdup (Name);
384 /* Create a new state variable and initialize it */
385 I = xmalloc (sizeof (*I));
389 I->Pos.Name = FileCount;
394 /* Use the new file */
406 void DoneInputFile (void)
407 /* Close the current input file */
411 /* Restore the old token */
415 /* Save a pointer to the current struct, then set it back */
419 /* Cleanup the current stuff */
427 void NewInputData (const char* Data, int Malloced)
428 /* Add a chunk of input data to the input stream */
432 /* Create a new state variable and initialize it */
433 I = xmalloc (sizeof (*I));
436 I->Malloced = Malloced;
440 /* Use the new data */
450 static void DoneInputData (void)
451 /* End the current input data stream */
455 /* Restore the old token */
459 /* Save a pointer to the current struct, then set it back */
463 /* Cleanup the current stuff */
472 static unsigned DigitVal (unsigned char C)
473 /* Convert a digit into it's numerical representation */
478 return toupper (C) - 'A' + 10;
484 static void NextChar (void)
485 /* Read the next character from the input file */
487 /* If we have an input data structure, read from there */
492 /* End of input data, will set to last file char */
498 /* Check for end of line, read the next line if needed */
499 while (IFile->Line [IFile->Pos.Col] == '\0') {
501 /* End of current line reached, read next line */
502 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
503 /* End of file. Add an empty line to the listing. This is a
504 * small hack needed to keep the PC output in sync.
506 NewListingLine ("", IFile->Pos.Name, ICount);
515 /* Remember the new line for the listing */
516 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
520 /* Return the next character from the file */
521 C = IFile->Line [IFile->Pos.Col++];
528 void UpcaseSVal (void)
529 /* Make SVal upper case */
533 SVal [I] = toupper (SVal [I]);
540 static int CmpDotKeyword (const void* K1, const void* K2)
541 /* Compare function for the dot keyword search */
543 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
548 static unsigned char FindDotKeyword (void)
549 /* Find the dot keyword in SVal. Return the corresponding token if found,
550 * return TOK_NONE if not found.
553 static const struct DotKeyword K = { SVal, 0 };
554 struct DotKeyword* R;
556 /* If we aren't in ignore case mode, we have to uppercase the keyword */
561 /* Search for the keyword */
562 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
563 sizeof (DotKeywords [0]), CmpDotKeyword);
573 static void ReadIdent (void)
574 /* Read an identifier from the current input position into Ident. It is
575 * assumed that the first character has already been checked.
578 /* Read the identifier */
581 if (I < MAX_STR_LEN) {
585 } while (IsIdChar (C));
588 /* If we should ignore case, convert the identifier to upper case */
596 static unsigned ReadStringConst (int StringTerm)
597 /* Read a string constant into SVal. Check for maximum string length and all
598 * other stuff. The length of the string is returned.
603 /* Skip the leading string terminator */
606 /* Read the string */
609 if (C == StringTerm) {
612 if (C == '\n' || C == EOF) {
613 Error (ERR_NEWLINE_IN_STRING);
617 /* Check for string length, print an error message once */
618 if (I == MAX_STR_LEN) {
619 Error (ERR_STRING_TOO_LONG);
620 } else if (I < MAX_STR_LEN) {
625 /* Skip the character */
629 /* Skip the trailing terminator */
632 /* Terminate the string */
633 if (I >= MAX_STR_LEN) {
638 /* Return the length of the string */
644 void NextRawTok (void)
645 /* Read the next raw token from the input stream */
647 /* If we've a forced end of assembly, don't read further */
654 /* Check if we have tokens from another input source */
655 if (InputFromStack ()) {
660 /* Skip whitespace, remember if we had some */
661 if ((WS = IsBlank (C)) != 0) {
664 } while (IsBlank (C));
667 /* If we're reading from the file, update the location from where the
668 * next token will be read. If we're reading from input data, keep the
675 /* Hex number or PC symbol? */
679 /* Hex digit must follow or DollarIsPC must be enabled */
685 Error (ERR_HEX_DIGIT_EXPECTED);
689 /* Read the number */
691 while (IsXDigit (C)) {
692 if (IVal & 0xF0000000) {
693 Error (ERR_NUM_OVERFLOW);
696 IVal = (IVal << 4) + DigitVal (C);
700 /* This is an integer constant */
709 /* 0 or 1 must follow */
711 Error (ERR_01_EXPECTED);
714 /* Read the number */
716 while (IsDDigit (C)) {
717 if (IVal & 0x80000000) {
718 Error (ERR_NUM_OVERFLOW);
721 IVal = (IVal << 1) + DigitVal (C);
725 /* This is an integer constant */
730 /* Decimal number? */
733 /* Read the number */
735 while (IsDigit (C)) {
736 if (IVal > (0xFFFFFFFF / 10)) {
737 Error (ERR_NUM_OVERFLOW);
740 IVal = (IVal * 10) + DigitVal (C);
744 /* This is an integer constant */
749 /* Control command? */
754 if (!IsIdStart (C)) {
755 Error (ERR_PSEUDO_EXPECTED);
756 /* Try to read an identifier */
760 /* Read the identifier */
763 /* Search the keyword */
764 Tok = FindDotKeyword ();
765 if (Tok == TOK_NONE) {
767 Error (ERR_PSEUDO_EXPECTED);
774 if (C == LocalStart) {
776 /* Read the identifier */
779 /* Start character alone is not enough */
780 if (SVal [1] == '\0') {
781 Error (ERR_IDENT_EXPECTED);
791 /* Identifier or keyword? */
794 /* Read the identifier */
797 /* Check for special names */
798 if (SVal [1] == '\0') {
799 switch (toupper (SVal [0])) {
823 /* Search for an opcode */
824 IVal = FindInstruction (SVal);
826 /* This is a mnemonic */
828 } else if (IsDefine (SVal)) {
829 /* This is a define style macro - expand it */
839 /* Ok, let's do the switch */
928 while (C != '\n' && C != EOF) {
963 } else if (C == '<') {
966 } else if (C == '>') {
989 } else if (C == '>') {
1003 /* Hack: If we allow ' as terminating character for strings, read
1004 * the following stuff as a string, and check for a one character
1007 if (LooseStringTerm) {
1008 if (ReadStringConst ('\'') == 1) {
1015 /* Always a character constant */
1017 if (C == '\n' || C == EOF) {
1018 Error (ERR_ILLEGAL_CHARCON);
1025 Error (ERR_ILLEGAL_CHARCON);
1033 ReadStringConst ('\"');
1038 /* Line continuation? */
1042 /* Handle as white space */
1056 /* Check if we have any open .IFs in this file */
1058 /* Check if we have any open token lists in this file */
1061 /* If this was an include file, then close it and handle like a
1062 * separator. Do not close the main file, but return EOF.
1073 /* If we go here, we could not identify the current character. Skip it
1076 Error (ERR_INVALID_CHAR, C & 0xFF);
1083 int TokHasSVal (enum Token Tok)
1084 /* Return true if the given token has an attached SVal */
1086 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1091 int TokHasIVal (enum Token Tok)
1092 /* Return true if the given token has an attached IVal */
1094 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1099 int GetSubKey (const char** Keys, unsigned Count)
1100 /* Search for a subkey in a table of keywords. The current token must be an
1101 * identifier and all keys must be in upper case. The identifier will be
1102 * uppercased in the process. The function returns the index of the keyword,
1103 * or -1 if the keyword was not found.
1108 /* Must have an identifier */
1109 PRECONDITION (Tok == TOK_IDENT);
1111 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1116 /* Do a linear search (a binary search is not worth the effort) */
1117 for (I = 0; I < Count; ++I) {
1118 if (strcmp (SVal, Keys [I]) == 0) {
1130 void WriteFiles (void)
1131 /* Write the list of input files to the object file */
1135 /* Tell the obj file module that we're about to start the file list */
1138 /* Write the file count */
1139 ObjWrite8 (FileCount);
1141 /* Write the file data */
1142 for (I = 0; I < FileCount; ++I) {
1143 ObjWrite32 (Files [I].MTime);
1144 ObjWrite32 (Files [I].Size);
1145 ObjWriteStr (Files [I].Name);
1148 /* Done writing files */
1154 void InitScanner (const char* InFile)
1155 /* Initialize the scanner, open the given input file */
1157 /* Open the input file */
1158 NewInputFile (InFile);
1163 void DoneScanner (void)
1164 /* Release scanner resources */