]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Work on named scopes
[cc65] / src / ca65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                 Main program for the ca65 macroassembler                  */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 1998-2003 Ullrich von Bassewitz                                       */
10 /*               Römerstrasse 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 <time.h>
40
41 /* common */
42 #include "chartype.h"
43 #include "cmdline.h"
44 #include "print.h"
45 #include "target.h"
46 #include "tgttrans.h"
47 #include "version.h"
48
49 /* ca65 */
50 #include "abend.h"
51 #include "asserts.h"
52 #include "error.h"
53 #include "expr.h"
54 #include "feature.h"
55 #include "filetab.h"
56 #include "global.h"
57 #include "incpath.h"
58 #include "instr.h"
59 #include "istack.h"
60 #include "lineinfo.h"
61 #include "listing.h"
62 #include "macro.h"
63 #include "nexttok.h"
64 #include "objfile.h"
65 #include "options.h"
66 #include "pseudo.h"
67 #include "scanner.h"
68 #include "segment.h"
69 #include "spool.h"
70 #include "symtab.h"
71 #include "ulabel.h"
72
73
74
75 /*****************************************************************************/
76 /*                                   Code                                    */
77 /*****************************************************************************/
78
79
80
81 static void Usage (void)
82 /* Print usage information and exit */
83 {
84     fprintf (stderr,
85              "Usage: %s [options] file\n"
86              "Short options:\n"
87              "  -D name[=value]\tDefine a symbol\n"
88              "  -I dir\t\tSet an include directory search path\n"
89              "  -U\t\t\tMark unresolved symbols as import\n"
90              "  -V\t\t\tPrint the assembler version\n"
91              "  -W n\t\t\tSet warning level n\n"
92              "  -g\t\t\tAdd debug info to object file\n"
93              "  -h\t\t\tHelp (this text)\n"
94              "  -i\t\t\tIgnore case of symbols\n"
95              "  -l\t\t\tCreate a listing if assembly was ok\n"
96              "  -o name\t\tName the output file\n"
97              "  -s\t\t\tEnable smart mode\n"
98              "  -t sys\t\tSet the target system\n"
99              "  -v\t\t\tIncrease verbosity\n"
100              "\n"
101              "Long options:\n"
102              "  --auto-import\t\tMark unresolved symbols as import\n"
103              "  --cpu type\t\tSet cpu type\n"
104              "  --debug-info\t\tAdd debug info to object file\n"
105              "  --feature name\tSet an emulation feature\n"
106              "  --help\t\tHelp (this text)\n"
107              "  --ignore-case\t\tIgnore case of symbols\n"
108              "  --include-dir dir\tSet an include directory search path\n"
109              "  --listing\t\tCreate a listing if assembly was ok\n"
110              "  --pagelength n\tSet the page length for the listing\n"
111              "  --smart\t\tEnable smart mode\n"
112              "  --target sys\t\tSet the target system\n"
113              "  --verbose\t\tIncrease verbosity\n"
114              "  --version\t\tPrint the assembler version\n",
115              ProgName);
116 }
117
118
119
120 static void SetOptions (void)
121 /* Set the option for the translator */
122 {
123     char Buf [256];
124
125     /* Set the translator */
126     sprintf (Buf, "ca65 V%u.%u.%u", VER_MAJOR, VER_MINOR, VER_PATCH);
127     OptTranslator (Buf);
128
129     /* Set date and time */
130     OptDateTime ((unsigned long) time(0));
131 }
132
133
134
135 static void DefineSymbol (const char* Def)
136 /* Define a symbol from the command line */
137 {
138     const char* P;
139     unsigned I;
140     long Val;
141     char SymName [MAX_STR_LEN+1];
142
143     /* The symbol must start with a character or underline */
144     if (Def [0] != '_' && !IsAlpha (Def [0])) {
145         InvDef (Def);
146     }
147     P = Def;
148
149     /* Copy the symbol, checking the rest */
150     I = 0;
151     while (IsAlNum (*P) || *P == '_') {
152         if (I <= MAX_STR_LEN) {
153             SymName [I++] = *P;
154         }
155         ++P;
156     }
157     SymName [I] = '\0';
158
159     /* Do we have a value given? */
160     if (*P != '=') {
161         if (*P != '\0') {
162             InvDef (Def);
163         }
164         Val = 0;
165     } else {
166         /* We have a value */
167         ++P;
168         if (*P == '$') {
169             ++P;
170             if (sscanf (P, "%lx", &Val) != 1) {
171                 InvDef (Def);
172             }
173         } else {
174             if (sscanf (P, "%li", &Val) != 1) {
175                 InvDef (Def);
176             }
177         }
178     }
179
180     /* Check if have already a symbol with this name */
181     if (SymIsDef (SymName, SCOPE_ANY)) {
182         AbEnd ("`%s' is already defined", SymName);
183     }
184
185     /* Define the symbol */
186     SymDef (SymName, GenLiteralExpr (Val), SYM_DEFAULT);
187 }
188
189
190
191 static void OptAutoImport (const char* Opt attribute ((unused)),
192                            const char* Arg attribute ((unused)))
193 /* Mark unresolved symbols as imported */
194 {
195     AutoImport = 1;
196 }
197
198
199
200 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
201 /* Handle the --cpu option */
202 {
203     cpu_t CPU = FindCPU (Arg);
204     if (CPU == CPU_UNKNOWN) {
205         AbEnd ("Invalid CPU: `%s'", Arg);
206     } else {
207         SetCPU (CPU);
208     }
209 }
210
211
212
213 static void OptDebugInfo (const char* Opt attribute ((unused)),
214                           const char* Arg attribute ((unused)))
215 /* Add debug info to the object file */
216 {
217     DbgSyms = 1;
218 }
219
220
221
222 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
223 /* Set an emulation feature */
224 {
225     /* Set the feature, check for errors */
226     if (SetFeature (Arg) == FEAT_UNKNOWN) {
227         AbEnd ("Illegal emulation feature: `%s'", Arg);
228     }
229 }
230
231
232
233 static void OptHelp (const char* Opt attribute ((unused)),
234                      const char* Arg attribute ((unused)))
235 /* Print usage information and exit */
236 {
237     Usage ();
238     exit (EXIT_SUCCESS);
239 }
240
241
242
243 static void OptIgnoreCase (const char* Opt attribute ((unused)),
244                            const char* Arg attribute ((unused)))
245 /* Ignore case on symbols */
246 {
247     IgnoreCase = 1;
248 }
249
250
251
252 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
253 /* Add an include search path */
254 {
255     AddIncludePath (Arg);
256 }
257
258
259
260 static void OptListing (const char* Opt attribute ((unused)),
261                         const char* Arg attribute ((unused)))
262 /* Create a listing file */
263 {
264     Listing = 1;
265 }
266
267
268
269 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
270 /* Handle the --pagelength option */
271 {
272     int Len = atoi (Arg);
273     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
274         AbEnd ("Invalid page length: %d", Len);
275     }
276     PageLength = Len;
277 }
278
279
280
281 static void OptSmart (const char* Opt attribute ((unused)),
282                       const char* Arg attribute ((unused)))
283 /* Handle the -s/--smart options */
284 {
285     SmartMode = 1;
286 }
287
288
289
290 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
291 /* Set the target system */
292 {
293     /* Map the target name to a target id */
294     Target = FindTarget (Arg);
295     if (Target == TGT_UNKNOWN) {
296         AbEnd ("Invalid target name: `%s'", Arg);
297     } else if (Target == TGT_MODULE) {
298         AbEnd ("Cannot use `module' as a target for the assembler");
299     }
300 }
301
302
303
304 static void OptVerbose (const char* Opt attribute ((unused)),
305                         const char* Arg attribute ((unused)))
306 /* Increase verbosity */
307 {
308     ++Verbosity;
309 }
310
311
312
313 static void OptVersion (const char* Opt attribute ((unused)),
314                         const char* Arg attribute ((unused)))
315 /* Print the assembler version */
316 {
317     fprintf (stderr,
318              "ca65 V%u.%u.%u - %s\n",
319              VER_MAJOR, VER_MINOR, VER_PATCH, Copyright);
320 }
321
322
323
324 static void DoPCAssign (void)
325 /* Start absolute code */
326 {
327     long PC = ConstExpression ();
328     if (PC < 0 || PC > 0xFFFFFF) {
329         Error (ERR_RANGE);
330     } else {
331         SetAbsPC (PC);
332     }
333 }
334
335
336
337 static void OneLine (void)
338 /* Assemble one line */
339 {
340     char Ident [MAX_STR_LEN+1];
341     int Done = 0;
342
343     /* Initialize the new listing line if we are actually reading from file
344      * and not from internally pushed input.
345      */
346     if (!HavePushedInput ()) {
347         InitListingLine ();
348     }
349
350     if (Tok == TOK_COLON) {
351         /* An unnamed label */
352         ULabDef ();
353         NextTok ();
354     }
355
356     /* Assemble the line */
357     if (Tok == TOK_IDENT) {
358
359         /* Is it a macro? */
360         if (IsMacro (SVal)) {
361
362             /* Yes, start a macro expansion */
363             MacExpandStart ();
364             Done = 1;
365
366         } else {
367
368             /* No, label. Remember the identifier, then skip it */
369             int HadWS = WS;     /* Did we have whitespace before the ident? */
370             strcpy (Ident, SVal);
371             NextTok ();
372
373             /* If a colon follows, this is a label definition. If there
374              * is no colon, it's an assignment.
375              */
376             if (Tok == TOK_EQ || Tok == TOK_ASSIGN) {
377                 /* If it's an assign token, we have a label */
378                 unsigned Flags = (Tok == TOK_ASSIGN)? SYM_LABEL : SYM_DEFAULT;
379                 /* Skip the '=' */
380                 NextTok ();
381                 /* Define the symbol with the expression following the '=' */
382                 SymDef (Ident, Expression(), Flags);
383                 /* Don't allow anything after a symbol definition */
384                 Done = 1;
385             } else {
386                 /* Define the symbol flags */
387                 unsigned Flags = IsZPSeg ()? SYM_ZP | SYM_LABEL : SYM_LABEL;
388                 /* Define a label */
389                 SymDef (Ident, GenCurrentPC (), Flags);
390                 /* Skip the colon. If NoColonLabels is enabled, allow labels
391                  * without a colon if there is no whitespace before the
392                  * identifier.
393                  */
394                 if (Tok != TOK_COLON) {
395                     if (HadWS || !NoColonLabels) {
396                         Error (ERR_COLON_EXPECTED);
397                     }
398                     if (Tok == TOK_NAMESPACE) {
399                         /* Smart :: handling */
400                         NextTok ();
401                     }
402                 } else {
403                     /* Skip the colon */
404                     NextTok ();
405                 }
406             }
407         }
408     }
409
410     if (!Done) {
411
412         if (TokIsPseudo (Tok)) {
413             /* A control command, IVal is index into table */
414             HandlePseudo ();
415         } else if (Tok == TOK_MNEMO) {
416             /* A mnemonic - assemble one instruction */
417             HandleInstruction (IVal);
418         } else if (Tok == TOK_IDENT && IsMacro (SVal)) {
419             /* A macro expansion */
420             MacExpandStart ();
421         } else if (PCAssignment && (Tok == TOK_STAR || Tok == TOK_PC)) {
422             NextTok ();
423             if (Tok != TOK_EQ) {
424                 Error (ERR_EQ_EXPECTED);
425                 SkipUntilSep ();
426             } else {
427                 /* Skip the equal sign */
428                 NextTok ();
429                 /* Enter absolute mode */
430                 DoPCAssign ();
431             }
432         }
433     }
434
435     /* Line separator must come here */
436     ConsumeSep ();
437 }
438
439
440
441 static void Assemble (void)
442 /* Start the ball rolling ... */
443 {
444     /* Prime the pump */
445     NextTok ();
446
447     /* Assemble lines until end of file */
448     while (Tok != TOK_EOF) {
449         OneLine ();
450     }
451 }
452
453
454
455 static void CreateObjFile (void)
456 /* Create the object file */
457 {
458     /* Open the object, write the header */
459     ObjOpen ();
460
461     /* Write the object file options */
462     WriteOptions ();
463
464     /* Write the list of input files */
465     WriteFiles ();
466
467     /* Write the segment data to the file */
468     WriteSegments ();
469
470     /* Write the import list */
471     WriteImports ();
472
473     /* Write the export list */
474     WriteExports ();
475
476     /* Write debug symbols if requested */
477     WriteDbgSyms ();
478
479     /* Write line infos if requested */
480     WriteLineInfo ();
481
482     /* Write the string pool */
483     WriteStrPool ();
484
485     /* Write the assertions */
486     WriteAssertions ();
487
488     /* Write an updated header and close the file */
489     ObjClose ();
490 }
491
492
493
494 int main (int argc, char* argv [])
495 /* Assembler main program */
496 {
497     /* Program long options */
498     static const LongOpt OptTab[] = {
499         { "--auto-import",      0,      OptAutoImport           },
500         { "--cpu",              1,      OptCPU                  },
501         { "--debug-info",       0,      OptDebugInfo            },
502         { "--feature",          1,      OptFeature              },
503         { "--help",             0,      OptHelp                 },
504         { "--ignore-case",      0,      OptIgnoreCase           },
505         { "--include-dir",      1,      OptIncludeDir           },
506         { "--listing",          0,      OptListing              },
507         { "--pagelength",       1,      OptPageLength           },
508         { "--smart",            0,      OptSmart                },
509         { "--target",           1,      OptTarget               },
510         { "--verbose",          0,      OptVerbose              },
511         { "--version",          0,      OptVersion              },
512     };
513
514     unsigned I;
515
516     /* Initialize the cmdline module */
517     InitCmdLine (&argc, &argv, "ca65");
518
519     /* Enter the base lexical level. We must do that here, since we may
520      * define symbols using -D.
521      */
522     SymEnterLevel (0);
523
524     /* Check the parameters */
525     I = 1;
526     while (I < ArgCount) {
527
528         /* Get the argument */
529         const char* Arg = ArgVec [I];
530
531         /* Check for an option */
532         if (Arg [0] == '-') {
533             switch (Arg [1]) {
534
535                 case '-':
536                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
537                     break;
538
539                 case 'g':
540                     OptDebugInfo (Arg, 0);
541                     break;
542
543                 case 'h':
544                     OptHelp (Arg, 0);
545                     break;
546
547                 case 'i':
548                     OptIgnoreCase (Arg, 0);
549                     break;
550
551                 case 'l':
552                     OptListing (Arg, 0);
553                     break;
554
555                 case 'o':
556                     OutFile = GetArg (&I, 2);
557                     break;
558
559                 case 's':
560                     OptSmart (Arg, 0);
561                     break;
562
563                 case 't':
564                     OptTarget (Arg, GetArg (&I, 2));
565                     break;
566
567                 case 'v':
568                     OptVerbose (Arg, 0);
569                     break;
570
571                 case 'D':
572                     DefineSymbol (GetArg (&I, 2));
573                     break;
574
575                 case 'I':
576                     OptIncludeDir (Arg, GetArg (&I, 2));
577                     break;
578
579                 case 'U':
580                     OptAutoImport (Arg, 0);
581                     break;
582
583                 case 'V':
584                     OptVersion (Arg, 0);
585                     break;
586
587                 case 'W':
588                     WarnLevel = atoi (GetArg (&I, 2));
589                     break;
590
591                 default:
592                     UnknownOption (Arg);
593                     break;
594
595             }
596         } else {
597             /* Filename. Check if we already had one */
598             if (InFile) {
599                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
600                          ProgName, Arg);
601                 exit (EXIT_FAILURE);
602             } else {
603                 InFile = Arg;
604             }
605         }
606
607         /* Next argument */
608         ++I;
609     }
610
611     /* Do we have an input file? */
612     if (InFile == 0) {
613         fprintf (stderr, "%s: No input files\n", ProgName);
614         exit (EXIT_FAILURE);
615     }
616
617     /* If no CPU given, use the default CPU for the target */
618     if (GetCPU () == CPU_UNKNOWN) {
619         if (Target != TGT_UNKNOWN) {
620             SetCPU (DefaultCPU[Target]);
621         } else {
622             SetCPU (CPU_6502);
623         }
624     }
625
626     /* Intialize the target translation tables */
627     TgtTranslateInit ();
628
629     /* Initialize the scanner, open the input file */
630     InitScanner (InFile);
631
632     /* Define the default options */
633     SetOptions ();
634
635     /* Assemble the input */
636     Assemble ();
637
638     /* If we didn't have any errors, check the segment stack */
639     if (ErrorCount == 0) {
640         SegStackCheck ();
641     }
642
643     /* If we didn't have any errors, check the unnamed labels */
644     if (ErrorCount == 0) {
645         ULabCheck ();
646     }
647
648     /* If we didn't have any errors, check the symbol table */
649     if (ErrorCount == 0) {
650         SymCheck ();
651     }
652
653     /* If we didn't have any errors, check and resolve the segment data */
654     if (ErrorCount == 0) {
655         SegCheck ();
656     }
657
658     /* If we didn't have an errors, index the line infos */
659     MakeLineInfoIndex ();
660
661     /* Dump the data */
662     if (Verbosity >= 2) {
663         SymDump (stdout);
664         SegDump ();
665     }
666
667     /* If we didn't have any errors, create the object and listing files */
668     if (ErrorCount == 0) {
669         CreateObjFile ();
670         if (Listing) {
671             CreateListing ();
672         }
673     }
674
675     /* Close the input file */
676     DoneScanner ();
677
678     /* Return an apropriate exit code */
679     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
680 }
681
682
683