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 { "STRING", TOK_STRING },
223 { "SUNPLUS", TOK_SUNPLUS },
224 { "WORD", TOK_WORD },
225 { "XMATCH", TOK_XMATCH },
227 { "ZEROPAGE", TOK_ZEROPAGE },
232 /*****************************************************************************/
234 /*****************************************************************************/
238 static void NextChar (void);
239 /* Read the next character from the input file */
243 /*****************************************************************************/
244 /* Character classification functions */
245 /*****************************************************************************/
249 static int IsBlank (int C)
250 /* Return true if the character is a blank or tab */
252 return (C == ' ' || C == '\t');
257 static int IsDigit (int C)
258 /* Return true if the character is a digit */
265 static int IsXDigit (int C)
266 /* Return true if the character is a hexadecimal digit */
273 static int IsDDigit (int C)
274 /* Return true if the character is a dual digit */
276 return (C == '0' || C == '1');
281 static int IsIdChar (int C)
282 /* Return true if the character is a valid character for an identifier */
284 return isalnum (C) ||
286 (C == '@' && AtInIdents) ||
287 (C == '$' && DollarInIdents);
292 static int IsIdStart (int C)
293 /* Return true if the character may start an identifier */
295 return isalpha (C) || C == '_';
300 /*****************************************************************************/
302 /*****************************************************************************/
306 const char* GetFileName (unsigned char Name)
307 /* Get the name of a file where the name index is known */
309 PRECONDITION (Name <= FileCount);
311 /* Name was defined outside any file scope, use the name of the first
312 * file instead. Errors are then reported with a file position of
313 * line zero in the first file.
315 if (FileCount == 0) {
316 /* No files defined until now */
317 return "(outside file scope)";
319 return Files [0].Name;
322 return Files [Name-1].Name;
328 void NewInputFile (const char* Name)
329 /* Open a new input file */
334 /* Check for nested include overflow */
335 if (FileCount >= MAX_INPUT_FILES) {
336 Fatal (FAT_MAX_INPUT_FILES);
339 /* First try to open the file */
340 F = fopen (Name, "r");
345 /* Error (fatal error if this is the main file) */
347 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
350 /* We are on include level. Search for the file in the include
353 PathName = FindInclude (Name);
354 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
355 /* Not found or cannot open, print an error and bail out */
356 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
359 /* Free the allocated memory */
364 /* check again if we do now have an open file */
367 /* Stat the file and remember the values */
369 if (fstat (fileno (F), &Buf) != 0) {
370 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
372 Files [FileCount].MTime = Buf.st_mtime;
373 Files [FileCount].Size = Buf.st_size;
374 Files [FileCount].Name = xstrdup (Name);
377 /* Create a new state variable and initialize it */
378 I = xmalloc (sizeof (*I));
382 I->Pos.Name = FileCount;
387 /* Use the new file */
399 void DoneInputFile (void)
400 /* Close the current input file */
404 /* Restore the old token */
408 /* Save a pointer to the current struct, then set it back */
412 /* Cleanup the current stuff */
420 void NewInputData (const char* Data, int Malloced)
421 /* Add a chunk of input data to the input stream */
425 /* Create a new state variable and initialize it */
426 I = xmalloc (sizeof (*I));
429 I->Malloced = Malloced;
433 /* Use the new data */
443 static void DoneInputData (void)
444 /* End the current input data stream */
448 /* Restore the old token */
452 /* Save a pointer to the current struct, then set it back */
456 /* Cleanup the current stuff */
465 static unsigned DigitVal (unsigned char C)
466 /* Convert a digit into it's numerical representation */
471 return toupper (C) - 'A' + 10;
477 static void NextChar (void)
478 /* Read the next character from the input file */
480 /* If we have an input data structure, read from there */
485 /* End of input data, will set to last file char */
491 /* Check for end of line, read the next line if needed */
492 while (IFile->Line [IFile->Pos.Col] == '\0') {
494 /* End of current line reached, read next line */
495 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
496 /* End of file. Add an empty line to the listing. This is a
497 * small hack needed to keep the PC output in sync.
499 NewListingLine ("", IFile->Pos.Name, ICount);
508 /* Remember the new line for the listing */
509 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
513 /* Return the next character from the file */
514 C = IFile->Line [IFile->Pos.Col++];
521 void UpcaseSVal (void)
522 /* Make SVal upper case */
526 SVal [I] = toupper (SVal [I]);
533 static int CmpDotKeyword (const void* K1, const void* K2)
534 /* Compare function for the dot keyword search */
536 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
541 static unsigned char FindDotKeyword (void)
542 /* Find the dot keyword in SVal. Return the corresponding token if found,
543 * return TOK_NONE if not found.
546 static const struct DotKeyword K = { SVal, 0 };
547 struct DotKeyword* R;
549 /* If we aren't in ignore case mode, we have to uppercase the keyword */
554 /* Search for the keyword */
555 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
556 sizeof (DotKeywords [0]), CmpDotKeyword);
566 static void ReadIdent (void)
567 /* Read an identifier from the current input position into Ident. It is
568 * assumed that the first character has already been checked.
571 /* Read the identifier */
574 if (I < MAX_STR_LEN) {
578 } while (IsIdChar (C));
581 /* If we should ignore case, convert the identifier to upper case */
589 static unsigned ReadStringConst (int StringTerm)
590 /* Read a string constant into SVal. Check for maximum string length and all
591 * other stuff. The length of the string is returned.
596 /* Skip the leading string terminator */
599 /* Read the string */
602 if (C == StringTerm) {
605 if (C == '\n' || C == EOF) {
606 Error (ERR_NEWLINE_IN_STRING);
610 /* Check for string length, print an error message once */
611 if (I == MAX_STR_LEN) {
612 Error (ERR_STRING_TOO_LONG);
613 } else if (I < MAX_STR_LEN) {
618 /* Skip the character */
622 /* Skip the trailing terminator */
625 /* Terminate the string */
626 if (I >= MAX_STR_LEN) {
631 /* Return the length of the string */
637 void NextRawTok (void)
638 /* Read the next raw token from the input stream */
640 /* If we've a forced end of assembly, don't read further */
647 /* Check if we have tokens from another input source */
648 if (InputFromStack ()) {
653 /* Skip whitespace, remember if we had some */
654 if ((WS = IsBlank (C)) != 0) {
657 } while (IsBlank (C));
660 /* If we're reading from the file, update the location from where the
661 * next token will be read. If we're reading from input data, keep the
668 /* Hex number or PC symbol? */
672 /* Hex digit must follow or DollarIsPC must be enabled */
678 Error (ERR_HEX_DIGIT_EXPECTED);
682 /* Read the number */
684 while (IsXDigit (C)) {
685 if (IVal & 0xF0000000) {
686 Error (ERR_NUM_OVERFLOW);
689 IVal = (IVal << 4) + DigitVal (C);
693 /* This is an integer constant */
702 /* 0 or 1 must follow */
704 Error (ERR_01_EXPECTED);
707 /* Read the number */
709 while (IsDDigit (C)) {
710 if (IVal & 0x80000000) {
711 Error (ERR_NUM_OVERFLOW);
714 IVal = (IVal << 1) + DigitVal (C);
718 /* This is an integer constant */
723 /* Decimal number? */
726 /* Read the number */
728 while (IsDigit (C)) {
729 if (IVal > (0xFFFFFFFF / 10)) {
730 Error (ERR_NUM_OVERFLOW);
733 IVal = (IVal * 10) + DigitVal (C);
737 /* This is an integer constant */
742 /* Control command? */
747 if (!IsIdStart (C)) {
748 Error (ERR_PSEUDO_EXPECTED);
749 /* Try to read an identifier */
753 /* Read the identifier */
756 /* Search the keyword */
757 Tok = FindDotKeyword ();
758 if (Tok == TOK_NONE) {
760 Error (ERR_PSEUDO_EXPECTED);
767 if (C == LocalStart) {
769 /* Read the identifier */
772 /* Start character alone is not enough */
773 if (SVal [1] == '\0') {
774 Error (ERR_IDENT_EXPECTED);
784 /* Identifier or keyword? */
787 /* Read the identifier */
790 /* Check for special names */
791 if (SVal [1] == '\0') {
792 switch (toupper (SVal [0])) {
816 /* Search for an opcode */
817 IVal = FindInstruction (SVal);
819 /* This is a mnemonic */
821 } else if (IsDefine (SVal)) {
822 /* This is a define style macro - expand it */
832 /* Ok, let's do the switch */
921 while (C != '\n' && C != EOF) {
956 } else if (C == '<') {
959 } else if (C == '>') {
982 } else if (C == '>') {
996 /* Hack: If we allow ' as terminating character for strings, read
997 * the following stuff as a string, and check for a one character
1000 if (LooseStringTerm) {
1001 if (ReadStringConst ('\'') == 1) {
1008 /* Always a character constant */
1010 if (C == '\n' || C == EOF) {
1011 Error (ERR_ILLEGAL_CHARCON);
1018 Error (ERR_ILLEGAL_CHARCON);
1026 ReadStringConst ('\"');
1031 /* Line continuation? */
1035 /* Handle as white space */
1049 /* Check if we have any open .IFs in this file */
1051 /* Check if we have any open token lists in this file */
1054 /* If this was an include file, then close it and handle like a
1055 * separator. Do not close the main file, but return EOF.
1066 /* If we go here, we could not identify the current character. Skip it
1069 Error (ERR_INVALID_CHAR, C & 0xFF);
1076 int TokHasSVal (enum Token Tok)
1077 /* Return true if the given token has an attached SVal */
1079 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1084 int TokHasIVal (enum Token Tok)
1085 /* Return true if the given token has an attached IVal */
1087 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1092 int GetSubKey (const char** Keys, unsigned Count)
1093 /* Search for a subkey in a table of keywords. The current token must be an
1094 * identifier and all keys must be in upper case. The identifier will be
1095 * uppercased in the process. The function returns the index of the keyword,
1096 * or -1 if the keyword was not found.
1101 /* Must have an identifier */
1102 PRECONDITION (Tok == TOK_IDENT);
1104 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1109 /* Do a linear search (a binary search is not worth the effort) */
1110 for (I = 0; I < Count; ++I) {
1111 if (strcmp (SVal, Keys [I]) == 0) {
1123 void WriteFiles (void)
1124 /* Write the list of input files to the object file */
1128 /* Tell the obj file module that we're about to start the file list */
1131 /* Write the file count */
1132 ObjWrite8 (FileCount);
1134 /* Write the file data */
1135 for (I = 0; I < FileCount; ++I) {
1136 ObjWrite32 (Files [I].MTime);
1137 ObjWrite32 (Files [I].Size);
1138 ObjWriteStr (Files [I].Name);
1141 /* Done writing files */
1147 void InitScanner (const char* InFile)
1148 /* Initialize the scanner, open the given input file */
1150 /* Open the input file */
1151 NewInputFile (InFile);
1156 void DoneScanner (void)
1157 /* Release scanner resources */