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 { "CONST", TOK_CONST },
141 { "DATA", TOK_DATA },
142 { "DBYT", TOK_DBYT },
143 { "DEBUGINFO", TOK_DEBUGINFO },
144 { "DEF", TOK_DEFINED },
145 { "DEFINE", TOK_DEFINE },
146 { "DEFINED", TOK_DEFINED },
147 { "DWORD", TOK_DWORD },
148 { "ELSE", TOK_ELSE },
149 { "ELSEIF", TOK_ELSEIF },
151 { "ENDIF", TOK_ENDIF },
152 { "ENDMAC", TOK_ENDMACRO },
153 { "ENDMACRO", TOK_ENDMACRO },
154 { "ENDPROC", TOK_ENDPROC },
155 { "ENDREP", TOK_ENDREP },
156 { "ENDREPEAT", TOK_ENDREP },
157 { "ERROR", TOK_ERROR },
158 { "EXITMAC", TOK_EXITMACRO },
159 { "EXITMACRO", TOK_EXITMACRO },
160 { "EXPORT", TOK_EXPORT },
161 { "EXPORTZP", TOK_EXPORTZP },
162 { "FARADDR", TOK_FARADDR },
163 { "FEATURE", TOK_FEATURE },
164 { "FILEOPT", TOK_FILEOPT },
165 { "FOPT", TOK_FILEOPT },
166 { "GLOBAL", TOK_GLOBAL },
167 { "GLOBALZP", TOK_GLOBALZP },
171 { "IFBLANK", TOK_IFBLANK },
172 { "IFCONST", TOK_IFCONST },
173 { "IFDEF", TOK_IFDEF },
174 { "IFNBLANK", TOK_IFNBLANK },
175 { "IFNCONST", TOK_IFNCONST },
176 { "IFNDEF", TOK_IFNDEF },
177 { "IFNREF", TOK_IFNREF },
178 { "IFP02", TOK_IFP02 },
179 { "IFP816", TOK_IFP816 },
180 { "IFPC02", TOK_IFPC02 },
181 { "IFREF", TOK_IFREF },
182 { "IMPORT", TOK_IMPORT },
183 { "IMPORTZP", TOK_IMPORTZP },
184 { "INCBIN", TOK_INCBIN },
185 { "INCLUDE", TOK_INCLUDE },
186 { "LINECONT", TOK_LINECONT },
187 { "LIST", TOK_LIST },
188 { "LISTBYTES", TOK_LISTBYTES },
189 { "LOCAL", TOK_LOCAL },
190 { "LOCALCHAR", TOK_LOCALCHAR },
191 { "MAC", TOK_MACRO },
192 { "MACPACK", TOK_MACPACK },
193 { "MACRO", TOK_MACRO },
194 { "MATCH", TOK_MATCH },
198 { "NULL", TOK_NULL },
203 { "P816", TOK_P816 },
204 { "PAGELEN", TOK_PAGELENGTH },
205 { "PAGELENGTH", TOK_PAGELENGTH },
206 { "PARAMCOUNT", TOK_PARAMCOUNT },
207 { "PC02", TOK_PC02 },
208 { "PROC", TOK_PROC },
209 { "REF", TOK_REFERENCED },
210 { "REFERENCED", TOK_REFERENCED },
211 { "RELOC", TOK_RELOC },
212 { "REPEAT", TOK_REPEAT },
214 { "RODATA", TOK_RODATA },
215 { "SEGMENT", TOK_SEGMENT },
218 { "SMART", TOK_SMART },
219 { "STRING", TOK_STRING },
220 { "SUNPLUS", TOK_SUNPLUS },
221 { "WORD", TOK_WORD },
222 { "XMATCH", TOK_XMATCH },
224 { "ZEROPAGE", TOK_ZEROPAGE },
229 /*****************************************************************************/
231 /*****************************************************************************/
235 static void NextChar (void);
236 /* Read the next character from the input file */
240 /*****************************************************************************/
241 /* Character classification functions */
242 /*****************************************************************************/
246 static int IsBlank (int C)
247 /* Return true if the character is a blank or tab */
249 return (C == ' ' || C == '\t');
254 static int IsDigit (int C)
255 /* Return true if the character is a digit */
262 static int IsXDigit (int C)
263 /* Return true if the character is a hexadecimal digit */
270 static int IsDDigit (int C)
271 /* Return true if the character is a dual digit */
273 return (C == '0' || C == '1');
278 static int IsIdChar (int C)
279 /* Return true if the character is a valid character for an identifier */
281 return isalnum (C) ||
283 (C == '@' && AtInIdents) ||
284 (C == '$' && DollarInIdents);
289 static int IsIdStart (int C)
290 /* Return true if the character may start an identifier */
292 return isalpha (C) || C == '_';
297 /*****************************************************************************/
299 /*****************************************************************************/
303 const char* GetFileName (unsigned char Name)
304 /* Get the name of a file where the name index is known */
306 PRECONDITION (Name <= FileCount);
308 /* Name was defined outside any file scope, use the name of the first
309 * file instead. Errors are then reported with a file position of
310 * line zero in the first file.
312 if (FileCount == 0) {
313 /* No files defined until now */
314 return "(outside file scope)";
316 return Files [0].Name;
319 return Files [Name-1].Name;
325 void NewInputFile (const char* Name)
326 /* Open a new input file */
331 /* Check for nested include overflow */
332 if (FileCount >= MAX_INPUT_FILES) {
333 Fatal (FAT_MAX_INPUT_FILES);
336 /* First try to open the file */
337 F = fopen (Name, "r");
342 /* Error (fatal error if this is the main file) */
344 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
347 /* We are on include level. Search for the file in the include
350 PathName = FindInclude (Name);
351 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
352 /* Not found or cannot open, print an error and bail out */
353 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
356 /* Free the allocated memory */
361 /* check again if we do now have an open file */
364 /* Stat the file and remember the values */
366 if (fstat (fileno (F), &Buf) != 0) {
367 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
369 Files [FileCount].MTime = Buf.st_mtime;
370 Files [FileCount].Size = Buf.st_size;
371 Files [FileCount].Name = xstrdup (Name);
374 /* Create a new state variable and initialize it */
375 I = xmalloc (sizeof (*I));
379 I->Pos.Name = FileCount;
384 /* Use the new file */
396 void DoneInputFile (void)
397 /* Close the current input file */
401 /* Restore the old token */
405 /* Save a pointer to the current struct, then set it back */
409 /* Cleanup the current stuff */
417 void NewInputData (const char* Data, int Malloced)
418 /* Add a chunk of input data to the input stream */
422 /* Create a new state variable and initialize it */
423 I = xmalloc (sizeof (*I));
426 I->Malloced = Malloced;
430 /* Use the new data */
440 static void DoneInputData (void)
441 /* End the current input data stream */
445 /* Restore the old token */
449 /* Save a pointer to the current struct, then set it back */
453 /* Cleanup the current stuff */
462 static unsigned DigitVal (unsigned char C)
463 /* Convert a digit into it's numerical representation */
468 return toupper (C) - 'A' + 10;
474 static void NextChar (void)
475 /* Read the next character from the input file */
477 /* If we have an input data structure, read from there */
482 /* End of input data, will set to last file char */
488 /* Check for end of line, read the next line if needed */
489 while (IFile->Line [IFile->Pos.Col] == '\0') {
491 /* End of current line reached, read next line */
492 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
493 /* End of file. Add an empty line to the listing. This is a
494 * small hack needed to keep the PC output in sync.
496 NewListingLine ("", IFile->Pos.Name, ICount);
505 /* Remember the new line for the listing */
506 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
510 /* Return the next character from the file */
511 C = IFile->Line [IFile->Pos.Col++];
518 void UpcaseSVal (void)
519 /* Make SVal upper case */
523 SVal [I] = toupper (SVal [I]);
530 static int CmpDotKeyword (const void* K1, const void* K2)
531 /* Compare function for the dot keyword search */
533 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
538 static unsigned char FindDotKeyword (void)
539 /* Find the dot keyword in SVal. Return the corresponding token if found,
540 * return TOK_NONE if not found.
543 static const struct DotKeyword K = { SVal, 0 };
544 struct DotKeyword* R;
546 /* If we aren't in ignore case mode, we have to uppercase the keyword */
551 /* Search for the keyword */
552 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
553 sizeof (DotKeywords [0]), CmpDotKeyword);
563 static void ReadIdent (void)
564 /* Read an identifier from the current input position into Ident. It is
565 * assumed that the first character has already been checked.
568 /* Read the identifier */
571 if (I < MAX_STR_LEN) {
575 } while (IsIdChar (C));
578 /* If we should ignore case, convert the identifier to upper case */
586 static unsigned ReadStringConst (int StringTerm)
587 /* Read a string constant into SVal. Check for maximum string length and all
588 * other stuff. The length of the string is returned.
593 /* Skip the leading string terminator */
596 /* Read the string */
599 if (C == StringTerm) {
602 if (C == '\n' || C == EOF) {
603 Error (ERR_NEWLINE_IN_STRING);
607 /* Check for string length, print an error message once */
608 if (I == MAX_STR_LEN) {
609 Error (ERR_STRING_TOO_LONG);
610 } else if (I < MAX_STR_LEN) {
615 /* Skip the character */
619 /* Skip the trailing terminator */
622 /* Terminate the string */
623 if (I >= MAX_STR_LEN) {
628 /* Return the length of the string */
634 void NextRawTok (void)
635 /* Read the next raw token from the input stream */
637 /* If we've a forced end of assembly, don't read further */
644 /* Check if we have tokens from another input source */
645 if (InputFromStack ()) {
650 /* Skip whitespace, remember if we had some */
651 if ((WS = IsBlank (C)) != 0) {
654 } while (IsBlank (C));
657 /* If we're reading from the file, update the location from where the
658 * next token will be read. If we're reading from input data, keep the
665 /* Hex number or PC symbol? */
669 /* Hex digit must follow or DollarIsPC must be enabled */
675 Error (ERR_HEX_DIGIT_EXPECTED);
679 /* Read the number */
681 while (IsXDigit (C)) {
682 if (IVal & 0xF0000000) {
683 Error (ERR_NUM_OVERFLOW);
686 IVal = (IVal << 4) + DigitVal (C);
690 /* This is an integer constant */
699 /* 0 or 1 must follow */
701 Error (ERR_01_EXPECTED);
704 /* Read the number */
706 while (IsDDigit (C)) {
707 if (IVal & 0x80000000) {
708 Error (ERR_NUM_OVERFLOW);
711 IVal = (IVal << 1) + DigitVal (C);
715 /* This is an integer constant */
720 /* Decimal number? */
723 /* Read the number */
725 while (IsDigit (C)) {
726 if (IVal > (0xFFFFFFFF / 10)) {
727 Error (ERR_NUM_OVERFLOW);
730 IVal = (IVal * 10) + DigitVal (C);
734 /* This is an integer constant */
739 /* Control command? */
744 if (!IsIdStart (C)) {
745 Error (ERR_PSEUDO_EXPECTED);
746 /* Try to read an identifier */
750 /* Read the identifier */
753 /* Search the keyword */
754 Tok = FindDotKeyword ();
755 if (Tok == TOK_NONE) {
757 Error (ERR_PSEUDO_EXPECTED);
764 if (C == LocalStart) {
766 /* Read the identifier */
769 /* Start character alone is not enough */
770 if (SVal [1] == '\0') {
771 Error (ERR_IDENT_EXPECTED);
781 /* Identifier or keyword? */
784 /* Read the identifier */
787 /* Check for special names */
788 if (SVal [1] == '\0') {
789 switch (toupper (SVal [0])) {
813 /* Search for an opcode */
814 IVal = FindInstruction (SVal);
816 /* This is a mnemonic */
818 } else if (IsDefine (SVal)) {
819 /* This is a define style macro - expand it */
829 /* Ok, let's do the switch */
918 while (C != '\n' && C != EOF) {
953 } else if (C == '<') {
956 } else if (C == '>') {
979 } else if (C == '>') {
993 /* Hack: If we allow ' as terminating character for strings, read
994 * the following stuff as a string, and check for a one character
997 if (LooseStringTerm) {
998 if (ReadStringConst ('\'') == 1) {
1005 /* Always a character constant */
1007 if (C == '\n' || C == EOF) {
1008 Error (ERR_ILLEGAL_CHARCON);
1015 Error (ERR_ILLEGAL_CHARCON);
1023 ReadStringConst ('\"');
1028 /* Line continuation? */
1032 /* Handle as white space */
1046 /* Check if we have any open .IFs in this file */
1048 /* Check if we have any open token lists in this file */
1051 /* If this was an include file, then close it and handle like a
1052 * separator. Do not close the main file, but return EOF.
1063 /* If we go here, we could not identify the current character. Skip it
1066 Error (ERR_INVALID_CHAR, C & 0xFF);
1073 int TokHasSVal (enum Token Tok)
1074 /* Return true if the given token has an attached SVal */
1076 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1081 int TokHasIVal (enum Token Tok)
1082 /* Return true if the given token has an attached IVal */
1084 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1089 int GetSubKey (const char** Keys, unsigned Count)
1090 /* Search for a subkey in a table of keywords. The current token must be an
1091 * identifier and all keys must be in upper case. The identifier will be
1092 * uppercased in the process. The function returns the index of the keyword,
1093 * or -1 if the keyword was not found.
1098 /* Must have an identifier */
1099 PRECONDITION (Tok == TOK_IDENT);
1101 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1106 /* Do a linear search (a binary search is not worth the effort) */
1107 for (I = 0; I < Count; ++I) {
1108 if (strcmp (SVal, Keys [I]) == 0) {
1120 void WriteFiles (void)
1121 /* Write the list of input files to the object file */
1125 /* Tell the obj file module that we're about to start the file list */
1128 /* Write the file count */
1129 ObjWrite8 (FileCount);
1131 /* Write the file data */
1132 for (I = 0; I < FileCount; ++I) {
1133 ObjWrite32 (Files [I].MTime);
1134 ObjWrite32 (Files [I].Size);
1135 ObjWriteStr (Files [I].Name);
1138 /* Done writing files */
1144 void InitScanner (const char* InFile)
1145 /* Initialize the scanner, open the given input file */
1147 /* Open the input file */
1148 NewInputFile (InFile);
1153 void DoneScanner (void)
1154 /* Release scanner resources */