1 /*****************************************************************************/
5 /* The scanner for the ca65 macroassembler */
9 /* (C) 1998-2002 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 },
124 { ".AND", TOK_BAND },
125 { ".ASCIIZ", TOK_ASCIIZ },
126 { ".AUTOIMPORT", TOK_AUTOIMPORT },
127 { ".BITAND", TOK_AND },
128 { ".BITNOT", TOK_NOT },
129 { ".BITOR", TOK_OR },
130 { ".BITXOR", TOK_XOR },
131 { ".BLANK", TOK_BLANK },
133 { ".BYT", TOK_BYTE },
134 { ".BYTE", TOK_BYTE },
135 { ".CASE", TOK_CASE },
136 { ".CHARMAP", TOK_CHARMAP },
137 { ".CODE", TOK_CODE },
138 { ".CONCAT", TOK_CONCAT },
139 { ".CONDES", TOK_CONDES },
140 { ".CONST", TOK_CONST },
141 { ".CONSTRUCTOR", TOK_CONSTRUCTOR },
143 { ".DATA", TOK_DATA },
145 { ".DBYT", TOK_DBYT },
146 { ".DEBUGINFO", TOK_DEBUGINFO },
147 { ".DEF", TOK_DEFINED },
148 { ".DEFINE", TOK_DEFINE },
149 { ".DEFINED", TOK_DEFINED },
150 { ".DESTRUCTOR", TOK_DESTRUCTOR },
151 { ".DWORD", TOK_DWORD },
152 { ".ELSE", TOK_ELSE },
153 { ".ELSEIF", TOK_ELSEIF },
155 { ".ENDIF", TOK_ENDIF },
156 { ".ENDMAC", TOK_ENDMACRO },
157 { ".ENDMACRO", TOK_ENDMACRO },
158 { ".ENDPROC", TOK_ENDPROC },
159 { ".ENDREP", TOK_ENDREP },
160 { ".ENDREPEAT", TOK_ENDREP },
161 { ".ERROR", TOK_ERROR },
162 { ".EXITMAC", TOK_EXITMACRO },
163 { ".EXITMACRO", TOK_EXITMACRO },
164 { ".EXPORT", TOK_EXPORT },
165 { ".EXPORTZP", TOK_EXPORTZP },
166 { ".FARADDR", TOK_FARADDR },
167 { ".FEATURE", TOK_FEATURE },
168 { ".FILEOPT", TOK_FILEOPT },
169 { ".FOPT", TOK_FILEOPT },
170 { ".FORCEWORD", TOK_FORCEWORD },
171 { ".GLOBAL", TOK_GLOBAL },
172 { ".GLOBALZP", TOK_GLOBALZP },
176 { ".IFBLANK", TOK_IFBLANK },
177 { ".IFCONST", TOK_IFCONST },
178 { ".IFDEF", TOK_IFDEF },
179 { ".IFNBLANK", TOK_IFNBLANK },
180 { ".IFNCONST", TOK_IFNCONST },
181 { ".IFNDEF", TOK_IFNDEF },
182 { ".IFNREF", TOK_IFNREF },
183 { ".IFP02", TOK_IFP02 },
184 { ".IFP816", TOK_IFP816 },
185 { ".IFPC02", TOK_IFPC02 },
186 { ".IFREF", TOK_IFREF },
187 { ".IMPORT", TOK_IMPORT },
188 { ".IMPORTZP", TOK_IMPORTZP },
189 { ".INCBIN", TOK_INCBIN },
190 { ".INCLUDE", TOK_INCLUDE },
191 { ".LEFT", TOK_LEFT },
192 { ".LINECONT", TOK_LINECONT },
193 { ".LIST", TOK_LIST },
194 { ".LISTBYTES", TOK_LISTBYTES },
195 { ".LOCAL", TOK_LOCAL },
196 { ".LOCALCHAR", TOK_LOCALCHAR },
197 { ".MAC", TOK_MACRO },
198 { ".MACPACK", TOK_MACPACK },
199 { ".MACRO", TOK_MACRO },
200 { ".MATCH", TOK_MATCH },
203 { ".NOT", TOK_BNOT },
204 { ".NULL", TOK_NULL },
209 { ".P816", TOK_P816 },
210 { ".PAGELEN", TOK_PAGELENGTH },
211 { ".PAGELENGTH", TOK_PAGELENGTH },
212 { ".PARAMCOUNT", TOK_PARAMCOUNT },
213 { ".PC02", TOK_PC02 },
214 { ".POPSEG", TOK_POPSEG },
215 { ".PROC", TOK_PROC },
216 { ".PUSHSEG", TOK_PUSHSEG },
217 { ".REF", TOK_REFERENCED },
218 { ".REFERENCED", TOK_REFERENCED },
219 { ".RELOC", TOK_RELOC },
220 { ".REPEAT", TOK_REPEAT },
222 { ".RIGHT", TOK_RIGHT },
223 { ".RODATA", TOK_RODATA },
224 { ".SEGMENT", TOK_SEGMENT },
227 { ".SMART", TOK_SMART },
228 { ".STRAT", TOK_STRAT },
229 { ".STRING", TOK_STRING },
230 { ".STRLEN", TOK_STRLEN },
231 { ".SUNPLUS", TOK_SUNPLUS },
232 { ".TCOUNT", TOK_TCOUNT },
233 { ".TIME", TOK_TIME },
234 { ".WARNING", TOK_WARNING },
235 { ".WORD", TOK_WORD },
236 { ".XMATCH", TOK_XMATCH },
237 { ".XOR", TOK_BXOR },
238 { ".ZEROPAGE", TOK_ZEROPAGE },
243 /*****************************************************************************/
245 /*****************************************************************************/
249 static void NextChar (void);
250 /* Read the next character from the input file */
254 /*****************************************************************************/
255 /* Character classification functions */
256 /*****************************************************************************/
260 static int IsIdChar (int C)
261 /* Return true if the character is a valid character for an identifier */
263 return IsAlNum (C) ||
265 (C == '@' && AtInIdents) ||
266 (C == '$' && DollarInIdents);
271 static int IsIdStart (int C)
272 /* Return true if the character may start an identifier */
274 return IsAlpha (C) || C == '_';
279 /*****************************************************************************/
281 /*****************************************************************************/
285 void NewInputFile (const char* Name)
286 /* Open a new input file */
291 /* First try to open the file */
292 F = fopen (Name, "r");
297 /* Error (fatal error if this is the main file) */
299 Fatal (FAT_CANNOT_OPEN_INPUT, Name, strerror (errno));
302 /* We are on include level. Search for the file in the include
305 PathName = FindInclude (Name);
306 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
307 /* Not found or cannot open, print an error and bail out */
308 Error (ERR_CANNOT_OPEN_INCLUDE, Name, strerror (errno));
311 /* Free the allocated memory */
316 /* check again if we do now have an open file */
321 /* Stat the file and remember the values */
323 if (fstat (fileno (F), &Buf) != 0) {
324 Fatal (FAT_CANNOT_STAT_INPUT, Name, strerror (errno));
327 /* Add the file to the input file table and remember the index */
328 FileIdx = AddFile (Name, Buf.st_size, Buf.st_mtime);
330 /* Create a new state variable and initialize it */
331 I = xmalloc (sizeof (*I));
335 I->Pos.Name = FileIdx;
340 /* Use the new file */
352 void DoneInputFile (void)
353 /* Close the current input file */
357 /* Restore the old token */
361 /* Save a pointer to the current struct, then set it back */
365 /* Cleanup the current stuff */
373 void NewInputData (const char* Data, int Malloced)
374 /* Add a chunk of input data to the input stream */
378 /* Create a new state variable and initialize it */
379 I = xmalloc (sizeof (*I));
382 I->Malloced = Malloced;
386 /* Use the new data */
396 static void DoneInputData (void)
397 /* End the current input data stream */
401 /* Restore the old token */
405 /* Save a pointer to the current struct, then set it back */
409 /* Cleanup the current stuff */
418 static unsigned DigitVal (unsigned char C)
419 /* Convert a digit into it's numerical representation */
424 return toupper (C) - 'A' + 10;
430 static void NextChar (void)
431 /* Read the next character from the input file */
433 /* If we have an input data structure, read from there */
438 /* End of input data, will set to last file char */
444 /* Check for end of line, read the next line if needed */
445 while (IFile->Line [IFile->Pos.Col] == '\0') {
447 /* End of current line reached, read next line */
448 if (fgets (IFile->Line, sizeof (IFile->Line), IFile->F) == 0) {
449 /* End of file. Add an empty line to the listing. This is a
450 * small hack needed to keep the PC output in sync.
452 NewListingLine ("", IFile->Pos.Name, ICount);
461 /* Remember the new line for the listing */
462 NewListingLine (IFile->Line, IFile->Pos.Name, ICount);
466 /* Return the next character from the file */
467 C = IFile->Line [IFile->Pos.Col++];
474 void LocaseSVal (void)
475 /* Make SVal lower case */
479 SVal [I] = tolower (SVal [I]);
486 void UpcaseSVal (void)
487 /* Make SVal upper case */
491 SVal [I] = toupper (SVal [I]);
498 static int CmpDotKeyword (const void* K1, const void* K2)
499 /* Compare function for the dot keyword search */
501 return strcmp (((struct DotKeyword*)K1)->Key, ((struct DotKeyword*)K2)->Key);
506 static unsigned char FindDotKeyword (void)
507 /* Find the dot keyword in SVal. Return the corresponding token if found,
508 * return TOK_NONE if not found.
511 static const struct DotKeyword K = { SVal, 0 };
512 struct DotKeyword* R;
514 /* If we aren't in ignore case mode, we have to uppercase the keyword */
519 /* Search for the keyword */
520 R = bsearch (&K, DotKeywords, sizeof (DotKeywords) / sizeof (DotKeywords [0]),
521 sizeof (DotKeywords [0]), CmpDotKeyword);
531 static void ReadIdent (unsigned Index)
532 /* Read an identifier from the current input position into Ident. Filling SVal
533 * starts at Index with the current character in C. It is assumed that any
534 * characters already filled in are ok, and the character in C is checked.
537 /* Read the identifier */
539 if (Index < MAX_STR_LEN) {
543 } while (IsIdChar (C));
546 /* If we should ignore case, convert the identifier to upper case */
554 static unsigned ReadStringConst (int StringTerm)
555 /* Read a string constant into SVal. Check for maximum string length and all
556 * other stuff. The length of the string is returned.
561 /* Skip the leading string terminator */
564 /* Read the string */
567 if (C == StringTerm) {
570 if (C == '\n' || C == EOF) {
571 Error (ERR_NEWLINE_IN_STRING);
575 /* Check for string length, print an error message once */
576 if (I == MAX_STR_LEN) {
577 Error (ERR_STRING_TOO_LONG);
578 } else if (I < MAX_STR_LEN) {
583 /* Skip the character */
587 /* Skip the trailing terminator */
590 /* Terminate the string */
591 if (I >= MAX_STR_LEN) {
596 /* Return the length of the string */
602 void NextRawTok (void)
603 /* Read the next raw token from the input stream */
605 /* If we've a forced end of assembly, don't read further */
612 /* Check if we have tokens from another input source */
613 if (InputFromStack ()) {
618 /* Skip whitespace, remember if we had some */
619 if ((WS = IsBlank (C)) != 0) {
622 } while (IsBlank (C));
625 /* If we're reading from the file, update the location from where the
626 * next token will be read. If we're reading from input data, keep the
633 /* Hex number or PC symbol? */
637 /* Hex digit must follow or DollarIsPC must be enabled */
643 Error (ERR_HEX_DIGIT_EXPECTED);
647 /* Read the number */
649 while (IsXDigit (C)) {
650 if (IVal & 0xF0000000) {
651 Error (ERR_NUM_OVERFLOW);
654 IVal = (IVal << 4) + DigitVal (C);
658 /* This is an integer constant */
667 /* 0 or 1 must follow */
669 Error (ERR_01_EXPECTED);
672 /* Read the number */
674 while (IsBDigit (C)) {
675 if (IVal & 0x80000000) {
676 Error (ERR_NUM_OVERFLOW);
679 IVal = (IVal << 1) + DigitVal (C);
683 /* This is an integer constant */
688 /* Decimal number? */
691 /* Read the number */
693 while (IsDigit (C)) {
694 if (IVal > (long) (0xFFFFFFFFUL / 10)) {
695 Error (ERR_NUM_OVERFLOW);
698 IVal = (IVal * 10) + DigitVal (C);
702 /* This is an integer constant */
707 /* Control command? */
710 /* Remember and skip the dot */
714 /* Check if it's just a dot */
715 if (!IsIdStart (C)) {
722 /* Read the remainder of the identifier */
725 /* Dot keyword, search for it */
726 Tok = FindDotKeyword ();
727 if (Tok == TOK_NONE) {
729 if (LeadingDotInIdents) {
730 /* An identifier with a dot */
733 /* Invalid pseudo instruction */
734 Error (ERR_PSEUDO_EXPECTED);
744 if (C == LocalStart) {
746 /* Read the identifier */
749 /* Start character alone is not enough */
750 if (SVal [1] == '\0') {
751 Error (ERR_IDENT_EXPECTED);
761 /* Identifier or keyword? */
764 /* Read the identifier */
767 /* Check for special names */
768 if (SVal [1] == '\0') {
769 switch (toupper (SVal [0])) {
793 /* Search for an opcode */
794 IVal = FindInstruction (SVal);
796 /* This is a mnemonic */
798 } else if (IsDefine (SVal)) {
799 /* This is a define style macro - expand it */
809 /* Ok, let's do the switch */
898 while (C != '\n' && C != EOF) {
933 } else if (C == '<') {
936 } else if (C == '>') {
959 } else if (C == '>') {
973 /* Hack: If we allow ' as terminating character for strings, read
974 * the following stuff as a string, and check for a one character
977 if (LooseStringTerm) {
978 if (ReadStringConst ('\'') == 1) {
985 /* Always a character constant */
987 if (C == '\n' || C == EOF) {
988 Error (ERR_ILLEGAL_CHARCON);
995 Error (ERR_ILLEGAL_CHARCON);
1003 ReadStringConst ('\"');
1008 /* Line continuation? */
1012 /* Handle as white space */
1026 /* Check if we have any open .IFs in this file */
1028 /* Check if we have any open token lists in this file */
1031 /* If this was an include file, then close it and handle like a
1032 * separator. Do not close the main file, but return EOF.
1043 /* If we go here, we could not identify the current character. Skip it
1046 Error (ERR_INVALID_CHAR, C & 0xFF);
1053 int TokHasSVal (enum Token Tok)
1054 /* Return true if the given token has an attached SVal */
1056 return (Tok == TOK_IDENT || Tok == TOK_STRCON);
1061 int TokHasIVal (enum Token Tok)
1062 /* Return true if the given token has an attached IVal */
1064 return (Tok == TOK_INTCON || Tok == TOK_CHARCON || Tok == TOK_MNEMO);
1069 int GetSubKey (const char** Keys, unsigned Count)
1070 /* Search for a subkey in a table of keywords. The current token must be an
1071 * identifier and all keys must be in upper case. The identifier will be
1072 * uppercased in the process. The function returns the index of the keyword,
1073 * or -1 if the keyword was not found.
1078 /* Must have an identifier */
1079 PRECONDITION (Tok == TOK_IDENT);
1081 /* If we aren't in ignore case mode, we have to uppercase the identifier */
1086 /* Do a linear search (a binary search is not worth the effort) */
1087 for (I = 0; I < Count; ++I) {
1088 if (strcmp (SVal, Keys [I]) == 0) {
1100 void InitScanner (const char* InFile)
1101 /* Initialize the scanner, open the given input file */
1103 /* Open the input file */
1104 NewInputFile (InFile);
1109 void DoneScanner (void)
1110 /* Release scanner resources */