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 /*****************************************************************************/
41 #include <sys/types.h> /* EMX needs this */
65 /*****************************************************************************/
67 /*****************************************************************************/
71 enum Token Tok = TOK_NONE; /* Current token */
72 int WS; /* Flag: Whitespace before token */
73 long IVal; /* Integer token attribute */
74 char SVal [MAX_STR_LEN+1]; /* String token attribute */
76 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
80 /* Struct to handle include files. Note: The length of the input line may
81 * not exceed 255+1, since the column is stored in the file position struct
82 * as a character. Increasing this value means changing the FilePos struct,
83 * and the read and write routines in the assembler and linker.
85 typedef struct InputFile_ InputFile;
87 FILE* F; /* Input file descriptor */
88 FilePos Pos; /* Position in file */
89 enum Token Tok; /* Last token */
90 int C; /* Last character */
91 char Line[256]; /* The current input line */
92 InputFile* Next; /* Linked list of input files */
95 /* Struct to handle textual input data */
96 typedef struct InputData_ InputData;
98 const char* Data; /* Pointer to the data */
99 const char* Pos; /* Pointer to current position */
100 int Malloced; /* Memory was malloced */
101 enum Token Tok; /* Last token */
102 int C; /* Last character */
103 InputData* Next; /* Linked list of input data */
106 /* Current input variables */
107 static InputFile* IFile = 0; /* Current input file */
108 static InputData* IData = 0; /* Current input memory data */
109 static unsigned ICount = 0; /* Count of input files */
110 static int C = 0; /* Current input character */
112 /* Force end of assembly */
115 /* List of dot keywords with the corresponding tokens */
117 const char* Key; /* MUST be first field */
122 { "ADDR", TOK_ADDR },
123 { "ALIGN", TOK_ALIGN },
125 { "ASCIIZ", TOK_ASCIIZ },
126 { "AUTOIMPORT", TOK_AUTOIMPORT },
127 { "BITAND", TOK_AND },
128 { "BITNOT", TOK_NOT },
130 { "BITXOR", TOK_XOR },
131 { "BLANK", TOK_BLANK },
134 { "BYTE", TOK_BYTE },
135 { "CASE", TOK_CASE },
136 { "CODE", TOK_CODE },
137 { "CONCAT", TOK_CONCAT },
138 { "CONDES", TOK_CONDES },
139 { "CONST", TOK_CONST },
140 { "CONSTRUCTOR", TOK_CONSTRUCTOR },
142 { "DATA", TOK_DATA },
144 { "DBYT", TOK_DBYT },
145 { "DEBUGINFO", TOK_DEBUGINFO },
146 { "DEF", TOK_DEFINED },
147 { "DEFINE", TOK_DEFINE },
148 { "DEFINED", TOK_DEFINED },
149 { "DESTRUCTOR", TOK_DESTRUCTOR },
150 { "DWORD", TOK_DWORD },
151 { "ELSE", TOK_ELSE },
152 { "ELSEIF", TOK_ELSEIF },
154 { "ENDIF", TOK_ENDIF },
155 { "ENDMAC", TOK_ENDMACRO },
156 { "ENDMACRO", TOK_ENDMACRO },
157 { "ENDPROC", TOK_ENDPROC },
158 { "ENDREP", TOK_ENDREP },
159 { "ENDREPEAT", TOK_ENDREP },
160 { "ERROR", TOK_ERROR },
161 { "EXITMAC", TOK_EXITMACRO },
162 { "EXITMACRO", TOK_EXITMACRO },
163 { "EXPORT", TOK_EXPORT },
164 { "EXPORTZP", TOK_EXPORTZP },
165 { "FARADDR", TOK_FARADDR },
166 { "FEATURE", TOK_FEATURE },
167 { "FILEOPT", TOK_FILEOPT },
168 { "FOPT", TOK_FILEOPT },
169 { "FORCEWORD", TOK_FORCEWORD },
170 { "GLOBAL", TOK_GLOBAL },
171 { "GLOBALZP", TOK_GLOBALZP },
175 { "IFBLANK", TOK_IFBLANK },
176 { "IFCONST", TOK_IFCONST },
177 { "IFDEF", TOK_IFDEF },
178 { "IFNBLANK", TOK_IFNBLANK },
179 { "IFNCONST", TOK_IFNCONST },
180 { "IFNDEF", TOK_IFNDEF },
181 { "IFNREF", TOK_IFNREF },
182 { "IFP02", TOK_IFP02 },
183 { "IFP816", TOK_IFP816 },
184 { "IFPC02", TOK_IFPC02 },
185 { "IFREF", TOK_IFREF },
186 { "IMPORT", TOK_IMPORT },
187 { "IMPORTZP", TOK_IMPORTZP },
188 { "INCBIN", TOK_INCBIN },
189 { "INCLUDE", TOK_INCLUDE },
190 { "LEFT", TOK_LEFT },
191 { "LINECONT", TOK_LINECONT },
192 { "LIST", TOK_LIST },
193 { "LISTBYTES", TOK_LISTBYTES },
194 { "LOCAL", TOK_LOCAL },
195 { "LOCALCHAR", TOK_LOCALCHAR },
196 { "MAC", TOK_MACRO },
197 { "MACPACK", TOK_MACPACK },
198 { "MACRO", TOK_MACRO },
199 { "MATCH", TOK_MATCH },
203 { "NULL", TOK_NULL },
208 { "P816", TOK_P816 },
209 { "PAGELEN", TOK_PAGELENGTH },
210 { "PAGELENGTH", TOK_PAGELENGTH },
211 { "PARAMCOUNT", TOK_PARAMCOUNT },
212 { "PC02", TOK_PC02 },
213 { "PROC", TOK_PROC },
214 { "REF", TOK_REFERENCED },
215 { "REFERENCED", TOK_REFERENCED },
216 { "RELOC", TOK_RELOC },
217 { "REPEAT", TOK_REPEAT },
219 { "RIGHT", TOK_RIGHT },
220 { "RODATA", TOK_RODATA },
221 { "SEGMENT", TOK_SEGMENT },
224 { "SMART", TOK_SMART },
225 { "STRAT", TOK_STRAT },
226 { "STRING", TOK_STRING },
227 { "STRLEN", TOK_STRLEN },
228 { "SUNPLUS", TOK_SUNPLUS },
229 { "TCOUNT", TOK_TCOUNT },
230 { "WARNING", TOK_WARNING },
231 { "WORD", TOK_WORD },
232 { "XMATCH", TOK_XMATCH },
234 { "ZEROPAGE", TOK_ZEROPAGE },
239 /*****************************************************************************/
241 /*****************************************************************************/
245 static void NextChar (void);
246 /* Read the next character from the input file */
250 /*****************************************************************************/
251 /* Character classification functions */
252 /*****************************************************************************/
256 static int IsIdChar (int C)
257 /* Return true if the character is a valid character for an identifier */
259 return IsAlNum (C) ||
261 (C == '@' && AtInIdents) ||
262 (C == '$' && DollarInIdents);
267 static int IsIdStart (int C)
268 /* Return true if the character may start an identifier */
270 return IsAlpha (C) || C == '_';
275 /*****************************************************************************/
277 /*****************************************************************************/
281 void NewInputFile (const char* Name)
282 /* Open a new input file */
287 /* First try to open the file */
288 F = fopen (Name, "r");
293 /* Error (fatal error if this is the main file) */
295 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
298 /* We are on include level. Search for the file in the include
301 PathName = FindInclude (Name);
302 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
303 /* Not found or cannot open, print an error and bail out */
304 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
307 /* Free the allocated memory */
312 /* check again if we do now have an open file */
317 /* Stat the file and remember the values */
319 if (fstat (fileno (F), &Buf) != 0) {
320 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
323 /* Add the file to the input file table and remember the index */
324 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
326 /* Create a new state variable and initialize it */
327 I = xmalloc (sizeof (*I));
331 I->Pos.Name = FileIdx;
336 /* Use the new file */
348 void DoneInputFile (void)
349 /* Close the current input file */
353 /* Restore the old token */
357 /* Save a pointer to the current struct, then set it back */
361 /* Cleanup the current stuff */
369 void NewInputData (const char* Data, int Malloced)
370 /* Add a chunk of input data to the input stream */
374 /* Create a new state variable and initialize it */
375 I = xmalloc (sizeof (*I));
378 I->Malloced = Malloced;
382 /* Use the new data */
392 static void DoneInputData (void)
393 /* End the current input data stream */
397 /* Restore the old token */
401 /* Save a pointer to the current struct, then set it back */
405 /* Cleanup the current stuff */
414 static unsigned DigitVal (unsigned char C)
415 /* Convert a digit into it's numerical representation */
420 return toupper (C) - 'A' + 10;
426 static void NextChar (void)
427 /* Read the next character from the input file */
429 /* If we have an input data structure, read from there */
434 /* End of input data, will set to last file char */
440 /* Check for end of line, read the next line if needed */
441 while (IFile->Line [IFile->Pos.Col] == '\0') {
443 /* End of current line reached, read next line */
444 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
445 /* End of file. Add an empty line to the listing. This is a
446 * small hack needed to keep the PC output in sync.
448 NewListingLine ("", IFile->Pos.Name, ICount);
457 /* Remember the new line for the listing */
458 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
462 /* Return the next character from the file */
463 C = IFile->Line [IFile->Pos.Col++];
470 void LocaseSVal (void)
471 /* Make SVal lower case */
475 SVal [I] = tolower (SVal [I]);
482 void UpcaseSVal (void)
483 /* Make SVal upper case */
487 SVal [I] = toupper (SVal [I]);
494 static int CmpDotKeyword (const void* K1, const void* K2)
495 /* Compare function for the dot keyword search */
497 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
502 static unsigned char FindDotKeyword (void)
503 /* Find the dot keyword in SVal. Return the corresponding token if found,
504 * return TOK_NONE if not found.
507 static const struct DotKeyword K = { SVal, 0 };
508 struct DotKeyword* R;
510 /* If we aren't in ignore case mode, we have to uppercase the keyword */
515 /* Search for the keyword */
516 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
517 sizeof (DotKeywords [0]), CmpDotKeyword);
527 static void ReadIdent (void)
528 /* Read an identifier from the current input position into Ident. It is
529 * assumed that the first character has already been checked.
532 /* Read the identifier */
535 if (I < MAX_STR_LEN) {
539 } while (IsIdChar (C));
542 /* If we should ignore case, convert the identifier to upper case */
550 static unsigned ReadStringConst (int StringTerm)
551 /* Read a string constant into SVal. Check for maximum string length and all
552 * other stuff. The length of the string is returned.
557 /* Skip the leading string terminator */
560 /* Read the string */
563 if (C == StringTerm) {
566 if (C == '\n' || C == EOF) {
567 Error (ERR_NEWLINE_IN_STRING);
571 /* Check for string length, print an error message once */
572 if (I == MAX_STR_LEN) {
573 Error (ERR_STRING_TOO_LONG);
574 } else if (I < MAX_STR_LEN) {
579 /* Skip the character */
583 /* Skip the trailing terminator */
586 /* Terminate the string */
587 if (I >= MAX_STR_LEN) {
592 /* Return the length of the string */
598 void NextRawTok (void)
599 /* Read the next raw token from the input stream */
601 /* If we've a forced end of assembly, don't read further */
608 /* Check if we have tokens from another input source */
609 if (InputFromStack ()) {
614 /* Skip whitespace, remember if we had some */
615 if ((WS = IsBlank (C)) != 0) {
618 } while (IsBlank (C));
621 /* If we're reading from the file, update the location from where the
622 * next token will be read. If we're reading from input data, keep the
629 /* Hex number or PC symbol? */
633 /* Hex digit must follow or DollarIsPC must be enabled */
639 Error (ERR_HEX_DIGIT_EXPECTED);
643 /* Read the number */
645 while (IsXDigit (C)) {
646 if (IVal & 0xF0000000) {
647 Error (ERR_NUM_OVERFLOW);
650 IVal = (IVal << 4) + DigitVal (C);
654 /* This is an integer constant */
663 /* 0 or 1 must follow */
665 Error (ERR_01_EXPECTED);
668 /* Read the number */
670 while (IsBDigit (C)) {
671 if (IVal & 0x80000000) {
672 Error (ERR_NUM_OVERFLOW);
675 IVal = (IVal << 1) + DigitVal (C);
679 /* This is an integer constant */
684 /* Decimal number? */
687 /* Read the number */
689 while (IsDigit (C)) {
690 if (IVal > (0xFFFFFFFF / 10)) {
691 Error (ERR_NUM_OVERFLOW);
694 IVal = (IVal * 10) + DigitVal (C);
698 /* This is an integer constant */
703 /* Control command? */
708 if (!IsIdStart (C)) {
709 Error (ERR_PSEUDO_EXPECTED);
710 /* Try to read an identifier */
714 /* Read the identifier */
717 /* Search the keyword */
718 Tok = FindDotKeyword ();
719 if (Tok == TOK_NONE) {
721 Error (ERR_PSEUDO_EXPECTED);
728 if (C == LocalStart) {
730 /* Read the identifier */
733 /* Start character alone is not enough */
734 if (SVal [1] == '\0') {
735 Error (ERR_IDENT_EXPECTED);
745 /* Identifier or keyword? */
748 /* Read the identifier */
751 /* Check for special names */
752 if (SVal [1] == '\0') {
753 switch (toupper (SVal [0])) {
777 /* Search for an opcode */
778 IVal = FindInstruction (SVal);
780 /* This is a mnemonic */
782 } else if (IsDefine (SVal)) {
783 /* This is a define style macro - expand it */
793 /* Ok, let's do the switch */
882 while (C != '\n' && C != EOF) {
917 } else if (C == '<') {
920 } else if (C == '>') {
943 } else if (C == '>') {
957 /* Hack: If we allow ' as terminating character for strings, read
958 * the following stuff as a string, and check for a one character
961 if (LooseStringTerm) {
962 if (ReadStringConst ('\'') == 1) {
969 /* Always a character constant */
971 if (C == '\n' || C == EOF) {
972 Error (ERR_ILLEGAL_CHARCON);
979 Error (ERR_ILLEGAL_CHARCON);
987 ReadStringConst ('\"');
992 /* Line continuation? */
996 /* Handle as white space */
1010 /* Check if we have any open .IFs in this file */
1012 /* Check if we have any open token lists in this file */
1015 /* If this was an include file, then close it and handle like a
1016 * separator. Do not close the main file, but return EOF.
1027 /* If we go here, we could not identify the current character. Skip it
1030 Error (ERR_INVALID_CHAR, C & 0xFF);
1037 int TokHasSVal (enum Token Tok)
1038 /* Return true if the given token has an attached SVal */
1040 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1045 int TokHasIVal (enum Token Tok)
1046 /* Return true if the given token has an attached IVal */
1048 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1053 int GetSubKey (const char** Keys, unsigned Count)
1054 /* Search for a subkey in a table of keywords. The current token must be an
1055 * identifier and all keys must be in upper case. The identifier will be
1056 * uppercased in the process. The function returns the index of the keyword,
1057 * or -1 if the keyword was not found.
1062 /* Must have an identifier */
1063 PRECONDITION (Tok == TOK_IDENT);
1065 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1070 /* Do a linear search (a binary search is not worth the effort) */
1071 for (I = 0; I < Count; ++I) {
1072 if (strcmp (SVal, Keys [I]) == 0) {
1084 void InitScanner (const char* InFile)
1085 /* Initialize the scanner, open the given input file */
1087 /* Open the input file */
1088 NewInputFile (InFile);
1093 void DoneScanner (void)
1094 /* Release scanner resources */