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 /*****************************************************************************/
63 /*****************************************************************************/
65 /*****************************************************************************/
69 enum Token Tok = TOK_NONE; /* Current token */
70 int WS; /* Flag: Whitespace before token */
71 long IVal; /* Integer token attribute */
72 char SVal [MAX_STR_LEN+1]; /* String token attribute */
74 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
78 /* Struct to handle include files. Note: The length of the input line may
79 * not exceed 255+1, since the column is stored in the file position struct
80 * as a character. Increasing this value means changing the FilePos struct,
81 * and the read and write routines in the assembler and linker.
83 typedef struct InputFile_ InputFile;
85 FILE* F; /* Input file descriptor */
86 FilePos Pos; /* Position in file */
87 enum Token Tok; /* Last token */
88 int C; /* Last character */
89 char Line[256]; /* The current input line */
90 InputFile* Next; /* Linked list of input files */
93 /* Struct to handle textual input data */
94 typedef struct InputData_ InputData;
96 const char* Data; /* Pointer to the data */
97 const char* Pos; /* Pointer to current position */
98 int Malloced; /* Memory was malloced */
99 enum Token Tok; /* Last token */
100 int C; /* Last character */
101 InputData* Next; /* Linked list of input data */
104 /* List of input files */
106 unsigned long MTime; /* Time of last modification */
107 unsigned long Size; /* Size of file */
108 const char* Name; /* Name of file */
109 } Files [MAX_INPUT_FILES];
110 static unsigned FileCount = 0;
112 /* Current input variables */
113 static InputFile* IFile = 0; /* Current input file */
114 static InputData* IData = 0; /* Current input memory data */
115 static unsigned ICount = 0; /* Count of input files */
116 static int C = 0; /* Current input character */
118 /* Force end of assembly */
121 /* List of dot keywords with the corresponding tokens */
123 const char* Key; /* MUST be first field */
128 { "ADDR", TOK_ADDR },
129 { "ALIGN", TOK_ALIGN },
131 { "ASCIIZ", TOK_ASCIIZ },
132 { "AUTOIMPORT", TOK_AUTOIMPORT },
133 { "BITAND", TOK_AND },
134 { "BITNOT", TOK_NOT },
136 { "BITXOR", TOK_XOR },
137 { "BLANK", TOK_BLANK },
139 { "BYTE", TOK_BYTE },
140 { "CASE", TOK_CASE },
141 { "CODE", TOK_CODE },
142 { "CONCAT", TOK_CONCAT },
143 { "CONST", TOK_CONST },
145 { "DATA", TOK_DATA },
146 { "DBYT", TOK_DBYT },
147 { "DEBUGINFO", TOK_DEBUGINFO },
148 { "DEF", TOK_DEFINED },
149 { "DEFINE", TOK_DEFINE },
150 { "DEFINED", TOK_DEFINED },
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 },
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 { "WARNING", TOK_WARNING },
232 { "WORD", TOK_WORD },
233 { "XMATCH", TOK_XMATCH },
235 { "ZEROPAGE", TOK_ZEROPAGE },
240 /*****************************************************************************/
242 /*****************************************************************************/
246 static void NextChar (void);
247 /* Read the next character from the input file */
251 /*****************************************************************************/
252 /* Character classification functions */
253 /*****************************************************************************/
257 static int IsBlank (int C)
258 /* Return true if the character is a blank or tab */
260 return (C == ' ' || C == '\t');
265 static int IsDigit (int C)
266 /* Return true if the character is a digit */
273 static int IsXDigit (int C)
274 /* Return true if the character is a hexadecimal digit */
281 static int IsDDigit (int C)
282 /* Return true if the character is a dual digit */
284 return (C == '0' || C == '1');
289 static int IsIdChar (int C)
290 /* Return true if the character is a valid character for an identifier */
292 return isalnum (C) ||
294 (C == '@' && AtInIdents) ||
295 (C == '$' && DollarInIdents);
300 static int IsIdStart (int C)
301 /* Return true if the character may start an identifier */
303 return isalpha (C) || C == '_';
308 /*****************************************************************************/
310 /*****************************************************************************/
314 const char* GetFileName (unsigned char Name)
315 /* Get the name of a file where the name index is known */
317 PRECONDITION (Name <= FileCount);
319 /* Name was defined outside any file scope, use the name of the first
320 * file instead. Errors are then reported with a file position of
321 * line zero in the first file.
323 if (FileCount == 0) {
324 /* No files defined until now */
325 return "(outside file scope)";
327 return Files [0].Name;
330 return Files [Name-1].Name;
336 void NewInputFile (const char* Name)
337 /* Open a new input file */
342 /* Check for nested include overflow */
343 if (FileCount >= MAX_INPUT_FILES) {
344 Fatal (FAT_MAX_INPUT_FILES);
347 /* First try to open the file */
348 F = fopen (Name, "r");
353 /* Error (fatal error if this is the main file) */
355 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
358 /* We are on include level. Search for the file in the include
361 PathName = FindInclude (Name);
362 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
363 /* Not found or cannot open, print an error and bail out */
364 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
367 /* Free the allocated memory */
372 /* check again if we do now have an open file */
375 /* Stat the file and remember the values */
377 if (fstat (fileno (F), &Buf) != 0) {
378 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
380 Files [FileCount].MTime = Buf.st_mtime;
381 Files [FileCount].Size = Buf.st_size;
382 Files [FileCount].Name = xstrdup (Name);
385 /* Create a new state variable and initialize it */
386 I = xmalloc (sizeof (*I));
390 I->Pos.Name = FileCount;
395 /* Use the new file */
407 void DoneInputFile (void)
408 /* Close the current input file */
412 /* Restore the old token */
416 /* Save a pointer to the current struct, then set it back */
420 /* Cleanup the current stuff */
428 void NewInputData (const char* Data, int Malloced)
429 /* Add a chunk of input data to the input stream */
433 /* Create a new state variable and initialize it */
434 I = xmalloc (sizeof (*I));
437 I->Malloced = Malloced;
441 /* Use the new data */
451 static void DoneInputData (void)
452 /* End the current input data stream */
456 /* Restore the old token */
460 /* Save a pointer to the current struct, then set it back */
464 /* Cleanup the current stuff */
473 static unsigned DigitVal (unsigned char C)
474 /* Convert a digit into it's numerical representation */
479 return toupper (C) - 'A' + 10;
485 static void NextChar (void)
486 /* Read the next character from the input file */
488 /* If we have an input data structure, read from there */
493 /* End of input data, will set to last file char */
499 /* Check for end of line, read the next line if needed */
500 while (IFile->Line [IFile->Pos.Col] == '\0') {
502 /* End of current line reached, read next line */
503 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
504 /* End of file. Add an empty line to the listing. This is a
505 * small hack needed to keep the PC output in sync.
507 NewListingLine ("", IFile->Pos.Name, ICount);
516 /* Remember the new line for the listing */
517 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
521 /* Return the next character from the file */
522 C = IFile->Line [IFile->Pos.Col++];
529 void UpcaseSVal (void)
530 /* Make SVal upper case */
534 SVal [I] = toupper (SVal [I]);
541 static int CmpDotKeyword (const void* K1, const void* K2)
542 /* Compare function for the dot keyword search */
544 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
549 static unsigned char FindDotKeyword (void)
550 /* Find the dot keyword in SVal. Return the corresponding token if found,
551 * return TOK_NONE if not found.
554 static const struct DotKeyword K = { SVal, 0 };
555 struct DotKeyword* R;
557 /* If we aren't in ignore case mode, we have to uppercase the keyword */
562 /* Search for the keyword */
563 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
564 sizeof (DotKeywords [0]), CmpDotKeyword);
574 static void ReadIdent (void)
575 /* Read an identifier from the current input position into Ident. It is
576 * assumed that the first character has already been checked.
579 /* Read the identifier */
582 if (I < MAX_STR_LEN) {
586 } while (IsIdChar (C));
589 /* If we should ignore case, convert the identifier to upper case */
597 static unsigned ReadStringConst (int StringTerm)
598 /* Read a string constant into SVal. Check for maximum string length and all
599 * other stuff. The length of the string is returned.
604 /* Skip the leading string terminator */
607 /* Read the string */
610 if (C == StringTerm) {
613 if (C == '\n' || C == EOF) {
614 Error (ERR_NEWLINE_IN_STRING);
618 /* Check for string length, print an error message once */
619 if (I == MAX_STR_LEN) {
620 Error (ERR_STRING_TOO_LONG);
621 } else if (I < MAX_STR_LEN) {
626 /* Skip the character */
630 /* Skip the trailing terminator */
633 /* Terminate the string */
634 if (I >= MAX_STR_LEN) {
639 /* Return the length of the string */
645 void NextRawTok (void)
646 /* Read the next raw token from the input stream */
648 /* If we've a forced end of assembly, don't read further */
655 /* Check if we have tokens from another input source */
656 if (InputFromStack ()) {
661 /* Skip whitespace, remember if we had some */
662 if ((WS = IsBlank (C)) != 0) {
665 } while (IsBlank (C));
668 /* If we're reading from the file, update the location from where the
669 * next token will be read. If we're reading from input data, keep the
676 /* Hex number or PC symbol? */
680 /* Hex digit must follow or DollarIsPC must be enabled */
686 Error (ERR_HEX_DIGIT_EXPECTED);
690 /* Read the number */
692 while (IsXDigit (C)) {
693 if (IVal & 0xF0000000) {
694 Error (ERR_NUM_OVERFLOW);
697 IVal = (IVal << 4) + DigitVal (C);
701 /* This is an integer constant */
710 /* 0 or 1 must follow */
712 Error (ERR_01_EXPECTED);
715 /* Read the number */
717 while (IsDDigit (C)) {
718 if (IVal & 0x80000000) {
719 Error (ERR_NUM_OVERFLOW);
722 IVal = (IVal << 1) + DigitVal (C);
726 /* This is an integer constant */
731 /* Decimal number? */
734 /* Read the number */
736 while (IsDigit (C)) {
737 if (IVal > (0xFFFFFFFF / 10)) {
738 Error (ERR_NUM_OVERFLOW);
741 IVal = (IVal * 10) + DigitVal (C);
745 /* This is an integer constant */
750 /* Control command? */
755 if (!IsIdStart (C)) {
756 Error (ERR_PSEUDO_EXPECTED);
757 /* Try to read an identifier */
761 /* Read the identifier */
764 /* Search the keyword */
765 Tok = FindDotKeyword ();
766 if (Tok == TOK_NONE) {
768 Error (ERR_PSEUDO_EXPECTED);
775 if (C == LocalStart) {
777 /* Read the identifier */
780 /* Start character alone is not enough */
781 if (SVal [1] == '\0') {
782 Error (ERR_IDENT_EXPECTED);
792 /* Identifier or keyword? */
795 /* Read the identifier */
798 /* Check for special names */
799 if (SVal [1] == '\0') {
800 switch (toupper (SVal [0])) {
824 /* Search for an opcode */
825 IVal = FindInstruction (SVal);
827 /* This is a mnemonic */
829 } else if (IsDefine (SVal)) {
830 /* This is a define style macro - expand it */
840 /* Ok, let's do the switch */
929 while (C != '\n' && C != EOF) {
964 } else if (C == '<') {
967 } else if (C == '>') {
990 } else if (C == '>') {
1004 /* Hack: If we allow ' as terminating character for strings, read
1005 * the following stuff as a string, and check for a one character
1008 if (LooseStringTerm) {
1009 if (ReadStringConst ('\'') == 1) {
1016 /* Always a character constant */
1018 if (C == '\n' || C == EOF) {
1019 Error (ERR_ILLEGAL_CHARCON);
1026 Error (ERR_ILLEGAL_CHARCON);
1034 ReadStringConst ('\"');
1039 /* Line continuation? */
1043 /* Handle as white space */
1057 /* Check if we have any open .IFs in this file */
1059 /* Check if we have any open token lists in this file */
1062 /* If this was an include file, then close it and handle like a
1063 * separator. Do not close the main file, but return EOF.
1074 /* If we go here, we could not identify the current character. Skip it
1077 Error (ERR_INVALID_CHAR, C & 0xFF);
1084 int TokHasSVal (enum Token Tok)
1085 /* Return true if the given token has an attached SVal */
1087 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1092 int TokHasIVal (enum Token Tok)
1093 /* Return true if the given token has an attached IVal */
1095 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1100 int GetSubKey (const char** Keys, unsigned Count)
1101 /* Search for a subkey in a table of keywords. The current token must be an
1102 * identifier and all keys must be in upper case. The identifier will be
1103 * uppercased in the process. The function returns the index of the keyword,
1104 * or -1 if the keyword was not found.
1109 /* Must have an identifier */
1110 PRECONDITION (Tok == TOK_IDENT);
1112 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1117 /* Do a linear search (a binary search is not worth the effort) */
1118 for (I = 0; I < Count; ++I) {
1119 if (strcmp (SVal, Keys [I]) == 0) {
1131 void WriteFiles (void)
1132 /* Write the list of input files to the object file */
1136 /* Tell the obj file module that we're about to start the file list */
1139 /* Write the file count */
1140 ObjWrite8 (FileCount);
1142 /* Write the file data */
1143 for (I = 0; I < FileCount; ++I) {
1144 ObjWrite32 (Files [I].MTime);
1145 ObjWrite32 (Files [I].Size);
1146 ObjWriteStr (Files [I].Name);
1149 /* Done writing files */
1155 void InitScanner (const char* InFile)
1156 /* Initialize the scanner, open the given input file */
1158 /* Open the input file */
1159 NewInputFile (InFile);
1164 void DoneScanner (void)
1165 /* Release scanner resources */