1 /*****************************************************************************/
5 /* Pseudo instructions for the ca65 macroassembler */
9 /* (C) 1998-2011, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
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 */
45 #include "assertion.h"
84 /*****************************************************************************/
86 /*****************************************************************************/
90 /* Keyword we're about to handle */
91 static StrBuf Keyword = STATIC_STRBUF_INITIALIZER;
94 static IntStack CPUStack = STATIC_INTSTACK_INITIALIZER;
97 #define MAX_PUSHED_SEGMENTS 16
98 static Collection SegStack = STATIC_COLLECTION_INITIALIZER;
102 /*****************************************************************************/
104 /*****************************************************************************/
108 static void DoUnexpected (void);
109 /* Got an unexpected keyword */
111 static void DoInvalid (void);
112 /* Handle a token that is invalid here, since it should have been handled on
113 * a much lower level of the expression hierarchy. Getting this sort of token
114 * means that the lower level code has bugs.
115 * This function differs to DoUnexpected in that the latter may be triggered
116 * by the user by using keywords in the wrong location. DoUnexpected is not
117 * an error in the assembler itself, while DoInvalid is.
122 /*****************************************************************************/
123 /* Helper functions */
124 /*****************************************************************************/
128 static unsigned char OptionalAddrSize (void)
129 /* If a colon follows, parse an optional address size spec and return it.
130 * Otherwise return ADDR_SIZE_DEFAULT.
133 unsigned AddrSize = ADDR_SIZE_DEFAULT;
134 if (CurTok.Tok == TOK_COLON) {
136 AddrSize = ParseAddrSize ();
137 if (!ValidAddrSizeForCPU (AddrSize)) {
138 /* Print an error and reset to default */
139 Error ("Invalid address size specification for current CPU");
140 AddrSize = ADDR_SIZE_DEFAULT;
149 static void SetBoolOption (unsigned char* Flag)
150 /* Read a on/off/+/- option and set flag accordingly */
152 static const char* Keys[] = {
157 if (CurTok.Tok == TOK_PLUS) {
160 } else if (CurTok.Tok == TOK_MINUS) {
163 } else if (CurTok.Tok == TOK_IDENT) {
164 /* Map the keyword to a number */
165 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
166 case 0: *Flag = 0; NextTok (); break;
167 case 1: *Flag = 1; NextTok (); break;
168 default: ErrorSkip ("`on' or `off' expected"); break;
170 } else if (TokIsSep (CurTok.Tok)) {
171 /* Without anything assume switch on */
174 ErrorSkip ("`on' or `off' expected");
180 static void ExportWithAssign (SymEntry* Sym, unsigned char AddrSize, unsigned Flags)
181 /* Allow to assign the value of an export in an .export statement */
183 /* The name and optional address size spec may be followed by an assignment
186 if (CurTok.Tok == TOK_ASSIGN || CurTok.Tok == TOK_EQ) {
188 /* Assignment means the symbol is a label */
189 if (CurTok.Tok == TOK_ASSIGN) {
193 /* Skip the assignment token */
196 /* Define the symbol with the expression following the '=' */
197 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
201 /* Now export the symbol */
202 SymExport (Sym, AddrSize, Flags);
207 static void ExportImport (void (*Func) (SymEntry*, unsigned char, unsigned),
208 unsigned char DefAddrSize, unsigned Flags)
209 /* Export or import symbols */
212 unsigned char AddrSize;
216 /* We need an identifier here */
217 if (CurTok.Tok != TOK_IDENT) {
218 ErrorSkip ("Identifier expected");
222 /* Find the symbol table entry, allocate a new one if necessary */
223 Sym = SymFind (CurrentScope, &CurTok.SVal, SYM_ALLOC_NEW);
228 /* Get an optional address size */
229 AddrSize = OptionalAddrSize ();
230 if (AddrSize == ADDR_SIZE_DEFAULT) {
231 AddrSize = DefAddrSize;
234 /* Call the actual import/export function */
235 Func (Sym, AddrSize, Flags);
238 if (CurTok.Tok == TOK_COMMA) {
248 static long IntArg (long Min, long Max)
249 /* Read an integer argument and check a range. Accept the token "unlimited"
250 * and return -1 in this case.
253 if (CurTok.Tok == TOK_IDENT && SB_CompareStr (&CurTok.SVal, "unlimited") == 0) {
257 long Val = ConstExpression ();
258 if (Val < Min || Val > Max) {
259 Error ("Range error");
268 static void ConDes (const StrBuf* Name, unsigned Type)
269 /* Parse remaining line for constructor/destructor of the remaining type */
274 /* Find the symbol table entry, allocate a new one if necessary */
275 SymEntry* Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW);
277 /* Optional constructor priority */
278 if (CurTok.Tok == TOK_COMMA) {
279 /* Priority value follows */
281 Prio = ConstExpression ();
282 if (Prio < CD_PRIO_MIN || Prio > CD_PRIO_MAX) {
283 /* Value out of range */
284 Error ("Range error");
288 /* Use the default priority value */
292 /* Define the symbol */
293 SymConDes (Sym, ADDR_SIZE_DEFAULT, Type, (unsigned) Prio);
298 /*****************************************************************************/
299 /* Handler functions */
300 /*****************************************************************************/
304 static void DoA16 (void)
305 /* Switch the accu to 16 bit mode (assembler only) */
307 if (GetCPU() != CPU_65816) {
308 Error ("Command is only valid in 65816 mode");
310 /* Immidiate mode has two extension bytes */
311 ExtBytes [AM65I_IMM_ACCU] = 2;
317 static void DoA8 (void)
318 /* Switch the accu to 8 bit mode (assembler only) */
320 if (GetCPU() != CPU_65816) {
321 Error ("Command is only valid in 65816 mode");
323 /* Immidiate mode has one extension byte */
324 ExtBytes [AM65I_IMM_ACCU] = 1;
330 static void DoAddr (void)
331 /* Define addresses */
334 if (GetCPU() == CPU_65816) {
335 EmitWord (GenWordExpr (Expression ()));
337 /* Do a range check */
338 EmitWord (Expression ());
340 if (CurTok.Tok != TOK_COMMA) {
350 static void DoAlign (void)
351 /* Align the PC to some boundary */
357 /* Read the alignment value */
358 Align = ConstExpression ();
359 if (Align <= 0 || Align > 0x10000) {
360 ErrorSkip ("Range error");
364 /* Optional value follows */
365 if (CurTok.Tok == TOK_COMMA) {
367 Val = ConstExpression ();
368 /* We need a byte value here */
369 if (!IsByteRange (Val)) {
370 ErrorSkip ("Range error");
377 /* Check if the alignment is a power of two */
378 Bit = BitFind (Align);
379 if (Align != (0x01L << Bit)) {
380 Error ("Alignment value must be a power of 2");
382 SegAlign (Bit, (int) Val);
388 static void DoASCIIZ (void)
389 /* Define text with a zero terminator */
392 /* Must have a string constant */
393 if (CurTok.Tok != TOK_STRCON) {
394 ErrorSkip ("String constant expected");
398 /* Translate into target charset and emit */
399 TgtTranslateStrBuf (&CurTok.SVal);
400 EmitStrBuf (&CurTok.SVal);
402 if (CurTok.Tok == TOK_COMMA) {
413 static void DoAssert (void)
414 /* Add an assertion */
416 static const char* ActionTab [] = {
419 "LDWARN", "LDWARNING",
426 /* First we have the expression that has to evaluated */
427 ExprNode* Expr = Expression ();
431 if (CurTok.Tok != TOK_IDENT) {
432 ErrorSkip ("Identifier expected");
435 switch (GetSubKey (ActionTab, sizeof (ActionTab) / sizeof (ActionTab[0]))) {
440 Action = ASSERT_ACT_WARN;
445 Action = ASSERT_ACT_ERROR;
451 Action = ASSERT_ACT_LDWARN;
456 Action = ASSERT_ACT_LDERROR;
460 Error ("Illegal assert action specifier");
461 /* Use lderror - there won't be an .o file anyway */
462 Action = ASSERT_ACT_LDERROR;
468 /* We can have an optional message. If no message is present, use
469 * "Assertion failed".
471 if (CurTok.Tok == TOK_COMMA) {
476 /* Read the message */
477 if (CurTok.Tok != TOK_STRCON) {
478 ErrorSkip ("String constant expected");
482 /* Translate the message into a string id. We can then skip the input
485 Msg = GetStrBufId (&CurTok.SVal);
490 /* Use "Assertion failed" */
491 Msg = GetStringId ("Assertion failed");
495 /* Remember the assertion */
496 AddAssertion (Expr, (AssertAction) Action, Msg);
501 static void DoAutoImport (void)
502 /* Mark unresolved symbols as imported */
504 SetBoolOption (&AutoImport);
508 static void DoBankBytes (void)
509 /* Define bytes, extracting the bank byte from each expression in the list */
512 EmitByte (FuncBankByte ());
513 if (CurTok.Tok != TOK_COMMA) {
523 static void DoBss (void)
524 /* Switch to the BSS segment */
531 static void DoByte (void)
535 if (CurTok.Tok == TOK_STRCON) {
536 /* A string, translate into target charset and emit */
537 TgtTranslateStrBuf (&CurTok.SVal);
538 EmitStrBuf (&CurTok.SVal);
541 EmitByte (Expression ());
543 if (CurTok.Tok != TOK_COMMA) {
547 /* Do smart handling of dangling comma */
548 if (CurTok.Tok == TOK_SEP) {
549 Error ("Unexpected end of line");
558 static void DoCase (void)
559 /* Switch the IgnoreCase option */
561 SetBoolOption (&IgnoreCase);
562 IgnoreCase = !IgnoreCase;
567 static void DoCharMap (void)
568 /* Allow custome character mappings */
573 /* Read the index as numerical value */
574 Index = ConstExpression ();
575 if (Index < 0 || Index > 255) {
576 /* Value out of range */
577 ErrorSkip ("Range error");
584 /* Read the character code */
585 Code = ConstExpression ();
586 if (Code < 0 || Code > 255) {
587 /* Value out of range */
588 ErrorSkip ("Range error");
592 /* Set the character translation */
593 TgtTranslateSet ((unsigned) Index, (unsigned char) Code);
598 static void DoCode (void)
599 /* Switch to the code segment */
601 UseSeg (&CodeSegDef);
606 static void DoConDes (void)
607 /* Export a symbol as constructor/destructor */
609 static const char* Keys[] = {
614 StrBuf Name = STATIC_STRBUF_INITIALIZER;
617 /* Symbol name follows */
618 if (CurTok.Tok != TOK_IDENT) {
619 ErrorSkip ("Identifier expected");
622 SB_Copy (&Name, &CurTok.SVal);
625 /* Type follows. May be encoded as identifier or numerical */
627 if (CurTok.Tok == TOK_IDENT) {
629 /* Map the following keyword to a number, then skip it */
630 Type = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
633 /* Check if we got a valid keyword */
635 ErrorSkip ("Syntax error");
641 /* Read the type as numerical value */
642 Type = ConstExpression ();
643 if (Type < CD_TYPE_MIN || Type > CD_TYPE_MAX) {
644 /* Value out of range */
645 ErrorSkip ("Range error");
651 /* Parse the remainder of the line and export the symbol */
652 ConDes (&Name, (unsigned) Type);
655 /* Free string memory */
661 static void DoConstructor (void)
662 /* Export a symbol as constructor */
664 StrBuf Name = STATIC_STRBUF_INITIALIZER;
666 /* Symbol name follows */
667 if (CurTok.Tok != TOK_IDENT) {
668 ErrorSkip ("Identifier expected");
671 SB_Copy (&Name, &CurTok.SVal);
674 /* Parse the remainder of the line and export the symbol */
675 ConDes (&Name, CD_TYPE_CON);
677 /* Free string memory */
683 static void DoData (void)
684 /* Switch to the data segment */
686 UseSeg (&DataSegDef);
691 static void DoDbg (void)
692 /* Add debug information from high level code */
694 static const char* Keys[] = {
702 /* We expect a subkey */
703 if (CurTok.Tok != TOK_IDENT) {
704 ErrorSkip ("Identifier expected");
708 /* Map the following keyword to a number */
709 Key = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
711 /* Skip the subkey */
714 /* Check the key and dispatch to a handler */
716 case 0: DbgInfoFile (); break;
717 case 1: DbgInfoLine (); break;
718 case 2: DbgInfoSym (); break;
719 default: ErrorSkip ("Syntax error"); break;
725 static void DoDByt (void)
726 /* Output double bytes */
729 EmitWord (GenSwapExpr (Expression ()));
730 if (CurTok.Tok != TOK_COMMA) {
740 static void DoDebugInfo (void)
741 /* Switch debug info on or off */
743 SetBoolOption (&DbgSyms);
748 static void DoDefine (void)
749 /* Define a one line macro */
751 MacDef (MAC_STYLE_DEFINE);
756 static void DoDestructor (void)
757 /* Export a symbol as destructor */
759 StrBuf Name = STATIC_STRBUF_INITIALIZER;
761 /* Symbol name follows */
762 if (CurTok.Tok != TOK_IDENT) {
763 ErrorSkip ("Identifier expected");
766 SB_Copy (&Name, &CurTok.SVal);
769 /* Parse the remainder of the line and export the symbol */
770 ConDes (&Name, CD_TYPE_DES);
772 /* Free string memory */
778 static void DoDWord (void)
782 EmitDWord (Expression ());
783 if (CurTok.Tok != TOK_COMMA) {
793 static void DoEnd (void)
794 /* End of assembly */
802 static void DoEndProc (void)
803 /* Leave a lexical level */
805 if (GetCurrentSymTabType () != ST_PROC) {
807 ErrorSkip ("No open .PROC");
815 static void DoEndScope (void)
816 /* Leave a lexical level */
818 if ( GetCurrentSymTabType () != ST_SCOPE) {
820 ErrorSkip ("No open .SCOPE");
828 static void DoError (void)
831 if (CurTok.Tok != TOK_STRCON) {
832 ErrorSkip ("String constant expected");
834 Error ("User error: %m%p", &CurTok.SVal);
841 static void DoExitMacro (void)
842 /* Exit a macro expansion */
844 if (!InMacExpansion ()) {
845 /* We aren't expanding a macro currently */
854 static void DoExport (void)
855 /* Export a symbol */
857 ExportImport (ExportWithAssign, ADDR_SIZE_DEFAULT, SF_NONE);
862 static void DoExportZP (void)
863 /* Export a zeropage symbol */
865 ExportImport (ExportWithAssign, ADDR_SIZE_ZP, SF_NONE);
870 static void DoFarAddr (void)
871 /* Define far addresses (24 bit) */
874 EmitFarAddr (Expression ());
875 if (CurTok.Tok != TOK_COMMA) {
885 static void DoFatal (void)
886 /* Fatal user error */
888 if (CurTok.Tok != TOK_STRCON) {
889 ErrorSkip ("String constant expected");
891 Fatal ("User error: %m%p", &CurTok.SVal);
898 static void DoFeature (void)
899 /* Switch the Feature option */
901 /* Allow a list of comma separated keywords */
904 /* We expect an identifier */
905 if (CurTok.Tok != TOK_IDENT) {
906 ErrorSkip ("Identifier expected");
910 /* Make the string attribute lower case */
913 /* Set the feature and check for errors */
914 if (SetFeature (&CurTok.SVal) == FEAT_UNKNOWN) {
916 ErrorSkip ("Invalid feature: `%m%p'", &CurTok.SVal);
919 /* Skip the keyword */
923 /* Allow more than one keyword */
924 if (CurTok.Tok == TOK_COMMA) {
934 static void DoFileOpt (void)
935 /* Insert a file option */
939 /* The option type may be given as a keyword or as a number. */
940 if (CurTok.Tok == TOK_IDENT) {
942 /* Option given as keyword */
943 static const char* Keys [] = {
944 "AUTHOR", "COMMENT", "COMPILER"
947 /* Map the option to a number */
948 OptNum = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
951 ErrorSkip ("File option keyword expected");
955 /* Skip the keyword */
958 /* Must be followed by a comma */
961 /* We accept only string options for now */
962 if (CurTok.Tok != TOK_STRCON) {
963 ErrorSkip ("String constant expected");
967 /* Insert the option */
972 OptAuthor (&CurTok.SVal);
977 OptComment (&CurTok.SVal);
982 OptCompiler (&CurTok.SVal);
986 Internal ("Invalid OptNum: %ld", OptNum);
995 /* Option given as number */
996 OptNum = ConstExpression ();
997 if (!IsByteRange (OptNum)) {
998 ErrorSkip ("Range error");
1002 /* Must be followed by a comma */
1005 /* We accept only string options for now */
1006 if (CurTok.Tok != TOK_STRCON) {
1007 ErrorSkip ("String constant expected");
1011 /* Insert the option */
1012 OptStr ((unsigned char) OptNum, &CurTok.SVal);
1021 static void DoForceImport (void)
1022 /* Do a forced import on a symbol */
1024 ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_FORCED);
1029 static void DoGlobal (void)
1030 /* Declare a global symbol */
1032 ExportImport (SymGlobal, ADDR_SIZE_DEFAULT, SF_NONE);
1037 static void DoGlobalZP (void)
1038 /* Declare a global zeropage symbol */
1040 ExportImport (SymGlobal, ADDR_SIZE_ZP, SF_NONE);
1044 static void DoHiBytes (void)
1045 /* Define bytes, extracting the hi byte from each expression in the list */
1048 EmitByte (FuncHiByte ());
1049 if (CurTok.Tok != TOK_COMMA) {
1059 static void DoI16 (void)
1060 /* Switch the index registers to 16 bit mode (assembler only) */
1062 if (GetCPU() != CPU_65816) {
1063 Error ("Command is only valid in 65816 mode");
1065 /* Immidiate mode has two extension bytes */
1066 ExtBytes [AM65I_IMM_INDEX] = 2;
1072 static void DoI8 (void)
1073 /* Switch the index registers to 16 bit mode (assembler only) */
1075 if (GetCPU() != CPU_65816) {
1076 Error ("Command is only valid in 65816 mode");
1078 /* Immidiate mode has one extension byte */
1079 ExtBytes [AM65I_IMM_INDEX] = 1;
1085 static void DoImport (void)
1086 /* Import a symbol */
1088 ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_NONE);
1093 static void DoImportZP (void)
1094 /* Import a zero page symbol */
1096 ExportImport (SymImport, ADDR_SIZE_ZP, SF_NONE);
1101 static void DoIncBin (void)
1102 /* Include a binary file */
1104 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1105 struct stat StatBuf;
1111 /* Name must follow */
1112 if (CurTok.Tok != TOK_STRCON) {
1113 ErrorSkip ("String constant expected");
1116 SB_Copy (&Name, &CurTok.SVal);
1117 SB_Terminate (&Name);
1120 /* A starting offset may follow */
1121 if (CurTok.Tok == TOK_COMMA) {
1123 Start = ConstExpression ();
1125 /* And a length may follow */
1126 if (CurTok.Tok == TOK_COMMA) {
1128 Count = ConstExpression ();
1133 /* Try to open the file */
1134 F = fopen (SB_GetConstBuf (&Name), "rb");
1137 /* Search for the file in the binary include directory */
1138 char* PathName = SearchFile (BinSearchPath, SB_GetConstBuf (&Name));
1139 if (PathName == 0 || (F = fopen (PathName, "rb")) == 0) {
1140 /* Not found or cannot open, print an error and bail out */
1141 ErrorSkip ("Cannot open include file `%m%p': %s", &Name, strerror (errno));
1146 /* Remember the new file name */
1147 SB_CopyStr (&Name, PathName);
1149 /* Free the allocated memory */
1153 /* Get the size of the file */
1154 fseek (F, 0, SEEK_END);
1157 /* Stat the file and remember the values. There a race condition here,
1158 * since we cannot use fileno() (non standard identifier in standard
1159 * header file), and therefore not fstat. When using stat with the
1160 * file name, there's a risk that the file was deleted and recreated
1161 * while it was open. Since mtime and size are only used to check
1162 * if a file has changed in the debugger, we will ignore this problem
1165 SB_Terminate (&Name);
1166 if (stat (SB_GetConstBuf (&Name), &StatBuf) != 0) {
1167 Fatal ("Cannot stat input file `%m%p': %s", &Name, strerror (errno));
1170 /* Add the file to the input file table */
1171 AddFile (&Name, FT_BINARY, Size, StatBuf.st_mtime);
1173 /* If a count was not given, calculate it now */
1175 Count = Size - Start;
1177 /* Nothing to read - flag this as a range error */
1178 ErrorSkip ("Range error");
1182 /* Count was given, check if it is valid */
1183 if (Start + Count > Size) {
1184 ErrorSkip ("Range error");
1189 /* Seek to the start position */
1190 fseek (F, Start, SEEK_SET);
1192 /* Read chunks and insert them into the output */
1195 unsigned char Buf [1024];
1197 /* Calculate the number of bytes to read */
1198 size_t BytesToRead = (Count > (long)sizeof(Buf))? sizeof(Buf) : (size_t) Count;
1201 size_t BytesRead = fread (Buf, 1, BytesToRead, F);
1202 if (BytesToRead != BytesRead) {
1203 /* Some sort of error */
1204 ErrorSkip ("Cannot read from include file `%m%p': %s",
1205 &Name, strerror (errno));
1209 /* Insert it into the output */
1210 EmitData (Buf, BytesRead);
1212 /* Keep the counters current */
1217 /* Close the file, ignore errors since it's r/o */
1221 /* Free string memory */
1227 static void DoInclude (void)
1228 /* Include another file */
1230 /* Name must follow */
1231 if (CurTok.Tok != TOK_STRCON) {
1232 ErrorSkip ("String constant expected");
1234 SB_Terminate (&CurTok.SVal);
1235 if (NewInputFile (SB_GetConstBuf (&CurTok.SVal)) == 0) {
1236 /* Error opening the file, skip remainder of line */
1244 static void DoInterruptor (void)
1245 /* Export a symbol as interruptor */
1247 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1249 /* Symbol name follows */
1250 if (CurTok.Tok != TOK_IDENT) {
1251 ErrorSkip ("Identifier expected");
1254 SB_Copy (&Name, &CurTok.SVal);
1257 /* Parse the remainder of the line and export the symbol */
1258 ConDes (&Name, CD_TYPE_INT);
1260 /* Free string memory */
1266 static void DoInvalid (void)
1267 /* Handle a token that is invalid here, since it should have been handled on
1268 * a much lower level of the expression hierarchy. Getting this sort of token
1269 * means that the lower level code has bugs.
1270 * This function differs to DoUnexpected in that the latter may be triggered
1271 * by the user by using keywords in the wrong location. DoUnexpected is not
1272 * an error in the assembler itself, while DoInvalid is.
1275 Internal ("Unexpected token: %m%p", &Keyword);
1280 static void DoLineCont (void)
1281 /* Switch the use of line continuations */
1283 SetBoolOption (&LineCont);
1288 static void DoList (void)
1289 /* Enable/disable the listing */
1291 /* Get the setting */
1293 SetBoolOption (&List);
1295 /* Manage the counter */
1305 static void DoLoBytes (void)
1306 /* Define bytes, extracting the lo byte from each expression in the list */
1309 EmitByte (FuncLoByte ());
1310 if (CurTok.Tok != TOK_COMMA) {
1319 static void DoListBytes (void)
1320 /* Set maximum number of bytes to list for one line */
1322 SetListBytes (IntArg (MIN_LIST_BYTES, MAX_LIST_BYTES));
1327 static void DoLocalChar (void)
1328 /* Define the character that starts local labels */
1330 if (CurTok.Tok != TOK_CHARCON) {
1331 ErrorSkip ("Character constant expected");
1333 if (CurTok.IVal != '@' && CurTok.IVal != '?') {
1334 Error ("Invalid start character for locals");
1336 LocalStart = (char) CurTok.IVal;
1344 static void DoMacPack (void)
1345 /* Insert a macro package */
1349 /* We expect an identifier */
1350 if (CurTok.Tok != TOK_IDENT) {
1351 ErrorSkip ("Identifier expected");
1355 /* Search for the macro package name */
1357 Package = MacPackFind (&CurTok.SVal);
1360 ErrorSkip ("Invalid macro package");
1364 /* Insert the package. If this fails, skip the remainder of the line to
1365 * avoid additional error messages.
1367 if (MacPackInsert (Package) == 0) {
1374 static void DoMacro (void)
1375 /* Start a macro definition */
1377 MacDef (MAC_STYLE_CLASSIC);
1382 static void DoNull (void)
1383 /* Switch to the NULL segment */
1385 UseSeg (&NullSegDef);
1390 static void DoOrg (void)
1391 /* Start absolute code */
1393 long PC = ConstExpression ();
1394 if (PC < 0 || PC > 0xFFFFFF) {
1395 Error ("Range error");
1398 EnterAbsoluteMode (PC);
1403 static void DoOut (void)
1404 /* Output a string */
1406 if (CurTok.Tok != TOK_STRCON) {
1407 ErrorSkip ("String constant expected");
1409 /* Output the string and be sure to flush the output to keep it in
1410 * sync with any error messages if the output is redirected to a file.
1413 (int) SB_GetLen (&CurTok.SVal),
1414 SB_GetConstBuf (&CurTok.SVal));
1422 static void DoP02 (void)
1423 /* Switch to 6502 CPU */
1430 static void DoPC02 (void)
1431 /* Switch to 65C02 CPU */
1438 static void DoP816 (void)
1439 /* Switch to 65816 CPU */
1446 static void DoPageLength (void)
1447 /* Set the page length for the listing */
1449 PageLength = IntArg (MIN_PAGE_LEN, MAX_PAGE_LEN);
1454 static void DoPopCPU (void)
1455 /* Pop an old CPU setting from the CPU stack */
1457 /* Must have a CPU on the stack */
1458 if (IS_IsEmpty (&CPUStack)) {
1459 ErrorSkip ("CPU stack is empty");
1463 /* Set the CPU to the value popped from stack */
1464 SetCPU (IS_Pop (&CPUStack));
1469 static void DoPopSeg (void)
1470 /* Pop an old segment from the segment stack */
1474 /* Must have a segment on the stack */
1475 if (CollCount (&SegStack) == 0) {
1476 ErrorSkip ("Segment stack is empty");
1480 /* Pop the last element */
1481 Def = CollPop (&SegStack);
1483 /* Restore this segment */
1486 /* Delete the segment definition */
1492 static void DoProc (void)
1493 /* Start a new lexical scope */
1495 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1496 unsigned char AddrSize;
1498 if (CurTok.Tok == TOK_IDENT) {
1502 /* The new scope has a name. Remember it. */
1503 SB_Copy (&Name, &CurTok.SVal);
1505 /* Search for the symbol, generate a new one if needed */
1506 Sym = SymFind (CurrentScope, &Name, SYM_ALLOC_NEW);
1508 /* Skip the scope name */
1511 /* Read an optional address size specifier */
1512 AddrSize = OptionalAddrSize ();
1514 /* Mark the symbol as defined */
1515 SymDef (Sym, GenCurrentPC (), AddrSize, SF_LABEL);
1519 /* A .PROC statement without a name */
1520 Warning (1, "Unnamed .PROCs are deprecated, please use .SCOPE");
1521 AnonName (&Name, "PROC");
1522 AddrSize = ADDR_SIZE_DEFAULT;
1526 /* Enter a new scope */
1527 SymEnterLevel (&Name, ST_PROC, AddrSize);
1529 /* Free memory for Name */
1535 static void DoPSC02 (void)
1536 /* Switch to 65SC02 CPU */
1538 SetCPU (CPU_65SC02);
1543 static void DoPushCPU (void)
1544 /* Push the current CPU setting onto the CPU stack */
1546 /* Can only push a limited size of segments */
1547 if (IS_IsFull (&CPUStack)) {
1548 ErrorSkip ("CPU stack overflow");
1552 /* Get the current segment and push it */
1553 IS_Push (&CPUStack, GetCPU ());
1558 static void DoPushSeg (void)
1559 /* Push the current segment onto the segment stack */
1561 /* Can only push a limited size of segments */
1562 if (CollCount (&SegStack) >= MAX_PUSHED_SEGMENTS) {
1563 ErrorSkip ("Segment stack overflow");
1567 /* Get the current segment and push it */
1568 CollAppend (&SegStack, DupSegDef (GetCurrentSegDef ()));
1573 static void DoReloc (void)
1574 /* Enter relocatable mode */
1581 static void DoRepeat (void)
1582 /* Repeat some instruction block */
1589 static void DoRes (void)
1590 /* Reserve some number of storage bytes */
1595 Count = ConstExpression ();
1596 if (Count > 0xFFFF || Count < 0) {
1597 ErrorSkip ("Range error");
1600 if (CurTok.Tok == TOK_COMMA) {
1602 Val = ConstExpression ();
1603 /* We need a byte value here */
1604 if (!IsByteRange (Val)) {
1605 ErrorSkip ("Range error");
1609 /* Emit constant values */
1611 Emit0 ((unsigned char) Val);
1615 /* Emit fill fragments */
1622 static void DoROData (void)
1623 /* Switch to the r/o data segment */
1625 UseSeg (&RODataSegDef);
1630 static void DoScope (void)
1631 /* Start a local scope */
1633 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1634 unsigned char AddrSize;
1637 if (CurTok.Tok == TOK_IDENT) {
1639 /* The new scope has a name. Remember and skip it. */
1640 SB_Copy (&Name, &CurTok.SVal);
1645 /* An unnamed scope */
1646 AnonName (&Name, "SCOPE");
1650 /* Read an optional address size specifier */
1651 AddrSize = OptionalAddrSize ();
1653 /* Enter the new scope */
1654 SymEnterLevel (&Name, ST_SCOPE, AddrSize);
1656 /* Free memory for Name */
1662 static void DoSegment (void)
1663 /* Switch to another segment */
1665 StrBuf Name = STATIC_STRBUF_INITIALIZER;
1668 if (CurTok.Tok != TOK_STRCON) {
1669 ErrorSkip ("String constant expected");
1672 /* Save the name of the segment and skip it */
1673 SB_Copy (&Name, &CurTok.SVal);
1676 /* Use the name for the segment definition */
1677 SB_Terminate (&Name);
1678 Def.Name = SB_GetBuf (&Name);
1680 /* Check for an optional address size modifier */
1681 Def.AddrSize = OptionalAddrSize ();
1683 /* Set the segment */
1687 /* Free memory for Name */
1693 static void DoSetCPU (void)
1694 /* Switch the CPU instruction set */
1696 /* We expect an identifier */
1697 if (CurTok.Tok != TOK_STRCON) {
1698 ErrorSkip ("String constant expected");
1702 /* Try to find the CPU */
1703 SB_Terminate (&CurTok.SVal);
1704 CPU = FindCPU (SB_GetConstBuf (&CurTok.SVal));
1706 /* Switch to the new CPU */
1709 /* Skip the identifier. If the CPU switch was successful, the scanner
1710 * will treat the input now correctly for the new CPU.
1718 static void DoSmart (void)
1719 /* Smart mode on/off */
1721 SetBoolOption (&SmartMode);
1726 static void DoSunPlus (void)
1727 /* Switch to the SUNPLUS CPU */
1729 SetCPU (CPU_SUNPLUS);
1734 static void DoTag (void)
1735 /* Allocate space for a struct */
1740 /* Read the struct name */
1741 SymTable* Struct = ParseScopedSymTable ();
1743 /* Check the supposed struct */
1745 ErrorSkip ("Unknown struct");
1748 if (GetSymTabType (Struct) != ST_STRUCT) {
1749 ErrorSkip ("Not a struct");
1753 /* Get the symbol that defines the size of the struct */
1754 SizeSym = GetSizeOfScope (Struct);
1756 /* Check if it does exist and if its value is known */
1757 if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
1758 ErrorSkip ("Size of struct/union is unknown");
1762 /* Optional multiplicator may follow */
1763 if (CurTok.Tok == TOK_COMMA) {
1766 Multiplicator = ConstExpression ();
1767 /* Multiplicator must make sense */
1768 if (Multiplicator <= 0) {
1769 ErrorSkip ("Range error");
1772 Size *= Multiplicator;
1775 /* Emit fill fragments */
1781 static void DoUnexpected (void)
1782 /* Got an unexpected keyword */
1784 Error ("Unexpected `%m%p'", &Keyword);
1790 static void DoWarning (void)
1793 if (CurTok.Tok != TOK_STRCON) {
1794 ErrorSkip ("String constant expected");
1796 Warning (0, "User warning: %m%p", &CurTok.SVal);
1803 static void DoWord (void)
1807 EmitWord (Expression ());
1808 if (CurTok.Tok != TOK_COMMA) {
1818 static void DoZeropage (void)
1819 /* Switch to the zeropage segment */
1821 UseSeg (&ZeropageSegDef);
1826 /*****************************************************************************/
1828 /*****************************************************************************/
1832 /* Control commands flags */
1834 ccNone = 0x0000, /* No special flags */
1835 ccKeepToken = 0x0001 /* Do not skip the current token */
1838 /* Control command table */
1839 typedef struct CtrlDesc CtrlDesc;
1841 unsigned Flags; /* Flags for this directive */
1842 void (*Handler) (void); /* Command handler */
1845 #define PSEUDO_COUNT (sizeof (CtrlCmdTab) / sizeof (CtrlCmdTab [0]))
1846 static CtrlDesc CtrlCmdTab [] = {
1849 { ccNone, DoAddr }, /* .ADDR */
1850 { ccNone, DoAlign },
1851 { ccNone, DoASCIIZ },
1852 { ccNone, DoAssert },
1853 { ccNone, DoAutoImport },
1854 { ccNone, DoUnexpected }, /* .BANKBYTE */
1855 { ccNone, DoBankBytes },
1856 { ccNone, DoUnexpected }, /* .BLANK */
1860 { ccNone, DoCharMap },
1862 { ccNone, DoUnexpected, }, /* .CONCAT */
1863 { ccNone, DoConDes },
1864 { ccNone, DoUnexpected }, /* .CONST */
1865 { ccNone, DoConstructor },
1866 { ccNone, DoUnexpected }, /* .CPU */
1870 { ccNone, DoDebugInfo },
1871 { ccNone, DoDefine },
1872 { ccNone, DoUnexpected }, /* .DEFINED */
1873 { ccNone, DoDestructor },
1874 { ccNone, DoDWord },
1875 { ccKeepToken, DoConditionals }, /* .ELSE */
1876 { ccKeepToken, DoConditionals }, /* .ELSEIF */
1877 { ccKeepToken, DoEnd },
1878 { ccNone, DoUnexpected }, /* .ENDENUM */
1879 { ccKeepToken, DoConditionals }, /* .ENDIF */
1880 { ccNone, DoUnexpected }, /* .ENDMACRO */
1881 { ccNone, DoEndProc },
1882 { ccNone, DoUnexpected }, /* .ENDREPEAT */
1883 { ccNone, DoEndScope },
1884 { ccNone, DoUnexpected }, /* .ENDSTRUCT */
1885 { ccNone, DoUnexpected }, /* .ENDUNION */
1887 { ccNone, DoError },
1888 { ccNone, DoExitMacro },
1889 { ccNone, DoExport },
1890 { ccNone, DoExportZP },
1891 { ccNone, DoFarAddr },
1892 { ccNone, DoFatal },
1893 { ccNone, DoFeature },
1894 { ccNone, DoFileOpt },
1895 { ccNone, DoForceImport },
1896 { ccNone, DoUnexpected }, /* .FORCEWORD */
1897 { ccNone, DoGlobal },
1898 { ccNone, DoGlobalZP },
1899 { ccNone, DoUnexpected }, /* .HIBYTE */
1900 { ccNone, DoHiBytes },
1901 { ccNone, DoUnexpected }, /* .HIWORD */
1904 { ccNone, DoUnexpected }, /* .IDENT */
1905 { ccKeepToken, DoConditionals }, /* .IF */
1906 { ccKeepToken, DoConditionals }, /* .IFBLANK */
1907 { ccKeepToken, DoConditionals }, /* .IFCONST */
1908 { ccKeepToken, DoConditionals }, /* .IFDEF */
1909 { ccKeepToken, DoConditionals }, /* .IFNBLANK */
1910 { ccKeepToken, DoConditionals }, /* .IFNCONST */
1911 { ccKeepToken, DoConditionals }, /* .IFNDEF */
1912 { ccKeepToken, DoConditionals }, /* .IFNREF */
1913 { ccKeepToken, DoConditionals }, /* .IFP02 */
1914 { ccKeepToken, DoConditionals }, /* .IFP816 */
1915 { ccKeepToken, DoConditionals }, /* .IFPC02 */
1916 { ccKeepToken, DoConditionals }, /* .IFPSC02 */
1917 { ccKeepToken, DoConditionals }, /* .IFREF */
1918 { ccNone, DoImport },
1919 { ccNone, DoImportZP },
1920 { ccNone, DoIncBin },
1921 { ccNone, DoInclude },
1922 { ccNone, DoInterruptor },
1923 { ccNone, DoInvalid }, /* .LEFT */
1924 { ccNone, DoLineCont },
1926 { ccNone, DoListBytes },
1927 { ccNone, DoUnexpected }, /* .LOBYTE */
1928 { ccNone, DoLoBytes },
1929 { ccNone, DoUnexpected }, /* .LOCAL */
1930 { ccNone, DoLocalChar },
1931 { ccNone, DoUnexpected }, /* .LOWORD */
1932 { ccNone, DoMacPack },
1933 { ccNone, DoMacro },
1934 { ccNone, DoUnexpected }, /* .MATCH */
1935 { ccNone, DoUnexpected }, /* .MAX */
1936 { ccNone, DoInvalid }, /* .MID */
1937 { ccNone, DoUnexpected }, /* .MIN */
1943 { ccNone, DoPageLength },
1944 { ccNone, DoUnexpected }, /* .PARAMCOUNT */
1946 { ccNone, DoPopCPU },
1947 { ccNone, DoPopSeg },
1949 { ccNone, DoPSC02 },
1950 { ccNone, DoPushCPU },
1951 { ccNone, DoPushSeg },
1952 { ccNone, DoUnexpected }, /* .REFERENCED */
1953 { ccNone, DoReloc },
1954 { ccNone, DoRepeat },
1956 { ccNone, DoInvalid }, /* .RIGHT */
1957 { ccNone, DoROData },
1958 { ccNone, DoScope },
1959 { ccNone, DoSegment },
1960 { ccNone, DoUnexpected }, /* .SET */
1961 { ccNone, DoSetCPU },
1962 { ccNone, DoUnexpected }, /* .SIZEOF */
1963 { ccNone, DoSmart },
1964 { ccNone, DoUnexpected }, /* .SPRINTF */
1965 { ccNone, DoUnexpected }, /* .STRAT */
1966 { ccNone, DoUnexpected }, /* .STRING */
1967 { ccNone, DoUnexpected }, /* .STRLEN */
1968 { ccNone, DoStruct },
1969 { ccNone, DoSunPlus },
1971 { ccNone, DoUnexpected }, /* .TCOUNT */
1972 { ccNone, DoUnexpected }, /* .TIME */
1973 { ccNone, DoUnion },
1974 { ccNone, DoUnexpected }, /* .VERSION */
1975 { ccNone, DoWarning },
1977 { ccNone, DoUnexpected }, /* .XMATCH */
1978 { ccNone, DoZeropage },
1983 /*****************************************************************************/
1985 /*****************************************************************************/
1989 void HandlePseudo (void)
1990 /* Handle a pseudo instruction */
1994 /* Calculate the index into the table */
1995 unsigned Index = CurTok.Tok - TOK_FIRSTPSEUDO;
1998 if (PSEUDO_COUNT != (TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1)) {
1999 Internal ("Pseudo mismatch: PSEUDO_COUNT = %u, actual count = %u\n",
2000 (unsigned) PSEUDO_COUNT, TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1);
2002 CHECK (Index < PSEUDO_COUNT);
2004 /* Get the pseudo intruction descriptor */
2005 D = &CtrlCmdTab [Index];
2007 /* Remember the instruction, then skip it if needed */
2008 if ((D->Flags & ccKeepToken) == 0) {
2009 SB_Copy (&Keyword, &CurTok.SVal);
2013 /* Call the handler */
2019 void CheckPseudo (void)
2020 /* Check if the stacks are empty at end of assembly */
2022 if (CollCount (&SegStack) != 0) {
2023 Warning (1, "Segment stack is not empty");
2025 if (!IS_IsEmpty (&CPUStack)) {
2026 Warning (1, "CPU stack is not empty");