]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
Fixed ca65's "ubiquitous_idents" feature.
[cc65] / src / ca65 / main.c
1 /*                                                                           */
2 /*                                  main.c                                   */
3 /*                                                                           */
4 /*                 Main program for the ca65 macroassembler                  */
5 /*                                                                           */
6 /*                                                                           */
7 /*                                                                           */
8 /* (C) 1998-2013, Ullrich von Bassewitz                                      */
9 /*                Roemerstrasse 52                                           */
10 /*                D-70794 Filderstadt                                        */
11 /* EMail:         uz@cc65.org                                                */
12 /*                                                                           */
13 /*                                                                           */
14 /* This software is provided 'as-is', without any expressed or implied       */
15 /* warranty.  In no event will the authors be held liable for any damages    */
16 /* arising from the use of this software.                                    */
17 /*                                                                           */
18 /* Permission is granted to anyone to use this software for any purpose,     */
19 /* including commercial applications, and to alter it and redistribute it    */
20 /* freely, subject to the following restrictions:                            */
21 /*                                                                           */
22 /* 1. The origin of this software must not be misrepresented; you must not   */
23 /*    claim that you wrote the original software. If you use this software   */
24 /*    in a product, an acknowledgment in the product documentation would be  */
25 /*    appreciated but is not required.                                       */
26 /* 2. Altered source versions must be plainly marked as such, and must not   */
27 /*    be misrepresented as being the original software.                      */
28 /* 3. This notice may not be removed or altered from any source              */
29 /*    distribution.                                                          */
30 /*                                                                           */
31 /*****************************************************************************/
32
33
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39
40 /* common */
41 #include "addrsize.h"
42 #include "chartype.h"
43 #include "cmdline.h"
44 #include "debugflag.h"
45 #include "mmodel.h"
46 #include "print.h"
47 #include "scopedefs.h"
48 #include "strbuf.h"
49 #include "target.h"
50 #include "tgttrans.h"
51 #include "version.h"
52
53 /* ca65 */
54 #include "abend.h"
55 #include "asserts.h"
56 #include "dbginfo.h"
57 #include "error.h"
58 #include "expr.h"
59 #include "feature.h"
60 #include "filetab.h"
61 #include "global.h"
62 #include "incpath.h"
63 #include "instr.h"
64 #include "istack.h"
65 #include "lineinfo.h"
66 #include "listing.h"
67 #include "macro.h"
68 #include "nexttok.h"
69 #include "objfile.h"
70 #include "options.h"
71 #include "pseudo.h"
72 #include "scanner.h"
73 #include "segment.h"
74 #include "sizeof.h"
75 #include "span.h"
76 #include "spool.h"
77 #include "symbol.h"
78 #include "symtab.h"
79 #include "ulabel.h"
80
81
82
83 /*****************************************************************************/
84 /*                                   Code                                    */
85 /*****************************************************************************/
86
87
88
89 static void Usage (void)
90 /* Print usage information and exit */
91 {
92     printf ("Usage: %s [options] file\n"
93             "Short options:\n"
94             "  -D name[=value]\t\tDefine a symbol\n"
95             "  -I dir\t\t\tSet an include directory search path\n"
96             "  -U\t\t\t\tMark unresolved symbols as import\n"
97             "  -V\t\t\t\tPrint the assembler version\n"
98             "  -W n\t\t\t\tSet warning level n\n"
99             "  -d\t\t\t\tDebug mode\n"
100             "  -g\t\t\t\tAdd debug info to object file\n"
101             "  -h\t\t\t\tHelp (this text)\n"
102             "  -i\t\t\t\tIgnore case of symbols\n"
103             "  -l name\t\t\tCreate a listing file if assembly was ok\n"
104             "  -mm model\t\t\tSet the memory model\n"
105             "  -o name\t\t\tName the output file\n"
106             "  -s\t\t\t\tEnable smart mode\n"
107             "  -t sys\t\t\tSet the target system\n"
108             "  -v\t\t\t\tIncrease verbosity\n"
109             "\n"
110             "Long options:\n"
111             "  --auto-import\t\t\tMark unresolved symbols as import\n"
112             "  --bin-include-dir dir\t\tSet a search path for binary includes\n"
113             "  --cpu type\t\t\tSet cpu type\n"
114             "  --create-dep name\t\tCreate a make dependency file\n"
115             "  --create-full-dep name\tCreate a full make dependency file\n"
116             "  --debug\t\t\tDebug mode\n"
117             "  --debug-info\t\t\tAdd debug info to object file\n"
118             "  --feature name\t\tSet an emulation feature\n"
119             "  --help\t\t\tHelp (this text)\n"
120             "  --ignore-case\t\t\tIgnore case of symbols\n"
121             "  --include-dir dir\t\tSet an include directory search path\n"
122             "  --large-alignment\t\tDon't warn about large alignments\n"
123             "  --listing name\t\tCreate a listing file if assembly was ok\n"
124             "  --list-bytes n\t\tMaximum number of bytes per listing line\n"
125             "  --macpack-dir dir\t\tSet a macro package directory\n"
126             "  --memory-model model\t\tSet the memory model\n"
127             "  --pagelength n\t\tSet the page length for the listing\n"
128             "  --relax-checks\t\tRelax some checks (see docs)\n"
129             "  --smart\t\t\tEnable smart mode\n"
130             "  --target sys\t\t\tSet the target system\n"
131             "  --verbose\t\t\tIncrease verbosity\n"
132             "  --version\t\t\tPrint the assembler version\n",
133             ProgName);
134 }
135
136
137
138 static void SetOptions (void)
139 /* Set the option for the translator */
140 {
141     StrBuf Buf = STATIC_STRBUF_INITIALIZER;
142
143     /* Set the translator */
144     SB_Printf (&Buf, "ca65 V%s", GetVersionAsString ());
145     OptTranslator (&Buf);
146
147     /* Set date and time */
148     OptDateTime ((unsigned long) time(0));
149
150     /* Release memory for the string */
151     SB_Done (&Buf);
152 }
153
154
155
156 static void NewSymbol (const char* SymName, long Val)
157 /* Define a symbol with a fixed numeric value in the current scope */
158 {
159     ExprNode* Expr;
160     SymEntry* Sym;
161
162     /* Convert the name to a string buffer */
163     StrBuf SymBuf = STATIC_STRBUF_INITIALIZER;
164     SB_CopyStr (&SymBuf, SymName);
165
166     /* Search for the symbol, allocate a new one if it doesn't exist */
167     Sym = SymFind (CurrentScope, &SymBuf, SYM_ALLOC_NEW);
168
169     /* Check if have already a symbol with this name */
170     if (SymIsDef (Sym)) {
171         AbEnd ("`%s' is already defined", SymName);
172     }
173
174     /* Generate an expression for the symbol */
175     Expr = GenLiteralExpr (Val);
176
177     /* Mark the symbol as defined */
178     SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_NONE);
179
180     /* Free string buffer memory */
181     SB_Done (&SymBuf);
182 }
183
184
185
186 static void CBMSystem (const char* Sys)
187 /* Define a CBM system */
188 {
189     NewSymbol ("__CBM__", 1);
190     NewSymbol (Sys, 1);
191 }
192
193
194
195 static void SetSys (const char* Sys)
196 /* Define a target system */
197 {
198     switch (Target = FindTarget (Sys)) {
199
200         case TGT_NONE:
201             break;
202
203         case TGT_MODULE:
204             AbEnd ("Cannot use `module' as a target for the assembler");
205             break;
206
207         case TGT_ATARI:
208             NewSymbol ("__ATARI__", 1);
209             break;
210
211         case TGT_ATARIXL:
212             NewSymbol ("__ATARI__", 1);
213             NewSymbol ("__ATARIXL__", 1);
214             break;
215
216         case TGT_C16:
217             CBMSystem ("__C16__");
218             break;
219
220         case TGT_C64:
221             CBMSystem ("__C64__");
222             break;
223
224         case TGT_VIC20:
225             CBMSystem ("__VIC20__");
226             break;
227
228         case TGT_C128:
229             CBMSystem ("__C128__");
230             break;
231
232         case TGT_PLUS4:
233             CBMSystem ("__C16__");
234             NewSymbol ("__PLUS4__", 1);
235             break;
236
237         case TGT_CBM510:
238             CBMSystem ("__CBM510__");
239             break;
240
241         case TGT_CBM610:
242             CBMSystem ("__CBM610__");
243             break;
244
245         case TGT_PET:
246             CBMSystem ("__PET__");
247             break;
248
249         case TGT_BBC:
250             NewSymbol ("__BBC__", 1);
251             break;
252
253         case TGT_APPLE2:
254             NewSymbol ("__APPLE2__", 1);
255             break;
256
257         case TGT_APPLE2ENH:
258             NewSymbol ("__APPLE2__", 1);
259             NewSymbol ("__APPLE2ENH__", 1);
260             break;
261
262         case TGT_GEOS_CBM:
263             /* Do not handle as a CBM system */
264             NewSymbol ("__GEOS__", 1);
265             NewSymbol ("__GEOS_CBM__", 1);
266             break;
267
268         case TGT_GEOS_APPLE:
269             NewSymbol ("__GEOS__", 1);
270             NewSymbol ("__GEOS_APPLE__", 1);
271             break;
272
273         case TGT_LUNIX:
274             NewSymbol ("__LUNIX__", 1);
275             break;
276
277         case TGT_ATMOS:
278             NewSymbol ("__ATMOS__", 1);
279             break;
280
281         case TGT_NES:
282             NewSymbol ("__NES__", 1);
283             break;
284
285         case TGT_SUPERVISION:
286             NewSymbol ("__SUPERVISION__", 1);
287             break;
288
289         case TGT_LYNX:
290             NewSymbol ("__LYNX__", 1);
291             break;
292
293         case TGT_SIM6502:
294             NewSymbol ("__SIM6502__", 1);
295             break;
296
297         case TGT_SIM65C02:
298             NewSymbol ("__SIM65C02__", 1);
299             break;
300
301         default:
302             AbEnd ("Invalid target name: `%s'", Sys);
303
304     }
305
306     /* Initialize the translation tables for the target system */
307     TgtTranslateInit ();
308 }
309
310
311
312 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
313 /* Handle an option that remembers a file name for later */
314 {
315     /* Cannot have the option twice */
316     if (SB_NotEmpty (Name)) {
317         AbEnd ("Cannot use option `%s' twice", Opt);
318     }
319     /* Remember the file name for later */
320     SB_CopyStr (Name, Arg);
321     SB_Terminate (Name);
322 }
323
324
325
326 static void DefineSymbol (const char* Def)
327 /* Define a symbol from the command line */
328 {
329     const char* P;
330     long Val;
331     StrBuf SymName = AUTO_STRBUF_INITIALIZER;
332
333
334     /* The symbol must start with a character or underline */
335     if (!IsIdStart (Def [0])) {
336         InvDef (Def);
337     }
338     P = Def;
339
340     /* Copy the symbol, checking the rest */
341     while (IsIdChar (*P)) {
342         SB_AppendChar (&SymName, *P++);
343     }
344     SB_Terminate (&SymName);
345
346     /* Do we have a value given? */
347     if (*P != '=') {
348         if (*P != '\0') {
349             InvDef (Def);
350         }
351         Val = 0;
352     } else {
353         /* We have a value */
354         ++P;
355         if (*P == '$') {
356             ++P;
357             if (sscanf (P, "%lx", &Val) != 1) {
358                 InvDef (Def);
359             }
360         } else {
361             if (sscanf (P, "%li", &Val) != 1) {
362                 InvDef (Def);
363             }
364         }
365     }
366
367     /* Define the new symbol */
368     NewSymbol (SB_GetConstBuf (&SymName), Val);
369
370     /* Release string memory */
371     SB_Done (&SymName);
372 }
373
374
375
376 static void OptAutoImport (const char* Opt attribute ((unused)),
377                            const char* Arg attribute ((unused)))
378 /* Mark unresolved symbols as imported */
379 {
380     AutoImport = 1;
381 }
382
383
384
385 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
386 /* Add an include search path for binaries */
387 {
388     AddSearchPath (BinSearchPath, Arg);
389 }
390
391
392
393 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
394 /* Handle the --cpu option */
395 {
396     cpu_t CPU = FindCPU (Arg);
397     if (CPU == CPU_UNKNOWN) {
398         AbEnd ("Invalid CPU: `%s'", Arg);
399     } else {
400         SetCPU (CPU);
401     }
402 }
403
404
405
406 static void OptCreateDep (const char* Opt, const char* Arg)
407 /* Handle the --create-dep option */
408 {
409     FileNameOption (Opt, Arg, &DepName);
410 }
411
412
413
414 static void OptCreateFullDep (const char* Opt attribute ((unused)),
415                               const char* Arg)
416 /* Handle the --create-full-dep option */
417 {
418     FileNameOption (Opt, Arg, &FullDepName);
419 }
420
421
422
423 static void OptDebug (const char* Opt attribute ((unused)),
424                       const char* Arg attribute ((unused)))
425 /* Compiler debug mode */
426 {
427     ++Debug;
428 }
429
430
431
432 static void OptDebugInfo (const char* Opt attribute ((unused)),
433                           const char* Arg attribute ((unused)))
434 /* Add debug info to the object file */
435 {
436     DbgSyms = 1;
437 }
438
439
440
441 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
442 /* Set an emulation feature */
443 {
444     /* Make a string buffer from Arg */
445     StrBuf Feature;
446
447     /* Set the feature, check for errors */
448     if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
449         AbEnd ("Illegal emulation feature: `%s'", Arg);
450     }
451 }
452
453
454
455 static void OptHelp (const char* Opt attribute ((unused)),
456                      const char* Arg attribute ((unused)))
457 /* Print usage information and exit */
458 {
459     Usage ();
460     exit (EXIT_SUCCESS);
461 }
462
463
464
465 static void OptIgnoreCase (const char* Opt attribute ((unused)),
466                            const char* Arg attribute ((unused)))
467 /* Ignore case on symbols */
468 {
469     IgnoreCase = 1;
470 }
471
472
473
474 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
475 /* Add an include search path */
476 {
477     AddSearchPath (IncSearchPath, Arg);
478 }
479
480
481
482 static void OptLargeAlignment (const char* Opt attribute ((unused)),
483                                const char* Arg attribute ((unused)))
484 /* Don't warn about large alignments */
485 {
486     LargeAlignment = 1;
487 }
488
489
490
491 static void OptListBytes (const char* Opt, const char* Arg)
492 /* Set the maximum number of bytes per listing line */
493 {
494     unsigned Num;
495     char     Check;
496
497     /* Convert the argument to a number */
498     if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
499         InvArg (Opt, Arg);
500     }
501
502     /* Check the bounds */
503     if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
504         AbEnd ("Argument for option `%s' is out of range", Opt);
505     }
506
507     /* Use the value */
508     SetListBytes (Num);
509 }
510
511
512
513 static void OptListing (const char* Opt, const char* Arg)
514 /* Create a listing file */
515 {
516     /* Since the meaning of -l and --listing has changed, print an error if
517      * the filename is empty or begins with the option char.
518      */
519     if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
520         Fatal ("The meaning of `%s' has changed. It does now "
521                "expect a file name as argument.", Opt);
522     }
523
524     /* Get the file name */
525     FileNameOption (Opt, Arg, &ListingName);
526 }
527
528
529
530 static void OptMemoryModel (const char* Opt, const char* Arg)
531 /* Set the memory model */
532 {
533     mmodel_t M;
534
535     /* Check the current memory model */
536     if (MemoryModel != MMODEL_UNKNOWN) {
537         AbEnd ("Cannot use option `%s' twice", Opt);
538     }
539
540     /* Translate the memory model name and check it */
541     M = FindMemoryModel (Arg);
542     if (M == MMODEL_UNKNOWN) {
543         AbEnd ("Unknown memory model: %s", Arg);
544     } else if (M == MMODEL_HUGE) {
545         AbEnd ("Unsupported memory model: %s", Arg);
546     }
547
548     /* Set the memory model */
549     SetMemoryModel (M);
550 }
551
552
553
554 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
555 /* Handle the --pagelength option */
556 {
557     int Len = atoi (Arg);
558     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
559         AbEnd ("Invalid page length: %d", Len);
560     }
561     PageLength = Len;
562 }
563
564
565
566 static void OptRelaxChecks (const char* Opt attribute ((unused)),
567                             const char* Arg attribute ((unused)))
568 /* Handle the --relax-checks options */
569 {
570     RelaxChecks = 1;
571 }
572
573
574
575 static void OptSmart (const char* Opt attribute ((unused)),
576                       const char* Arg attribute ((unused)))
577 /* Handle the -s/--smart options */
578 {
579     SmartMode = 1;
580 }
581
582
583
584 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
585 /* Set the target system */
586 {
587     SetSys (Arg);
588 }
589
590
591
592 static void OptVerbose (const char* Opt attribute ((unused)),
593                         const char* Arg attribute ((unused)))
594 /* Increase verbosity */
595 {
596     ++Verbosity;
597 }
598
599
600
601 static void OptVersion (const char* Opt attribute ((unused)),
602                         const char* Arg attribute ((unused)))
603 /* Print the assembler version */
604 {
605     fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
606 }
607
608
609
610 static void DoPCAssign (void)
611 /* Start absolute code */
612 {
613     long PC = ConstExpression ();
614     if (PC < 0 || PC > 0xFFFFFF) {
615         Error ("Range error");
616     } else {
617         EnterAbsoluteMode (PC);
618     }
619 }
620
621
622
623 static void OneLine (void)
624 /* Assemble one line */
625 {
626     Segment*      Seg   = 0;
627     unsigned long PC    = 0;
628     SymEntry*     Sym   = 0;
629     Macro*        Mac   = 0;
630     int           Instr = -1;
631
632     /* Initialize the new listing line if we are actually reading from file
633      * and not from internally pushed input.
634      */
635     if (!HavePushedInput ()) {
636         InitListingLine ();
637     }
638
639     /* Single colon means unnamed label */
640     if (CurTok.Tok == TOK_COLON) {
641         ULabDef ();
642         NextTok ();
643     }
644
645     /* If the first token on the line is an identifier, check for a macro or
646      * an instruction.
647      */
648     if (CurTok.Tok == TOK_IDENT) {
649         if (UbiquitousIdents) {
650             /* Macros CAN be instructions, so check for them first */
651             Mac = FindMacro (&CurTok.SVal);
652             if (Mac == 0) {
653                 Instr = FindInstruction (&CurTok.SVal);
654             }
655         } else {
656             /* Macros and symbols may NOT use the names of instructions */
657             Instr = FindInstruction (&CurTok.SVal);
658             if (Instr < 0) {
659                 Mac = FindMacro (&CurTok.SVal);
660             }
661         }
662     }
663
664     /* Handle an identifier. This may be a cheap local symbol, or a fully
665      * scoped identifier which may start with a namespace token (for global
666      * namespace)
667      */
668     if (CurTok.Tok == TOK_LOCAL_IDENT ||
669         CurTok.Tok == TOK_NAMESPACE   ||
670         (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
671
672         /* Did we have whitespace before the ident? */
673         int HadWS = CurTok.WS;
674
675         /* Generate the symbol table entry, then skip the name */
676         Sym = ParseAnySymName (SYM_ALLOC_NEW);
677
678         /* If a colon follows, this is a label definition. If there
679          * is no colon, it's an assignment.
680          */
681         if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
682
683             /* Determine the symbol flags from the assignment token */
684             unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
685
686             /* Skip the '=' */
687             NextTok ();
688
689             /* Define the symbol with the expression following the '=' */
690             SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
691
692             /* Don't allow anything after a symbol definition */
693             ConsumeSep ();
694             return;
695
696         } else if (CurTok.Tok == TOK_SET) {
697
698             ExprNode* Expr;
699
700             /* .SET defines variables (= redefinable symbols) */
701             NextTok ();
702
703             /* Read the assignment expression, which must be constant */
704             Expr = GenLiteralExpr (ConstExpression ());
705
706             /* Define the symbol with the constant expression following
707              * the '='
708              */
709             SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
710
711             /* Don't allow anything after a symbol definition */
712             ConsumeSep ();
713             return;
714
715         } else {
716
717             /* A label. Remember the current segment, so we can later
718              * determine the size of the data stored under the label.
719              */
720             Seg = ActiveSeg;
721             PC  = GetPC ();
722
723             /* Define the label */
724             SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
725
726             /* Skip the colon. If NoColonLabels is enabled, allow labels
727              * without a colon if there is no whitespace before the
728              * identifier.
729              */
730             if (CurTok.Tok != TOK_COLON) {
731                 if (HadWS || !NoColonLabels) {
732                     Error ("`:' expected");
733                     /* Try some smart error recovery */
734                     if (CurTok.Tok == TOK_NAMESPACE) {
735                         NextTok ();
736                     }
737                 }
738             } else {
739                 /* Skip the colon */
740                 NextTok ();
741             }
742
743             /* If we come here, a new identifier may be waiting, which may
744              * be a macro or instruction.
745              */
746             if (CurTok.Tok == TOK_IDENT) {
747                 if (UbiquitousIdents) {
748                     /* Macros CAN be instructions, so check for them first */
749                     Mac = FindMacro (&CurTok.SVal);
750                     if (Mac == 0) {
751                         Instr = FindInstruction (&CurTok.SVal);
752                     }
753                 } else {
754                     /* Macros and symbols may NOT use the names of instructions */
755                     Instr = FindInstruction (&CurTok.SVal);
756                     if (Instr < 0) {
757                         Mac = FindMacro (&CurTok.SVal);
758                     }
759                 }
760             }
761         }
762     }
763
764     /* We've handled a possible label, now handle the remainder of the line */
765     if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
766         /* A control command */
767         HandlePseudo ();
768     } else if (Mac != 0) {
769         /* A macro expansion */
770         MacExpandStart (Mac);
771     } else if (Instr >= 0 ||
772                (UbiquitousIdents && ((Instr = FindInstruction (&CurTok.SVal)) >= 0))) {
773         /* A mnemonic - assemble one instruction */
774         HandleInstruction (Instr);
775     } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
776         NextTok ();
777         if (CurTok.Tok != TOK_EQ) {
778             Error ("`=' expected");
779             SkipUntilSep ();
780         } else {
781             /* Skip the equal sign */
782             NextTok ();
783             /* Enter absolute mode */
784             DoPCAssign ();
785         }
786     }
787
788     /* If we have defined a label, remember its size. Sym is also set by
789      * a symbol assignment, but in this case Done is false, so we don't
790      * come here.
791      */
792     if (Sym) {
793         unsigned long Size;
794         if (Seg == ActiveSeg) {
795             /* Same segment */
796             Size = GetPC () - PC;
797         } else {
798             /* The line has switched the segment */
799             Size = 0;
800         }
801         DefSizeOfSymbol (Sym, Size);
802     }
803
804     /* Line separator must come here */
805     ConsumeSep ();
806 }
807
808
809
810 static void Assemble (void)
811 /* Start the ball rolling ... */
812 {
813     /* Prime the pump */
814     NextTok ();
815
816     /* Assemble lines until end of file */
817     while (CurTok.Tok != TOK_EOF) {
818         OneLine ();
819     }
820 }
821
822
823
824 static void CreateObjFile (void)
825 /* Create the object file */
826 {
827     /* Open the object, write the header */
828     ObjOpen ();
829
830     /* Write the object file options */
831     WriteOptions ();
832
833     /* Write the list of input files */
834     WriteFiles ();
835
836     /* Write the segment data to the file */
837     WriteSegments ();
838
839     /* Write the import list */
840     WriteImports ();
841
842     /* Write the export list */
843     WriteExports ();
844
845     /* Write debug symbols if requested */
846     WriteDbgSyms ();
847
848     /* Write the scopes if requested */
849     WriteScopes ();
850
851     /* Write line infos if requested */
852     WriteLineInfos ();
853
854     /* Write the string pool */
855     WriteStrPool ();
856
857     /* Write the assertions */
858     WriteAssertions ();
859
860     /* Write the spans */
861     WriteSpans ();
862
863     /* Write an updated header and close the file */
864     ObjClose ();
865 }
866
867
868
869 int main (int argc, char* argv [])
870 /* Assembler main program */
871 {
872     /* Program long options */
873     static const LongOpt OptTab[] = {
874         { "--auto-import",      0,      OptAutoImport           },
875         { "--bin-include-dir",  1,      OptBinIncludeDir        },
876         { "--cpu",              1,      OptCPU                  },
877         { "--create-dep",       1,      OptCreateDep            },
878         { "--create-full-dep",  1,      OptCreateFullDep        },
879         { "--debug",            0,      OptDebug                },
880         { "--debug-info",       0,      OptDebugInfo            },
881         { "--feature",          1,      OptFeature              },
882         { "--help",             0,      OptHelp                 },
883         { "--ignore-case",      0,      OptIgnoreCase           },
884         { "--include-dir",      1,      OptIncludeDir           },
885         { "--large-alignment",  0,      OptLargeAlignment       },
886         { "--list-bytes",       1,      OptListBytes            },
887         { "--listing",          1,      OptListing              },
888         { "--memory-model",     1,      OptMemoryModel          },
889         { "--pagelength",       1,      OptPageLength           },
890         { "--relax-checks",     0,      OptRelaxChecks          },
891         { "--smart",            0,      OptSmart                },
892         { "--target",           1,      OptTarget               },
893         { "--verbose",          0,      OptVerbose              },
894         { "--version",          0,      OptVersion              },
895     };
896
897     /* Name of the global name space */
898     static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
899
900     unsigned I;
901
902     /* Initialize the cmdline module */
903     InitCmdLine (&argc, &argv, "ca65");
904
905     /* Initialize the string pool */
906     InitStrPool ();
907
908     /* Initialize the include search paths */
909     InitIncludePaths ();
910
911     /* Create the predefined segments */
912     SegInit ();
913
914     /* Enter the base lexical level. We must do that here, since we may
915      * define symbols using -D.
916      */
917     SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
918
919     /* Initialize the line infos. Must be done here, since we need line infos
920      * for symbol definitions.
921      */
922     InitLineInfo ();
923
924     /* Check the parameters */
925     I = 1;
926     while (I < ArgCount) {
927
928         /* Get the argument */
929         const char* Arg = ArgVec [I];
930
931         /* Check for an option */
932         if (Arg[0] == '-') {
933             switch (Arg[1]) {
934
935                 case '-':
936                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
937                     break;
938
939                 case 'd':
940                     OptDebug (Arg, 0);
941                     break;
942
943                 case 'g':
944                     OptDebugInfo (Arg, 0);
945                     break;
946
947                 case 'h':
948                     OptHelp (Arg, 0);
949                     break;
950
951                 case 'i':
952                     OptIgnoreCase (Arg, 0);
953                     break;
954
955                 case 'l':
956                     OptListing (Arg, GetArg (&I, 2));
957                     break;
958
959                 case 'm':
960                     if (Arg[2] == 'm') {
961                         OptMemoryModel (Arg, GetArg (&I, 3));
962                     } else {
963                         UnknownOption (Arg);
964                     }
965                     break;
966
967                 case 'o':
968                     OutFile = GetArg (&I, 2);
969                     break;
970
971                 case 's':
972                     OptSmart (Arg, 0);
973                     break;
974
975                 case 't':
976                     OptTarget (Arg, GetArg (&I, 2));
977                     break;
978
979                 case 'v':
980                     OptVerbose (Arg, 0);
981                     break;
982
983                 case 'D':
984                     DefineSymbol (GetArg (&I, 2));
985                     break;
986
987                 case 'I':
988                     OptIncludeDir (Arg, GetArg (&I, 2));
989                     break;
990
991                 case 'U':
992                     OptAutoImport (Arg, 0);
993                     break;
994
995                 case 'V':
996                     OptVersion (Arg, 0);
997                     break;
998
999                 case 'W':
1000                     WarnLevel = atoi (GetArg (&I, 2));
1001                     break;
1002
1003                 default:
1004                     UnknownOption (Arg);
1005                     break;
1006
1007             }
1008         } else {
1009             /* Filename. Check if we already had one */
1010             if (InFile) {
1011                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1012                          ProgName, Arg);
1013                 exit (EXIT_FAILURE);
1014             } else {
1015                 InFile = Arg;
1016             }
1017         }
1018
1019         /* Next argument */
1020         ++I;
1021     }
1022
1023     /* Do we have an input file? */
1024     if (InFile == 0) {
1025         fprintf (stderr, "%s: No input files\n", ProgName);
1026         exit (EXIT_FAILURE);
1027     }
1028
1029     /* Add the default include search paths. */
1030     FinishIncludePaths ();
1031
1032     /* If no CPU given, use the default CPU for the target */
1033     if (GetCPU () == CPU_UNKNOWN) {
1034         if (Target != TGT_UNKNOWN) {
1035             SetCPU (GetTargetProperties (Target)->DefaultCPU);
1036         } else {
1037             SetCPU (CPU_6502);
1038         }
1039     }
1040
1041     /* If no memory model was given, use the default */
1042     if (MemoryModel == MMODEL_UNKNOWN) {
1043         SetMemoryModel (MMODEL_NEAR);
1044     }
1045
1046     /* Set the default segment sizes according to the memory model */
1047     SetSegmentSizes ();
1048
1049     /* Initialize the scanner, open the input file */
1050     InitScanner (InFile);
1051
1052     /* Define the default options */
1053     SetOptions ();
1054
1055     /* Assemble the input */
1056     Assemble ();
1057
1058     /* If we didn't have any errors, check the pseudo insn stacks */
1059     if (ErrorCount == 0) {
1060         CheckPseudo ();
1061     }
1062
1063     /* If we didn't have any errors, check and cleanup the unnamed labels */
1064     if (ErrorCount == 0) {
1065         ULabDone ();
1066     }
1067
1068     /* If we didn't have any errors, check the symbol table */
1069     if (ErrorCount == 0) {
1070         SymCheck ();
1071     }
1072
1073     /* If we didn't have any errors, check the hll debug symbols */
1074     if (ErrorCount == 0) {
1075         DbgInfoCheck ();
1076     }
1077
1078     /* If we didn't have any errors, close the file scope lexical level */
1079     if (ErrorCount == 0) {
1080         SymLeaveLevel ();
1081     }
1082
1083     /* If we didn't have any errors, check and resolve the segment data */
1084     if (ErrorCount == 0) {
1085         SegDone ();
1086     }
1087
1088     /* If we didn't have any errors, check the assertions */
1089     if (ErrorCount == 0) {
1090         CheckAssertions ();
1091     }
1092
1093     /* Dump the data */
1094     if (Verbosity >= 2) {
1095         SymDump (stdout);
1096         SegDump ();
1097     }
1098
1099     /* If we didn't have an errors, finish off the line infos */
1100     DoneLineInfo ();
1101
1102     /* If we didn't have any errors, create the object, listing and
1103      * dependency files
1104      */
1105     if (ErrorCount == 0) {
1106         CreateObjFile ();
1107         if (SB_GetLen (&ListingName) > 0) {
1108             CreateListing ();
1109         }
1110        CreateDependencies ();
1111     }
1112
1113     /* Close the input file */
1114     DoneScanner ();
1115
1116     /* Return an apropriate exit code */
1117     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
1118 }
1119
1120
1121