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 /* Current input variables */
105 static InputFile* IFile = 0; /* Current input file */
106 static InputData* IData = 0; /* Current input memory data */
107 static unsigned ICount = 0; /* Count of input files */
108 static int C = 0; /* Current input character */
110 /* Force end of assembly */
113 /* List of dot keywords with the corresponding tokens */
115 const char* Key; /* MUST be first field */
120 { "ADDR", TOK_ADDR },
121 { "ALIGN", TOK_ALIGN },
123 { "ASCIIZ", TOK_ASCIIZ },
124 { "AUTOIMPORT", TOK_AUTOIMPORT },
125 { "BITAND", TOK_AND },
126 { "BITNOT", TOK_NOT },
128 { "BITXOR", TOK_XOR },
129 { "BLANK", TOK_BLANK },
131 { "BYTE", TOK_BYTE },
132 { "CASE", TOK_CASE },
133 { "CODE", TOK_CODE },
134 { "CONCAT", TOK_CONCAT },
135 { "CONST", TOK_CONST },
137 { "DATA", TOK_DATA },
139 { "DBYT", TOK_DBYT },
140 { "DEBUGINFO", TOK_DEBUGINFO },
141 { "DEF", TOK_DEFINED },
142 { "DEFINE", TOK_DEFINE },
143 { "DEFINED", TOK_DEFINED },
144 { "DWORD", TOK_DWORD },
145 { "ELSE", TOK_ELSE },
146 { "ELSEIF", TOK_ELSEIF },
148 { "ENDIF", TOK_ENDIF },
149 { "ENDMAC", TOK_ENDMACRO },
150 { "ENDMACRO", TOK_ENDMACRO },
151 { "ENDPROC", TOK_ENDPROC },
152 { "ENDREP", TOK_ENDREP },
153 { "ENDREPEAT", TOK_ENDREP },
154 { "ERROR", TOK_ERROR },
155 { "EXITMAC", TOK_EXITMACRO },
156 { "EXITMACRO", TOK_EXITMACRO },
157 { "EXPORT", TOK_EXPORT },
158 { "EXPORTZP", TOK_EXPORTZP },
159 { "FARADDR", TOK_FARADDR },
160 { "FEATURE", TOK_FEATURE },
161 { "FILEOPT", TOK_FILEOPT },
162 { "FOPT", TOK_FILEOPT },
163 { "FORCEWORD", TOK_FORCEWORD },
164 { "GLOBAL", TOK_GLOBAL },
165 { "GLOBALZP", TOK_GLOBALZP },
169 { "IFBLANK", TOK_IFBLANK },
170 { "IFCONST", TOK_IFCONST },
171 { "IFDEF", TOK_IFDEF },
172 { "IFNBLANK", TOK_IFNBLANK },
173 { "IFNCONST", TOK_IFNCONST },
174 { "IFNDEF", TOK_IFNDEF },
175 { "IFNREF", TOK_IFNREF },
176 { "IFP02", TOK_IFP02 },
177 { "IFP816", TOK_IFP816 },
178 { "IFPC02", TOK_IFPC02 },
179 { "IFREF", TOK_IFREF },
180 { "IMPORT", TOK_IMPORT },
181 { "IMPORTZP", TOK_IMPORTZP },
182 { "INCBIN", TOK_INCBIN },
183 { "INCLUDE", TOK_INCLUDE },
184 { "LEFT", TOK_LEFT },
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 { "RIGHT", TOK_RIGHT },
214 { "RODATA", TOK_RODATA },
215 { "SEGMENT", TOK_SEGMENT },
218 { "SMART", TOK_SMART },
219 { "STRAT", TOK_STRAT },
220 { "STRING", TOK_STRING },
221 { "STRLEN", TOK_STRLEN },
222 { "SUNPLUS", TOK_SUNPLUS },
223 { "TCOUNT", TOK_TCOUNT },
224 { "WARNING", TOK_WARNING },
225 { "WORD", TOK_WORD },
226 { "XMATCH", TOK_XMATCH },
228 { "ZEROPAGE", TOK_ZEROPAGE },
233 /*****************************************************************************/
235 /*****************************************************************************/
239 static void NextChar (void);
240 /* Read the next character from the input file */
244 /*****************************************************************************/
245 /* Character classification functions */
246 /*****************************************************************************/
250 static int IsBlank (int C)
251 /* Return true if the character is a blank or tab */
253 return (C == ' ' || C == '\t');
258 static int IsDigit (int C)
259 /* Return true if the character is a digit */
266 static int IsXDigit (int C)
267 /* Return true if the character is a hexadecimal digit */
274 static int IsDDigit (int C)
275 /* Return true if the character is a dual digit */
277 return (C == '0' || C == '1');
282 static int IsIdChar (int C)
283 /* Return true if the character is a valid character for an identifier */
285 return isalnum (C) ||
287 (C == '@' && AtInIdents) ||
288 (C == '$' && DollarInIdents);
293 static int IsIdStart (int C)
294 /* Return true if the character may start an identifier */
296 return isalpha (C) || C == '_';
301 /*****************************************************************************/
303 /*****************************************************************************/
307 void NewInputFile (const char* Name)
308 /* Open a new input file */
313 /* First try to open the file */
314 F = fopen (Name, "r");
319 /* Error (fatal error if this is the main file) */
321 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
324 /* We are on include level. Search for the file in the include
327 PathName = FindInclude (Name);
328 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
329 /* Not found or cannot open, print an error and bail out */
330 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
333 /* Free the allocated memory */
338 /* check again if we do now have an open file */
343 /* Stat the file and remember the values */
345 if (fstat (fileno (F), &Buf) != 0) {
346 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
349 /* Add the file to the input file table and remember the index */
350 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
352 /* Create a new state variable and initialize it */
353 I = xmalloc (sizeof (*I));
357 I->Pos.Name = FileIdx;
362 /* Use the new file */
374 void DoneInputFile (void)
375 /* Close the current input file */
379 /* Restore the old token */
383 /* Save a pointer to the current struct, then set it back */
387 /* Cleanup the current stuff */
395 void NewInputData (const char* Data, int Malloced)
396 /* Add a chunk of input data to the input stream */
400 /* Create a new state variable and initialize it */
401 I = xmalloc (sizeof (*I));
404 I->Malloced = Malloced;
408 /* Use the new data */
418 static void DoneInputData (void)
419 /* End the current input data stream */
423 /* Restore the old token */
427 /* Save a pointer to the current struct, then set it back */
431 /* Cleanup the current stuff */
440 static unsigned DigitVal (unsigned char C)
441 /* Convert a digit into it's numerical representation */
446 return toupper (C) - 'A' + 10;
452 static void NextChar (void)
453 /* Read the next character from the input file */
455 /* If we have an input data structure, read from there */
460 /* End of input data, will set to last file char */
466 /* Check for end of line, read the next line if needed */
467 while (IFile->Line [IFile->Pos.Col] == '\0') {
469 /* End of current line reached, read next line */
470 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
471 /* End of file. Add an empty line to the listing. This is a
472 * small hack needed to keep the PC output in sync.
474 NewListingLine ("", IFile->Pos.Name, ICount);
483 /* Remember the new line for the listing */
484 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
488 /* Return the next character from the file */
489 C = IFile->Line [IFile->Pos.Col++];
496 void LocaseSVal (void)
497 /* Make SVal lower case */
501 SVal [I] = tolower (SVal [I]);
508 void UpcaseSVal (void)
509 /* Make SVal upper case */
513 SVal [I] = toupper (SVal [I]);
520 static int CmpDotKeyword (const void* K1, const void* K2)
521 /* Compare function for the dot keyword search */
523 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
528 static unsigned char FindDotKeyword (void)
529 /* Find the dot keyword in SVal. Return the corresponding token if found,
530 * return TOK_NONE if not found.
533 static const struct DotKeyword K = { SVal, 0 };
534 struct DotKeyword* R;
536 /* If we aren't in ignore case mode, we have to uppercase the keyword */
541 /* Search for the keyword */
542 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
543 sizeof (DotKeywords [0]), CmpDotKeyword);
553 static void ReadIdent (void)
554 /* Read an identifier from the current input position into Ident. It is
555 * assumed that the first character has already been checked.
558 /* Read the identifier */
561 if (I < MAX_STR_LEN) {
565 } while (IsIdChar (C));
568 /* If we should ignore case, convert the identifier to upper case */
576 static unsigned ReadStringConst (int StringTerm)
577 /* Read a string constant into SVal. Check for maximum string length and all
578 * other stuff. The length of the string is returned.
583 /* Skip the leading string terminator */
586 /* Read the string */
589 if (C == StringTerm) {
592 if (C == '\n' || C == EOF) {
593 Error (ERR_NEWLINE_IN_STRING);
597 /* Check for string length, print an error message once */
598 if (I == MAX_STR_LEN) {
599 Error (ERR_STRING_TOO_LONG);
600 } else if (I < MAX_STR_LEN) {
605 /* Skip the character */
609 /* Skip the trailing terminator */
612 /* Terminate the string */
613 if (I >= MAX_STR_LEN) {
618 /* Return the length of the string */
624 void NextRawTok (void)
625 /* Read the next raw token from the input stream */
627 /* If we've a forced end of assembly, don't read further */
634 /* Check if we have tokens from another input source */
635 if (InputFromStack ()) {
640 /* Skip whitespace, remember if we had some */
641 if ((WS = IsBlank (C)) != 0) {
644 } while (IsBlank (C));
647 /* If we're reading from the file, update the location from where the
648 * next token will be read. If we're reading from input data, keep the
655 /* Hex number or PC symbol? */
659 /* Hex digit must follow or DollarIsPC must be enabled */
665 Error (ERR_HEX_DIGIT_EXPECTED);
669 /* Read the number */
671 while (IsXDigit (C)) {
672 if (IVal & 0xF0000000) {
673 Error (ERR_NUM_OVERFLOW);
676 IVal = (IVal << 4) + DigitVal (C);
680 /* This is an integer constant */
689 /* 0 or 1 must follow */
691 Error (ERR_01_EXPECTED);
694 /* Read the number */
696 while (IsDDigit (C)) {
697 if (IVal & 0x80000000) {
698 Error (ERR_NUM_OVERFLOW);
701 IVal = (IVal << 1) + DigitVal (C);
705 /* This is an integer constant */
710 /* Decimal number? */
713 /* Read the number */
715 while (IsDigit (C)) {
716 if (IVal > (0xFFFFFFFF / 10)) {
717 Error (ERR_NUM_OVERFLOW);
720 IVal = (IVal * 10) + DigitVal (C);
724 /* This is an integer constant */
729 /* Control command? */
734 if (!IsIdStart (C)) {
735 Error (ERR_PSEUDO_EXPECTED);
736 /* Try to read an identifier */
740 /* Read the identifier */
743 /* Search the keyword */
744 Tok = FindDotKeyword ();
745 if (Tok == TOK_NONE) {
747 Error (ERR_PSEUDO_EXPECTED);
754 if (C == LocalStart) {
756 /* Read the identifier */
759 /* Start character alone is not enough */
760 if (SVal [1] == '\0') {
761 Error (ERR_IDENT_EXPECTED);
771 /* Identifier or keyword? */
774 /* Read the identifier */
777 /* Check for special names */
778 if (SVal [1] == '\0') {
779 switch (toupper (SVal [0])) {
803 /* Search for an opcode */
804 IVal = FindInstruction (SVal);
806 /* This is a mnemonic */
808 } else if (IsDefine (SVal)) {
809 /* This is a define style macro - expand it */
819 /* Ok, let's do the switch */
908 while (C != '\n' && C != EOF) {
943 } else if (C == '<') {
946 } else if (C == '>') {
969 } else if (C == '>') {
983 /* Hack: If we allow ' as terminating character for strings, read
984 * the following stuff as a string, and check for a one character
987 if (LooseStringTerm) {
988 if (ReadStringConst ('\'') == 1) {
995 /* Always a character constant */
997 if (C == '\n' || C == EOF) {
998 Error (ERR_ILLEGAL_CHARCON);
1005 Error (ERR_ILLEGAL_CHARCON);
1013 ReadStringConst ('\"');
1018 /* Line continuation? */
1022 /* Handle as white space */
1036 /* Check if we have any open .IFs in this file */
1038 /* Check if we have any open token lists in this file */
1041 /* If this was an include file, then close it and handle like a
1042 * separator. Do not close the main file, but return EOF.
1053 /* If we go here, we could not identify the current character. Skip it
1056 Error (ERR_INVALID_CHAR, C & 0xFF);
1063 int TokHasSVal (enum Token Tok)
1064 /* Return true if the given token has an attached SVal */
1066 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1071 int TokHasIVal (enum Token Tok)
1072 /* Return true if the given token has an attached IVal */
1074 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1079 int GetSubKey (const char** Keys, unsigned Count)
1080 /* Search for a subkey in a table of keywords. The current token must be an
1081 * identifier and all keys must be in upper case. The identifier will be
1082 * uppercased in the process. The function returns the index of the keyword,
1083 * or -1 if the keyword was not found.
1088 /* Must have an identifier */
1089 PRECONDITION (Tok == TOK_IDENT);
1091 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1096 /* Do a linear search (a binary search is not worth the effort) */
1097 for (I = 0; I < Count; ++I) {
1098 if (strcmp (SVal, Keys [I]) == 0) {
1110 void InitScanner (const char* InFile)
1111 /* Initialize the scanner, open the given input file */
1113 /* Open the input file */
1114 NewInputFile (InFile);
1119 void DoneScanner (void)
1120 /* Release scanner resources */