]> git.sur5r.net Git - cc65/blob - src/ca65/pseudo.c
More work on .sizeof
[cc65] / src / ca65 / pseudo.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 pseudo.c                                  */
4 /*                                                                           */
5 /*              Pseudo instructions for the ca65 macroassembler              */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2003 Ullrich von Bassewitz                                       */
10 /*               Römerstraße 52                                              */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <errno.h>
41
42 /* common */
43 #include "assertdefs.h"
44 #include "bitops.h"
45 #include "cddefs.h"
46 #include "coll.h"
47 #include "symdefs.h"
48 #include "tgttrans.h"
49 #include "xmalloc.h"
50
51 /* ca65 */
52 #include "anonname.h"
53 #include "asserts.h"
54 #include "condasm.h"
55 #include "dbginfo.h"
56 #include "enum.h"
57 #include "error.h"
58 #include "expr.h"
59 #include "feature.h"
60 #include "global.h"
61 #include "incpath.h"
62 #include "instr.h"
63 #include "listing.h"
64 #include "macpack.h"
65 #include "macro.h"
66 #include "nexttok.h"
67 #include "objcode.h"
68 #include "options.h"
69 #include "pseudo.h"
70 #include "repeat.h"
71 #include "segment.h"
72 #include "sizeof.h"
73 #include "spool.h"
74 #include "struct.h"
75 #include "symbol.h"
76 #include "symtab.h"
77
78
79
80 /*****************************************************************************/
81 /*                                   Data                                    */
82 /*****************************************************************************/
83
84
85
86 /* Keyword we're about to handle */
87 static char Keyword [sizeof (SVal)+1];
88
89 /* Segment stack */
90 #define MAX_PUSHED_SEGMENTS     16
91 static Collection SegStack = STATIC_COLLECTION_INITIALIZER;
92
93
94
95 /*****************************************************************************/
96 /*                               Forwards                                    */
97 /*****************************************************************************/
98
99
100
101 static void DoUnexpected (void);
102 /* Got an unexpected keyword */
103
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.
111  */
112
113
114
115 /*****************************************************************************/
116 /*                              Helper functions                             */
117 /*****************************************************************************/
118
119
120
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.
124  */
125 {
126     unsigned AddrSize = ADDR_SIZE_DEFAULT;
127     if (Tok == TOK_COLON) {
128         NextTok ();
129         AddrSize = ParseAddrSize ();
130         NextTok ();
131     }
132     return AddrSize;
133 }
134
135
136
137 static void SetBoolOption (unsigned char* Flag)
138 /* Read a on/off/+/- option and set flag accordingly */
139 {
140     static const char* Keys[] = {
141         "OFF",
142         "ON",
143     };
144
145     if (Tok == TOK_PLUS) {
146         *Flag = 1;
147         NextTok ();
148     } else if (Tok == TOK_MINUS) {
149         *Flag = 0;
150         NextTok ();
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;
157         }
158     } else if (TokIsSep (Tok)) {
159         /* Without anything assume switch on */
160         *Flag = 1;
161     } else {
162         ErrorSkip ("`on' or `off' expected");
163     }
164 }
165
166
167
168 static void ExportImport (void (*Func) (SymEntry*, unsigned char, unsigned),
169                           unsigned char DefAddrSize, unsigned Flags)
170 /* Export or import symbols */
171 {
172     SymEntry* Sym;
173     unsigned char AddrSize;
174
175     while (1) {
176
177         /* We need an identifier here */
178         if (Tok != TOK_IDENT) {
179             ErrorSkip ("Identifier expected");
180             return;
181         }
182
183         /* Find the symbol table entry, allocate a new one if necessary */
184         Sym = SymFind (CurrentScope, SVal, SYM_ALLOC_NEW);
185
186         /* Skip the name */
187         NextTok ();
188
189         /* Get an optional address size */
190         AddrSize = OptionalAddrSize ();
191         if (AddrSize == ADDR_SIZE_DEFAULT) {
192             AddrSize = DefAddrSize;
193         }
194
195         /* Call the actual import/export function */
196         Func (Sym, AddrSize, Flags);
197
198         /* More symbols? */
199         if (Tok == TOK_COMMA) {
200             NextTok ();
201         } else {
202             break;
203         }
204     }
205 }
206
207
208
209 static long IntArg (long Min, long Max)
210 /* Read an integer argument and check a range. Accept the token "unlimited"
211  * and return -1 in this case.
212  */
213 {
214     if (Tok == TOK_IDENT && strcmp (SVal, "unlimited") == 0) {
215         NextTok ();
216         return -1;
217     } else {
218         long Val = ConstExpression ();
219         if (Val < Min || Val > Max) {
220             Error ("Range error");
221             Val = Min;
222         }
223         return Val;
224     }
225 }
226
227
228
229 static void ConDes (const char* Name, unsigned Type)
230 /* Parse remaining line for constructor/destructor of the remaining type */
231 {
232     long Prio;
233
234
235     /* Find the symbol table entry, allocate a new one if necessary */
236     SymEntry* Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW);
237
238     /* Optional constructor priority */
239     if (Tok == TOK_COMMA) {
240         /* Priority value follows */
241         NextTok ();
242         Prio = ConstExpression ();
243         if (Prio < CD_PRIO_MIN || Prio > CD_PRIO_MAX) {
244             /* Value out of range */
245             Error ("Range error");
246             return;
247         }
248     } else {
249         /* Use the default priority value */
250         Prio = CD_PRIO_DEF;
251     }
252
253     /* Define the symbol */
254     SymConDes (Sym, ADDR_SIZE_DEFAULT, Type, (unsigned) Prio);
255 }
256
257
258
259 /*****************************************************************************/
260 /*                             Handler functions                             */
261 /*****************************************************************************/
262
263
264
265 static void DoA16 (void)
266 /* Switch the accu to 16 bit mode (assembler only) */
267 {
268     if (GetCPU() != CPU_65816) {
269         Error ("Command is only valid in 65816 mode");
270     } else {
271         /* Immidiate mode has two extension bytes */
272         ExtBytes [AMI_IMM_ACCU] = 2;
273     }
274 }
275
276
277
278 static void DoA8 (void)
279 /* Switch the accu to 8 bit mode (assembler only) */
280 {
281     if (GetCPU() != CPU_65816) {
282         Error ("Command is only valid in 65816 mode");
283     } else {
284         /* Immidiate mode has one extension byte */
285         ExtBytes [AMI_IMM_ACCU] = 1;
286     }
287 }
288
289
290
291 static void DoAddr (void)
292 /* Define addresses */
293 {
294     while (1) {
295         if (GetCPU() == CPU_65816) {
296             EmitWord (GenWordExpr (Expression ()));
297         } else {
298             /* Do a range check */
299             EmitWord (Expression ());
300         }
301         if (Tok != TOK_COMMA) {
302             break;
303         } else {
304             NextTok ();
305         }
306     }
307 }
308
309
310
311 static void DoAlign (void)
312 /* Align the PC to some boundary */
313 {
314     long Val;
315     long Align;
316     unsigned Bit;
317
318     /* Read the alignment value */
319     Align = ConstExpression ();
320     if (Align <= 0 || Align > 0x10000) {
321         ErrorSkip ("Range error");
322         return;
323     }
324
325     /* Optional value follows */
326     if (Tok == TOK_COMMA) {
327         NextTok ();
328         Val = ConstExpression ();
329         /* We need a byte value here */
330         if (!IsByteRange (Val)) {
331             ErrorSkip ("Range error");
332             return;
333         }
334     } else {
335         Val = -1;
336     }
337
338     /* Check if the alignment is a power of two */
339     Bit = BitFind (Align);
340     if (Align != (0x01L << Bit)) {
341         Error ("Alignment value must be a power of 2");
342     } else {
343         SegAlign (Bit, (int) Val);
344     }
345 }
346
347
348
349 static void DoASCIIZ (void)
350 /* Define text with a zero terminator */
351 {
352     unsigned Len;
353
354     while (1) {
355         /* Must have a string constant */
356         if (Tok != TOK_STRCON) {
357             ErrorSkip ("String constant expected");
358             return;
359         }
360
361         /* Get the length of the string constant */
362         Len = strlen (SVal);
363
364         /* Translate into target charset and emit */
365         TgtTranslateBuf (SVal, Len);
366         EmitData ((unsigned char*) SVal, Len);
367         NextTok ();
368         if (Tok == TOK_COMMA) {
369             NextTok ();
370         } else {
371             break;
372         }
373     }
374     Emit0 (0);
375 }
376
377
378
379 static void DoAssert (void)
380 /* Add an assertion */
381 {
382     static const char* ActionTab [] = {
383         "WARN", "WARNING",
384         "ERROR"
385     };
386
387     int Action;
388
389
390     /* First we have the expression that has to evaluated */
391     ExprNode* Expr = Expression ();
392     ConsumeComma ();
393
394     /* Action follows */
395     if (Tok != TOK_IDENT) {
396         ErrorSkip ("Identifier expected");
397         return;
398     }
399     Action = GetSubKey (ActionTab, sizeof (ActionTab) / sizeof (ActionTab[0]));
400     switch (Action) {
401
402         case 0:
403         case 1:
404             /* Warning */
405             Action = ASSERT_ACT_WARN;
406             break;
407
408         case 2:
409             /* Error */
410             Action = ASSERT_ACT_ERROR;
411             break;
412
413         default:
414             Error ("Illegal assert action specifier");
415     }
416     NextTok ();
417     ConsumeComma ();
418
419     /* Read the message */
420     if (Tok != TOK_STRCON) {
421         ErrorSkip ("String constant expected");
422     } else {
423         AddAssertion (Expr, Action, GetStringId (SVal));
424         NextTok ();
425     }
426 }
427
428
429
430 static void DoAutoImport (void)
431 /* Mark unresolved symbols as imported */
432 {
433     SetBoolOption (&AutoImport);
434 }
435
436
437
438 static void DoBss (void)
439 /* Switch to the BSS segment */
440 {
441     UseSeg (&BssSegDef);
442 }
443
444
445
446 static void DoByte (void)
447 /* Define bytes */
448 {
449     while (1) {
450         if (Tok == TOK_STRCON) {
451             /* A string, translate into target charset and emit */
452             unsigned Len = strlen (SVal);
453             TgtTranslateBuf (SVal, Len);
454             EmitData ((unsigned char*) SVal, Len);
455             NextTok ();
456         } else {
457             EmitByte (Expression ());
458         }
459         if (Tok != TOK_COMMA) {
460             break;
461         } else {
462             NextTok ();
463             /* Do smart handling of dangling comma */
464             if (Tok == TOK_SEP) {
465                 Error ("Unexpected end of line");
466                 break;
467             }
468         }
469     }
470 }
471
472
473
474 static void DoCase (void)
475 /* Switch the IgnoreCase option */
476 {
477     SetBoolOption (&IgnoreCase);
478     IgnoreCase = !IgnoreCase;
479 }
480
481
482
483 static void DoCharMap (void)
484 /* Allow custome character mappings */
485 {
486     long Index;
487     long Code;
488
489     /* Read the index as numerical value */
490     Index = ConstExpression ();
491     if (Index < 1 || Index > 255) {
492         /* Value out of range */
493         ErrorSkip ("Range error");
494         return;
495     }
496
497     /* Comma follows */
498     ConsumeComma ();
499
500     /* Read the character code */
501     Code = ConstExpression ();
502     if (Code < 1 || Code > 255) {
503         /* Value out of range */
504         ErrorSkip ("Range error");
505         return;
506     }
507
508     /* Set the character translation */
509     TgtTranslateSet ((unsigned) Index, (unsigned char) Code);
510 }
511
512
513
514 static void DoCode (void)
515 /* Switch to the code segment */
516 {
517     UseSeg (&CodeSegDef);
518 }
519
520
521
522 static void DoConDes (void)
523 /* Export a symbol as constructor/destructor */
524 {
525     static const char* Keys[] = {
526         "CONSTRUCTOR",
527         "DESTRUCTOR",
528     };
529     char Name [sizeof (SVal)];
530     long Type;
531
532     /* Symbol name follows */
533     if (Tok != TOK_IDENT) {
534         ErrorSkip ("Identifier expected");
535         return;
536     }
537     strcpy (Name, SVal);
538     NextTok ();
539
540     /* Type follows. May be encoded as identifier or numerical */
541     ConsumeComma ();
542     if (Tok == TOK_IDENT) {
543
544         /* Map the following keyword to a number, then skip it */
545         Type = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
546         NextTok ();
547
548         /* Check if we got a valid keyword */
549         if (Type < 0) {
550             Error ("Syntax error");
551             SkipUntilSep ();
552             return;
553         }
554
555     } else {
556
557         /* Read the type as numerical value */
558         Type = ConstExpression ();
559         if (Type < CD_TYPE_MIN || Type > CD_TYPE_MAX) {
560             /* Value out of range */
561             Error ("Range error");
562             return;
563         }
564
565     }
566
567     /* Parse the remainder of the line and export the symbol */
568     ConDes (Name, (unsigned) Type);
569 }
570
571
572
573 static void DoConstructor (void)
574 /* Export a symbol as constructor */
575 {
576     char Name [sizeof (SVal)];
577
578     /* Symbol name follows */
579     if (Tok != TOK_IDENT) {
580         ErrorSkip ("Identifier expected");
581         return;
582     }
583     strcpy (Name, SVal);
584     NextTok ();
585
586     /* Parse the remainder of the line and export the symbol */
587     ConDes (Name, CD_TYPE_CON);
588 }
589
590
591
592 static void DoData (void)
593 /* Switch to the data segment */
594 {
595     UseSeg (&DataSegDef);
596 }
597
598
599
600 static void DoDbg (void)
601 /* Add debug information from high level code */
602 {
603     static const char* Keys[] = {
604         "FILE",
605         "LINE",
606         "SYM",
607     };
608     int Key;
609
610
611     /* We expect a subkey */
612     if (Tok != TOK_IDENT) {
613         ErrorSkip ("Identifier expected");
614         return;
615     }
616
617     /* Map the following keyword to a number */
618     Key = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
619
620     /* Skip the subkey */
621     NextTok ();
622
623     /* Check the key and dispatch to a handler */
624     switch (Key) {
625         case 0:     DbgInfoFile ();             break;
626         case 1:     DbgInfoLine ();             break;
627         case 2:     DbgInfoSym ();              break;
628         default:    ErrorSkip ("Syntax error"); break;
629     }
630 }
631
632
633
634 static void DoDByt (void)
635 /* Output double bytes */
636 {
637     while (1) {
638         EmitWord (GenSwapExpr (Expression ()));
639         if (Tok != TOK_COMMA) {
640             break;
641         } else {
642             NextTok ();
643         }
644     }
645 }
646
647
648
649 static void DoDebugInfo (void)
650 /* Switch debug info on or off */
651 {
652     SetBoolOption (&DbgSyms);
653 }
654
655
656
657 static void DoDefine (void)
658 /* Define a one line macro */
659 {
660     MacDef (MAC_STYLE_DEFINE);
661 }
662
663
664
665 static void DoDestructor (void)
666 /* Export a symbol as destructor */
667 {
668     char Name [sizeof (SVal)];
669
670     /* Symbol name follows */
671     if (Tok != TOK_IDENT) {
672         ErrorSkip ("Identifier expected");
673         return;
674     }
675     strcpy (Name, SVal);
676     NextTok ();
677
678     /* Parse the remainder of the line and export the symbol */
679     ConDes (Name, CD_TYPE_DES);
680 }
681
682
683
684 static void DoDWord (void)
685 /* Define dwords */
686 {
687     while (1) {
688         EmitDWord (Expression ());
689         if (Tok != TOK_COMMA) {
690             break;
691         } else {
692             NextTok ();
693         }
694     }
695 }
696
697
698
699 static void DoEnd (void)
700 /* End of assembly */
701 {
702     ForcedEnd = 1;
703     NextTok ();
704 }
705
706
707
708 static void DoEndProc (void)
709 /* Leave a lexical level */
710 {
711     if (CurrentScope == RootScope || GetCurrentSymTabType () != ST_PROC) {
712         /* No local scope */
713         ErrorSkip ("No open .PROC");
714     } else {
715         SymLeaveLevel ();
716     }
717 }
718
719
720
721 static void DoEndScope (void)
722 /* Leave a lexical level */
723 {
724     if (CurrentScope == RootScope || GetCurrentSymTabType () != ST_SCOPE) {
725         /* No local scope */
726         ErrorSkip ("No open .SCOPE");
727     } else {
728         SymLeaveLevel ();
729     }
730 }
731
732
733
734 static void DoError (void)
735 /* User error */
736 {
737     if (Tok != TOK_STRCON) {
738         ErrorSkip ("String constant expected");
739     } else {
740         Error ("User error: %s", SVal);
741         SkipUntilSep ();
742     }
743 }
744
745
746
747 static void DoExitMacro (void)
748 /* Exit a macro expansion */
749 {
750     if (!InMacExpansion ()) {
751         /* We aren't expanding a macro currently */
752         DoUnexpected ();
753     } else {
754         MacAbort ();
755     }
756 }
757
758
759
760 static void DoExport (void)
761 /* Export a symbol */
762 {
763     ExportImport (SymExport, ADDR_SIZE_DEFAULT, SF_NONE);
764 }
765
766
767
768 static void DoExportZP (void)
769 /* Export a zeropage symbol */
770 {
771     ExportImport (SymExport, ADDR_SIZE_ZP, SF_NONE);
772 }
773
774
775
776 static void DoFarAddr (void)
777 /* Define far addresses (24 bit) */
778 {
779     while (1) {
780         EmitFarAddr (Expression ());
781         if (Tok != TOK_COMMA) {
782             break;
783         } else {
784             NextTok ();
785         }
786     }
787 }
788
789
790
791 static void DoFeature (void)
792 /* Switch the Feature option */
793 {
794     /* Allow a list of comma separated keywords */
795     while (1) {
796
797         /* We expect an identifier */
798         if (Tok != TOK_IDENT) {
799             ErrorSkip ("Identifier expected");
800             return;
801         }
802
803         /* Make the string attribute lower case */
804         LocaseSVal ();
805
806         /* Set the feature and check for errors */
807         if (SetFeature (SVal) == FEAT_UNKNOWN) {
808             /* Not found */
809             ErrorSkip ("Invalid feature: `%s'", SVal);
810             return;
811         } else {
812             /* Skip the keyword */
813             NextTok ();
814         }
815
816         /* Allow more than one keyword */
817         if (Tok == TOK_COMMA) {
818             NextTok ();
819         } else {
820             break;
821         }
822     }
823 }
824
825
826
827 static void DoFileOpt (void)
828 /* Insert a file option */
829 {
830     long OptNum;
831
832     /* The option type may be given as a keyword or as a number. */
833     if (Tok == TOK_IDENT) {
834
835         /* Option given as keyword */
836         static const char* Keys [] = {
837             "AUTHOR", "COMMENT", "COMPILER"
838         };
839
840         /* Map the option to a number */
841         OptNum = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
842         if (OptNum < 0) {
843             /* Not found */
844             ErrorSkip ("File option keyword expected");
845             return;
846         }
847
848         /* Skip the keyword */
849         NextTok ();
850
851         /* Must be followed by a comma */
852         ConsumeComma ();
853
854         /* We accept only string options for now */
855         if (Tok != TOK_STRCON) {
856             ErrorSkip ("String constant expected");
857             return;
858         }
859
860         /* Insert the option */
861         switch (OptNum) {
862
863             case 0:
864                 /* Author */
865                 OptAuthor (SVal);
866                 break;
867
868             case 1:
869                 /* Comment */
870                 OptComment (SVal);
871                 break;
872
873             case 2:
874                 /* Compiler */
875                 OptCompiler (SVal);
876                 break;
877
878             default:
879                 Internal ("Invalid OptNum: %ld", OptNum);
880
881         }
882
883         /* Done */
884         NextTok ();
885
886     } else {
887
888         /* Option given as number */
889         OptNum = ConstExpression ();
890         if (!IsByteRange (OptNum)) {
891             ErrorSkip ("Range error");
892             return;
893         }
894
895         /* Must be followed by a comma */
896         ConsumeComma ();
897
898         /* We accept only string options for now */
899         if (Tok != TOK_STRCON) {
900             ErrorSkip ("String constant expected");
901             return;
902         }
903
904         /* Insert the option */
905         OptStr ((unsigned char) OptNum, SVal);
906
907         /* Done */
908         NextTok ();
909     }
910 }
911
912
913
914 static void DoForceImport (void)
915 /* Do a forced import on a symbol */
916 {
917     ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_FORCED);
918 }
919
920
921
922 static void DoGlobal (void)
923 /* Declare a global symbol */
924 {
925     ExportImport (SymGlobal, ADDR_SIZE_DEFAULT, SF_NONE);
926 }
927
928
929
930 static void DoGlobalZP (void)
931 /* Declare a global zeropage symbol */
932 {
933     ExportImport (SymGlobal, ADDR_SIZE_ZP, SF_NONE);
934 }
935
936
937
938 static void DoI16 (void)
939 /* Switch the index registers to 16 bit mode (assembler only) */
940 {
941     if (GetCPU() != CPU_65816) {
942         Error ("Command is only valid in 65816 mode");
943     } else {
944         /* Immidiate mode has two extension bytes */
945         ExtBytes [AMI_IMM_INDEX] = 2;
946     }
947 }
948
949
950
951 static void DoI8 (void)
952 /* Switch the index registers to 16 bit mode (assembler only) */
953 {
954     if (GetCPU() != CPU_65816) {
955         Error ("Command is only valid in 65816 mode");
956     } else {
957         /* Immidiate mode has one extension byte */
958         ExtBytes [AMI_IMM_INDEX] = 1;
959     }
960 }
961
962
963
964 static void DoImport (void)
965 /* Import a symbol */
966 {
967     ExportImport (SymImport, ADDR_SIZE_DEFAULT, SF_NONE);
968 }
969
970
971
972 static void DoImportZP (void)
973 /* Import a zero page symbol */
974 {
975     ExportImport (SymImport, ADDR_SIZE_ZP, SF_NONE);
976 }
977
978
979
980 static void DoIncBin (void)
981 /* Include a binary file */
982 {
983     char Name [sizeof (SVal)];
984     long Start = 0L;
985     long Count = -1L;
986     long Size;
987     FILE* F;
988
989     /* Name must follow */
990     if (Tok != TOK_STRCON) {
991         ErrorSkip ("String constant expected");
992         return;
993     }
994     strcpy (Name, SVal);
995     NextTok ();
996
997     /* A starting offset may follow */
998     if (Tok == TOK_COMMA) {
999         NextTok ();
1000         Start = ConstExpression ();
1001
1002         /* And a length may follow */
1003         if (Tok == TOK_COMMA) {
1004             NextTok ();
1005             Count = ConstExpression ();
1006         }
1007
1008     }
1009
1010     /* Try to open the file */
1011     F = fopen (Name, "rb");
1012     if (F == 0) {
1013
1014         /* Search for the file in the include directories. */
1015         char* PathName = FindInclude (Name);
1016         if (PathName == 0 || (F = fopen (PathName, "r")) == 0) {
1017             /* Not found or cannot open, print an error and bail out */
1018             ErrorSkip ("Cannot open include file `%s': %s", Name, strerror (errno));
1019         }
1020
1021         /* Free the allocated memory */
1022         xfree (PathName);
1023
1024         /* If we had an error before, bail out now */
1025         if (F == 0) {
1026             return;
1027         }
1028     }
1029
1030     /* Get the size of the file */
1031     fseek (F, 0, SEEK_END);
1032     Size = ftell (F);
1033
1034     /* If a count was not given, calculate it now */
1035     if (Count < 0) {
1036         Count = Size - Start;
1037         if (Count < 0) {
1038             /* Nothing to read - flag this as a range error */
1039             ErrorSkip ("Range error");
1040             goto Done;
1041         }
1042     } else {
1043         /* Count was given, check if it is valid */
1044         if (Start + Count > Size) {
1045             ErrorSkip ("Range error");
1046             goto Done;
1047         }
1048     }
1049
1050     /* Seek to the start position */
1051     fseek (F, Start, SEEK_SET);
1052
1053     /* Read chunks and insert them into the output */
1054     while (Count > 0) {
1055
1056         unsigned char Buf [1024];
1057
1058         /* Calculate the number of bytes to read */
1059         size_t BytesToRead = (Count > (long)sizeof(Buf))? sizeof(Buf) : (size_t) Count;
1060
1061         /* Read chunk */
1062         size_t BytesRead = fread (Buf, 1, BytesToRead, F);
1063         if (BytesToRead != BytesRead) {
1064             /* Some sort of error */
1065             ErrorSkip ("Cannot read from include file `%s': %s",
1066                        Name, strerror (errno));
1067             break;
1068         }
1069
1070         /* Insert it into the output */
1071         EmitData (Buf, BytesRead);
1072
1073         /* Keep the counters current */
1074         Count -= BytesRead;
1075     }
1076
1077 Done:
1078     /* Close the file, ignore errors since it's r/o */
1079     (void) fclose (F);
1080 }
1081
1082
1083
1084 static void DoInclude (void)
1085 /* Include another file */
1086 {
1087     char Name [MAX_STR_LEN+1];
1088
1089     /* Name must follow */
1090     if (Tok != TOK_STRCON) {
1091         ErrorSkip ("String constant expected");
1092     } else {
1093         strcpy (Name, SVal);
1094         NextTok ();
1095         NewInputFile (Name);
1096     }
1097 }
1098
1099
1100
1101 static void DoInvalid (void)
1102 /* Handle a token that is invalid here, since it should have been handled on
1103  * a much lower level of the expression hierarchy. Getting this sort of token
1104  * means that the lower level code has bugs.
1105  * This function differs to DoUnexpected in that the latter may be triggered
1106  * by the user by using keywords in the wrong location. DoUnexpected is not
1107  * an error in the assembler itself, while DoInvalid is.
1108  */
1109 {
1110     Internal ("Unexpected token: %s", Keyword);
1111 }
1112
1113
1114
1115 static void DoLineCont (void)
1116 /* Switch the use of line continuations */
1117 {
1118     SetBoolOption (&LineCont);
1119 }
1120
1121
1122
1123 static void DoList (void)
1124 /* Enable/disable the listing */
1125 {
1126     /* Get the setting */
1127     unsigned char List;
1128     SetBoolOption (&List);
1129
1130     /* Manage the counter */
1131     if (List) {
1132         EnableListing ();
1133     } else {
1134         DisableListing ();
1135     }
1136 }
1137
1138
1139
1140 static void DoListBytes (void)
1141 /* Set maximum number of bytes to list for one line */
1142 {
1143     SetListBytes (IntArg (MIN_LIST_BYTES, MAX_LIST_BYTES));
1144 }
1145
1146
1147
1148 static void DoLocalChar (void)
1149 /* Define the character that starts local labels */
1150 {
1151     if (Tok != TOK_CHARCON) {
1152         ErrorSkip ("Character constant expected");
1153     } else {
1154         if (IVal != '@' && IVal != '?') {
1155             Error ("Invalid start character for locals");
1156         } else {
1157             LocalStart = (char) IVal;
1158         }
1159         NextTok ();
1160     }
1161 }
1162
1163
1164
1165 static void DoMacPack (void)
1166 /* Insert a macro package */
1167 {
1168     /* Macro package names */
1169     static const char* Keys [] = {
1170         "GENERIC",
1171         "LONGBRANCH",
1172         "CBM",
1173         "CPU"
1174     };
1175
1176     int Package;
1177
1178     /* We expect an identifier */
1179     if (Tok != TOK_IDENT) {
1180         ErrorSkip ("Identifier expected");
1181         return;
1182     }
1183
1184     /* Map the keyword to a number */
1185     Package = GetSubKey (Keys, sizeof (Keys) / sizeof (Keys [0]));
1186     if (Package < 0) {
1187         /* Not found */
1188         ErrorSkip ("Invalid macro package");
1189         return;
1190     }
1191
1192     /* Skip the package name */
1193     NextTok ();
1194
1195     /* Insert the package */
1196     InsertMacPack (Package);
1197 }
1198
1199
1200
1201 static void DoMacro (void)
1202 /* Start a macro definition */
1203 {
1204     MacDef (MAC_STYLE_CLASSIC);
1205 }
1206
1207
1208
1209 static void DoNull (void)
1210 /* Switch to the NULL segment */
1211 {
1212     UseSeg (&NullSegDef);
1213 }
1214
1215
1216
1217 static void DoOrg (void)
1218 /* Start absolute code */
1219 {
1220     long PC = ConstExpression ();
1221     if (PC < 0 || PC > 0xFFFFFF) {
1222         Error ("Range error");
1223         return;
1224     }
1225     SetAbsPC (PC);
1226 }
1227
1228
1229
1230 static void DoOut (void)
1231 /* Output a string */
1232 {
1233     if (Tok != TOK_STRCON) {
1234         ErrorSkip ("String constant expected");
1235     } else {
1236         /* Output the string and be sure to flush the output to keep it in
1237          * sync with any error messages if the output is redirected to a file.
1238          */
1239         printf ("%s\n", SVal);
1240         fflush (stdout);
1241         NextTok ();
1242     }
1243 }
1244
1245
1246
1247 static void DoP02 (void)
1248 /* Switch to 6502 CPU */
1249 {
1250     SetCPU (CPU_6502);
1251 }
1252
1253
1254
1255 static void DoPC02 (void)
1256 /* Switch to 65C02 CPU */
1257 {
1258     SetCPU (CPU_65C02);
1259 }
1260
1261
1262
1263 static void DoP816 (void)
1264 /* Switch to 65816 CPU */
1265 {
1266     SetCPU (CPU_65816);
1267 }
1268
1269
1270
1271 static void DoPageLength (void)
1272 /* Set the page length for the listing */
1273 {
1274     PageLength = IntArg (MIN_PAGE_LEN, MAX_PAGE_LEN);
1275 }
1276
1277
1278
1279 static void DoPopSeg (void)
1280 /* Pop an old segment from the segment stack */
1281 {
1282     SegDef* Def;
1283
1284     /* Must have a segment on the stack */
1285     if (CollCount (&SegStack) == 0) {
1286         ErrorSkip ("Segment stack is empty");
1287         return;
1288     }
1289
1290     /* Pop the last element */
1291     Def = CollPop (&SegStack);
1292
1293     /* Restore this segment */
1294     UseSeg (Def);
1295
1296     /* Delete the segment definition */
1297     FreeSegDef (Def);
1298 }
1299
1300
1301
1302 static void DoProc (void)
1303 /* Start a new lexical scope */
1304 {
1305     char Name[sizeof(SVal)];
1306     unsigned char AddrSize;
1307
1308     if (Tok == TOK_IDENT) {
1309
1310         /* The new scope has a name. Remember it. */
1311         strcpy (Name, SVal);
1312
1313         /* Search for the symbol, generate a new one if needed */
1314         SymEntry* Sym = SymFind (CurrentScope, Name, SYM_ALLOC_NEW);
1315
1316         /* Skip the scope name */
1317         NextTok ();
1318
1319         /* Read an optional address size specifier */
1320         AddrSize = OptionalAddrSize ();
1321
1322         /* Mark the symbol as defined */
1323         SymDef (Sym, GenCurrentPC (), AddrSize, SF_LABEL);
1324
1325     } else {
1326
1327         /* A .PROC statement without a name */
1328         Warning (1, "Unnamed .PROCs are deprecated, please use .SCOPE");
1329         AnonName (Name, sizeof (Name), "PROC");
1330         AddrSize = ADDR_SIZE_DEFAULT;
1331
1332     }
1333
1334     /* Enter a new scope */
1335     SymEnterLevel (Name, ST_PROC, AddrSize);
1336 }
1337
1338
1339
1340 static void DoPSC02 (void)
1341 /* Switch to 65SC02 CPU */
1342 {
1343     SetCPU (CPU_65SC02);
1344 }
1345
1346
1347
1348 static void DoPushSeg (void)
1349 /* Push the current segment onto the segment stack */
1350 {
1351     /* Can only push a limited size of segments */
1352     if (CollCount (&SegStack) >= MAX_PUSHED_SEGMENTS) {
1353         ErrorSkip ("Segment stack overflow");
1354         return;
1355     }
1356
1357     /* Get the current segment and push it */
1358     CollAppend (&SegStack, DupSegDef (GetCurrentSegDef ()));
1359 }
1360
1361
1362
1363 static void DoReloc (void)
1364 /* Enter relocatable mode */
1365 {
1366     RelocMode = 1;
1367 }
1368
1369
1370
1371 static void DoRepeat (void)
1372 /* Repeat some instruction block */
1373 {
1374     ParseRepeat ();
1375 }
1376
1377
1378
1379 static void DoRes (void)
1380 /* Reserve some number of storage bytes */
1381 {
1382     long Count;
1383     long Val;
1384
1385     Count = ConstExpression ();
1386     if (Count > 0xFFFF || Count < 0) {
1387         ErrorSkip ("Range error");
1388         return;
1389     }
1390     if (Tok == TOK_COMMA) {
1391         NextTok ();
1392         Val = ConstExpression ();
1393         /* We need a byte value here */
1394         if (!IsByteRange (Val)) {
1395             ErrorSkip ("Range error");
1396             return;
1397         }
1398
1399         /* Emit constant values */
1400         while (Count--) {
1401             Emit0 ((unsigned char) Val);
1402         }
1403
1404     } else {
1405         /* Emit fill fragments */
1406         EmitFill (Count);
1407     }
1408 }
1409
1410
1411
1412 static void DoROData (void)
1413 /* Switch to the r/o data segment */
1414 {
1415     UseSeg (&RODataSegDef);
1416 }
1417
1418
1419
1420 static void DoScope (void)
1421 /* Start a local scope */
1422 {
1423     char Name[sizeof (SVal)];
1424     unsigned char AddrSize;
1425
1426
1427     if (Tok == TOK_IDENT) {
1428
1429         /* The new scope has a name. Remember and skip it. */
1430         strcpy (Name, SVal);
1431         NextTok ();
1432
1433     } else {
1434
1435         /* An unnamed scope */
1436         AnonName (Name, sizeof (Name), "SCOPE");
1437
1438     }
1439
1440     /* Read an optional address size specifier */
1441     AddrSize = OptionalAddrSize ();
1442
1443     /* Enter the new scope */
1444     SymEnterLevel (Name, ST_SCOPE, AddrSize);
1445
1446 }
1447
1448
1449
1450 static void DoSegment (void)
1451 /* Switch to another segment */
1452 {
1453     char Name [sizeof (SVal)];
1454     SegDef Def;
1455     Def.Name = Name;
1456
1457     if (Tok != TOK_STRCON) {
1458         ErrorSkip ("String constant expected");
1459     } else {
1460
1461         /* Save the name of the segment and skip it */
1462         strcpy (Name, SVal);
1463         NextTok ();
1464
1465         /* Check for an optional address size modifier */
1466         Def.AddrSize = OptionalAddrSize ();
1467
1468         /* Set the segment */
1469         UseSeg (&Def);
1470     }
1471 }
1472
1473
1474
1475 static void DoSetCPU (void)
1476 /* Switch the CPU instruction set */
1477 {
1478     /* We expect an identifier */
1479     if (Tok != TOK_STRCON) {
1480         ErrorSkip ("String constant expected");
1481     } else {
1482         /* Try to find the CPU, then skip the identifier */
1483         cpu_t CPU = FindCPU (SVal);
1484         NextTok ();
1485
1486         /* Switch to the new CPU */
1487         SetCPU (CPU);
1488     }
1489 }
1490
1491
1492
1493 static void DoSmart (void)
1494 /* Smart mode on/off */
1495 {
1496     SetBoolOption (&SmartMode);
1497 }
1498
1499
1500
1501 static void DoSunPlus (void)
1502 /* Switch to the SUNPLUS CPU */
1503 {
1504     SetCPU (CPU_SUNPLUS);
1505 }
1506
1507
1508
1509 static void DoTag (void)
1510 /* Allocate space for a struct */
1511 {                                           
1512     SymEntry* SizeSym;
1513     long Size;
1514
1515     /* Read the struct name */
1516     SymTable* Struct = ParseScopedSymTable ();
1517
1518     /* Check the supposed struct */
1519     if (Struct == 0) {
1520         ErrorSkip ("Unknown struct");
1521         return;
1522     }
1523     if (GetSymTabType (Struct) != ST_STRUCT) {
1524         ErrorSkip ("Not a struct");
1525         return;
1526     }
1527
1528     /* Get the symbol that defines the size of the struct */
1529     SizeSym = GetSizeOfScope (Struct);
1530
1531     /* Check if it does exist and if its value is known */
1532     if (SizeSym == 0 || !SymIsConst (SizeSym, &Size)) {
1533         ErrorSkip ("Size of struct/union is unknown");
1534         return;
1535     }
1536
1537     /* Optional multiplicator may follow */
1538     if (Tok == TOK_COMMA) {
1539         long Multiplicator;
1540         NextTok ();
1541         Multiplicator = ConstExpression ();
1542         /* Multiplicator must make sense */
1543         if (Multiplicator <= 0) {
1544             ErrorSkip ("Range error");
1545             return;
1546         }
1547         Size *= Multiplicator;
1548     }
1549
1550     /* Emit fill fragments */
1551     EmitFill (Size);
1552 }
1553
1554
1555
1556 static void DoUnexpected (void)
1557 /* Got an unexpected keyword */
1558 {
1559     Error ("Unexpected `%s'", Keyword);
1560     SkipUntilSep ();
1561 }
1562
1563
1564
1565 static void DoWarning (void)
1566 /* User warning */
1567 {
1568     if (Tok != TOK_STRCON) {
1569         ErrorSkip ("String constant expected");
1570     } else {
1571         Warning (0, "User warning: %s", SVal);
1572         SkipUntilSep ();
1573     }
1574 }
1575
1576
1577
1578 static void DoWord (void)
1579 /* Define words */
1580 {
1581     while (1) {
1582         EmitWord (Expression ());
1583         if (Tok != TOK_COMMA) {
1584             break;
1585         } else {
1586             NextTok ();
1587         }
1588     }
1589 }
1590
1591
1592
1593 static void DoZeropage (void)
1594 /* Switch to the zeropage segment */
1595 {
1596     UseSeg (&ZeropageSegDef);
1597 }
1598
1599
1600
1601 /*****************************************************************************/
1602 /*                                Table data                                 */
1603 /*****************************************************************************/
1604
1605
1606
1607 /* Control commands flags */
1608 enum {
1609     ccNone      = 0x0000,               /* No special flags */
1610     ccKeepToken = 0x0001                /* Do not skip the current token */
1611 };
1612
1613 /* Control command table */
1614 typedef struct CtrlDesc CtrlDesc;
1615 struct CtrlDesc {
1616     unsigned    Flags;                  /* Flags for this directive */
1617     void        (*Handler) (void);      /* Command handler */
1618 };
1619
1620 #define PSEUDO_COUNT    (sizeof (CtrlCmdTab) / sizeof (CtrlCmdTab [0]))
1621 static CtrlDesc CtrlCmdTab [] = {
1622     { ccNone,           DoA16           },
1623     { ccNone,           DoA8            },
1624     { ccNone,           DoAddr          },      /* .ADDR */
1625     { ccNone,           DoAlign         },
1626     { ccNone,           DoASCIIZ        },
1627     { ccNone,           DoAssert        },
1628     { ccNone,           DoAutoImport    },
1629     { ccNone,           DoUnexpected    },      /* .BLANK */
1630     { ccNone,           DoBss           },
1631     { ccNone,           DoByte          },
1632     { ccNone,           DoCase          },
1633     { ccNone,           DoCharMap       },
1634     { ccNone,           DoCode          },
1635     { ccNone,           DoUnexpected,   },      /* .CONCAT */
1636     { ccNone,           DoConDes        },
1637     { ccNone,           DoUnexpected    },      /* .CONST */
1638     { ccNone,           DoConstructor   },
1639     { ccNone,           DoUnexpected    },      /* .CPU */
1640     { ccNone,           DoData          },
1641     { ccNone,           DoDbg,          },
1642     { ccNone,           DoDByt          },
1643     { ccNone,           DoDebugInfo     },
1644     { ccNone,           DoDefine        },
1645     { ccNone,           DoUnexpected    },      /* .DEFINED */
1646     { ccNone,           DoDestructor    },
1647     { ccNone,           DoDWord         },
1648     { ccKeepToken,      DoConditionals  },      /* .ELSE */
1649     { ccKeepToken,      DoConditionals  },      /* .ELSEIF */
1650     { ccKeepToken,      DoEnd           },
1651     { ccNone,           DoUnexpected    },      /* .ENDENUM */
1652     { ccKeepToken,      DoConditionals  },      /* .ENDIF */
1653     { ccNone,           DoUnexpected    },      /* .ENDMACRO */
1654     { ccNone,           DoEndProc       },
1655     { ccNone,           DoUnexpected    },      /* .ENDREPEAT */
1656     { ccNone,           DoEndScope      },
1657     { ccNone,           DoUnexpected    },      /* .ENDSTRUCT */
1658     { ccNone,           DoUnexpected    },      /* .ENDUNION */
1659     { ccNone,           DoEnum          },
1660     { ccNone,           DoError         },
1661     { ccNone,           DoExitMacro     },
1662     { ccNone,           DoExport        },
1663     { ccNone,           DoExportZP      },
1664     { ccNone,           DoFarAddr       },
1665     { ccNone,           DoFeature       },
1666     { ccNone,           DoFileOpt       },
1667     { ccNone,           DoForceImport   },
1668     { ccNone,           DoUnexpected    },      /* .FORCEWORD */
1669     { ccNone,           DoGlobal        },
1670     { ccNone,           DoGlobalZP      },
1671     { ccNone,           DoI16           },
1672     { ccNone,           DoI8            },
1673     { ccKeepToken,      DoConditionals  },      /* .IF */
1674     { ccKeepToken,      DoConditionals  },      /* .IFBLANK */
1675     { ccKeepToken,      DoConditionals  },      /* .IFCONST */
1676     { ccKeepToken,      DoConditionals  },      /* .IFDEF */
1677     { ccKeepToken,      DoConditionals  },      /* .IFNBLANK */
1678     { ccKeepToken,      DoConditionals  },      /* .IFNCONST */
1679     { ccKeepToken,      DoConditionals  },      /* .IFNDEF */
1680     { ccKeepToken,      DoConditionals  },      /* .IFNREF */
1681     { ccKeepToken,      DoConditionals  },      /* .IFP02 */
1682     { ccKeepToken,      DoConditionals  },      /* .IFP816 */
1683     { ccKeepToken,      DoConditionals  },      /* .IFPC02 */
1684     { ccKeepToken,      DoConditionals  },      /* .IFPSC02 */
1685     { ccKeepToken,      DoConditionals  },      /* .IFREF */
1686     { ccNone,           DoImport        },
1687     { ccNone,           DoImportZP      },
1688     { ccNone,           DoIncBin        },
1689     { ccNone,           DoInclude       },
1690     { ccNone,           DoInvalid       },      /* .LEFT */
1691     { ccNone,           DoLineCont      },
1692     { ccNone,           DoList          },
1693     { ccNone,           DoListBytes     },
1694     { ccNone,           DoUnexpected    },      /* .LOCAL */
1695     { ccNone,           DoLocalChar     },
1696     { ccNone,           DoMacPack       },
1697     { ccNone,           DoMacro         },
1698     { ccNone,           DoUnexpected    },      /* .MATCH */
1699     { ccNone,           DoInvalid       },      /* .MID */
1700     { ccNone,           DoNull          },
1701     { ccNone,           DoOrg           },
1702     { ccNone,           DoOut           },
1703     { ccNone,           DoP02           },
1704     { ccNone,           DoP816          },
1705     { ccNone,           DoPageLength    },
1706     { ccNone,           DoUnexpected    },      /* .PARAMCOUNT */
1707     { ccNone,           DoPC02          },
1708     { ccNone,           DoPopSeg        },
1709     { ccNone,           DoProc          },
1710     { ccNone,           DoPSC02         },
1711     { ccNone,           DoPushSeg       },
1712     { ccNone,           DoUnexpected    },      /* .REFERENCED */
1713     { ccNone,           DoReloc         },
1714     { ccNone,           DoRepeat        },
1715     { ccNone,           DoRes           },
1716     { ccNone,           DoInvalid       },      /* .RIGHT */
1717     { ccNone,           DoROData        },
1718     { ccNone,           DoScope         },
1719     { ccNone,           DoSegment       },
1720     { ccNone,           DoSetCPU        },
1721     { ccNone,           DoUnexpected    },      /* .SIZEOF */
1722     { ccNone,           DoSmart         },
1723     { ccNone,           DoUnexpected    },      /* .STRAT */
1724     { ccNone,           DoUnexpected    },      /* .STRING */
1725     { ccNone,           DoUnexpected    },      /* .STRLEN */
1726     { ccNone,           DoStruct        },
1727     { ccNone,           DoSunPlus       },
1728     { ccNone,           DoTag           },
1729     { ccNone,           DoUnexpected    },      /* .TCOUNT */
1730     { ccNone,           DoUnexpected    },      /* .TIME */
1731     { ccNone,           DoUnion         },
1732     { ccNone,           DoUnexpected    },      /* .VERSION */
1733     { ccNone,           DoWarning       },
1734     { ccNone,           DoWord          },
1735     { ccNone,           DoUnexpected    },      /* .XMATCH */
1736     { ccNone,           DoZeropage      },
1737 };
1738
1739
1740
1741 /*****************************************************************************/
1742 /*                                   Code                                    */
1743 /*****************************************************************************/
1744
1745
1746
1747 void HandlePseudo (void)
1748 /* Handle a pseudo instruction */
1749 {
1750     CtrlDesc* D;
1751
1752     /* Calculate the index into the table */
1753     unsigned Index = Tok - TOK_FIRSTPSEUDO;
1754
1755     /* Safety check */
1756     if (PSEUDO_COUNT != (TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1)) {
1757         Internal ("Pseudo mismatch: PSEUDO_COUNT = %u, actual count = %u\n",
1758                   PSEUDO_COUNT, TOK_LASTPSEUDO - TOK_FIRSTPSEUDO + 1);
1759     }
1760     CHECK (Index < PSEUDO_COUNT);
1761
1762     /* Get the pseudo intruction descriptor */
1763     D = &CtrlCmdTab [Index];
1764
1765     /* Remember the instruction, then skip it if needed */
1766     if ((D->Flags & ccKeepToken) == 0) {
1767         strcpy (Keyword, SVal);
1768         NextTok ();
1769     }
1770
1771     /* Call the handler */
1772     D->Handler ();
1773 }
1774
1775
1776
1777 void SegStackCheck (void)
1778 /* Check if the segment stack is empty at end of assembly */
1779 {
1780     if (CollCount (&SegStack) != 0) {
1781         Error ("Segment stack is not empty");
1782     }
1783 }
1784
1785
1786