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