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 { "FORCEWORD", TOK_FORCEWORD },
168 { "GLOBAL", TOK_GLOBAL },
169 { "GLOBALZP", TOK_GLOBALZP },
173 { "IFBLANK", TOK_IFBLANK },
174 { "IFCONST", TOK_IFCONST },
175 { "IFDEF", TOK_IFDEF },
176 { "IFNBLANK", TOK_IFNBLANK },
177 { "IFNCONST", TOK_IFNCONST },
178 { "IFNDEF", TOK_IFNDEF },
179 { "IFNREF", TOK_IFNREF },
180 { "IFP02", TOK_IFP02 },
181 { "IFP816", TOK_IFP816 },
182 { "IFPC02", TOK_IFPC02 },
183 { "IFREF", TOK_IFREF },
184 { "IMPORT", TOK_IMPORT },
185 { "IMPORTZP", TOK_IMPORTZP },
186 { "INCBIN", TOK_INCBIN },
187 { "INCLUDE", TOK_INCLUDE },
188 { "LEFT", TOK_LEFT },
189 { "LINECONT", TOK_LINECONT },
190 { "LIST", TOK_LIST },
191 { "LISTBYTES", TOK_LISTBYTES },
192 { "LOCAL", TOK_LOCAL },
193 { "LOCALCHAR", TOK_LOCALCHAR },
194 { "MAC", TOK_MACRO },
195 { "MACPACK", TOK_MACPACK },
196 { "MACRO", TOK_MACRO },
197 { "MATCH", TOK_MATCH },
201 { "NULL", TOK_NULL },
206 { "P816", TOK_P816 },
207 { "PAGELEN", TOK_PAGELENGTH },
208 { "PAGELENGTH", TOK_PAGELENGTH },
209 { "PARAMCOUNT", TOK_PARAMCOUNT },
210 { "PC02", TOK_PC02 },
211 { "PROC", TOK_PROC },
212 { "REF", TOK_REFERENCED },
213 { "REFERENCED", TOK_REFERENCED },
214 { "RELOC", TOK_RELOC },
215 { "REPEAT", TOK_REPEAT },
217 { "RIGHT", TOK_RIGHT },
218 { "RODATA", TOK_RODATA },
219 { "SEGMENT", TOK_SEGMENT },
222 { "SMART", TOK_SMART },
223 { "STRAT", TOK_STRAT },
224 { "STRING", TOK_STRING },
225 { "STRLEN", TOK_STRLEN },
226 { "SUNPLUS", TOK_SUNPLUS },
227 { "TCOUNT", TOK_TCOUNT },
228 { "WARNING", TOK_WARNING },
229 { "WORD", TOK_WORD },
230 { "XMATCH", TOK_XMATCH },
232 { "ZEROPAGE", TOK_ZEROPAGE },
237 /*****************************************************************************/
239 /*****************************************************************************/
243 static void NextChar (void);
244 /* Read the next character from the input file */
248 /*****************************************************************************/
249 /* Character classification functions */
250 /*****************************************************************************/
254 static int IsBlank (int C)
255 /* Return true if the character is a blank or tab */
257 return (C == ' ' || C == '\t');
262 static int IsDigit (int C)
263 /* Return true if the character is a digit */
270 static int IsXDigit (int C)
271 /* Return true if the character is a hexadecimal digit */
278 static int IsDDigit (int C)
279 /* Return true if the character is a dual digit */
281 return (C == '0' || C == '1');
286 static int IsIdChar (int C)
287 /* Return true if the character is a valid character for an identifier */
289 return isalnum (C) ||
291 (C == '@' && AtInIdents) ||
292 (C == '$' && DollarInIdents);
297 static int IsIdStart (int C)
298 /* Return true if the character may start an identifier */
300 return isalpha (C) || C == '_';
305 /*****************************************************************************/
307 /*****************************************************************************/
311 const char* GetFileName (unsigned char Name)
312 /* Get the name of a file where the name index is known */
314 PRECONDITION (Name <= FileCount);
316 /* Name was defined outside any file scope, use the name of the first
317 * file instead. Errors are then reported with a file position of
318 * line zero in the first file.
320 if (FileCount == 0) {
321 /* No files defined until now */
322 return "(outside file scope)";
324 return Files [0].Name;
327 return Files [Name-1].Name;
333 void NewInputFile (const char* Name)
334 /* Open a new input file */
339 /* Check for nested include overflow */
340 if (FileCount >= MAX_INPUT_FILES) {
341 Fatal (FAT_MAX_INPUT_FILES);
344 /* First try to open the file */
345 F = fopen (Name, "r");
350 /* Error (fatal error if this is the main file) */
352 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
355 /* We are on include level. Search for the file in the include
358 PathName = FindInclude (Name);
359 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
360 /* Not found or cannot open, print an error and bail out */
361 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
364 /* Free the allocated memory */
369 /* check again if we do now have an open file */
372 /* Stat the file and remember the values */
374 if (fstat (fileno (F), &Buf) != 0) {
375 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
377 Files [FileCount].MTime = Buf.st_mtime;
378 Files [FileCount].Size = Buf.st_size;
379 Files [FileCount].Name = xstrdup (Name);
382 /* Create a new state variable and initialize it */
383 I = xmalloc (sizeof (*I));
387 I->Pos.Name = FileCount;
392 /* Use the new file */
404 void DoneInputFile (void)
405 /* Close the current input file */
409 /* Restore the old token */
413 /* Save a pointer to the current struct, then set it back */
417 /* Cleanup the current stuff */
425 void NewInputData (const char* Data, int Malloced)
426 /* Add a chunk of input data to the input stream */
430 /* Create a new state variable and initialize it */
431 I = xmalloc (sizeof (*I));
434 I->Malloced = Malloced;
438 /* Use the new data */
448 static void DoneInputData (void)
449 /* End the current input data stream */
453 /* Restore the old token */
457 /* Save a pointer to the current struct, then set it back */
461 /* Cleanup the current stuff */
470 static unsigned DigitVal (unsigned char C)
471 /* Convert a digit into it's numerical representation */
476 return toupper (C) - 'A' + 10;
482 static void NextChar (void)
483 /* Read the next character from the input file */
485 /* If we have an input data structure, read from there */
490 /* End of input data, will set to last file char */
496 /* Check for end of line, read the next line if needed */
497 while (IFile->Line [IFile->Pos.Col] == '\0') {
499 /* End of current line reached, read next line */
500 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
501 /* End of file. Add an empty line to the listing. This is a
502 * small hack needed to keep the PC output in sync.
504 NewListingLine ("", IFile->Pos.Name, ICount);
513 /* Remember the new line for the listing */
514 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
518 /* Return the next character from the file */
519 C = IFile->Line [IFile->Pos.Col++];
526 void UpcaseSVal (void)
527 /* Make SVal upper case */
531 SVal [I] = toupper (SVal [I]);
538 static int CmpDotKeyword (const void* K1, const void* K2)
539 /* Compare function for the dot keyword search */
541 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
546 static unsigned char FindDotKeyword (void)
547 /* Find the dot keyword in SVal. Return the corresponding token if found,
548 * return TOK_NONE if not found.
551 static const struct DotKeyword K = { SVal, 0 };
552 struct DotKeyword* R;
554 /* If we aren't in ignore case mode, we have to uppercase the keyword */
559 /* Search for the keyword */
560 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
561 sizeof (DotKeywords [0]), CmpDotKeyword);
571 static void ReadIdent (void)
572 /* Read an identifier from the current input position into Ident. It is
573 * assumed that the first character has already been checked.
576 /* Read the identifier */
579 if (I < MAX_STR_LEN) {
583 } while (IsIdChar (C));
586 /* If we should ignore case, convert the identifier to upper case */
594 static unsigned ReadStringConst (int StringTerm)
595 /* Read a string constant into SVal. Check for maximum string length and all
596 * other stuff. The length of the string is returned.
601 /* Skip the leading string terminator */
604 /* Read the string */
607 if (C == StringTerm) {
610 if (C == '\n' || C == EOF) {
611 Error (ERR_NEWLINE_IN_STRING);
615 /* Check for string length, print an error message once */
616 if (I == MAX_STR_LEN) {
617 Error (ERR_STRING_TOO_LONG);
618 } else if (I < MAX_STR_LEN) {
623 /* Skip the character */
627 /* Skip the trailing terminator */
630 /* Terminate the string */
631 if (I >= MAX_STR_LEN) {
636 /* Return the length of the string */
642 void NextRawTok (void)
643 /* Read the next raw token from the input stream */
645 /* If we've a forced end of assembly, don't read further */
652 /* Check if we have tokens from another input source */
653 if (InputFromStack ()) {
658 /* Skip whitespace, remember if we had some */
659 if ((WS = IsBlank (C)) != 0) {
662 } while (IsBlank (C));
665 /* If we're reading from the file, update the location from where the
666 * next token will be read. If we're reading from input data, keep the
673 /* Hex number or PC symbol? */
677 /* Hex digit must follow or DollarIsPC must be enabled */
683 Error (ERR_HEX_DIGIT_EXPECTED);
687 /* Read the number */
689 while (IsXDigit (C)) {
690 if (IVal & 0xF0000000) {
691 Error (ERR_NUM_OVERFLOW);
694 IVal = (IVal << 4) + DigitVal (C);
698 /* This is an integer constant */
707 /* 0 or 1 must follow */
709 Error (ERR_01_EXPECTED);
712 /* Read the number */
714 while (IsDDigit (C)) {
715 if (IVal & 0x80000000) {
716 Error (ERR_NUM_OVERFLOW);
719 IVal = (IVal << 1) + DigitVal (C);
723 /* This is an integer constant */
728 /* Decimal number? */
731 /* Read the number */
733 while (IsDigit (C)) {
734 if (IVal > (0xFFFFFFFF / 10)) {
735 Error (ERR_NUM_OVERFLOW);
738 IVal = (IVal * 10) + DigitVal (C);
742 /* This is an integer constant */
747 /* Control command? */
752 if (!IsIdStart (C)) {
753 Error (ERR_PSEUDO_EXPECTED);
754 /* Try to read an identifier */
758 /* Read the identifier */
761 /* Search the keyword */
762 Tok = FindDotKeyword ();
763 if (Tok == TOK_NONE) {
765 Error (ERR_PSEUDO_EXPECTED);
772 if (C == LocalStart) {
774 /* Read the identifier */
777 /* Start character alone is not enough */
778 if (SVal [1] == '\0') {
779 Error (ERR_IDENT_EXPECTED);
789 /* Identifier or keyword? */
792 /* Read the identifier */
795 /* Check for special names */
796 if (SVal [1] == '\0') {
797 switch (toupper (SVal [0])) {
821 /* Search for an opcode */
822 IVal = FindInstruction (SVal);
824 /* This is a mnemonic */
826 } else if (IsDefine (SVal)) {
827 /* This is a define style macro - expand it */
837 /* Ok, let's do the switch */
926 while (C != '\n' && C != EOF) {
961 } else if (C == '<') {
964 } else if (C == '>') {
987 } else if (C == '>') {
1001 /* Hack: If we allow ' as terminating character for strings, read
1002 * the following stuff as a string, and check for a one character
1005 if (LooseStringTerm) {
1006 if (ReadStringConst ('\'') == 1) {
1013 /* Always a character constant */
1015 if (C == '\n' || C == EOF) {
1016 Error (ERR_ILLEGAL_CHARCON);
1023 Error (ERR_ILLEGAL_CHARCON);
1031 ReadStringConst ('\"');
1036 /* Line continuation? */
1040 /* Handle as white space */
1054 /* Check if we have any open .IFs in this file */
1056 /* Check if we have any open token lists in this file */
1059 /* If this was an include file, then close it and handle like a
1060 * separator. Do not close the main file, but return EOF.
1071 /* If we go here, we could not identify the current character. Skip it
1074 Error (ERR_INVALID_CHAR, C & 0xFF);
1081 int TokHasSVal (enum Token Tok)
1082 /* Return true if the given token has an attached SVal */
1084 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1089 int TokHasIVal (enum Token Tok)
1090 /* Return true if the given token has an attached IVal */
1092 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1097 int GetSubKey (const char** Keys, unsigned Count)
1098 /* Search for a subkey in a table of keywords. The current token must be an
1099 * identifier and all keys must be in upper case. The identifier will be
1100 * uppercased in the process. The function returns the index of the keyword,
1101 * or -1 if the keyword was not found.
1106 /* Must have an identifier */
1107 PRECONDITION (Tok == TOK_IDENT);
1109 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1114 /* Do a linear search (a binary search is not worth the effort) */
1115 for (I = 0; I < Count; ++I) {
1116 if (strcmp (SVal, Keys [I]) == 0) {
1128 void WriteFiles (void)
1129 /* Write the list of input files to the object file */
1133 /* Tell the obj file module that we're about to start the file list */
1136 /* Write the file count */
1137 ObjWrite8 (FileCount);
1139 /* Write the file data */
1140 for (I = 0; I < FileCount; ++I) {
1141 ObjWrite32 (Files [I].MTime);
1142 ObjWrite32 (Files [I].Size);
1143 ObjWriteStr (Files [I].Name);
1146 /* Done writing files */
1152 void InitScanner (const char* InFile)
1153 /* Initialize the scanner, open the given input file */
1155 /* Open the input file */
1156 NewInputFile (InFile);
1161 void DoneScanner (void)
1162 /* Release scanner resources */