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