1 /*****************************************************************************/
5 /* Pseudo instructions for the ca65 macroassembler */
9 /* (C) 1998-2007, 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 /*****************************************************************************/
43 #include "assertdefs.h"
80 /*****************************************************************************/
82 /*****************************************************************************/
86 /* Keyword we're about to handle */
87 static char Keyword [sizeof (SVal)+1];
90 #define MAX_PUSHED_SEGMENTS 16
91 static Collection SegStack = STATIC_COLLECTION_INITIALIZER;
95 /*****************************************************************************/
97 /*****************************************************************************/
101 static void DoUnexpected (void);
102 /* Got an unexpected keyword */
104 static void DoInvalid (void);
105 /* Handle a token that is invalid here, since it should have been handled on
106 * a much lower level of the expression hierarchy. Getting this sort of token
107 * means that the lower level code has bugs.
108 * This function differs to DoUnexpected in that the latter may be triggered
109 * by the user by using keywords in the wrong location. DoUnexpected is not
110 * an error in the assembler itself, while DoInvalid is.
115 /*****************************************************************************/
116 /* Helper functions */
117 /*****************************************************************************/
121 static unsigned char OptionalAddrSize (void)
122 /* If a colon follows, parse an optional address size spec and return it.
123 * Otherwise return ADDR_SIZE_DEFAULT.
126 unsigned AddrSize = ADDR_SIZE_DEFAULT;
127 if (Tok == TOK_COLON) {
129 AddrSize = ParseAddrSize ();
137 static void SetBoolOption (unsigned char* Flag)
138 /* Read a on/off/+/- option and set flag accordingly */
140 static const char* Keys[] = {
145 if (Tok == TOK_PLUS) {
148 } else if (Tok == TOK_MINUS) {
151 } else if (Tok == TOK_IDENT) {
152 /* Map the keyword to a number */
153 switch (GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]))) {
154 case 0: *Flag = 0; NextTok (); break;
155 case 1: *Flag = 1; NextTok (); break;
156 default: ErrorSkip ("`on' or `off' expected"); break;
158 } else if (TokIsSep (Tok)) {
159 /* Without anything assume switch on */
162 ErrorSkip ("`on' or `off' expected");
168 static void ExportWithAssign (SymEntry* Sym, unsigned char AddrSize, unsigned Flags)
169 /* Allow to assign the value of an export in an .export statement */
171 /* The name and optional address size spec may be followed by an assignment
174 if (Tok == TOK_ASSIGN || Tok == TOK_EQ) {
176 /* Assignment means the symbol is a label */
177 if (Tok == TOK_ASSIGN) {
181 /* Skip the assignment token */
184 /* Define the symbol with the expression following the '=' */
185 SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
189 /* Now export the symbol */
190 SymExport (Sym, AddrSize, Flags);
195 static void ExportImport (void (*Func) (SymEntry*, unsigned char, unsigned),
196 unsigned char DefAddrSize, unsigned Flags)
197 /* Export or import symbols */
200 unsigned char AddrSize;
204 /* We need an identifier here */
205 if (Tok != TOK_IDENT) {
206 ErrorSkip ("Identifier expected");
210 /* Find the symbol table entry, allocate a new one if necessary */
211 Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
216 /* Get an optional address size */
217 AddrSize = OptionalAddrSize ();
218 if (AddrSize == ADDR_SIZE_DEFAULT) {
219 AddrSize = DefAddrSize;
222 /* Call the actual import/export function */
223 Func (Sym, AddrSize, Flags);
226 if (Tok == TOK_COMMA) {
236 static long IntArg (long Min, long Max)
237 /* Read an integer argument and check a range. Accept the token "unlimited"
238 * and return -1 in this case.
241 if (Tok == TOK_IDENT && strcmp (SVal, "unlimited") == 0) {
245 long Val = ConstExpression ();
246 if (Val < Min || Val > Max) {
247 Error ("Range error");
256 static void ConDes (const char* Name, unsigned Type)
257 /* Parse remaining line for constructor/destructor of the remaining type */
262 /* Find the symbol table entry, allocate a new one if necessary */
263 SymEntry* Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW);
265 /* Optional constructor priority */
266 if (Tok == TOK_COMMA) {
267 /* Priority value follows */
269 Prio = ConstExpression ();
270 if (Prio < CD_PRIO_MIN || Prio > CD_PRIO_MAX) {
271 /* Value out of range */
272 Error ("Range error");
276 /* Use the default priority value */
280 /* Define the symbol */
281 SymConDes (Sym, ADDR_SIZE_DEFAULT, Type, (unsigned) Prio);
286 /*****************************************************************************/
287 /* Handler functions */
288 /*****************************************************************************/
292 static void DoA16 (void)
293 /* Switch the accu to 16 bit mode (assembler only) */
295 if (GetCPU() != CPU_65816) {
296 Error ("Command is only valid in 65816 mode");
298 /* Immidiate mode has two extension bytes */
299 ExtBytes [AM65I_IMM_ACCU] = 2;
305 static void DoA8 (void)
306 /* Switch the accu to 8 bit mode (assembler only) */
308 if (GetCPU() != CPU_65816) {
309 Error ("Command is only valid in 65816 mode");
311 /* Immidiate mode has one extension byte */
312 ExtBytes [AM65I_IMM_ACCU] = 1;
318 static void DoAddr (void)
319 /* Define addresses */
322 if (GetCPU() == CPU_65816) {
323 EmitWord (GenWordExpr (Expression ()));
325 /* Do a range check */
326 EmitWord (Expression ());
328 if (Tok != TOK_COMMA) {
338 static void DoAlign (void)
339 /* Align the PC to some boundary */
345 /* Read the alignment value */
346 Align = ConstExpression ();
347 if (Align <= 0 || Align > 0x10000) {
348 ErrorSkip ("Range error");
352 /* Optional value follows */
353 if (Tok == TOK_COMMA) {
355 Val = ConstExpression ();
356 /* We need a byte value here */
357 if (!IsByteRange (Val)) {
358 ErrorSkip ("Range error");
365 /* Check if the alignment is a power of two */
366 Bit = BitFind (Align);
367 if (Align != (0x01L << Bit)) {
368 Error ("Alignment value must be a power of 2");
370 SegAlign (Bit, (int) Val);
376 static void DoASCIIZ (void)
377 /* Define text with a zero terminator */
382 /* Must have a string constant */
383 if (Tok != TOK_STRCON) {
384 ErrorSkip ("String constant expected");
388 /* Get the length of the string constant */
391 /* Translate into target charset and emit */
392 TgtTranslateBuf (SVal, Len);
393 EmitData ((unsigned char*) SVal, Len);
395 if (Tok == TOK_COMMA) {
406 static void DoAssert (void)
407 /* Add an assertion */
409 static const char* ActionTab [] = {
417 /* First we have the expression that has to evaluated */
418 ExprNode* Expr = Expression ();
422 if (Tok != TOK_IDENT) {
423 ErrorSkip ("Identifier expected");
426 Action = GetSubKey (ActionTab, sizeof (ActionTab) / sizeof (ActionTab[0]));
432 Action = ASSERT_ACT_WARN;
437 Action = ASSERT_ACT_ERROR;
441 Error ("Illegal assert action specifier");
445 /* We can have an optional message. If no message is present, use
446 * "Assertion failed".
448 if (Tok == TOK_COMMA) {
453 /* Read the message */
454 if (Tok != TOK_STRCON) {
455 ErrorSkip ("String constant expected");
459 /* Translate the message into a string id. We can then skip the input
462 Msg = GetStringId (SVal);
467 /* Use "Assertion failed" */
468 Msg = GetStringId ("Assertion failed");
472 /* Remember the assertion */
473 AddAssertion (Expr, Action, Msg);
478 static void DoAutoImport (void)
479 /* Mark unresolved symbols as imported */
481 SetBoolOption (&AutoImport);
486 static void DoBss (void)
487 /* Switch to the BSS segment */
494 static void DoByte (void)
498 if (Tok == TOK_STRCON) {
499 /* A string, translate into target charset and emit */
500 unsigned Len = strlen (SVal);
501 TgtTranslateBuf (SVal, Len);
502 EmitData ((unsigned char*) SVal, Len);
505 EmitByte (Expression ());
507 if (Tok != TOK_COMMA) {
511 /* Do smart handling of dangling comma */
512 if (Tok == TOK_SEP) {
513 Error ("Unexpected end of line");
522 static void DoCase (void)
523 /* Switch the IgnoreCase option */
525 SetBoolOption (&IgnoreCase);
526 IgnoreCase = !IgnoreCase;
531 static void DoCharMap (void)
532 /* Allow custome character mappings */
537 /* Read the index as numerical value */
538 Index = ConstExpression ();
539 if (Index < 0 || Index > 255) {
540 /* Value out of range */
541 ErrorSkip ("Range error");
548 /* Read the character code */
549 Code = ConstExpression ();
550 if (Code < 0 || Code > 255) {
551 /* Value out of range */
552 ErrorSkip ("Range error");
556 /* Set the character translation */
557 TgtTranslateSet ((unsigned) Index, (unsigned char) Code);
562 static void DoCode (void)
563 /* Switch to the code segment */
565 UseSeg (&CodeSegDef);
570 static void DoConDes (void)
571 /* Export a symbol as constructor/destructor */
573 static const char* Keys[] = {
578 char Name [sizeof (SVal)];
581 /* Symbol name follows */
582 if (Tok != TOK_IDENT) {
583 ErrorSkip ("Identifier expected");
589 /* Type follows. May be encoded as identifier or numerical */
591 if (Tok == TOK_IDENT) {
593 /* Map the following keyword to a number, then skip it */
594 Type = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
597 /* Check if we got a valid keyword */
599 Error ("Syntax error");
606 /* Read the type as numerical value */
607 Type = ConstExpression ();
608 if (Type < CD_TYPE_MIN || Type > CD_TYPE_MAX) {
609 /* Value out of range */
610 Error ("Range error");
616 /* Parse the remainder of the line and export the symbol */
617 ConDes (Name, (unsigned) Type);
622 static void DoConstructor (void)
623 /* Export a symbol as constructor */
625 char Name [sizeof (SVal)];
627 /* Symbol name follows */
628 if (Tok != TOK_IDENT) {
629 ErrorSkip ("Identifier expected");
635 /* Parse the remainder of the line and export the symbol */
636 ConDes (Name, CD_TYPE_CON);
641 static void DoData (void)
642 /* Switch to the data segment */
644 UseSeg (&DataSegDef);
649 static void DoDbg (void)
650 /* Add debug information from high level code */
652 static const char* Keys[] = {
660 /* We expect a subkey */
661 if (Tok != TOK_IDENT) {
662 ErrorSkip ("Identifier expected");
666 /* Map the following keyword to a number */
667 Key = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
669 /* Skip the subkey */
672 /* Check the key and dispatch to a handler */
674 case 0: DbgInfoFile (); break;
675 case 1: DbgInfoLine (); break;
676 case 2: DbgInfoSym (); break;
677 default: ErrorSkip ("Syntax error"); break;
683 static void DoDByt (void)
684 /* Output double bytes */
687 EmitWord (GenSwapExpr (Expression ()));
688 if (Tok != TOK_COMMA) {
698 static void DoDebugInfo (void)
699 /* Switch debug info on or off */
701 SetBoolOption (&DbgSyms);
706 static void DoDefine (void)
707 /* Define a one line macro */
709 MacDef (MAC_STYLE_DEFINE);
714 static void DoDestructor (void)
715 /* Export a symbol as destructor */
717 char Name [sizeof (SVal)];
719 /* Symbol name follows */
720 if (Tok != TOK_IDENT) {
721 ErrorSkip ("Identifier expected");
727 /* Parse the remainder of the line and export the symbol */
728 ConDes (Name, CD_TYPE_DES);
733 static void DoDWord (void)
737 EmitDWord (Expression ());
738 if (Tok != TOK_COMMA) {
748 static void DoEnd (void)
749 /* End of assembly */
757 static void DoEndProc (void)
758 /* Leave a lexical level */
760 if (GetCurrentSymTabType () != ST_PROC) {
762 ErrorSkip ("No open .PROC");
770 static void DoEndScope (void)
771 /* Leave a lexical level */
773 if ( GetCurrentSymTabType () != ST_SCOPE) {
775 ErrorSkip ("No open .SCOPE");
783 static void DoError (void)
786 if (Tok != TOK_STRCON) {
787 ErrorSkip ("String constant expected");
789 Error ("User error: %s", SVal);
796 static void DoExitMacro (void)
797 /* Exit a macro expansion */
799 if (!InMacExpansion ()) {
800 /* We aren't expanding a macro currently */
809 static void DoExport (void)
810 /* Export a symbol */
812 ExportImport (ExportWithAssign, ADDR_SIZE_DEFAULT, SF_NONE);
817 static void DoExportZP (void)
818 /* Export a zeropage symbol */
820 ExportImport (ExportWithAssign, ADDR_SIZE_ZP, SF_NONE);
825 static void DoFarAddr (void)
826 /* Define far addresses (24 bit) */
829 EmitFarAddr (Expression ());
830 if (Tok != TOK_COMMA) {
840 static void DoFeature (void)
841 /* Switch the Feature option */
843 /* Allow a list of comma separated keywords */
846 /* We expect an identifier */
847 if (Tok != TOK_IDENT) {
848 ErrorSkip ("Identifier expected");
852 /* Make the string attribute lower case */
855 /* Set the feature and check for errors */
856 if (SetFeature (SVal) == FEAT_UNKNOWN) {
858 ErrorSkip ("Invalid feature: `%s'", SVal);
861 /* Skip the keyword */
865 /* Allow more than one keyword */
866 if (Tok == TOK_COMMA) {
876 static void DoFileOpt (void)
877 /* Insert a file option */
881 /* The option type may be given as a keyword or as a number. */
882 if (Tok == TOK_IDENT) {
884 /* Option given as keyword */
885 static const char* Keys [] = {
886 "AUTHOR", "COMMENT", "COMPILER"
889 /* Map the option to a number */
890 OptNum = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
893 ErrorSkip ("File option keyword expected");
897 /* Skip the keyword */
900 /* Must be followed by a comma */
903 /* We accept only string options for now */
904 if (Tok != TOK_STRCON) {
905 ErrorSkip ("String constant expected");
909 /* Insert the option */
928 Internal ("Invalid OptNum: %ld", OptNum);
937 /* Option given as number */
938 OptNum = ConstExpression ();
939 if (!IsByteRange (OptNum)) {
940 ErrorSkip ("Range error");
944 /* Must be followed by a comma */
947 /* We accept only string options for now */
948 if (Tok != TOK_STRCON) {
949 ErrorSkip ("String constant expected");
953 /* Insert the option */
954 OptStr ((unsigned char) OptNum, SVal);
963 static void DoForceImport (void)
964 /* Do a forced import on a symbol */
966 ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_FORCED);
971 static void DoGlobal (void)
972 /* Declare a global symbol */
974 ExportImport (SymGlobal, ADDR_SIZE_DEFAULT, SF_NONE);
979 static void DoGlobalZP (void)
980 /* Declare a global zeropage symbol */
982 ExportImport (SymGlobal, ADDR_SIZE_ZP, SF_NONE);
987 static void DoI16 (void)
988 /* Switch the index registers to 16 bit mode (assembler only) */
990 if (GetCPU() != CPU_65816) {
991 Error ("Command is only valid in 65816 mode");
993 /* Immidiate mode has two extension bytes */
994 ExtBytes [AM65I_IMM_INDEX] = 2;
1000 static void DoI8 (void)
1001 /* Switch the index registers to 16 bit mode (assembler only) */
1003 if (GetCPU() != CPU_65816) {
1004 Error ("Command is only valid in 65816 mode");
1006 /* Immidiate mode has one extension byte */
1007 ExtBytes [AM65I_IMM_INDEX] = 1;
1013 static void DoImport (void)
1014 /* Import a symbol */
1016 ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_NONE);
1021 static void DoImportZP (void)
1022 /* Import a zero page symbol */
1024 ExportImport (SymImport, ADDR_SIZE_ZP, SF_NONE);
1029 static void DoIncBin (void)
1030 /* Include a binary file */
1032 char Name [sizeof (SVal)];
1038 /* Name must follow */
1039 if (Tok != TOK_STRCON) {
1040 ErrorSkip ("String constant expected");
1043 strcpy (Name, SVal);
1046 /* A starting offset may follow */
1047 if (Tok == TOK_COMMA) {
1049 Start = ConstExpression ();
1051 /* And a length may follow */
1052 if (Tok == TOK_COMMA) {
1054 Count = ConstExpression ();
1059 /* Try to open the file */
1060 F = fopen (Name, "rb");
1063 /* Search for the file in the include directories. */
1064 char* PathName = FindInclude (Name);
1065 if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
1066 /* Not found or cannot open, print an error and bail out */
1067 ErrorSkip ("Cannot open include file `%s': %s", Name, strerror (errno));
1070 /* Free the allocated memory */
1073 /* If we had an error before, bail out now */
1079 /* Get the size of the file */
1080 fseek (F, 0, SEEK_END);
1083 /* If a count was not given, calculate it now */
1085 Count = Size - Start;
1087 /* Nothing to read - flag this as a range error */
1088 ErrorSkip ("Range error");
1092 /* Count was given, check if it is valid */
1093 if (Start + Count > Size) {
1094 ErrorSkip ("Range error");
1099 /* Seek to the start position */
1100 fseek (F, Start, SEEK_SET);
1102 /* Read chunks and insert them into the output */
1105 unsigned char Buf [1024];
1107 /* Calculate the number of bytes to read */
1108 size_t BytesToRead = (Count > (long)sizeof(Buf))? sizeof(Buf) : (size_t) Count;
1111 size_t BytesRead = fread (Buf, 1, BytesToRead, F);
1112 if (BytesToRead != BytesRead) {
1113 /* Some sort of error */
1114 ErrorSkip ("Cannot read from include file `%s': %s",
1115 Name, strerror (errno));
1119 /* Insert it into the output */
1120 EmitData (Buf, BytesRead);
1122 /* Keep the counters current */
1127 /* Close the file, ignore errors since it's r/o */
1133 static void DoInclude (void)
1134 /* Include another file */
1136 /* Name must follow */
1137 if (Tok != TOK_STRCON) {
1138 ErrorSkip ("String constant expected");
1140 NewInputFile (SVal);
1146 static void DoInterruptor (void)
1147 /* Export a symbol as interruptor */
1149 char Name [sizeof (SVal)];
1151 /* Symbol name follows */
1152 if (Tok != TOK_IDENT) {
1153 ErrorSkip ("Identifier expected");
1156 strcpy (Name, SVal);
1159 /* Parse the remainder of the line and export the symbol */
1160 ConDes (Name, CD_TYPE_INT);
1165 static void DoInvalid (void)
1166 /* Handle a token that is invalid here, since it should have been handled on
1167 * a much lower level of the expression hierarchy. Getting this sort of token
1168 * means that the lower level code has bugs.
1169 * This function differs to DoUnexpected in that the latter may be triggered
1170 * by the user by using keywords in the wrong location. DoUnexpected is not
1171 * an error in the assembler itself, while DoInvalid is.
1174 Internal ("Unexpected token: %s", Keyword);
1179 static void DoLineCont (void)
1180 /* Switch the use of line continuations */
1182 SetBoolOption (&LineCont);
1187 static void DoList (void)
1188 /* Enable/disable the listing */
1190 /* Get the setting */
1192 SetBoolOption (&List);
1194 /* Manage the counter */
1204 static void DoListBytes (void)
1205 /* Set maximum number of bytes to list for one line */
1207 SetListBytes (IntArg (MIN_LIST_BYTES, MAX_LIST_BYTES));
1212 static void DoLocalChar (void)
1213 /* Define the character that starts local labels */
1215 if (Tok != TOK_CHARCON) {
1216 ErrorSkip ("Character constant expected");
1218 if (IVal != '@' && IVal != '?') {
1219 Error ("Invalid start character for locals");
1221 LocalStart = (char) IVal;
1229 static void DoMacPack (void)
1230 /* Insert a macro package */
1234 /* We expect an identifier */
1235 if (Tok != TOK_IDENT) {
1236 ErrorSkip ("Identifier expected");
1240 /* Search for the macro package name */
1241 Package = MacPackFind (SVal);
1244 ErrorSkip ("Invalid macro package");
1248 /* Insert the package */
1249 MacPackInsert (Package);
1254 static void DoMacro (void)
1255 /* Start a macro definition */
1257 MacDef (MAC_STYLE_CLASSIC);
1262 static void DoNull (void)
1263 /* Switch to the NULL segment */
1265 UseSeg (&NullSegDef);
1270 static void DoOrg (void)
1271 /* Start absolute code */
1273 long PC = ConstExpression ();
1274 if (PC < 0 || PC > 0xFFFFFF) {
1275 Error ("Range error");
1278 EnterAbsoluteMode (PC);
1283 static void DoOut (void)
1284 /* Output a string */
1286 if (Tok != TOK_STRCON) {
1287 ErrorSkip ("String constant expected");
1289 /* Output the string and be sure to flush the output to keep it in
1290 * sync with any error messages if the output is redirected to a file.
1292 printf ("%s\n", SVal);
1300 static void DoP02 (void)
1301 /* Switch to 6502 CPU */
1308 static void DoPC02 (void)
1309 /* Switch to 65C02 CPU */
1316 static void DoP816 (void)
1317 /* Switch to 65816 CPU */
1324 static void DoPageLength (void)
1325 /* Set the page length for the listing */
1327 PageLength = IntArg (MIN_PAGE_LEN, MAX_PAGE_LEN);
1332 static void DoPopSeg (void)
1333 /* Pop an old segment from the segment stack */
1337 /* Must have a segment on the stack */
1338 if (CollCount (&SegStack) == 0) {
1339 ErrorSkip ("Segment stack is empty");
1343 /* Pop the last element */
1344 Def = CollPop (&SegStack);
1346 /* Restore this segment */
1349 /* Delete the segment definition */
1355 static void DoProc (void)
1356 /* Start a new lexical scope */
1358 char Name[sizeof(SVal)];
1359 unsigned char AddrSize;
1361 if (Tok == TOK_IDENT) {
1365 /* The new scope has a name. Remember it. */
1366 strcpy (Name, SVal);
1368 /* Search for the symbol, generate a new one if needed */
1369 Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW);
1371 /* Skip the scope name */
1374 /* Read an optional address size specifier */
1375 AddrSize = OptionalAddrSize ();
1377 /* Mark the symbol as defined */
1378 SymDef (Sym, GenCurrentPC (), AddrSize, SF_LABEL);
1382 /* A .PROC statement without a name */
1383 Warning (1, "Unnamed .PROCs are deprecated, please use .SCOPE");
1384 AnonName (Name, sizeof (Name), "PROC");
1385 AddrSize = ADDR_SIZE_DEFAULT;
1389 /* Enter a new scope */
1390 SymEnterLevel (Name, ST_PROC, AddrSize);
1395 static void DoPSC02 (void)
1396 /* Switch to 65SC02 CPU */
1398 SetCPU (CPU_65SC02);
1403 static void DoPushSeg (void)
1404 /* Push the current segment onto the segment stack */
1406 /* Can only push a limited size of segments */
1407 if (CollCount (&SegStack) >= MAX_PUSHED_SEGMENTS) {
1408 ErrorSkip ("Segment stack overflow");
1412 /* Get the current segment and push it */
1413 CollAppend (&SegStack, DupSegDef (GetCurrentSegDef ()));
1418 static void DoReloc (void)
1419 /* Enter relocatable mode */
1426 static void DoRepeat (void)
1427 /* Repeat some instruction block */
1434 static void DoRes (void)
1435 /* Reserve some number of storage bytes */
1440 Count = ConstExpression ();
1441 if (Count > 0xFFFF || Count < 0) {
1442 ErrorSkip ("Range error");
1445 if (Tok == TOK_COMMA) {
1447 Val = ConstExpression ();
1448 /* We need a byte value here */
1449 if (!IsByteRange (Val)) {
1450 ErrorSkip ("Range error");
1454 /* Emit constant values */
1456 Emit0 ((unsigned char) Val);
1460 /* Emit fill fragments */
1467 static void DoROData (void)
1468 /* Switch to the r/o data segment */
1470 UseSeg (&RODataSegDef);
1475 static void DoScope (void)
1476 /* Start a local scope */
1478 char Name[sizeof (SVal)];
1479 unsigned char AddrSize;
1482 if (Tok == TOK_IDENT) {
1484 /* The new scope has a name. Remember and skip it. */
1485 strcpy (Name, SVal);
1490 /* An unnamed scope */
1491 AnonName (Name, sizeof (Name), "SCOPE");
1495 /* Read an optional address size specifier */
1496 AddrSize = OptionalAddrSize ();
1498 /* Enter the new scope */
1499 SymEnterLevel (Name, ST_SCOPE, AddrSize);
1505 static void DoSegment (void)
1506 /* Switch to another segment */
1508 char Name [sizeof (SVal)];
1512 if (Tok != TOK_STRCON) {
1513 ErrorSkip ("String constant expected");
1516 /* Save the name of the segment and skip it */
1517 strcpy (Name, SVal);
1520 /* Check for an optional address size modifier */
1521 Def.AddrSize = OptionalAddrSize ();
1523 /* Set the segment */
1530 static void DoSetCPU (void)
1531 /* Switch the CPU instruction set */
1533 /* We expect an identifier */
1534 if (Tok != TOK_STRCON) {
1535 ErrorSkip ("String constant expected");
1537 /* Try to find the CPU */
1538 cpu_t CPU = FindCPU (SVal);
1540 /* Switch to the new CPU */
1543 /* Skip the identifier. If the CPU switch was successful, the scanner
1544 * will treat the input now correctly for the new CPU.
1552 static void DoSmart (void)
1553 /* Smart mode on/off */
1555 SetBoolOption (&SmartMode);
1560 static void DoSunPlus (void)
1561 /* Switch to the SUNPLUS CPU */
1563 SetCPU (CPU_SUNPLUS);
1568 static void DoTag (void)
1569 /* Allocate space for a struct */
1574 /* Read the struct name */
1575 SymTable* Struct = ParseScopedSymTable ();
1577 /* Check the supposed struct */
1579 ErrorSkip ("Unknown struct");
1582 if (GetSymTabType (Struct) != ST_STRUCT) {
1583 ErrorSkip ("Not a struct");
1587 /* Get the symbol that defines the size of the struct */
1588 SizeSym = GetSizeOfScope (Struct);
1590 /* Check if it does exist and if its value is known */
1591 if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
1592 ErrorSkip ("Size of struct/union is unknown");
1596 /* Optional multiplicator may follow */
1597 if (Tok == TOK_COMMA) {
1600 Multiplicator = ConstExpression ();
1601 /* Multiplicator must make sense */
1602 if (Multiplicator <= 0) {
1603 ErrorSkip ("Range error");
1606 Size *= Multiplicator;
1609 /* Emit fill fragments */
1615 static void DoUnexpected (void)
1616 /* Got an unexpected keyword */
1618 Error ("Unexpected `%s'", Keyword);
1624 static void DoWarning (void)
1627 if (Tok != TOK_STRCON) {
1628 ErrorSkip ("String constant expected");
1630 Warning (0, "User warning: %s", SVal);
1637 static void DoWord (void)
1641 EmitWord (Expression ());
1642 if (Tok != TOK_COMMA) {
1652 static void DoZeropage (void)
1653 /* Switch to the zeropage segment */
1655 UseSeg (&ZeropageSegDef);
1660 /*****************************************************************************/
1662 /*****************************************************************************/
1666 /* Control commands flags */
1668 ccNone = 0x0000, /* No special flags */
1669 ccKeepToken = 0x0001 /* Do not skip the current token */
1672 /* Control command table */
1673 typedef struct CtrlDesc CtrlDesc;
1675 unsigned Flags; /* Flags for this directive */
1676 void (*Handler) (void); /* Command handler */
1679 #define PSEUDO_COUNT (sizeof (CtrlCmdTab) / sizeof (CtrlCmdTab [0]))
1680 static CtrlDesc CtrlCmdTab [] = {
1683 { ccNone, DoAddr }, /* .ADDR */
1684 { ccNone, DoAlign },
1685 { ccNone, DoASCIIZ },
1686 { ccNone, DoAssert },
1687 { ccNone, DoAutoImport },
1688 { ccNone, DoUnexpected }, /* .BANKBYTE */
1689 { ccNone, DoUnexpected }, /* .BLANK */
1693 { ccNone, DoCharMap },
1695 { ccNone, DoUnexpected, }, /* .CONCAT */
1696 { ccNone, DoConDes },
1697 { ccNone, DoUnexpected }, /* .CONST */
1698 { ccNone, DoConstructor },
1699 { ccNone, DoUnexpected }, /* .CPU */
1703 { ccNone, DoDebugInfo },
1704 { ccNone, DoDefine },
1705 { ccNone, DoUnexpected }, /* .DEFINED */
1706 { ccNone, DoDestructor },
1707 { ccNone, DoDWord },
1708 { ccKeepToken, DoConditionals }, /* .ELSE */
1709 { ccKeepToken, DoConditionals }, /* .ELSEIF */
1710 { ccKeepToken, DoEnd },
1711 { ccNone, DoUnexpected }, /* .ENDENUM */
1712 { ccKeepToken, DoConditionals }, /* .ENDIF */
1713 { ccNone, DoUnexpected }, /* .ENDMACRO */
1714 { ccNone, DoEndProc },
1715 { ccNone, DoUnexpected }, /* .ENDREPEAT */
1716 { ccNone, DoEndScope },
1717 { ccNone, DoUnexpected }, /* .ENDSTRUCT */
1718 { ccNone, DoUnexpected }, /* .ENDUNION */
1720 { ccNone, DoError },
1721 { ccNone, DoExitMacro },
1722 { ccNone, DoExport },
1723 { ccNone, DoExportZP },
1724 { ccNone, DoFarAddr },
1725 { ccNone, DoFeature },
1726 { ccNone, DoFileOpt },
1727 { ccNone, DoForceImport },
1728 { ccNone, DoUnexpected }, /* .FORCEWORD */
1729 { ccNone, DoGlobal },
1730 { ccNone, DoGlobalZP },
1731 { ccNone, DoUnexpected }, /* .HIBYTE */
1732 { ccNone, DoUnexpected }, /* .HIWORD */
1735 { ccNone, DoUnexpected }, /* .IDENT */
1736 { ccKeepToken, DoConditionals }, /* .IF */
1737 { ccKeepToken, DoConditionals }, /* .IFBLANK */
1738 { ccKeepToken, DoConditionals }, /* .IFCONST */
1739 { ccKeepToken, DoConditionals }, /* .IFDEF */
1740 { ccKeepToken, DoConditionals }, /* .IFNBLANK */
1741 { ccKeepToken, DoConditionals }, /* .IFNCONST */
1742 { ccKeepToken, DoConditionals }, /* .IFNDEF */
1743 { ccKeepToken, DoConditionals }, /* .IFNREF */
1744 { ccKeepToken, DoConditionals }, /* .IFP02 */
1745 { ccKeepToken, DoConditionals }, /* .IFP816 */
1746 { ccKeepToken, DoConditionals }, /* .IFPC02 */
1747 { ccKeepToken, DoConditionals }, /* .IFPSC02 */
1748 { ccKeepToken, DoConditionals }, /* .IFREF */
1749 { ccNone, DoImport },
1750 { ccNone, DoImportZP },
1751 { ccNone, DoIncBin },
1752 { ccNone, DoInclude },
1753 { ccNone, DoInterruptor },
1754 { ccNone, DoInvalid }, /* .LEFT */
1755 { ccNone, DoLineCont },
1757 { ccNone, DoListBytes },
1758 { ccNone, DoUnexpected }, /* .LOBYTE */
1759 { ccNone, DoUnexpected }, /* .LOCAL */
1760 { ccNone, DoLocalChar },
1761 { ccNone, DoUnexpected }, /* .LOWORD */
1762 { ccNone, DoMacPack },
1763 { ccNone, DoMacro },
1764 { ccNone, DoUnexpected }, /* .MATCH */
1765 { ccNone, DoInvalid }, /* .MID */
1771 { ccNone, DoPageLength },
1772 { ccNone, DoUnexpected }, /* .PARAMCOUNT */
1774 { ccNone, DoPopSeg },
1776 { ccNone, DoPSC02 },
1777 { ccNone, DoPushSeg },
1778 { ccNone, DoUnexpected }, /* .REFERENCED */
1779 { ccNone, DoReloc },
1780 { ccNone, DoRepeat },
1782 { ccNone, DoInvalid }, /* .RIGHT */
1783 { ccNone, DoROData },
1784 { ccNone, DoScope },
1785 { ccNone, DoSegment },
1786 { ccNone, DoUnexpected }, /* .SET */
1787 { ccNone, DoSetCPU },
1788 { ccNone, DoUnexpected }, /* .SIZEOF */
1789 { ccNone, DoSmart },
1790 { ccNone, DoUnexpected }, /* .SPRINTF */
1791 { ccNone, DoUnexpected }, /* .STRAT */
1792 { ccNone, DoUnexpected }, /* .STRING */
1793 { ccNone, DoUnexpected }, /* .STRLEN */
1794 { ccNone, DoStruct },
1795 { ccNone, DoSunPlus },
1797 { ccNone, DoUnexpected }, /* .TCOUNT */
1798 { ccNone, DoUnexpected }, /* .TIME */
1799 { ccNone, DoUnion },
1800 { ccNone, DoUnexpected }, /* .VERSION */
1801 { ccNone, DoWarning },
1803 { ccNone, DoUnexpected }, /* .XMATCH */
1804 { ccNone, DoZeropage },
1809 /*****************************************************************************/
1811 /*****************************************************************************/
1815 void HandlePseudo (void)
1816 /* Handle a pseudo instruction */
1820 /* Calculate the index into the table */
1821 unsigned Index = Tok - TOK_FIRSTPSEUDO;
1824 if (PSEUDO_COUNT != (TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1)) {
1825 Internal ("Pseudo mismatch: PSEUDO_COUNT = %u, actual count = %u\n",
1826 (unsigned) PSEUDO_COUNT, TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1);
1828 CHECK (Index < PSEUDO_COUNT);
1830 /* Get the pseudo intruction descriptor */
1831 D = &CtrlCmdTab [Index];
1833 /* Remember the instruction, then skip it if needed */
1834 if ((D->Flags & ccKeepToken) == 0) {
1835 strcpy (Keyword, SVal);
1839 /* Call the handler */
1845 void SegStackCheck (void)
1846 /* Check if the segment stack is empty at end of assembly */
1848 if (CollCount (&SegStack) != 0) {
1849 Error ("Segment stack is not empty");