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 /*****************************************************************************/
59 /*****************************************************************************/
61 /*****************************************************************************/
65 enum Token Tok = TOK_NONE; /* Current token */
66 int WS; /* Flag: Whitespace before token */
67 long IVal; /* Integer token attribute */
68 char SVal [MAX_STR_LEN+1]; /* String token attribute */
70 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
74 /* Struct to handle include files. Note: The length of the input line may
75 * not exceed 255+1, since the column is stored in the file position struct
76 * as a character. Increasing this value means changing the FilePos struct,
77 * and the read and write routines in the assembler and linker.
79 typedef struct InputFile_ InputFile;
81 FILE* F; /* Input file descriptor */
82 FilePos Pos; /* Position in file */
83 enum Token Tok; /* Last token */
84 int C; /* Last character */
85 char Line[256]; /* The current input line */
86 InputFile* Next; /* Linked list of input files */
89 /* Struct to handle textual input data */
90 typedef struct InputData_ InputData;
92 const char* Data; /* Pointer to the data */
93 const char* Pos; /* Pointer to current position */
94 int Malloced; /* Memory was malloced */
95 enum Token Tok; /* Last token */
96 int C; /* Last character */
97 InputData* Next; /* Linked list of input data */
100 /* List of input files */
102 unsigned long MTime; /* Time of last modification */
103 unsigned long Size; /* Size of file */
104 const char* Name; /* Name of file */
105 } Files [MAX_INPUT_FILES];
106 static unsigned FileCount = 0;
108 /* Current input variables */
109 static InputFile* IFile = 0; /* Current input file */
110 static InputData* IData = 0; /* Current input memory data */
111 static unsigned ICount = 0; /* Count of input files */
112 static int C = 0; /* Current input character */
114 /* Force end of assembly */
117 /* List of dot keywords with the corresponding tokens */
119 const char* Key; /* MUST be first field */
124 { "ADDR", TOK_ADDR },
125 { "ALIGN", TOK_ALIGN },
127 { "ASCIIZ", TOK_ASCIIZ },
128 { "AUTOIMPORT", TOK_AUTOIMPORT },
129 { "BITAND", TOK_AND },
130 { "BITNOT", TOK_NOT },
132 { "BITXOR", TOK_XOR },
133 { "BLANK", TOK_BLANK },
135 { "BYTE", TOK_BYTE },
136 { "CASE", TOK_CASE },
137 { "CODE", TOK_CODE },
138 { "CONST", TOK_CONST },
140 { "DATA", TOK_DATA },
141 { "DBYT", TOK_DBYT },
142 { "DEBUGINFO", TOK_DEBUGINFO },
143 { "DEF", TOK_DEFINED },
144 { "DEFINE", TOK_DEFINE },
145 { "DEFINED", TOK_DEFINED },
146 { "DWORD", TOK_DWORD },
147 { "ELSE", TOK_ELSE },
148 { "ELSEIF", TOK_ELSEIF },
150 { "ENDIF", TOK_ENDIF },
151 { "ENDMAC", TOK_ENDMACRO },
152 { "ENDMACRO", TOK_ENDMACRO },
153 { "ENDPROC", TOK_ENDPROC },
154 { "ENDREP", TOK_ENDREP },
155 { "ENDREPEAT", TOK_ENDREP },
156 { "ERROR", TOK_ERROR },
157 { "EXITMAC", TOK_EXITMACRO },
158 { "EXITMACRO", TOK_EXITMACRO },
159 { "EXPORT", TOK_EXPORT },
160 { "EXPORTZP", TOK_EXPORTZP },
161 { "FARADDR", TOK_FARADDR },
162 { "FEATURE", TOK_FEATURE },
163 { "FILEOPT", TOK_FILEOPT },
164 { "FOPT", TOK_FILEOPT },
165 { "GLOBAL", TOK_GLOBAL },
166 { "GLOBALZP", TOK_GLOBALZP },
170 { "IFBLANK", TOK_IFBLANK },
171 { "IFCONST", TOK_IFCONST },
172 { "IFDEF", TOK_IFDEF },
173 { "IFNBLANK", TOK_IFNBLANK },
174 { "IFNCONST", TOK_IFNCONST },
175 { "IFNDEF", TOK_IFNDEF },
176 { "IFNREF", TOK_IFNREF },
177 { "IFP02", TOK_IFP02 },
178 { "IFP816", TOK_IFP816 },
179 { "IFPC02", TOK_IFPC02 },
180 { "IFREF", TOK_IFREF },
181 { "IMPORT", TOK_IMPORT },
182 { "IMPORTZP", TOK_IMPORTZP },
183 { "INCBIN", TOK_INCBIN },
184 { "INCLUDE", TOK_INCLUDE },
185 { "LINECONT", TOK_LINECONT },
186 { "LIST", TOK_LIST },
187 { "LISTBYTES", TOK_LISTBYTES },
188 { "LOCAL", TOK_LOCAL },
189 { "LOCALCHAR", TOK_LOCALCHAR },
190 { "MAC", TOK_MACRO },
191 { "MACPACK", TOK_MACPACK },
192 { "MACRO", TOK_MACRO },
193 { "MATCH", TOK_MATCH },
197 { "NULL", TOK_NULL },
202 { "P816", TOK_P816 },
203 { "PAGELEN", TOK_PAGELENGTH },
204 { "PAGELENGTH", TOK_PAGELENGTH },
205 { "PARAMCOUNT", TOK_PARAMCOUNT },
206 { "PC02", TOK_PC02 },
207 { "PROC", TOK_PROC },
208 { "REF", TOK_REFERENCED },
209 { "REFERENCED", TOK_REFERENCED },
210 { "RELOC", TOK_RELOC },
211 { "REPEAT", TOK_REPEAT },
213 { "RODATA", TOK_RODATA },
214 { "SEGMENT", TOK_SEGMENT },
217 { "SMART", TOK_SMART },
218 { "STRING", TOK_STRING },
219 { "SUNPLUS", TOK_SUNPLUS },
220 { "WORD", TOK_WORD },
221 { "XMATCH", TOK_XMATCH },
223 { "ZEROPAGE", TOK_ZEROPAGE },
228 /*****************************************************************************/
230 /*****************************************************************************/
234 static void NextChar (void);
235 /* Read the next character from the input file */
239 /*****************************************************************************/
240 /* Character classification functions */
241 /*****************************************************************************/
245 static int IsBlank (int C)
246 /* Return true if the character is a blank or tab */
248 return (C == ' ' || C == '\t');
253 static int IsDigit (int C)
254 /* Return true if the character is a digit */
261 static int IsXDigit (int C)
262 /* Return true if the character is a hexadecimal digit */
269 static int IsDDigit (int C)
270 /* Return true if the character is a dual digit */
272 return (C == '0' || C == '1');
277 static int IsIdChar (int C)
278 /* Return true if the character is a valid character for an identifier */
280 return isalnum (C) ||
282 (C == '@' && AtInIdents) ||
283 (C == '$' && DollarInIdents);
288 static int IsIdStart (int C)
289 /* Return true if the character may start an identifier */
291 return isalpha (C) || C == '_';
296 /*****************************************************************************/
298 /*****************************************************************************/
302 const char* GetFileName (unsigned char Name)
303 /* Get the name of a file where the name index is known */
305 PRECONDITION (Name <= FileCount);
307 /* Name was defined outside any file scope, use the name of the first
308 * file instead. Errors are then reported with a file position of
309 * line zero in the first file.
311 if (FileCount == 0) {
312 /* No files defined until now */
313 return "(outside file scope)";
315 return Files [0].Name;
318 return Files [Name-1].Name;
324 void NewInputFile (const char* Name)
325 /* Open a new input file */
330 /* Check for nested include overflow */
331 if (FileCount >= MAX_INPUT_FILES) {
332 Fatal (FAT_MAX_INPUT_FILES);
335 /* First try to open the file */
336 F = fopen (Name, "r");
341 /* Error (fatal error if this is the main file) */
343 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
346 /* We are on include level. Search for the file in the include
349 PathName = FindInclude (Name);
350 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
351 /* Not found or cannot open, print an error and bail out */
352 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
355 /* Free the allocated memory */
360 /* check again if we do now have an open file */
363 /* Stat the file and remember the values */
365 if (fstat (fileno (F), &Buf) != 0) {
366 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
368 Files [FileCount].MTime = Buf.st_mtime;
369 Files [FileCount].Size = Buf.st_size;
370 Files [FileCount].Name = StrDup (Name);
373 /* Create a new state variable and initialize it */
374 I = Xmalloc (sizeof (*I));
378 I->Pos.Name = FileCount;
383 /* Use the new file */
395 void DoneInputFile (void)
396 /* Close the current input file */
400 /* Restore the old token */
404 /* Save a pointer to the current struct, then set it back */
408 /* Cleanup the current stuff */
416 void NewInputData (const char* Data, int Malloced)
417 /* Add a chunk of input data to the input stream */
421 /* Create a new state variable and initialize it */
422 I = Xmalloc (sizeof (*I));
425 I->Malloced = Malloced;
429 /* Use the new data */
439 static void DoneInputData (void)
440 /* End the current input data stream */
444 /* Restore the old token */
448 /* Save a pointer to the current struct, then set it back */
452 /* Cleanup the current stuff */
461 static unsigned DigitVal (unsigned char C)
462 /* Convert a digit into it's numerical representation */
467 return toupper (C) - 'A' + 10;
473 static void NextChar (void)
474 /* Read the next character from the input file */
476 /* If we have an input data structure, read from there */
481 /* End of input data, will set to last file char */
487 /* Check for end of line, read the next line if needed */
488 while (IFile->Line [IFile->Pos.Col] == '\0') {
490 /* End of current line reached, read next line */
491 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
492 /* End of file. Add an empty line to the listing. This is a
493 * small hack needed to keep the PC output in sync.
495 NewListingLine ("", IFile->Pos.Name, ICount);
504 /* Remember the new line for the listing */
505 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
509 /* Return the next character from the file */
510 C = IFile->Line [IFile->Pos.Col++];
517 void UpcaseSVal (void)
518 /* Make SVal upper case */
522 SVal [I] = toupper (SVal [I]);
529 static int CmpDotKeyword (const void* K1, const void* K2)
530 /* Compare function for the dot keyword search */
532 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
537 static unsigned char FindDotKeyword (void)
538 /* Find the dot keyword in SVal. Return the corresponding token if found,
539 * return TOK_NONE if not found.
542 static const struct DotKeyword K = { SVal, 0 };
543 struct DotKeyword* R;
545 /* If we aren't in ignore case mode, we have to uppercase the keyword */
550 /* Search for the keyword */
551 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
552 sizeof (DotKeywords [0]), CmpDotKeyword);
562 static void ReadIdent (void)
563 /* Read an identifier from the current input position into Ident. It is
564 * assumed that the first character has already been checked.
567 /* Read the identifier */
570 if (I < MAX_STR_LEN) {
574 } while (IsIdChar (C));
577 /* If we should ignore case, convert the identifier to upper case */
585 static unsigned ReadStringConst (int StringTerm)
586 /* Read a string constant into SVal. Check for maximum string length and all
587 * other stuff. The length of the string is returned.
592 /* Skip the leading string terminator */
595 /* Read the string */
598 if (C == StringTerm) {
601 if (C == '\n' || C == EOF) {
602 Error (ERR_NEWLINE_IN_STRING);
606 /* Check for string length, print an error message once */
607 if (I == MAX_STR_LEN) {
608 Error (ERR_STRING_TOO_LONG);
609 } else if (I < MAX_STR_LEN) {
614 /* Skip the character */
618 /* Skip the trailing terminator */
621 /* Terminate the string */
622 if (I >= MAX_STR_LEN) {
627 /* Return the length of the string */
633 void NextRawTok (void)
634 /* Read the next raw token from the input stream */
636 /* If we've a forced end of assembly, don't read further */
643 /* Check if we have tokens from another input source */
644 if (InputFromStack ()) {
649 /* Skip whitespace, remember if we had some */
650 if ((WS = IsBlank (C)) != 0) {
653 } while (IsBlank (C));
656 /* If we're reading from the file, update the location from where the
657 * next token will be read. If we're reading from input data, keep the
664 /* Hex number or PC symbol? */
668 /* Hex digit must follow or DollarIsPC must be enabled */
674 Error (ERR_HEX_DIGIT_EXPECTED);
678 /* Read the number */
680 while (IsXDigit (C)) {
681 if (IVal & 0xF0000000) {
682 Error (ERR_NUM_OVERFLOW);
685 IVal = (IVal << 4) + DigitVal (C);
689 /* This is an integer constant */
698 /* 0 or 1 must follow */
700 Error (ERR_01_EXPECTED);
703 /* Read the number */
705 while (IsDDigit (C)) {
706 if (IVal & 0x80000000) {
707 Error (ERR_NUM_OVERFLOW);
710 IVal = (IVal << 1) + DigitVal (C);
714 /* This is an integer constant */
719 /* Decimal number? */
722 /* Read the number */
724 while (IsDigit (C)) {
725 if (IVal > (0xFFFFFFFF / 10)) {
726 Error (ERR_NUM_OVERFLOW);
729 IVal = (IVal * 10) + DigitVal (C);
733 /* This is an integer constant */
738 /* Control command? */
743 if (!IsIdStart (C)) {
744 Error (ERR_PSEUDO_EXPECTED);
745 /* Try to read an identifier */
749 /* Read the identifier */
752 /* Search the keyword */
753 Tok = FindDotKeyword ();
754 if (Tok == TOK_NONE) {
756 Error (ERR_PSEUDO_EXPECTED);
763 if (C == LocalStart) {
765 /* Read the identifier */
768 /* Start character alone is not enough */
769 if (SVal [1] == '\0') {
770 Error (ERR_IDENT_EXPECTED);
780 /* Identifier or keyword? */
783 /* Read the identifier */
786 /* Check for special names */
787 if (SVal [1] == '\0') {
788 switch (toupper (SVal [0])) {
812 /* Search for an opcode */
813 IVal = FindInstruction (SVal);
815 /* This is a mnemonic */
817 } else if (IsDefine (SVal)) {
818 /* This is a define style macro - expand it */
828 /* Ok, let's do the switch */
917 while (C != '\n' && C != EOF) {
952 } else if (C == '<') {
955 } else if (C == '>') {
978 } else if (C == '>') {
992 /* Hack: If we allow ' as terminating character for strings, read
993 * the following stuff as a string, and check for a one character
996 if (LooseStringTerm) {
997 if (ReadStringConst ('\'') == 1) {
1004 /* Always a character constant */
1006 if (C == '\n' || C == EOF) {
1007 Error (ERR_ILLEGAL_CHARCON);
1014 Error (ERR_ILLEGAL_CHARCON);
1022 ReadStringConst ('\"');
1027 /* Line continuation? */
1031 /* Handle as white space */
1045 /* Check if we have any open .IFs in this file */
1047 /* Check if we have any open token lists in this file */
1050 /* If this was an include file, then close it and handle like a
1051 * separator. Do not close the main file, but return EOF.
1062 /* If we go here, we could not identify the current character. Skip it
1065 Error (ERR_INVALID_CHAR, C & 0xFF);
1072 int TokHasSVal (enum Token Tok)
1073 /* Return true if the given token has an attached SVal */
1075 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1080 int TokHasIVal (enum Token Tok)
1081 /* Return true if the given token has an attached IVal */
1083 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1088 int GetSubKey (const char** Keys, unsigned Count)
1089 /* Search for a subkey in a table of keywords. The current token must be an
1090 * identifier and all keys must be in upper case. The identifier will be
1091 * uppercased in the process. The function returns the index of the keyword,
1092 * or -1 if the keyword was not found.
1097 /* Must have an identifier */
1098 PRECONDITION (Tok == TOK_IDENT);
1100 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1105 /* Do a linear search (a binary search is not worth the effort) */
1106 for (I = 0; I < Count; ++I) {
1107 if (strcmp (SVal, Keys [I]) == 0) {
1119 void WriteFiles (void)
1120 /* Write the list of input files to the object file */
1124 /* Tell the obj file module that we're about to start the file list */
1127 /* Write the file count */
1128 ObjWrite8 (FileCount);
1130 /* Write the file data */
1131 for (I = 0; I < FileCount; ++I) {
1132 ObjWrite32 (Files [I].MTime);
1133 ObjWrite32 (Files [I].Size);
1134 ObjWriteStr (Files [I].Name);
1137 /* Done writing files */
1143 void InitScanner (const char* InFile)
1144 /* Initialize the scanner, open the given input file */
1146 /* Open the input file */
1147 NewInputFile (InFile);
1152 void DoneScanner (void)
1153 /* Release scanner resources */