]> git.sur5r.net Git - cc65/blob - src/ca65/main.c
b25d5ad9f4ad5bcdd9f3a4909ac167941bd08665
[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_APPLE2:
255             NewSymbol ("__APPLE2__", 1);
256             break;
257
258         case TGT_APPLE2ENH:
259             NewSymbol ("__APPLE2__", 1);
260             NewSymbol ("__APPLE2ENH__", 1);
261             break;
262
263         case TGT_GAMATE:
264             NewSymbol ("__GAMATE__", 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_ATMOS:
274             NewSymbol ("__ATMOS__", 1);
275             break;
276
277         case TGT_BBC:
278             NewSymbol ("__BBC__", 1);
279             break;
280
281         case TGT_CREATIVISION:
282             NewSymbol ("__CREATIVISION__", 1);
283             break;
284
285         case TGT_GEOS_APPLE:
286             NewSymbol ("__GEOS__", 1);
287             NewSymbol ("__GEOS_APPLE__", 1);
288             break;
289
290         case TGT_GEOS_CBM:
291             /* Do not handle as a CBM system */
292             NewSymbol ("__GEOS__", 1);
293             NewSymbol ("__GEOS_CBM__", 1);
294             break;
295
296         case TGT_LUNIX:
297             NewSymbol ("__LUNIX__", 1);
298             break;
299
300         case TGT_LYNX:
301             NewSymbol ("__LYNX__", 1);
302             break;
303
304         case TGT_NES:
305             NewSymbol ("__NES__", 1);
306             break;
307
308         case TGT_SIM6502:
309             NewSymbol ("__SIM6502__", 1);
310             break;
311
312         case TGT_SIM65C02:
313             NewSymbol ("__SIM65C02__", 1);
314             break;
315
316         case TGT_OSIC1P:
317             NewSymbol ("__OSIC1P__", 1);
318             break;
319
320         case TGT_PCENGINE:
321             NewSymbol ("__PCE__", 1);
322             break;
323
324         case TGT_SUPERVISION:
325             NewSymbol ("__SUPERVISION__", 1);
326             break;
327
328         default:
329             AbEnd ("Invalid target name: `%s'", Sys);
330
331     }
332
333     /* Initialize the translation tables for the target system */
334     TgtTranslateInit ();
335 }
336
337
338
339 static void FileNameOption (const char* Opt, const char* Arg, StrBuf* Name)
340 /* Handle an option that remembers a file name for later */
341 {
342     /* Cannot have the option twice */
343     if (SB_NotEmpty (Name)) {
344         AbEnd ("Cannot use option `%s' twice", Opt);
345     }
346     /* Remember the file name for later */
347     SB_CopyStr (Name, Arg);
348     SB_Terminate (Name);
349 }
350
351
352
353 static void DefineSymbol (const char* Def)
354 /* Define a symbol from the command line */
355 {
356     const char* P;
357     long Val;
358     StrBuf SymName = AUTO_STRBUF_INITIALIZER;
359
360
361     /* The symbol must start with a character or underline */
362     if (!IsIdStart (Def [0])) {
363         InvDef (Def);
364     }
365     P = Def;
366
367     /* Copy the symbol, checking the rest */
368     while (IsIdChar (*P)) {
369         SB_AppendChar (&SymName, *P++);
370     }
371     SB_Terminate (&SymName);
372
373     /* Do we have a value given? */
374     if (*P != '=') {
375         if (*P != '\0') {
376             InvDef (Def);
377         }
378         Val = 0;
379     } else {
380         /* We have a value */
381         ++P;
382         if (*P == '$') {
383             ++P;
384             if (sscanf (P, "%lx", &Val) != 1) {
385                 InvDef (Def);
386             }
387         } else {
388             if (sscanf (P, "%li", &Val) != 1) {
389                 InvDef (Def);
390             }
391         }
392     }
393
394     /* Define the new symbol */
395     NewSymbol (SB_GetConstBuf (&SymName), Val);
396
397     /* Release string memory */
398     SB_Done (&SymName);
399 }
400
401
402
403 static void OptAutoImport (const char* Opt attribute ((unused)),
404                            const char* Arg attribute ((unused)))
405 /* Mark unresolved symbols as imported */
406 {
407     AutoImport = 1;
408 }
409
410
411
412 static void OptBinIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
413 /* Add an include search path for binaries */
414 {
415     AddSearchPath (BinSearchPath, Arg);
416 }
417
418
419
420 static void OptCPU (const char* Opt attribute ((unused)), const char* Arg)
421 /* Handle the --cpu option */
422 {
423     cpu_t CPU = FindCPU (Arg);
424     if (CPU == CPU_UNKNOWN) {
425         AbEnd ("Invalid CPU: `%s'", Arg);
426     } else {
427         SetCPU (CPU);
428     }
429 }
430
431
432
433 static void OptCreateDep (const char* Opt, const char* Arg)
434 /* Handle the --create-dep option */
435 {
436     FileNameOption (Opt, Arg, &DepName);
437 }
438
439
440
441 static void OptCreateFullDep (const char* Opt attribute ((unused)),
442                               const char* Arg)
443 /* Handle the --create-full-dep option */
444 {
445     FileNameOption (Opt, Arg, &FullDepName);
446 }
447
448
449
450 static void OptDebug (const char* Opt attribute ((unused)),
451                       const char* Arg attribute ((unused)))
452 /* Compiler debug mode */
453 {
454     ++Debug;
455 }
456
457
458
459 static void OptDebugInfo (const char* Opt attribute ((unused)),
460                           const char* Arg attribute ((unused)))
461 /* Add debug info to the object file */
462 {
463     DbgSyms = 1;
464 }
465
466
467
468 static void OptFeature (const char* Opt attribute ((unused)), const char* Arg)
469 /* Set an emulation feature */
470 {
471     /* Make a string buffer from Arg */
472     StrBuf Feature;
473
474     /* Set the feature, check for errors */
475     if (SetFeature (SB_InitFromString (&Feature, Arg)) == FEAT_UNKNOWN) {
476         AbEnd ("Illegal emulation feature: `%s'", Arg);
477     }
478 }
479
480
481
482 static void OptHelp (const char* Opt attribute ((unused)),
483                      const char* Arg attribute ((unused)))
484 /* Print usage information and exit */
485 {
486     Usage ();
487     exit (EXIT_SUCCESS);
488 }
489
490
491
492 static void OptIgnoreCase (const char* Opt attribute ((unused)),
493                            const char* Arg attribute ((unused)))
494 /* Ignore case on symbols */
495 {
496     IgnoreCase = 1;
497 }
498
499
500
501 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
502 /* Add an include search path */
503 {
504     AddSearchPath (IncSearchPath, Arg);
505 }
506
507
508
509 static void OptLargeAlignment (const char* Opt attribute ((unused)),
510                                const char* Arg attribute ((unused)))
511 /* Don't warn about large alignments */
512 {
513     LargeAlignment = 1;
514 }
515
516
517
518 static void OptListBytes (const char* Opt, const char* Arg)
519 /* Set the maximum number of bytes per listing line */
520 {
521     unsigned Num;
522     char     Check;
523
524     /* Convert the argument to a number */
525     if (sscanf (Arg, "%u%c", &Num, &Check) != 1) {
526         InvArg (Opt, Arg);
527     }
528
529     /* Check the bounds */
530     if (Num != 0 && (Num < MIN_LIST_BYTES || Num > MAX_LIST_BYTES)) {
531         AbEnd ("Argument for option `%s' is out of range", Opt);
532     }
533
534     /* Use the value */
535     SetListBytes (Num);
536 }
537
538
539
540 static void OptListing (const char* Opt, const char* Arg)
541 /* Create a listing file */
542 {
543     /* Since the meaning of -l and --listing has changed, print an error if
544     ** the filename is empty or begins with the option char.
545     */
546     if (Arg == 0 || *Arg == '\0' || *Arg == '-') {
547         Fatal ("The meaning of `%s' has changed. It does now "
548                "expect a file name as argument.", Opt);
549     }
550
551     /* Get the file name */
552     FileNameOption (Opt, Arg, &ListingName);
553 }
554
555
556
557 static void OptMemoryModel (const char* Opt, const char* Arg)
558 /* Set the memory model */
559 {
560     mmodel_t M;
561
562     /* Check the current memory model */
563     if (MemoryModel != MMODEL_UNKNOWN) {
564         AbEnd ("Cannot use option `%s' twice", Opt);
565     }
566
567     /* Translate the memory model name and check it */
568     M = FindMemoryModel (Arg);
569     if (M == MMODEL_UNKNOWN) {
570         AbEnd ("Unknown memory model: %s", Arg);
571     } else if (M == MMODEL_HUGE) {
572         AbEnd ("Unsupported memory model: %s", Arg);
573     }
574
575     /* Set the memory model */
576     SetMemoryModel (M);
577 }
578
579
580
581 static void OptPageLength (const char* Opt attribute ((unused)), const char* Arg)
582 /* Handle the --pagelength option */
583 {
584     int Len = atoi (Arg);
585     if (Len != -1 && (Len < MIN_PAGE_LEN || Len > MAX_PAGE_LEN)) {
586         AbEnd ("Invalid page length: %d", Len);
587     }
588     PageLength = Len;
589 }
590
591
592
593 static void OptRelaxChecks (const char* Opt attribute ((unused)),
594                             const char* Arg attribute ((unused)))
595 /* Handle the --relax-checks options */
596 {
597     RelaxChecks = 1;
598 }
599
600
601
602 static void OptSmart (const char* Opt attribute ((unused)),
603                       const char* Arg attribute ((unused)))
604 /* Handle the -s/--smart options */
605 {
606     SmartMode = 1;
607 }
608
609
610
611 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
612 /* Set the target system */
613 {
614     SetSys (Arg);
615 }
616
617
618
619 static void OptVerbose (const char* Opt attribute ((unused)),
620                         const char* Arg attribute ((unused)))
621 /* Increase verbosity */
622 {
623     ++Verbosity;
624 }
625
626
627
628 static void OptVersion (const char* Opt attribute ((unused)),
629                         const char* Arg attribute ((unused)))
630 /* Print the assembler version */
631 {
632     fprintf (stderr, "ca65 V%s\n", GetVersionAsString ());
633 }
634
635
636
637 static void DoPCAssign (void)
638 /* Start absolute code */
639 {
640     long PC = ConstExpression ();
641     if (PC < 0 || PC > 0xFFFFFF) {
642         Error ("Range error");
643     } else {
644         EnterAbsoluteMode (PC);
645     }
646 }
647
648
649
650 static void OneLine (void)
651 /* Assemble one line */
652 {
653     Segment*      Seg   = 0;
654     unsigned long PC    = 0;
655     SymEntry*     Sym   = 0;
656     Macro*        Mac   = 0;
657     int           Instr = -1;
658
659     /* Initialize the new listing line if we are actually reading from file
660     ** and not from internally pushed input.
661     */
662     if (!HavePushedInput ()) {
663         InitListingLine ();
664     }
665
666     /* Single colon means unnamed label */
667     if (CurTok.Tok == TOK_COLON) {
668         ULabDef ();
669         NextTok ();
670     }
671
672     /* If the first token on the line is an identifier, check for a macro or
673     ** an instruction.
674     */
675     if (CurTok.Tok == TOK_IDENT) {
676         if (UbiquitousIdents) {
677             /* Macros CAN be instructions, so check for them first */
678             Mac = FindMacro (&CurTok.SVal);
679             if (Mac == 0) {
680                 Instr = FindInstruction (&CurTok.SVal);
681             }
682         } else {
683             /* Macros and symbols may NOT use the names of instructions */
684             Instr = FindInstruction (&CurTok.SVal);
685             if (Instr < 0) {
686                 Mac = FindMacro (&CurTok.SVal);
687             }
688         }
689     }
690
691     /* Handle an identifier. This may be a cheap local symbol, or a fully
692     ** scoped identifier which may start with a namespace token (for global
693     ** namespace)
694     */
695     if (CurTok.Tok == TOK_LOCAL_IDENT ||
696         CurTok.Tok == TOK_NAMESPACE   ||
697         (CurTok.Tok == TOK_IDENT && Instr < 0 && Mac == 0)) {
698
699         /* Did we have whitespace before the ident? */
700         int HadWS = CurTok.WS;
701
702         /* Generate the symbol table entry, then skip the name */
703         Sym = ParseAnySymName (SYM_ALLOC_NEW);
704
705         /* If a colon follows, this is a label definition. If there
706         ** is no colon, it's an assignment.
707         */
708         if (CurTok.Tok == TOK_EQ || CurTok.Tok == TOK_ASSIGN) {
709
710             /* Determine the symbol flags from the assignment token */
711             unsigned Flags = (CurTok.Tok == TOK_ASSIGN)? SF_LABEL : SF_NONE;
712
713             /* Skip the '=' */
714             NextTok ();
715
716             /* Define the symbol with the expression following the '=' */
717             SymDef (Sym, Expression(), ADDR_SIZE_DEFAULT, Flags);
718
719             /* Don't allow anything after a symbol definition */
720             ConsumeSep ();
721             return;
722
723         } else if (CurTok.Tok == TOK_SET) {
724
725             ExprNode* Expr;
726
727             /* .SET defines variables (= redefinable symbols) */
728             NextTok ();
729
730             /* Read the assignment expression, which must be constant */
731             Expr = GenLiteralExpr (ConstExpression ());
732
733             /* Define the symbol with the constant expression following
734             ** the '='
735             */
736             SymDef (Sym, Expr, ADDR_SIZE_DEFAULT, SF_VAR);
737
738             /* Don't allow anything after a symbol definition */
739             ConsumeSep ();
740             return;
741
742         } else {
743
744             /* A label. Remember the current segment, so we can later
745             ** determine the size of the data stored under the label.
746             */
747             Seg = ActiveSeg;
748             PC  = GetPC ();
749
750             /* Define the label */
751             SymDef (Sym, GenCurrentPC (), ADDR_SIZE_DEFAULT, SF_LABEL);
752
753             /* Skip the colon. If NoColonLabels is enabled, allow labels
754             ** without a colon if there is no whitespace before the
755             ** identifier.
756             */
757             if (CurTok.Tok != TOK_COLON) {
758                 if (HadWS || !NoColonLabels) {
759                     Error ("`:' expected");
760                     /* Try some smart error recovery */
761                     if (CurTok.Tok == TOK_NAMESPACE) {
762                         NextTok ();
763                     }
764                 }
765             } else {
766                 /* Skip the colon */
767                 NextTok ();
768             }
769
770             /* If we come here, a new identifier may be waiting, which may
771             ** be a macro or instruction.
772             */
773             if (CurTok.Tok == TOK_IDENT) {
774                 if (UbiquitousIdents) {
775                     /* Macros CAN be instructions, so check for them first */
776                     Mac = FindMacro (&CurTok.SVal);
777                     if (Mac == 0) {
778                         Instr = FindInstruction (&CurTok.SVal);
779                     }
780                 } else {
781                     /* Macros and symbols may NOT use the names of instructions */
782                     Instr = FindInstruction (&CurTok.SVal);
783                     if (Instr < 0) {
784                         Mac = FindMacro (&CurTok.SVal);
785                     }
786                 }
787             }
788         }
789     }
790
791     /* We've handled a possible label, now handle the remainder of the line */
792     if (CurTok.Tok >= TOK_FIRSTPSEUDO && CurTok.Tok <= TOK_LASTPSEUDO) {
793         /* A control command */
794         HandlePseudo ();
795     } else if (Mac != 0) {
796         /* A macro expansion */
797         MacExpandStart (Mac);
798     } else if (Instr >= 0) {
799         /* A mnemonic - assemble one instruction */
800         HandleInstruction (Instr);
801     } else if (PCAssignment && (CurTok.Tok == TOK_STAR || CurTok.Tok == TOK_PC)) {
802         NextTok ();
803         if (CurTok.Tok != TOK_EQ) {
804             Error ("`=' expected");
805             SkipUntilSep ();
806         } else {
807             /* Skip the equal sign */
808             NextTok ();
809             /* Enter absolute mode */
810             DoPCAssign ();
811         }
812     }
813
814     /* If we have defined a label, remember its size. Sym is also set by
815     ** a symbol assignment, but in this case Done is false, so we don't
816     ** come here.
817     */
818     if (Sym) {
819         unsigned long Size;
820         if (Seg == ActiveSeg) {
821             /* Same segment */
822             Size = GetPC () - PC;
823         } else {
824             /* The line has switched the segment */
825             Size = 0;
826         }
827         DefSizeOfSymbol (Sym, Size);
828     }
829
830     /* Line separator must come here */
831     ConsumeSep ();
832 }
833
834
835
836 static void Assemble (void)
837 /* Start the ball rolling ... */
838 {
839     /* Prime the pump */
840     NextTok ();
841
842     /* Assemble lines until end of file */
843     while (CurTok.Tok != TOK_EOF) {
844         OneLine ();
845     }
846 }
847
848
849
850 static void CreateObjFile (void)
851 /* Create the object file */
852 {
853     /* Open the object, write the header */
854     ObjOpen ();
855
856     /* Write the object file options */
857     WriteOptions ();
858
859     /* Write the list of input files */
860     WriteFiles ();
861
862     /* Write the segment data to the file */
863     WriteSegments ();
864
865     /* Write the import list */
866     WriteImports ();
867
868     /* Write the export list */
869     WriteExports ();
870
871     /* Write debug symbols if requested */
872     WriteDbgSyms ();
873
874     /* Write the scopes if requested */
875     WriteScopes ();
876
877     /* Write line infos if requested */
878     WriteLineInfos ();
879
880     /* Write the string pool */
881     WriteStrPool ();
882
883     /* Write the assertions */
884     WriteAssertions ();
885
886     /* Write the spans */
887     WriteSpans ();
888
889     /* Write an updated header and close the file */
890     ObjClose ();
891 }
892
893
894
895 int main (int argc, char* argv [])
896 /* Assembler main program */
897 {
898     /* Program long options */
899     static const LongOpt OptTab[] = {
900         { "--auto-import",      0,      OptAutoImport           },
901         { "--bin-include-dir",  1,      OptBinIncludeDir        },
902         { "--cpu",              1,      OptCPU                  },
903         { "--create-dep",       1,      OptCreateDep            },
904         { "--create-full-dep",  1,      OptCreateFullDep        },
905         { "--debug",            0,      OptDebug                },
906         { "--debug-info",       0,      OptDebugInfo            },
907         { "--feature",          1,      OptFeature              },
908         { "--help",             0,      OptHelp                 },
909         { "--ignore-case",      0,      OptIgnoreCase           },
910         { "--include-dir",      1,      OptIncludeDir           },
911         { "--large-alignment",  0,      OptLargeAlignment       },
912         { "--list-bytes",       1,      OptListBytes            },
913         { "--listing",          1,      OptListing              },
914         { "--memory-model",     1,      OptMemoryModel          },
915         { "--pagelength",       1,      OptPageLength           },
916         { "--relax-checks",     0,      OptRelaxChecks          },
917         { "--smart",            0,      OptSmart                },
918         { "--target",           1,      OptTarget               },
919         { "--verbose",          0,      OptVerbose              },
920         { "--version",          0,      OptVersion              },
921     };
922
923     /* Name of the global name space */
924     static const StrBuf GlobalNameSpace = STATIC_STRBUF_INITIALIZER;
925
926     unsigned I;
927
928     /* Initialize the cmdline module */
929     InitCmdLine (&argc, &argv, "ca65");
930
931     /* Initialize the string pool */
932     InitStrPool ();
933
934     /* Initialize the include search paths */
935     InitIncludePaths ();
936
937     /* Create the predefined segments */
938     SegInit ();
939
940     /* Enter the base lexical level. We must do that here, since we may
941     ** define symbols using -D.
942     */
943     SymEnterLevel (&GlobalNameSpace, SCOPE_FILE, ADDR_SIZE_DEFAULT, 0);
944
945     /* Initialize the line infos. Must be done here, since we need line infos
946     ** for symbol definitions.
947     */
948     InitLineInfo ();
949
950     /* Check the parameters */
951     I = 1;
952     while (I < ArgCount) {
953
954         /* Get the argument */
955         const char* Arg = ArgVec [I];
956
957         /* Check for an option */
958         if (Arg[0] == '-') {
959             switch (Arg[1]) {
960
961                 case '-':
962                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
963                     break;
964
965                 case 'd':
966                     OptDebug (Arg, 0);
967                     break;
968
969                 case 'g':
970                     OptDebugInfo (Arg, 0);
971                     break;
972
973                 case 'h':
974                     OptHelp (Arg, 0);
975                     break;
976
977                 case 'i':
978                     OptIgnoreCase (Arg, 0);
979                     break;
980
981                 case 'l':
982                     OptListing (Arg, GetArg (&I, 2));
983                     break;
984
985                 case 'm':
986                     if (Arg[2] == 'm') {
987                         OptMemoryModel (Arg, GetArg (&I, 3));
988                     } else {
989                         UnknownOption (Arg);
990                     }
991                     break;
992
993                 case 'o':
994                     OutFile = GetArg (&I, 2);
995                     break;
996
997                 case 's':
998                     OptSmart (Arg, 0);
999                     break;
1000
1001                 case 't':
1002                     OptTarget (Arg, GetArg (&I, 2));
1003                     break;
1004
1005                 case 'v':
1006                     OptVerbose (Arg, 0);
1007                     break;
1008
1009                 case 'D':
1010                     DefineSymbol (GetArg (&I, 2));
1011                     break;
1012
1013                 case 'I':
1014                     OptIncludeDir (Arg, GetArg (&I, 2));
1015                     break;
1016
1017                 case 'U':
1018                     OptAutoImport (Arg, 0);
1019                     break;
1020
1021                 case 'V':
1022                     OptVersion (Arg, 0);
1023                     break;
1024
1025                 case 'W':
1026                     WarnLevel = atoi (GetArg (&I, 2));
1027                     break;
1028
1029                 default:
1030                     UnknownOption (Arg);
1031                     break;
1032
1033             }
1034         } else {
1035             /* Filename. Check if we already had one */
1036             if (InFile) {
1037                 fprintf (stderr, "%s: Don't know what to do with `%s'\n",
1038                          ProgName, Arg);
1039                 exit (EXIT_FAILURE);
1040             } else {
1041                 InFile = Arg;
1042             }
1043         }
1044
1045         /* Next argument */
1046         ++I;
1047     }
1048
1049     /* Do we have an input file? */
1050     if (InFile == 0) {
1051         fprintf (stderr, "%s: No input files\n", ProgName);
1052         exit (EXIT_FAILURE);
1053     }
1054
1055     /* Add the default include search paths. */
1056     FinishIncludePaths ();
1057
1058     /* If no CPU given, use the default CPU for the target */
1059     if (GetCPU () == CPU_UNKNOWN) {
1060         if (Target != TGT_UNKNOWN) {
1061             SetCPU (GetTargetProperties (Target)->DefaultCPU);
1062         } else {
1063             SetCPU (CPU_6502);
1064         }
1065     }
1066
1067     /* If no memory model was given, use the default */
1068     if (MemoryModel == MMODEL_UNKNOWN) {
1069         SetMemoryModel (MMODEL_NEAR);
1070     }
1071
1072     /* Set the default segment sizes according to the memory model */
1073     SetSegmentSizes ();
1074
1075     /* Initialize the scanner, open the input file */
1076     InitScanner (InFile);
1077
1078     /* Define the default options */
1079     SetOptions ();
1080
1081     /* Assemble the input */
1082     Assemble ();
1083
1084     /* If we didn't have any errors, check the pseudo insn stacks */
1085     if (ErrorCount == 0) {
1086         CheckPseudo ();
1087     }
1088
1089     /* If we didn't have any errors, check and cleanup the unnamed labels */
1090     if (ErrorCount == 0) {
1091         ULabDone ();
1092     }
1093
1094     /* If we didn't have any errors, check the symbol table */
1095     if (ErrorCount == 0) {
1096         SymCheck ();
1097     }
1098
1099     /* If we didn't have any errors, check the hll debug symbols */
1100     if (ErrorCount == 0) {
1101         DbgInfoCheck ();
1102     }
1103
1104     /* If we didn't have any errors, close the file scope lexical level */
1105     if (ErrorCount == 0) {
1106         SymLeaveLevel ();
1107     }
1108
1109     /* If we didn't have any errors, check and resolve the segment data */
1110     if (ErrorCount == 0) {
1111         SegDone ();
1112     }
1113
1114     /* If we didn't have any errors, check the assertions */
1115     if (ErrorCount == 0) {
1116         CheckAssertions ();
1117     }
1118
1119     /* Dump the data */
1120     if (Verbosity >= 2) {
1121         SymDump (stdout);
1122         SegDump ();
1123     }
1124
1125     /* If we didn't have an errors, finish off the line infos */
1126     DoneLineInfo ();
1127
1128     /* If we didn't have any errors, create the object, listing and
1129     ** dependency files
1130     */
1131     if (ErrorCount == 0) {
1132         CreateObjFile ();
1133         if (SB_GetLen (&ListingName) > 0) {
1134             CreateListing ();
1135         }
1136        CreateDependencies ();
1137     }
1138
1139     /* Close the input file */
1140     DoneScanner ();
1141
1142     /* Return an apropriate exit code */
1143     return (ErrorCount == 0)? EXIT_SUCCESS : EXIT_FAILURE;
1144 }