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 /*****************************************************************************/
57 /*****************************************************************************/
59 /*****************************************************************************/
63 enum Token Tok = TOK_NONE; /* Current token */
64 int WS; /* Flag: Whitespace before token */
65 long IVal; /* Integer token attribute */
66 char SVal [MAX_STR_LEN+1]; /* String token attribute */
68 FilePos CurPos = { 0, 0, 0 }; /* Name and position in current file */
72 /* Struct to handle include files. Note: The length of the input line may
73 * not exceed 255+1, since the column is stored in the file position struct
74 * as a character. Increasing this value means changing the FilePos struct,
75 * and the read and write routines in the assembler and linker.
77 typedef struct InputFile_ InputFile;
79 FILE* F; /* Input file descriptor */
80 FilePos Pos; /* Position in file */
81 enum Token Tok; /* Last token */
82 int C; /* Last character */
83 char Line[256]; /* The current input line */
84 InputFile* Next; /* Linked list of input files */
87 /* Struct to handle textual input data */
88 typedef struct InputData_ InputData;
90 const char* Data; /* Pointer to the data */
91 const char* Pos; /* Pointer to current position */
92 int Malloced; /* Memory was malloced */
93 enum Token Tok; /* Last token */
94 int C; /* Last character */
95 InputData* Next; /* Linked list of input data */
98 /* List of input files */
100 unsigned long MTime; /* Time of last modification */
101 unsigned long Size; /* Size of file */
102 const char* Name; /* Name of file */
103 } Files [MAX_INPUT_FILES];
104 static unsigned FileCount = 0;
106 /* Current input variables */
107 static InputFile* IFile = 0;
108 static InputData* IData = 0;
109 static unsigned ICount = 0; /* Count of input files */
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 },
133 { "BYTE", TOK_BYTE },
134 { "CASE", TOK_CASE },
135 { "CODE", TOK_CODE },
136 { "CONST", TOK_CONST },
138 { "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 { "GLOBAL", TOK_GLOBAL },
164 { "GLOBALZP", TOK_GLOBALZP },
168 { "IFBLANK", TOK_IFBLANK },
169 { "IFCONST", TOK_IFCONST },
170 { "IFDEF", TOK_IFDEF },
171 { "IFNBLANK", TOK_IFNBLANK },
172 { "IFNCONST", TOK_IFNCONST },
173 { "IFNDEF", TOK_IFNDEF },
174 { "IFNREF", TOK_IFNREF },
175 { "IFP02", TOK_IFP02 },
176 { "IFP816", TOK_IFP816 },
177 { "IFPC02", TOK_IFPC02 },
178 { "IFREF", TOK_IFREF },
179 { "IMPORT", TOK_IMPORT },
180 { "IMPORTZP", TOK_IMPORTZP },
181 { "INCBIN", TOK_INCBIN },
182 { "INCLUDE", TOK_INCLUDE },
183 { "LINECONT", TOK_LINECONT },
184 { "LIST", TOK_LIST },
185 { "LISTBYTES", TOK_LISTBYTES },
186 { "LOCAL", TOK_LOCAL },
187 { "LOCALCHAR", TOK_LOCALCHAR },
188 { "MAC", TOK_MACRO },
189 { "MACPACK", TOK_MACPACK },
190 { "MACRO", TOK_MACRO },
191 { "MATCH", TOK_MATCH },
194 { "NULL", TOK_NULL },
199 { "P816", TOK_P816 },
200 { "PAGELEN", TOK_PAGELENGTH },
201 { "PAGELENGTH", TOK_PAGELENGTH },
202 { "PARAMCOUNT", TOK_PARAMCOUNT },
203 { "PC02", TOK_PC02 },
204 { "PROC", TOK_PROC },
205 { "REF", TOK_REFERENCED },
206 { "REFERENCED", TOK_REFERENCED },
207 { "RELOC", TOK_RELOC },
208 { "REPEAT", TOK_REPEAT },
210 { "RODATA", TOK_RODATA },
211 { "SEGMENT", TOK_SEGMENT },
214 { "SMART", TOK_SMART },
215 { "STRING", TOK_STRING },
216 { "SUNPLUS", TOK_SUNPLUS },
217 { "WORD", TOK_WORD },
218 { "XMATCH", TOK_XMATCH },
220 { "ZEROPAGE", TOK_ZEROPAGE },
225 /*****************************************************************************/
227 /*****************************************************************************/
231 static void NextChar (void);
232 /* Read the next character from the input file */
236 /*****************************************************************************/
237 /* Character classification functions */
238 /*****************************************************************************/
242 static int IsBlank (int C)
243 /* Return true if the character is a blank or tab */
245 return (C == ' ' || C == '\t');
250 static int IsDigit (int C)
251 /* Return true if the character is a digit */
258 static int IsXDigit (int C)
259 /* Return true if the character is a hexadecimal digit */
266 static int IsDDigit (int C)
267 /* Return true if the character is a dual digit */
269 return (C == '0' || C == '1');
274 static int IsIdChar (int C)
275 /* Return true if the character is a valid character for an identifier */
277 return isalnum (C) ||
279 (C == '@' && AtInIdents) ||
280 (C == '$' && DollarInIdents);
285 static int IsIdStart (int C)
286 /* Return true if the character may start an identifier */
288 return isalpha (C) || C == '_';
293 /*****************************************************************************/
295 /*****************************************************************************/
299 const char* GetFileName (unsigned char Name)
300 /* Get the name of a file where the name index is known */
302 PRECONDITION (Name <= FileCount);
304 /* Name was defined outside any file scope, use the name of the first
305 * file instead. Errors are then reported with a file position of
306 * line zero in the first file.
308 if (FileCount == 0) {
309 /* No files defined until now */
310 return "(outside file scope)";
312 return Files [0].Name;
315 return Files [Name-1].Name;
321 void NewInputFile (const char* Name)
322 /* Open a new input file */
327 /* Check for nested include overflow */
328 if (FileCount >= MAX_INPUT_FILES) {
329 Fatal (FAT_MAX_INPUT_FILES);
332 /* First try to open the file */
333 F = fopen (Name, "r");
338 /* Error (fatal error if this is the main file) */
340 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
343 /* We are on include level. Search for the file in the include
346 PathName = FindInclude (Name);
347 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
348 /* Not found or cannot open, print an error and bail out */
349 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
352 /* Free the allocated memory */
357 /* check again if we do now have an open file */
360 /* Stat the file and remember the values */
362 if (fstat (fileno (F), &Buf) != 0) {
363 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
365 Files [FileCount].MTime = Buf.st_mtime;
366 Files [FileCount].Size = Buf.st_size;
367 Files [FileCount].Name = StrDup (Name);
370 /* Create a new state variable and initialize it */
371 I = Xmalloc (sizeof (*I));
375 I->Pos.Name = FileCount;
380 /* Use the new file */
392 void DoneInputFile (void)
393 /* Close the current input file */
397 /* Restore the old token */
401 /* Save a pointer to the current struct, then set it back */
405 /* Cleanup the current stuff */
413 void NewInputData (const char* Data, int Malloced)
414 /* Add a chunk of input data to the input stream */
418 /* Create a new state variable and initialize it */
419 I = Xmalloc (sizeof (*I));
422 I->Malloced = Malloced;
426 /* Use the new data */
436 static void DoneInputData (void)
437 /* End the current input data stream */
441 /* Restore the old token */
445 /* Save a pointer to the current struct, then set it back */
449 /* Cleanup the current stuff */
458 static unsigned DigitVal (unsigned char C)
459 /* Convert a digit into it's numerical representation */
464 return toupper (C) - 'A' + 10;
470 static void NextChar (void)
471 /* Read the next character from the input file */
473 /* If we have an input data structure, read from there */
478 /* End of input data, will set to last file char */
484 /* Check for end of line, read the next line if needed */
485 while (IFile->Line [IFile->Pos.Col] == '\0') {
487 /* End of current line reached, read next line */
488 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
489 /* End of file. Add an empty line to the listing. This is a
490 * small hack needed to keep the PC output in sync.
492 NewListingLine ("", IFile->Pos.Name, ICount);
501 /* Remember the new line for the listing */
502 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
506 /* Return the next character from the file */
507 C = IFile->Line [IFile->Pos.Col++];
514 void UpcaseSVal (void)
515 /* Make SVal upper case */
519 SVal [I] = toupper (SVal [I]);
526 static int CmpDotKeyword (const void* K1, const void* K2)
527 /* Compare function for the dot keyword search */
529 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
534 static unsigned char FindDotKeyword (void)
535 /* Find the dot keyword in SVal. Return the corresponding token if found,
536 * return TOK_NONE if not found.
539 static const struct DotKeyword K = { SVal, 0 };
540 struct DotKeyword* R;
542 /* If we aren't in ignore case mode, we have to uppercase the keyword */
547 /* Search for the keyword */
548 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
549 sizeof (DotKeywords [0]), CmpDotKeyword);
559 static void ReadIdent (void)
560 /* Read an identifier from the current input position into Ident. It is
561 * assumed that the first character has already been checked.
564 /* Read the identifier */
567 if (I < MAX_STR_LEN) {
571 } while (IsIdChar (C));
574 /* If we should ignore case, convert the identifier to upper case */
582 static unsigned ReadStringConst (int StringTerm)
583 /* Read a string constant into SVal. Check for maximum string length and all
584 * other stuff. The length of the string is returned.
589 /* Skip the leading string terminator */
592 /* Read the string */
595 if (C == StringTerm) {
598 if (C == '\n' || C == EOF) {
599 Error (ERR_NEWLINE_IN_STRING);
603 /* Check for string length, print an error message once */
604 if (I == MAX_STR_LEN) {
605 Error (ERR_STRING_TOO_LONG);
606 } else if (I < MAX_STR_LEN) {
611 /* Skip the character */
615 /* Skip the trailing terminator */
618 /* Terminate the string */
619 if (I >= MAX_STR_LEN) {
624 /* Return the length of the string */
631 /* Read the next raw token from the input stream */
633 /* If we've a forced end of assembly, don't read further */
639 /* If we're expanding a macro, the tokens come from the macro expansion */
645 /* Skip whitespace, remember if we had some */
646 if ((WS = IsBlank (C)) != 0) {
649 } while (IsBlank (C));
652 /* If we're reading from the file, update the location from where the
653 * next token will be read. If we're reading from input data, keep the
660 /* Hex number or PC symbol? */
664 /* Hex digit must follow or DollarIsPC must be enabled */
670 Error (ERR_HEX_DIGIT_EXPECTED);
674 /* Read the number */
676 while (IsXDigit (C)) {
677 if (IVal & 0xF0000000) {
678 Error (ERR_NUM_OVERFLOW);
681 IVal = (IVal << 4) + DigitVal (C);
685 /* This is an integer constant */
694 /* 0 or 1 must follow */
696 Error (ERR_01_EXPECTED);
699 /* Read the number */
701 while (IsDDigit (C)) {
702 if (IVal & 0x80000000) {
703 Error (ERR_NUM_OVERFLOW);
706 IVal = (IVal << 1) + DigitVal (C);
710 /* This is an integer constant */
715 /* Decimal number? */
718 /* Read the number */
720 while (IsDigit (C)) {
721 if (IVal > (0xFFFFFFFF / 10)) {
722 Error (ERR_NUM_OVERFLOW);
725 IVal = (IVal * 10) + DigitVal (C);
729 /* This is an integer constant */
734 /* Control command? */
739 if (!IsIdStart (C)) {
740 Error (ERR_PSEUDO_EXPECTED);
741 /* Try to read an identifier */
745 /* Read the identifier */
748 /* Search the keyword */
749 Tok = FindDotKeyword ();
750 if (Tok == TOK_NONE) {
752 Error (ERR_PSEUDO_EXPECTED);
759 if (C == LocalStart) {
761 /* Read the identifier */
764 /* Start character alone is not enough */
765 if (SVal [1] == '\0') {
766 Error (ERR_IDENT_EXPECTED);
776 /* Identifier or keyword? */
779 /* Read the identifier */
782 /* Check for special names */
783 if (SVal [1] == '\0') {
784 switch (toupper (SVal [0])) {
808 /* Search for an opcode */
809 IVal = FindInstruction (SVal);
811 /* This is a mnemonic */
813 } else if (IsDefine (SVal)) {
814 /* This is a define style macro - expand it */
826 /* Ok, let's do the switch */
915 while (C != '\n' && C != EOF) {
950 } else if (C == '<') {
953 } else if (C == '>') {
976 } else if (C == '>') {
990 /* Hack: If we allow ' as terminating character for strings, read
991 * the following stuff as a string, and check for a one character
994 if (LooseStringTerm) {
995 if (ReadStringConst ('\'') == 1) {
1002 /* Always a character constant */
1004 if (C == '\n' || C == EOF) {
1005 Error (ERR_ILLEGAL_CHARCON);
1012 Error (ERR_ILLEGAL_CHARCON);
1020 ReadStringConst ('\"');
1025 /* Line continuation? */
1029 /* Handle as white space */
1043 /* Check if we have any open .IFs in this file */
1046 /* If this was an include file, then close it and handle like a
1047 * separator. Do not close the main file, but return EOF.
1058 /* If we go here, we could not identify the current character. Skip it
1061 Error (ERR_INVALID_CHAR, C & 0xFF);
1068 void Consume (enum Token Expected, unsigned ErrMsg)
1069 /* Consume Expected, print an error if we don't find it */
1071 if (Tok == Expected) {
1080 void ConsumeSep (void)
1081 /* Consume a separator token */
1083 /* Accept an EOF as separator */
1084 if (Tok != TOK_EOF) {
1085 if (Tok != TOK_SEP) {
1086 Error (ERR_TOO_MANY_CHARS);
1096 void ConsumeLParen (void)
1097 /* Consume a left paren */
1099 Consume (TOK_LPAREN, ERR_LPAREN_EXPECTED);
1104 void ConsumeRParen (void)
1105 /* Consume a right paren */
1107 Consume (TOK_RPAREN, ERR_RPAREN_EXPECTED);
1112 void ConsumeComma (void)
1113 /* Consume a comma */
1115 Consume (TOK_COMMA, ERR_COMMA_EXPECTED);
1120 void SkipUntilSep (void)
1121 /* Skip tokens until we reach a line separator */
1123 while (Tok != TOK_SEP && Tok != TOK_EOF) {
1130 int TokHasSVal (enum Token Tok)
1131 /* Return true if the given token has an attached SVal */
1133 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1138 int TokHasIVal (enum Token Tok)
1139 /* Return true if the given token has an attached IVal */
1141 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1146 int GetSubKey (const char** Keys, unsigned Count)
1147 /* Search for a subkey in a table of keywords. The current token must be an
1148 * identifier and all keys must be in upper case. The identifier will be
1149 * uppercased in the process. The function returns the index of the keyword,
1150 * or -1 if the keyword was not found.
1155 /* Must have an identifier */
1156 PRECONDITION (Tok == TOK_IDENT);
1158 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1163 /* Do a linear search (a binary search is not worth the effort) */
1164 for (I = 0; I < Count; ++I) {
1165 if (strcmp (SVal, Keys [I]) == 0) {
1177 void WriteFiles (void)
1178 /* Write the list of input files to the object file */
1182 /* Tell the obj file module that we're about to start the file list */
1185 /* Write the file count */
1186 ObjWrite8 (FileCount);
1188 /* Write the file data */
1189 for (I = 0; I < FileCount; ++I) {
1190 ObjWrite32 (Files [I].MTime);
1191 ObjWrite32 (Files [I].Size);
1192 ObjWriteStr (Files [I].Name);
1195 /* Done writing files */
1201 void InitScanner (const char* InFile)
1202 /* Initialize the scanner, open the given input file */
1204 /* Open the input file */
1205 NewInputFile (InFile);
1210 void DoneScanner (void)
1211 /* Release scanner resources */