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