]> git.sur5r.net Git - cc65/blob - doc/ca65.sgml
Fixed a typo
[cc65] / doc / ca65.sgml
1 <!doctype linuxdoc system>
2
3 <article>
4 <title>ca65 Users Guide
5 <author>Ullrich von Bassewitz, <htmlurl url="mailto:uz@cc65.org" name="uz@cc65.org">
6 <date>19.07.2000, 29.11.2000, 02.10.2001
7
8 <abstract>
9 ca65 is a powerful macro assembler for the 6502, 65C02 and 65816 CPUs. It is
10 used as a companion assembler for the cc65 crosscompiler, but it may also be
11 used as a standalone product.
12 </abstract>
13
14 <!-- Table of contents -->
15 <toc>
16
17 <!-- Begin the document -->
18
19 <sect>Overview<p>
20
21 ca65 is a replacement for the ra65 assembler that was part of the cc65 C
22 compiler, originally developed by John R. Dunning. I had some problems with
23 ra65 and the copyright does not permit some things which I wanted to be
24 possible, so I decided to write a completely new assembler/linker/archiver
25 suite for the cc65 compiler. ca65 is part of this suite.
26
27 Some parts of the assembler (code generation and some routines for symbol
28 table handling) are taken from an older crossassembler named a816 written
29 by me a long time ago.
30
31
32 <sect1>Design criteria<p>
33
34 Here's a list of the design criteria, that I considered important for the
35 development:
36
37 <itemize>
38
39 <item>  The assembler must support macros. Macros are not essential, but they
40         make some things easier, especially when you use the assembler in the
41         backend of a compiler.
42 <item>  The assembler must support the newer 65C02 and 65816 CPUs. I have been
43         thinking about a 65816 backend for the C compiler, and even my old
44         a816 assembler had support for these CPUs, so this wasn't really a
45         problem.
46 <item>  The assembler must produce relocatable code. This is necessary for the
47         compiler support, and it is more convenient.
48 <item>  Conditional assembly must be supported. This is a must for bigger
49         projects written in assembler (like Elite128).
50 <item>  The assembler must support segments, and it must support more than
51         three segments (this is the count, most other assemblers support).
52         Having more than one code segments helps developing code for systems
53         with a divided ROM area (like the C64).
54 <item>  The linker must be able to resolve arbitrary expressions. It should
55         be able to get things like
56 <tscreen><verb>
57         .import S1, S2
58         .export Special
59         Special = 2*S1 + S2/7
60 </verb></tscreen>
61         right.
62 <item>  True lexical nesting for symbols. This is very convenient for larger
63         assembly projects.
64 <item>  "Cheap" local symbols without lexical nesting for those quick, late
65         night hacks.
66 <item>  I liked the idea of "options" as Anre Fachats .o65 format has it, so I
67         introduced the concept into the object file format use by the new cc65
68         binutils.
69 <item>  The assembler will be a one pass assembler. There was no real need for
70         this decision, but I've written several multipass assemblers, and it
71         started to get boring. A one pass assembler needs much more elaborated
72         data structures, and because of that it's much more fun:-)
73 <item>  Non-GPLed code that may be used in any project without restrictions or
74         fear of "GPL infecting" other code.
75 </itemize>
76 <p>
77
78
79 <sect>Usage<p>
80
81
82 <sect1>Command line option overview<p>
83
84 The assembler accepts the following options:
85
86 <tscreen><verb>
87 ---------------------------------------------------------------------------
88 Usage: ca65 [options] file
89 Short options:
90   -D name[=value]       Define a symbol
91   -I dir                Set an include directory search path
92   -U                    Mark unresolved symbols as import
93   -V                    Print the assembler version
94   -W n                  Set warning level n
95   -g                    Add debug info to object file
96   -h                    Help (this text)
97   -i                    Ignore case of symbols
98   -l                    Create a listing if assembly was ok
99   -o name               Name the output file
100   -s                    Enable smart mode
101   -t sys                Set the target system
102   -v                    Increase verbosity
103
104 Long options:
105   --auto-import         Mark unresolved symbols as import
106   --cpu type            Set cpu type
107   --debug-info          Add debug info to object file
108   --feature name        Set an emulation feature
109   --help                Help (this text)
110   --ignore-case         Ignore case of symbols
111   --include-dir dir     Set an include directory search path
112   --list-bytes n        Maximum number of bytes per listing line
113   --listing             Create a listing if assembly was ok
114   --pagelength n        Set the page length for the listing
115   --smart               Enable smart mode
116   --target sys          Set the target system
117   --verbose             Increase verbosity
118   --version             Print the assembler version
119 ---------------------------------------------------------------------------
120 </verb></tscreen>
121
122
123 <sect1>Command line options in detail<p>
124
125 Here is a description of all the command line options:
126
127 <descrip>
128
129   <label id="option--cpu">
130   <tag><tt>--cpu type</tt></tag>
131
132   Set the default for the CPU type. The option takes a parameter, which
133   may be one of
134
135         6502, 65SC02, 65C02, 65816 and sunplus
136
137   The last one (sunplus) is not available in the freeware version, because the
138   instruction set of the sunplus CPU is "proprietary and confidential".
139
140
141   <label id="option--feature">
142   <tag><tt>--feature name</tt></tag>
143
144   Enable an emulation feature. This is identical as using <tt/.FEATURE/
145   in the source with two exceptions: Feature names must be lower case, and
146   each feature must be specified by using an extra <tt/--feature/ option,
147   comma separated lists are not allowed.
148
149   See the discussion of the <tt><ref id=".FEATURE" name=".FEATURE"></tt>
150   command for a list of emulation features.
151
152
153   <label id="option-g">
154   <tag><tt>-g, --debug-info</tt></tag>
155
156   When this option (or the equivalent control command <tt/.DEBUGINFO/) is
157   used, the assembler will add a section to the object file that contains
158   all symbols (including local ones) together with the symbol values and
159   source file positions. The linker will put these additional symbols into
160   the VICE label file, so even local symbols can be seen in the VICE
161   monitor.
162
163
164   <tag><tt>-h, --help</tt></tag>
165
166   Print the short option summary shown above.
167
168
169   <tag><tt>-i, --ignore-case</tt></tag>
170
171   This option makes the assembler case insensitive on identifiers and labels.
172   This option will override the default, but may itself be overriden by the
173   <tt><ref id=".CASE" name=".CASE"></tt> control command.
174
175
176   <tag><tt>-l, --listing</tt></tag>
177
178   Generate an assembler listing. The listing file will always have the
179   name of the main input file with the extension replaced by ".lst". This
180   may change in future versions.
181
182
183   <tag><tt>--list-bytes n</tt></tag>
184
185   Set the maximum number of bytes printed in the listing for one line of
186   input. See the <tt><ref id=".LISTBYTES" name=".LISTBYTES"></tt> directive
187   for more information. The value zero can be used to encode an unlimited
188   number of printed bytes.
189
190
191   <tag><tt>-o name</tt></tag>
192
193   The default output name is the name of the input file with the extension
194   replaced by ".o". If you don't like that, you may give another name with
195   the -o option. The output file will be placed in the same directory as
196   the source file, or, if -o is given, the full path in this name is used.
197
198
199   <tag><tt>--pagelength n</tt></tag>
200
201   sets the length of a listing page in lines. See the <tt><ref
202   id=".PAGELENGTH" name=".PAGELENGTH"></tt> directive for more information.
203
204
205   <tag><tt>-s, --smart-mode</tt></tag>
206
207   In smart mode (enabled by -s or the <tt><ref id=".SMART" name=".SMART"></tt>
208   pseudo instruction) the assembler will track usage of the <tt/REP/ and
209   <tt/SEP/ instructions in 65816 mode and update the operand sizes
210   accordingly. If the operand of such an instruction cannot be evaluated by
211   the assembler (for example, because the operand is an imported symbol), a
212   warning is issued.
213
214   Beware: Since the assembler cannot trace the execution flow this may
215   lead to false results in some cases. If in doubt, use the .ixx and .axx
216   instructions to tell the assembler about the current settings. Smart
217   mode is off by default.
218
219
220   <label id="option-t">
221   <tag><tt>-t sys, --target sys</tt></tag>
222
223   Set the target system. This will enable translation of character strings
224   and character constants into the character set of the target platform.
225   The default for the target system is "none", which means that no translation
226   will take place. The assembler supports the same target systems as the
227   compiler, see there for a list.
228
229
230   <tag><tt>-v, --verbose</tt></tag>
231
232   Increase the assembler verbosity. Usually only needed for debugging
233   purposes. You may use this option more than one time for even more
234   verbose output.
235
236
237   <tag><tt>-D</tt></tag>
238
239   This option allows you to define symbols on the command line. Without a
240   value, the symbol is defined with the value zero. When giving a value,
241   you may use the '&dollar;' prefix for hexadecimal symbols. Please note
242   that for some operating systems, '&dollar;' has a special meaning, so
243   you may have to quote the expression.
244
245
246   <tag><tt>-I dir, --include-dir dir</tt></tag>
247
248   Name a directory which is searched for include files. The option may be
249   used more than once to specify more than one directory to search. The
250   current directory is always searched first before considering any
251   additional directores.
252
253
254   <tag><tt>-U, --auto-import</tt></tag>
255
256   Mark symbols that are not defined in the sources as imported symbols. This
257   should be used with care since it delays error messages about typos and such
258   until the linker is run. The compiler uses the equivalent of this switch
259   (<tt><ref id=".AUTOIMPORT" name=".AUTOIMPORT"></tt>) to enable auto imported
260   symbols for the runtime library. However, the compiler is supposed to
261   generate code that runs through the assembler without problems, something
262   which is not always true for assembler programmers.
263
264
265   <tag><tt>-V, --version</tt></tag>
266
267   Print the version number of the assembler. If you send any suggestions
268   or bugfixes, please include the version number.
269
270
271   <label id="option-W">
272   <tag><tt>-Wn</tt></tag>
273
274   Set the warning level for the assembler. Using -W2 the assembler will
275   even warn about such things like unused imported symbols. The default
276   warning level is 1, and it would probably be silly to set it to
277   something lower.
278
279 </descrip>
280 <p>
281
282
283 <sect>Input format<p>
284
285 <sect1>Assembler syntax<p>
286
287 The assembler accepts the standard 6502/65816 assembler syntax. One line may
288 contain a label (which is identified by a colon), and, in addition to the
289 label, an assembler mnemonic, a macro, or a control command (see section <ref
290 id="control-commands" name="Control Commands"> for supported control
291 commands). Alternatively, the line may contain a symbol definition using the
292 '=' token. Everything after a semicolon is handled as a comment (that is, it
293 is ignored).
294
295 Here are some examples for valid input lines:
296
297 <tscreen><verb>
298         Label:                          ; A label and a comment
299                 lda     #$20            ; A 6502 instruction plus comment
300         L1:     ldx     #$20            ; Same with label
301         L2:     .byte   "Hello world"   ; Label plus control command
302                 mymac   $20             ; Macro expansion
303                 MySym = 3*L1            ; Symbol definition
304         MaSym   = Label                 ; Another symbol
305 </verb></tscreen>
306
307 The assembler accepts
308
309 <itemize>
310 <item>all valid 6502 mnemonics when in 6502 mode (the default or after the
311       <tt><ref id=".P02" name=".P02"></tt> command was given).
312 <item>all valid 6502 mnemonics plus a set of illegal instructions when in
313       <ref id="6502X-mode" name="6502X mode">.
314 <item>all valid 65SC02 mnemonics when in 65SC02 mode (after the
315       <tt><ref id=".PSC02" name=".PSC02"></tt> command was given).
316 <item>all valid 65C02 mnemonics when in 65C02 mode (after the
317       <tt><ref id=".PC02" name=".PC02"></tt> command was given).
318 <item>all valid 65618 mnemonics when in 65816 mode (after the
319       <tt><ref id=".P816" name=".P816"></tt> command was given).
320 <item>all valid SunPlus mnemonics when in SunPlus mode (after the
321       <tt><ref id=".SUNPLUS" name=".SUNPLUS"></tt> command was given).
322 </itemize>
323
324
325 <sect1>65816 mode<p>
326
327 In 65816 mode several aliases are accepted in addition to the official
328 mnemonics:
329
330 <tscreen><verb>
331         BGE is an alias for BCS
332         BLT is an alias for BCC
333         CPA is an alias for CMP
334         DEA is an alias for DEC A
335         INA is an alias for INC A
336         SWA is an alias for XBA
337         TAD is an alias for TCD
338         TAS is an alias for TCS
339         TDA is an alias for TDC
340         TSA is an alias for TSC
341 </verb></tscreen>
342
343
344
345 <sect1>6502X mode<label id="6502X-mode"><p>
346
347 6502X mode is an extension to the normal 6502 mode. In this mode, several
348 mnemomics for illegal instructions of the NMOS 6502 CPUs are accepted. Since
349 these instructions are illegal, there are no official mnemonics for them. The
350 unofficial ones are taken from <htmlurl
351 url="http://oxyron.net/graham/opcodes02.html"
352 name="http://oxyron.net/graham/opcodes02.html">. Please note that only the
353 ones marked as "stable" are supported. The following table uses information
354 from the mentioned web page, for more information, see there.
355
356 <itemize>
357 <item><tt>ALR: A:=(A and #{imm})*2;</tt>
358 <item><tt>ANC: A:=A and #{imm};</tt> Generates opcode &dollar;0B.
359 <item><tt>ARR: A:=(A and #{imm})/2;</tt>
360 <item><tt>AXS: X:=A and X-#{imm};</tt>
361 <item><tt>DCP: {adr}:={adr}-1; A-{adr};</tt>
362 <item><tt>ISC: {adr}:={adr}+1; A:=A-{adr};</tt>
363 <item><tt>LAS: A,X,S:={adr} and S;</tt>
364 <item><tt>LAX: A,X:={adr};</tt>
365 <item><tt>RLA: {adr}:={adr}rol; A:=A and {adr};</tt>
366 <item><tt>RRA: {adr}:={adr}ror; A:=A adc {adr};</tt>
367 <item><tt>SAX: {adr}:=A and X;</tt>
368 <item><tt>SLO: {adr}:={adr}*2; A:=A or {adr};</tt>
369 <item><tt>SRE: {adr}:={adr}/2; A:=A xor {adr};</tt>
370 </itemize>
371
372
373
374 <sect1>Number format<p>
375
376 For literal values, the assembler accepts the widely used number formats:
377 A preceeding '&dollar;' denotes a hex value, a preceeding '%' denotes a
378 binary value, and a bare number is interpeted as a decimal. There are
379 currently no octal values and no floats.
380
381
382 <sect1>Conditional assembly<p>
383
384 Please note that when using the conditional directives (<tt/.IF/ and friends),
385 the input must consist of valid assembler tokens, even in <tt/.IF/ branches
386 that are not assembled. The reason for this behaviour is that the assembler
387 must still be able to detect the ending tokens (like <tt/.ENDIF/), so
388 conversion of the input stream into tokens still takes place. As a consequence
389 conditional assembly directives may <bf/not/ be used to prevent normal text
390 (used as a comment or similar) from being assembled. <p>
391
392
393 <sect>Expressions<p>
394
395
396 <sect1>Expression evaluation<p>
397
398 All expressions are evaluated with (at least) 32 bit precision. An
399 expression may contain constant values and any combination of internal and
400 external symbols. Expressions that cannot be evaluated at assembly time
401 are stored inside the object file for evaluation by the linker.
402 Expressions referencing imported symbols must always be evaluated by the
403 linker.
404
405
406 <sect1>Size of an expression result<p>
407
408 Sometimes, the assembler must know about the size of the value that is the
409 result of an expression. This is usually the case, if a decision has to be
410 made, to generate a zero page or an absolute memory references. In this
411 case, the assembler has to make some assumptions about the result of an
412 expression:
413
414 <itemize>
415 <item>  If the result of an expression is constant, the actual value is
416         checked to see if it's a byte sized expression or not.
417 <item>  If the expression is explicitly casted to a byte sized expression by
418         one of the '&gt;', '&lt;' or '^' operators, it is a byte expression.
419 <item>  If this is not the case, and the expression contains a symbol,
420         explicitly declared as zero page symbol (by one of the .importzp or
421         .exportzp instructions), then the whole expression is assumed to be
422         byte sized.
423 <item>  If the expression contains symbols that are not defined, and these
424         symbols are local symbols, the enclosing scopes are searched for a
425         symbol with the same name. If one exists and this symbol is defined,
426         it's attributes are used to determine the result size.
427 <item>  In all other cases the expression is assumed to be word sized.
428 </itemize>
429
430 Note: If the assembler is not able to evaluate the expression at assembly
431 time, the linker will evaluate it and check for range errors as soon as
432 the result is known.
433
434
435 <sect1>Boolean expressions<p>
436
437 In the context of a boolean expression, any non zero value is evaluated as
438 true, any other value to false. The result of a boolean expression is 1 if
439 it's true, and zero if it's false. There are boolean operators with extrem
440 low precedence with version 2.x (where x &gt; 0). The <tt/.AND/ and <tt/.OR/
441 operators are shortcut operators. That is, if the result of the expression is
442 already known, after evaluating the left hand side, the right hand side is
443 not evaluated.
444
445
446 <sect1>Constant expressions<p>
447
448 Sometimes an expression must evaluate to a constant without looking at any
449 further input. One such example is the <tt/<ref id=".IF" name=".IF">/ command
450 that decides if parts of the code are assembled or not. An expression used in
451 the <tt/.IF/ command cannot reference a symbol defined later, because the
452 decision about the <tt/.IF/ must be made at the point when it is read. If the
453 expression used in such a context contains only constant numerical values,
454 there is no problem. When unresolvable symbols are involved it may get harder
455 for the assembler to determine if the expression is actually constant, and it
456 is even possible to create expressions that aren't recognized as constant.
457 Simplifying the expressions will often help.
458
459 In cases where the result of the expression is not needed immediately, the
460 assembler will delay evaluation until all input is read, at which point all
461 symbols are known. So using arbitrary complex constant expressions is no
462 problem in most cases.
463
464
465
466 <sect1>Available operators<label id="operators"><p>
467
468 Available operators sorted by precedence:
469
470 <tscreen><verb>
471     Op          Description                             Precedence
472   -------------------------------------------------------------------
473                 Builtin string functions                0
474
475                 Builtin pseudo variables                1
476                 Builtin pseudo functions                1
477     +           Unary plus                              1
478     -           Unary minus                             1
479     ~           Unary bitwise not                       1
480     .BITNOT     Unary bitwise not                       1
481     &lt;           Low byte operator                       1
482     &gt;           High byte operator                      1
483     ^           Bank byte operator                      1
484
485     *           Multiplication                          2
486     /           Division                                2
487     .MOD        Modulo operation                        2
488     &amp;           Bitwise and                             2
489     .BITAND     Bitwise and                             2
490     ^           Bitwise xor                             2
491     .BITXOR     Bitwise xor                             2
492     &lt;&lt;          Shift left operator                     2
493     .SHL        Shift left operator                     2
494     &gt;&gt;          Shift right operator
495     .SHR        Shift right operator                    2
496
497     +           Binary plus                             3
498     -           Binary minus                            3
499     |           Binary or                               3
500     .BITOR      Binary or                               3
501
502     =           Compare operation (equal)               4
503     &lt;&gt;          Compare operation (not equal)           4
504     &lt;           Compare operation (less)                4
505     &gt;           Compare operation (greater)             4
506     &lt;=          Compare operation (less or equal)       4
507     &gt;=          Compare operation (greater or equal)    4
508
509     &amp;&amp;          Boolean and                             5
510     .AND        Boolean and                             5
511     .XOR        Boolean xor                             5
512
513     ||          Boolean or                              6
514     .OR         Boolean or                              6
515
516     !           Boolean not                             7
517     .NOT        Boolean not                             7
518 </verb></tscreen>
519
520
521 To force a specific order of evaluation, braces may be used as usual.
522
523 <p>
524
525
526
527 <sect>Symbols and labels<p>
528
529 The assembler allows you to use symbols instead of naked values to make
530 the source more readable. There are a lot of different ways to define and
531 use symbols and labels, giving a lot of flexibility.
532
533
534 <sect1>Numeric constants<p>
535
536 Numeric constants are defined using the equal sign or the label assignment
537 operator. After doing
538
539 <tscreen><verb>
540       two = 2
541 </verb></tscreen>
542
543 may use the symbol "two" in every place where a number is expected, and it is
544 evaluated to the value 2 in this context. The label assignment operator causes
545 the same, but causes the symbol to be marked as a label, which may cause a
546 different handling in the debugger:
547
548 <tscreen><verb>
549       io := $d000
550 </verb></tscreen>
551
552 The right side can of course be an expression:
553
554 <tscreen><verb>
555       four = two * two
556 </verb></tscreen>
557
558
559 <sect1>Standard labels<p>
560
561 A label is defined by writing the name of the label at the start of the line
562 (before any instruction mnemonic, macro or pseudo directive), followed by a
563 colon. This will declare a symbol with the given name and the value of the
564 current program counter.
565
566
567 <sect1>Local labels and symbols<p>
568
569 Using the <tt><ref id=".PROC" name=".PROC"></tt> directive, it is possible to
570 create regions of code where the names of labels and symbols are local to this
571 region. They are not known outside of this region and cannot be accessed from
572 there. Such regions may be nested like PROCEDUREs in Pascal.
573
574 See the description of the <tt><ref id=".PROC" name=".PROC"></tt>
575 directive for more information.
576
577
578 <sect1>Cheap local labels<p>
579
580 Cheap local labels are defined like standard labels, but the name of the
581 label must begin with a special symbol (usually '@', but this can be
582 changed by the <tt><ref id=".LOCALCHAR" name=".LOCALCHAR"></tt>
583 directive).
584
585 Cheap local labels are visible only between two non cheap labels. As soon as a
586 standard symbol is encountered (this may also be a local symbol if inside a
587 region defined with the <tt><ref id=".PROC" name=".PROC"></tt> directive), the
588 cheap local symbol goes out of scope.
589
590 You may use cheap local labels as an easy way to reuse common label
591 names like "Loop". Here is an example:
592
593 <tscreen><verb>
594         Clear:  lda    #$00             ; Global label
595                 ldy    #$20
596         @Loop:  sta    Mem,y            ; Local label
597                 dey
598                 bne    @Loop            ; Ok
599                 rts
600         Sub:    ...                     ; New global label
601                 bne    @Loop            ; ERROR: Unknown identifier!
602 </verb></tscreen>
603
604 <sect1>Unnamed labels<p>
605
606 If you really want to write messy code, there are also unnamed
607 labels. These labels do not have a name (you guessed that already,
608 didn't you?). A colon is used to mark the absence of the name.
609
610 Unnamed labels may be accessed by using the colon plus several minus
611 or plus characters as a label designator. Using the '-' characters
612 will create a back reference (use the n'th label backwards), using
613 '+' will create a forward reference (use the n'th label in forward
614 direction). An example will help to understand this:
615
616 <tscreen><verb>
617         :       lda     (ptr1),y        ; #1
618                 cmp     (ptr2),y
619                 bne     :+              ; -> #2
620                 tax
621                 beq     :+++            ; -> #4
622                 iny
623                 bne     :-              ; -> #1
624                 inc     ptr1+1
625                 inc     ptr2+1
626                 bne     :-              ; -> #1
627
628         :       bcs     :+              ; #2 -> #3
629                 ldx     #$FF
630                 rts
631
632         :       ldx     #$01            ; #3
633         :       rts                     ; #4
634 </verb></tscreen>
635
636 As you can see from the example, unnamed labels will make even short
637 sections of code hard to understand, because you have to count labels
638 to find branch targets (this is the reason why I for my part do
639 prefer the "cheap" local labels). Nevertheless, unnamed labels are
640 convenient in some situations, so it's your decision.
641
642
643 <sect1>Using macros to define labels and constants<p>
644
645 While there are drawbacks with this approach, it may be handy in some
646 situations. Using <tt><ref id=".DEFINE" name=".DEFINE"></tt>, it is
647 possible to define symbols or constants that may be used elsewhere. Since
648 the macro facility works on a very low level, there is no scoping. On the
649 other side, you may also define string constants this way (this is not
650 possible with the other symbol types).
651
652 Example:
653
654 <tscreen><verb>
655         .DEFINE two     2
656         .DEFINE version "SOS V2.3"
657
658         four = two * two        ; Ok
659         .byte   version         ; Ok
660
661         .PROC                   ; Start local scope
662         two = 3                 ; Will give "2 = 3" - invalid!
663         .ENDPROC
664 </verb></tscreen>
665
666
667 <sect1>Symbols and <tt>.DEBUGINFO</tt><p>
668
669 If <tt><ref id=".DEBUGINFO" name=".DEBUGINFO"></tt> is enabled (or <ref
670 id="option-g" name="-g"> is given on the command line), global, local and
671 cheap local labels are written to the object file and will be available in the
672 symbol file via the linker. Unnamed labels are not written to the object file,
673 because they don't have a name which would allow to access them.
674
675
676
677 <sect>Scopes<label id="scopes"><p>
678
679 ca65 implements several sorts of scopes for symbols.
680
681 <sect1>Global scope<p>
682
683 All (non cheap local) symbols that are declared outside of any nested scopes
684 are in global scope.
685
686
687 <sect1>A special scope: cheap locals<p>
688
689 A special scope is the scope for cheap local symbols. It lasts from one non
690 local symbol to the next one, without any provisions made by the programmer.
691 All other scopes differ in usage but use the same concept internally.
692
693
694 <sect1>Generic nested scopes<p>
695
696 A nested scoped for generic use is started with <tt/<ref id=".SCOPE"
697 name=".SCOPE">/ and closed with <tt/<ref id=".ENDSCOPE" name=".ENDSCOPE">/.
698 The scope can have a name, in which case it is accessible from the outside by
699 using <ref id="scopesyntax" name="explicit scopes">. If the scope does not
700 have a name, all symbols created within the scope are local to the scope, and
701 aren't accessible from the outside.
702
703 A nested scope can access symbols from the local or from enclosing scopes by
704 name without using explicit scope names. In some cases there may be
705 ambiguities, for example if there is a reference to a local symbol that is not
706 yet defined, but a symbol with the same name exists in outer scopes:
707
708 <tscreen><verb>
709         .scope  outer
710                 foo     = 2
711                 .scope  inner
712                         lda     #foo
713                         foo     = 3
714                 .endscope
715         .endscope
716 </verb></tscreen>
717
718 In the example above, the <tt/lda/ instruction will load the value 3 into the
719 accumulator, because <tt/foo/ is redefined in the scope. However:
720
721 <tscreen><verb>
722         .scope  outer
723                 foo     = $1234
724                 .scope  inner
725                         lda     foo,x
726                         foo     = $12
727                 .endscope
728         .endscope
729 </verb></tscreen>
730
731 Here, <tt/lda/ will still load from <tt/$12,x/, but since it is unknown to the
732 assembler that <tt/foo/ is a zeropage symbol when translating the instruction,
733 absolute mode is used instead. In fact, the assembler will not use absolute
734 mode by default, but it will search through the enclosing scopes for a symbol
735 with the given name. If one is found, the address size of this symbol is used.
736 This may lead to errors:
737
738 <tscreen><verb>
739         .scope  outer
740                 foo     = $12
741                 .scope  inner
742                         lda     foo,x
743                         foo     = $1234
744                 .endscope
745         .endscope
746 </verb></tscreen>
747
748 In this case, when the assembler sees the symbol <tt/foo/ in the <tt/lda/
749 instruction, it will search for an already defined symbol <tt/foo/. It will
750 find <tt/foo/ in scope <tt/outer/, and a close look reveals that it is a
751 zeropage symbol. So the assembler will use zeropage addressing mode. If
752 <tt/foo/ is redefined later in scope <tt/inner/, the assembler tries to change
753 the address in the <tt/lda/ instruction already translated, but since the new
754 value needs absolute addressing mode, this fails, and an error message "Range
755 error" is output.
756
757 Of course the most simple solution for the problem is to move the definition
758 of <tt/foo/ in scope <tt/inner/ upwards, so it preceeds its use. There may be
759 rare cases when this cannot be done. In these cases, you can use one of the
760 address size override operators:
761
762 <tscreen><verb>
763         .scope  outer
764                 foo     = $12
765                 .scope  inner
766                         lda     a:foo,x
767                         foo     = $1234
768                 .endscope
769         .endscope
770 </verb></tscreen>
771
772 This will cause the <tt/lda/ instruction to be translated using absolute
773 addressing mode, which means changing the symbol reference later does not
774 cause any errors.
775
776
777 <sect1>Nested procedures<p>
778
779 A nested procedure is created by use of <tt/<ref id=".PROC" name=".PROC">/. It
780 differs from a <tt/<ref id=".SCOPE" name=".SCOPE">/ in that it must have a
781 name, and a it will introduce a symbol with this name in the enclosing scope.
782 So
783
784 <tscreen><verb>
785         .proc   foo
786                 ...
787         .endscope
788 </verb></tscreen>
789
790 is actually the same as
791
792 <tscreen><verb>
793         foo:
794         .scope  foo
795                 ...
796         .endscope
797 </verb></tscreen>
798
799 This is the reason why a procedure must have a name. If you want a scope
800 without a name, use <tt/<ref id=".SCOPE" name=".SCOPE">/.
801
802 <bf/Note:/ As you can see from the example above, scopes and symbols live in
803 different namespaces. There can be a symbol named <tt/foo/ and a scope named
804 <tt/foo/ without any conflicts (but see the section titled <ref
805 id="scopesearch" name="&quot;Scope search order&quot;">).
806
807
808 <sect1>Structs, unions and enums<p>
809
810 Structs, unions and enums are explained in a <ref id="structs" name="separate
811 section">, I do only cover them here, because if they are declared with a
812 name, they open a nested scope, similar to <tt/<ref id=".SCOPE"
813 name=".SCOPE">/. However, when no name is specified, the behaviour is
814 different: In this case, no new scope will be opened, symbols declared within
815 a struct, union, or enum declaration will then be added to the enclosing scope
816 instead.
817
818
819 <sect1>Explicit scope specification<label id="scopesyntax"><p>
820
821 Accessing symbols from other scopes is possible by using an explicit scope
822 specification, provided that the scope where the symbol lives in has a name.
823 The namespace token (<tt/::/) is used to access other scopes:
824
825 <tscreen><verb>
826         .scope  foo
827         bar:    .word   0
828         .endscope
829
830                 ...
831                 lda     foo::bar        ; Access foo in scope bar
832 </verb></tscreen>
833
834 The only way to deny access to a scope from the outside is to declare a scope
835 without a name (using the <tt/<ref id=".SCOPE" name=".SCOPE">/ command).
836
837 A special syntax is used to specify the global scope: If a symbol or scope is
838 preceeded by the namespace token, the global scope is searched:
839
840 <tscreen><verb>
841         bar     = 3
842
843         .scope  foo
844                 bar     = 2
845                 lda     #::bar  ; Access the global bar (which is 3)
846         .endscope
847 </verb></tscreen>
848
849
850 <sect1>Scope search order<label id="scopesearch"><p>
851
852 The assembler searches for a scope in a similar way as for a symbol. First, it
853 looks in the current scope, and then it walks up the enclosing scopes until
854 the scope is found.
855
856 However, one important thing to note when using explicit scope syntax is, that
857 a symbol may be accessed before it is defined, but a scope may <bf/not/ be
858 used without a preceeding definition. This means that in the following
859 example:
860
861 <tscreen><verb>
862         .scope  foo
863                 bar     = 3
864         .endscope
865
866         .scope  outer
867                 lda     #foo::bar  ; Will load 3, not 2!
868                 .scope  foo
869                         bar     = 2
870                 .endscope
871         .endscope
872 </verb></tscreen>
873
874 the reference to the scope <tt/foo/ will use the global scope, and not the
875 local one, because the local one is not visible at the point where it is
876 referenced.
877
878 Things get more complex if a complete chain of scopes is specified:
879
880 <tscreen><verb>
881         .scope  foo
882                 .scope  outer
883                         .scope  inner
884                                 bar = 1
885                         .endscope
886                 .endscope
887                 .scope  another
888                         .scope  nested
889                                 lda     #outer::inner::bar      ; 1
890                         .endscope
891                 .endscope
892         .endscope
893
894         .scope  outer
895                 .scope  inner
896                         bar = 2
897                 .endscope
898         .endscope
899 </verb></tscreen>
900
901 When <tt/outer::inner::bar/ is referenced in the <tt/lda/ instruction, the
902 assembler will first search in the local scope for a scope named <tt/outer/.
903 Since none is found, the enclosing scope (<tt/another/) is checked. There is
904 still no scope named <tt/outer/, so scope <tt/foo/ is checked, and finally
905 scope <tt/outer/ is found. Within this scope, <tt/inner/ is searched, and in
906 this scope, the assembler looks for a symbol named <tt/bar/.
907
908 Please note that once the anchor scope is found, all following scopes
909 (<tt/inner/ in this case) are expected to be found exactly in this scope. The
910 assembler will search the scope tree only for the first scope (if it is not
911 anchored in the root scope). Starting from there on, there is no flexibility,
912 so if the scope named <tt/outer/ found by the assembler does not contain a
913 scope named <tt/inner/, this would be an error, even if such a pair does exist
914 (one level up in global scope).
915
916 Ambiguities that may be introduced by this search algorithm may be removed by
917 anchoring the scope specification in the global scope. In the example above,
918 if you want to access the "other" symbol <tt/bar/, you would have to write:
919
920 <tscreen><verb>
921         .scope  foo
922                 .scope  outer
923                         .scope  inner
924                                 bar = 1
925                         .endscope
926                 .endscope
927                 .scope  another
928                         .scope  nested
929                                 lda     #::outer::inner::bar    ; 2
930                         .endscope
931                 .endscope
932         .endscope
933
934         .scope  outer
935                 .scope  inner
936                         bar = 2
937                 .endscope
938         .endscope
939 </verb></tscreen>
940
941
942 <sect>Address sizes and memory models<label id="address-sizes"><p>
943
944 <sect1>Address sizes<p>
945
946 ca65 assigns each segment and each symbol an address size. This is true, even
947 if the symbol is not used as an address. You may also think of a value range
948 of the symbol instead of an address size.
949
950 Possible address sizes are:
951
952 <itemize>
953 <item>Zeropage or direct (8 bits)
954 <item>Absolute (16 bits)
955 <item>Far (24 bits)
956 <item>Long (32 bits)
957 </itemize>
958
959 Since the assembler uses default address sizes for the segments and symbols,
960 it is usually not necessary to override the default behaviour. In cases, where
961 it is necessary, the following keywords may be used to specify address sizes:
962
963 <itemize>
964 <item>DIRECT, ZEROPAGE or ZP for zeropage addressing (8 bits).
965 <item>ABSOLUTE, ABS or NEAR for absolute addressing (16 bits).
966 <item>FAR for far addressing (24 bits).
967 <item>LONG or DWORD for long addressing (32 bits).
968 </itemize>
969
970
971 <sect1>Address sizes of segments<p>
972
973 The assembler assigns an address size to each segment. Since the
974 representation of a label within this segment is "segment start + offset",
975 labels will inherit the address size of the segment they are declared in.
976
977 The address size of a segment may be changed, by using an optional address
978 size modifier. See the <tt/<ref id=".SEGMENT" name="segment directive">/ for
979 an explanation on how this is done.
980
981
982 <sect1>Address sizes of symbols<p>
983
984
985
986
987 <sect1>Memory models<p>
988
989 The default address size of a segment depends on the memory model used. Since
990 labels inherit the address size from the segment they are declared in,
991 changing the memory model is an easy way to change the address size of many
992 symbols at once.
993
994
995
996
997 <sect>Pseudo variables<label id="pseudo-variables"><p>
998
999 Pseudo variables are readable in all cases, and in some special cases also
1000 writable.
1001
1002 <sect1><tt>*</tt><p>
1003
1004   Reading this pseudo variable will return the program counter at the start
1005   of the current input line.
1006
1007   Assignment to this variable is possible when <tt/<ref id=".FEATURE"
1008   name=".FEATURE pc_assignment">/ is used. Note: You should not use
1009   assignments to <tt/*/, use <tt/<ref id=".ORG" name=".ORG">/ instead.
1010
1011
1012 <sect1><tt>.CPU</tt><label id=".CPU"><p>
1013
1014   Reading this pseudo variable will give a constant integer value that
1015   tells which CPU is currently enabled. It can also tell which instruction
1016   set the CPU is able to translate. The value read from the pseudo variable
1017   should be further examined by using one of the constants defined by the
1018   "cpu" macro package (see <tt/<ref id=".MACPACK" name=".MACPACK">/).
1019
1020   It may be used to replace the .IFPxx pseudo instructions or to construct
1021   even more complex expressions.
1022
1023   Example:
1024
1025   <tscreen><verb>
1026         .macpack        cpu
1027         .if     (.cpu .bitand CPU_ISET_65816)
1028                 phx
1029                 phy
1030         .else
1031                 txa
1032                 pha
1033                 tya
1034                 pha
1035         .endif
1036   </verb></tscreen>
1037
1038
1039 <sect1><tt>.PARAMCOUNT</tt><label id=".PARAMCOUNT"><p>
1040
1041   This builtin pseudo variable is only available in macros. It is replaced by
1042   the actual number of parameters that were given in the macro invocation.
1043
1044   Example:
1045
1046   <tscreen><verb>
1047         .macro  foo     arg1, arg2, arg3
1048         .if     .paramcount <> 3
1049         .error  "Too few parameters for macro foo"
1050         .endif
1051         ...
1052         .endmacro
1053   </verb></tscreen>
1054
1055   See section <ref id="macros" name="Macros">.
1056
1057
1058 <sect1><tt>.TIME</tt><label id=".TIME"><p>
1059
1060   Reading this pseudo variable will give a constant integer value that
1061   represents the current time in POSIX standard (as seconds since the
1062   Epoch).
1063
1064   It may be used to encode the time of translation somewhere in the created
1065   code.
1066
1067   Example:
1068
1069   <tscreen><verb>
1070         .dword  .time   ; Place time here
1071   </verb></tscreen>
1072
1073
1074 <sect1><tt>.VERSION</tt><label id=".VERSION"><p>
1075
1076   Reading this pseudo variable will give the assembler version according to
1077   the following formula:
1078
1079         VER_MAJOR*$100 + VER_MINOR*$10 + VER_PATCH
1080
1081   It may be used to encode the assembler version or check the assembler for
1082   special features not available with older versions.
1083
1084   Example:
1085
1086   Version 2.11.1 of the assembler will return $2B1 as numerical constant when
1087   reading the pseudo variable <tt/.VERSION/.
1088
1089
1090
1091 <sect>Pseudo functions<label id="pseudo-functions"><p>
1092
1093 Pseudo functions expect their arguments in parenthesis, and they have a result,
1094 either a string or an expression.
1095
1096
1097 <sect1><tt>.BANKBYTE</tt><label id=".BANKBYTE"><p>
1098
1099   The function returns the bank byte (that is, bits 16-23) of its argument.
1100   It works identical to the '^' operator.
1101
1102   See: <tt><ref id=".HIBYTE" name=".HIBYTE"></tt>,
1103        <tt><ref id=".LOBYTE" name=".LOBYTE"></tt>
1104
1105
1106 <sect1><tt>.BLANK</tt><label id=".BLANK"><p>
1107
1108   Builtin function. The function evaluates its argument in braces and yields
1109   "false" if the argument is non blank (there is an argument), and "true" if
1110   there is no argument.  The token list that makes up the function argument
1111   may optionally be enclosed in curly braces. This allows the inclusion of
1112   tokens that would otherwise terminate the list (the closing right
1113   parenthesis). The curly braces are not considered part of the list, a list
1114   just consisting of curly braces is considered to be empty.
1115
1116   As an example, the <tt/.IFBLANK/ statement may be replaced by
1117
1118   <tscreen><verb>
1119         .if     .blank({arg})
1120   </verb></tscreen>
1121
1122
1123
1124 <sect1><tt>.CONCAT</tt><label id=".CONCAT"><p>
1125
1126   Builtin string function. The function allows to concatenate a list of string
1127   constants separated by commas. The result is a string constant that is the
1128   concatentation of all arguments. This function is most useful in macros and
1129   when used together with the <tt/.STRING/ builtin function. The function may
1130   be used in any case where a string constant is expected.
1131
1132   Example:
1133
1134   <tscreen><verb>
1135         .include        .concat ("myheader", ".", "inc")
1136   </verb></tscreen>
1137
1138   This is the same as the command
1139
1140   <tscreen><verb>
1141         .include        "myheader.inc"
1142   </verb></tscreen>
1143
1144
1145 <sect1><tt>.CONST</tt><label id=".CONST"><p>
1146
1147   Builtin function. The function evaluates its argument in braces and
1148   yields "true" if the argument is a constant expression (that is, an
1149   expression that yields a constant value at assembly time) and "false"
1150   otherwise. As an example, the .IFCONST statement may be replaced by
1151
1152   <tscreen><verb>
1153         .if     .const(a + 3)
1154   </verb></tscreen>
1155
1156
1157 <sect1><tt>.HIBYTE</tt><label id=".HIBYTE"><p>
1158
1159   The function returns the high byte (that is, bits 8-15) of its argument.
1160   It works identical to the '>' operator.
1161
1162   See: <tt><ref id=".LOBYTE" name=".LOBYTE"></tt>,
1163        <tt><ref id=".BANKBYTE" name=".BANKBYTE"></tt>
1164
1165
1166 <sect1><tt>.HIWORD</tt><label id=".HIWORD"><p>
1167
1168   The function returns the high word (that is, bits 16-31) of its argument.
1169
1170   See: <tt><ref id=".LOWORD" name=".LOWORD"></tt>
1171
1172
1173 <sect1><tt>.LEFT</tt><label id=".LEFT"><p>
1174
1175   Builtin function. Extracts the left part of a given token list.
1176
1177   Syntax:
1178
1179   <tscreen><verb>
1180         .LEFT (&lt;int expr&gt;, &lt;token list&gt;)
1181   </verb></tscreen>
1182
1183   The first integer expression gives the number of tokens to extract from
1184   the token list. The second argument is the token list itself. The token
1185   list may optionally be enclosed into curly braces. This allows the
1186   inclusion of tokens that would otherwise terminate the list (the closing
1187   right paren in the given case).
1188
1189   Example:
1190
1191   To check in a macro if the given argument has a '#' as first token
1192   (immidiate addressing mode), use something like this:
1193
1194   <tscreen><verb>
1195         .macro  ldax    arg
1196                 ...
1197                 .if (.match (.left (1, {arg}), #))
1198
1199                 ; ldax called with immidiate operand
1200                 ...
1201
1202                 .endif
1203                 ...
1204         .endmacro
1205   </verb></tscreen>
1206
1207   See also the <tt><ref id=".MID" name=".MID"></tt> and <tt><ref id=".RIGHT"
1208   name=".RIGHT"></tt> builtin functions.
1209
1210
1211 <sect1><tt>.LOBYTE</tt><label id=".LOBYTE"><p>
1212
1213   The function returns the low byte (that is, bits 0-7) of its argument.
1214   It works identical to the '<' operator.
1215
1216   See: <tt><ref id=".HIBYTE" name=".HIBYTE"></tt>,
1217        <tt><ref id=".BANKBYTE" name=".BANKBYTE"></tt>
1218
1219
1220 <sect1><tt>.LOWORD</tt><label id=".LOWORD"><p>
1221
1222   The function returns the low word (that is, bits 0-15) of its argument.
1223
1224   See: <tt><ref id=".HIWORD" name=".HIWORD"></tt>
1225
1226
1227 <sect1><tt>.MATCH</tt><label id=".MATCH"><p>
1228
1229   Builtin function. Matches two token lists against each other. This is
1230   most useful within macros, since macros are not stored as strings, but
1231   as lists of tokens.
1232
1233   The syntax is
1234
1235   <tscreen><verb>
1236         .MATCH(&lt;token list #1&gt;, &lt;token list #2&gt;)
1237   </verb></tscreen>
1238
1239   Both token list may contain arbitrary tokens with the exception of the
1240   terminator token (comma resp. right parenthesis) and
1241
1242   <itemize>
1243   <item>end-of-line
1244   <item>end-of-file
1245   </itemize>
1246
1247   The token lists may optionally be enclosed into curly braces. This allows
1248   the inclusion of tokens that would otherwise terminate the list (the closing
1249   right paren in the given case). Often a macro parameter is used for any of
1250   the token lists.
1251
1252   Please note that the function does only compare tokens, not token
1253   attributes. So any number is equal to any other number, regardless of the
1254   actual value. The same is true for strings. If you need to compare tokens
1255   <em/and/ token attributes, use the <tt><ref id=".XMATCH"
1256   name=".XMATCH"></tt> function.
1257
1258   Example:
1259
1260   Assume the macro <tt/ASR/, that will shift right the accumulator by one,
1261   while honoring the sign bit. The builtin processor instructions will allow
1262   an optional "A" for accu addressing for instructions like <tt/ROL/ and
1263   <tt/ROR/. We will use the <tt><ref id=".MATCH" name=".MATCH"></tt> function
1264   to check for this and print and error for invalid calls.
1265
1266   <tscreen><verb>
1267         .macro  asr     arg
1268
1269                 .if (.not .blank(arg)) .and (.not .match ({arg}, a))
1270                 .error "Syntax error"
1271                 .endif
1272
1273                 cmp     #$80            ; Bit 7 into carry
1274                 lsr     a               ; Shift carry into bit 7
1275
1276         .endmacro
1277   </verb></tscreen>
1278
1279   The macro will only accept no arguments, or one argument that must be the
1280   reserved keyword "A".
1281
1282   See: <tt><ref id=".XMATCH" name=".XMATCH"></tt>
1283
1284
1285 <sect1><tt>.MID</tt><label id=".MID"><p>
1286
1287   Builtin function. Takes a starting index, a count and a token list as
1288   arguments. Will return part of the token list.
1289
1290   Syntax:
1291
1292   <tscreen><verb>
1293         .MID (&lt;int expr&gt;, &lt;int expr&gt;, &lt;token list&gt;)
1294   </verb></tscreen>
1295
1296   The first integer expression gives the starting token in the list (the first
1297   token has index 0). The second integer expression gives the number of tokens
1298   to extract from the token list. The third argument is the token list itself.
1299   The token list may optionally be enclosed into curly braces. This allows the
1300   inclusion of tokens that would otherwise terminate the list (the closing
1301   right paren in the given case).
1302
1303   Example:
1304
1305   To check in a macro if the given argument has a '<tt/#/' as first token
1306   (immidiate addressing mode), use something like this:
1307
1308     <tscreen><verb>
1309         .macro  ldax    arg
1310                 ...
1311                 .if (.match (.mid (0, 1, {arg}), #))
1312
1313                 ; ldax called with immidiate operand
1314                 ...
1315
1316                 .endif
1317                 ...
1318         .endmacro
1319   </verb></tscreen>
1320
1321   See also the <tt><ref id=".LEFT" name=".LEFT"></tt> and <tt><ref id=".RIGHT"
1322   name=".RIGHT"></tt> builtin functions.
1323
1324
1325 <sect1><tt>.REF, .REFERENCED</tt><label id=".REFERENCED"><p>
1326
1327   Builtin function. The function expects an identifier as argument in braces.
1328   The argument is evaluated, and the function yields "true" if the identifier
1329   is a symbol that has already been referenced somewhere in the source file up
1330   to the current position. Otherwise the function yields false. As an example,
1331   the <tt><ref id=".IFREF" name=".IFREF"></tt> statement may be replaced by
1332
1333   <tscreen><verb>
1334         .if     .referenced(a)
1335   </verb></tscreen>
1336
1337   See: <tt><ref id=".DEFINED" name=".DEFINED"></tt>
1338
1339
1340 <sect1><tt>.RIGHT</tt><label id=".RIGHT"><p>
1341
1342   Builtin function. Extracts the right part of a given token list.
1343
1344   Syntax:
1345
1346   <tscreen><verb>
1347         .RIGHT (&lt;int expr&gt;, &lt;token list&gt;)
1348   </verb></tscreen>
1349
1350   The first integer expression gives the number of tokens to extract from the
1351   token list. The second argument is the token list itself.  The token list
1352   may optionally be enclosed into curly braces. This allows the inclusion of
1353   tokens that would otherwise terminate the list (the closing right paren in
1354   the given case).
1355
1356   See also the <tt><ref id=".LEFT" name=".LEFT"></tt> and <tt><ref id=".MID"
1357   name=".MID"></tt> builtin functions.
1358
1359
1360 <sect1><tt>.SIZEOF</tt><label id=".SIZEOF"><p>
1361
1362   <tt/.SIZEOF/ is a pseudo function that returns the size of its argument. The
1363   argument can be a struct/union, a struct member, a procedure, or a label. In
1364   case of a procedure or label, its size is defined by the amount of data
1365   placed in the segment where the label is relative to. If a line of code
1366   switches segments (for example in a macro) data placed in other segments
1367   does not count for the size.
1368
1369   Please note that a symbol or scope must exist, before it is used together with
1370   <tt/.SIZEOF/ (this may get relaxed later, but will always be true for scopes).
1371   A scope has preference over a symbol with the same name, so if the last part
1372   of a name represents both, a scope and a symbol, the scope is choosen over the
1373   symbol.
1374
1375   After the following code:
1376
1377   <tscreen><verb>
1378         .struct Point                   ; Struct size = 4
1379                 xcoord  .word
1380                 xcoord  .word
1381         .endstruct
1382
1383         P:      .tag    Point           ; Declare a point
1384         @P:     .tag    Point           ; Declare another point
1385
1386         .code
1387         .proc   Code
1388                 nop
1389                 .proc   Inner
1390                         nop
1391                 .endproc
1392                 nop
1393         .endproc
1394
1395         .proc   Data
1396         .data                           ; Segment switch!!!
1397                 .res    4
1398         .endproc
1399   </verb></tscreen>
1400
1401   <descrip>
1402     <tag><tt/.sizeof(Point)/</tag>
1403     will have the value 4, because this is the size of struct <tt/Point/.
1404
1405     <tag><tt/.sizeof(Point::xcoord)/</tag>
1406     will have the value 2, because this is the size of the member <tt/xcoord/
1407     in struct <tt/Point/.
1408
1409     <tag><tt/.sizeof(P)/</tag>
1410     will have the value 4, this is the size of the data declared on the same
1411     source line as the label <tt/P/, which is in the same segment that <tt/P/
1412     is relative to.
1413
1414     <tag><tt/.sizeof(@P)/</tag>
1415     will have the value 4, see above. The example demonstrates that <tt/.SIZEOF/
1416     does also work for cheap local symbols.
1417
1418     <tag><tt/.sizeof(Code)/</tag>
1419     will have the value 3, since this is amount of data emitted into the code
1420     segment, the segment that was active when <tt/Code/ was entered. Note that
1421     this value includes the amount of data emitted in child scopes (in this
1422     case <tt/Code::Inner/).
1423
1424     <tag><tt/.sizeof(Code::Inner)/</tag>
1425     will have the value 1 as expected.
1426
1427     <tag><tt/.sizeof(Data)/</tag>
1428     will have the value 0. Data is emitted within the scope <tt/Data/, but since
1429     the segment is switched after entry, this data is emitted into another
1430     segment.
1431   </descrip>
1432
1433
1434 <sect1><tt>.STRAT</tt><label id=".STRAT"><p>
1435
1436   Builtin function. The function accepts a string and an index as
1437   arguments and returns the value of the character at the given position
1438   as an integer value. The index is zero based.
1439
1440   Example:
1441
1442   <tscreen><verb>
1443         .macro  M       Arg
1444                 ; Check if the argument string starts with '#'
1445                 .if (.strat (Arg, 0) = '#')
1446                 ...
1447                 .endif
1448         .endmacro
1449   </verb></tscreen>
1450
1451
1452 <sect1><tt>.STRING</tt><label id=".STRING"><p>
1453
1454   Builtin function. The function accepts an argument in braces and converts
1455   this argument into a string constant. The argument may be an identifier, or
1456   a constant numeric value.
1457
1458   Since you can use a string in the first place, the use of the function may
1459   not be obvious. However, it is useful in macros, or more complex setups.
1460
1461   Example:
1462
1463   <tscreen><verb>
1464         ; Emulate other assemblers:
1465         .macro  section name
1466                 .segment        .string(name)
1467         .endmacro
1468   </verb></tscreen>
1469
1470
1471 <sect1><tt>.STRLEN</tt><label id=".STRLEN"><p>
1472
1473   Builtin function. The function accepts a string argument in braces and
1474   eveluates to the length of the string.
1475
1476   Example:
1477
1478   The following macro encodes a string as a pascal style string with
1479   a leading length byte.
1480
1481   <tscreen><verb>
1482         .macro  PString Arg
1483                 .byte   .strlen(Arg), Arg
1484         .endmacro
1485   </verb></tscreen>
1486
1487
1488 <sect1><tt>.TCOUNT</tt><label id=".TCOUNT"><p>
1489
1490   Builtin function. The function accepts a token list in braces. The function
1491   result is the number of tokens given as argument. The token list may
1492   optionally be enclosed into curly braces which are not considered part of
1493   the list and not counted. Enclosement in curly braces allows the inclusion
1494   of tokens that would otherwise terminate the list (the closing right paren
1495   in the given case).
1496
1497   Example:
1498
1499   The <tt/ldax/ macro accepts the '#' token to denote immidiate addressing (as
1500   with the normal 6502 instructions). To translate it into two separate 8 bit
1501   load instructions, the '#' token has to get stripped from the argument:
1502
1503   <tscreen><verb>
1504         .macro  ldax    arg
1505                 .if (.match (.mid (0, 1, {arg}), #))
1506                 ; ldax called with immidiate operand
1507                 lda     #<(.right (.tcount ({arg})-1, {arg}))
1508                 ldx     #>(.right (.tcount ({arg})-1, {arg}))
1509                 .else
1510                 ...
1511                 .endif
1512         .endmacro
1513   </verb></tscreen>
1514
1515
1516 <sect1><tt>.XMATCH</tt><label id=".XMATCH"><p>
1517
1518   Builtin function. Matches two token lists against each other. This is
1519   most useful within macros, since macros are not stored as strings, but
1520   as lists of tokens.
1521
1522   The syntax is
1523
1524   <tscreen><verb>
1525         .XMATCH(&lt;token list #1&gt;, &lt;token list #2&gt;)
1526   </verb></tscreen>
1527
1528   Both token list may contain arbitrary tokens with the exception of the
1529   terminator token (comma resp. right parenthesis) and
1530
1531   <itemize>
1532   <item>end-of-line
1533   <item>end-of-file
1534   </itemize>
1535
1536   The token lists may optionally be enclosed into curly braces. This allows
1537   the inclusion of tokens that would otherwise terminate the list (the closing
1538   right paren in the given case). Often a macro parameter is used for any of
1539   the token lists.
1540
1541   The function compares tokens <em/and/ token values. If you need a function
1542   that just compares the type of tokens, have a look at the <tt><ref
1543   id=".MATCH" name=".MATCH"></tt> function.
1544
1545   See: <tt><ref id=".MATCH" name=".MATCH"></tt>
1546
1547
1548
1549 <sect>Control commands<label id="control-commands"><p>
1550
1551 Here's a list of all control commands and a description, what they do:
1552
1553
1554 <sect1><tt>.A16</tt><label id=".A16"><p>
1555
1556   Valid only in 65816 mode. Switch the accumulator to 16 bit.
1557
1558   Note: This command will not emit any code, it will tell the assembler to
1559   create 16 bit operands for immediate accumulator adressing mode.
1560
1561   See also: <tt><ref id=".SMART" name=".SMART"></tt>
1562
1563
1564 <sect1><tt>.A8</tt><label id=".A8"><p>
1565
1566   Valid only in 65816 mode. Switch the accumulator to 8 bit.
1567
1568   Note: This command will not emit any code, it will tell the assembler to
1569   create 8 bit operands for immediate accu adressing mode.
1570
1571   See also: <tt><ref id=".SMART" name=".SMART"></tt>
1572
1573
1574 <sect1><tt>.ADDR</tt><label id=".ADDR"><p>
1575
1576   Define word sized data. In 6502 mode, this is an alias for <tt/.WORD/ and
1577   may be used for better readability if the data words are address values. In
1578   65816 mode, the address is forced to be 16 bit wide to fit into the current
1579   segment. See also <tt><ref id=".FARADDR" name=".FARADDR"></tt>. The command
1580   must be followed by a sequence of (not necessarily constant) expressions.
1581
1582   Example:
1583
1584   <tscreen><verb>
1585         .addr   $0D00, $AF13, _Clear
1586   </verb></tscreen>
1587
1588   See: <tt><ref id=".FARADDR" name=".FARADDR"></tt>, <tt><ref id=".WORD"
1589        name=".WORD"></tt>
1590
1591
1592 <sect1><tt>.ALIGN</tt><label id=".ALIGN"><p>
1593
1594   Align data to a given boundary. The command expects a constant integer
1595   argument that must be a power of two, plus an optional second argument
1596   in byte range. If there is a second argument, it is used as fill value,
1597   otherwise the value defined in the linker configuration file is used
1598   (the default for this value is zero).
1599
1600   Since alignment depends on the base address of the module, you must
1601   give the same (or a greater) alignment for the segment when linking.
1602   The linker will give you a warning, if you don't do that.
1603
1604   Example:
1605
1606   <tscreen><verb>
1607         .align  256
1608   </verb></tscreen>
1609
1610
1611 <sect1><tt>.ASCIIZ</tt><label id=".ASCIIZ"><p>
1612
1613   Define a string with a trailing zero.
1614
1615   Example:
1616
1617   <tscreen><verb>
1618         Msg:    .asciiz "Hello world"
1619   </verb></tscreen>
1620
1621   This will put the string "Hello world" followed by a binary zero into
1622   the current segment. There may be more strings separated by commas, but
1623   the binary zero is only appended once (after the last one).
1624
1625
1626 <sect1><tt>.ASSERT</tt><label id=".ASSERT"><p>
1627
1628   Add an assertion. The command is followed by an expression, an action
1629   specifier and a message that is output in case the assertion fails. The
1630   action specifier may be one of <tt/warning/ or <tt/error/. The assertion
1631   is passed to the linker and will be evaluated when segment placement has
1632   been done.
1633
1634   Example:
1635
1636   <tscreen><verb>
1637         .assert         * = $8000, error, "Code not at $8000"
1638   </verb></tscreen>
1639
1640   The example assertion will check that the current location is at $8000,
1641   when the output file is written, and abort with an error if this is not
1642   the case. More complex expressions are possible. The action specifier
1643   <tt/warning/ outputs a warning, while the <tt/error/ specifier outputs
1644   an error message. In the latter case, generation if the output file is
1645   suppressed.
1646
1647
1648 <sect1><tt>.AUTOIMPORT</tt><label id=".AUTOIMPORT"><p>
1649
1650   Is followed by a plus or a minus character. When switched on (using a
1651   +), undefined symbols are automatically marked as import instead of
1652   giving errors. When switched off (which is the default so this does not
1653   make much sense), this does not happen and an error message is
1654   displayed. The state of the autoimport flag is evaluated when the
1655   complete source was translated, before outputing actual code, so it is
1656   <em/not/ possible to switch this feature on or off for separate sections
1657   of code. The last setting is used for all symbols.
1658
1659   You should probably not use this switch because it delays error
1660   messages about undefined symbols until the link stage. The cc65
1661   compiler (which is supposed to produce correct assembler code in all
1662   circumstances, something which is not true for most assembler
1663   programmers) will insert this command to avoid importing each and every
1664   routine from the runtime library.
1665
1666   Example:
1667
1668   <tscreen><verb>
1669         .autoimport     +       ; Switch on auto import
1670   </verb></tscreen>
1671
1672
1673 <sect1><tt>.BSS</tt><label id=".BSS"><p>
1674
1675   Switch to the BSS segment. The name of the BSS segment is always "BSS",
1676   so this is a shortcut for
1677
1678   <tscreen><verb>
1679         .segment  "BSS"
1680   </verb></tscreen>
1681
1682   See also the <tt><ref id=".SEGMENT" name=".SEGMENT"></tt> command.
1683
1684
1685 <sect1><tt>.BYT, .BYTE</tt><label id=".BYTE"><p>
1686
1687   Define byte sized data. Must be followed by a sequence of (byte ranged)
1688   expressions or strings.
1689
1690   Example:
1691
1692   <tscreen><verb>
1693         .byte   "Hello "
1694         .byt    "world", $0D, $00
1695   </verb></tscreen>
1696
1697
1698 <sect1><tt>.CASE</tt><label id=".CASE"><p>
1699
1700   Switch on or off case sensitivity on identifiers. The default is off
1701   (that is, identifiers are case sensitive), but may be changed by the
1702   -i switch on the command line.
1703   The command must be followed by a '+' or '-' character to switch the
1704   option on or off respectively.
1705
1706   Example:
1707
1708   <tscreen><verb>
1709         .case   -               ; Identifiers are not case sensitive
1710   </verb></tscreen>
1711
1712
1713 <sect1><tt>.CHARMAP</tt><label id=".CHARMAP"><p>
1714
1715   Apply a custom mapping for characters. The command is followed by two
1716   numbers in the range 1..255. The first one is the index of the source
1717   character, the second one is the mapping. The mapping applies to all
1718   character and string constants when they generate output, and overrides
1719   a mapping table specified with the <tt><ref id="option-t" name="-t"></tt>
1720   command line switch.
1721
1722   Example:
1723
1724   <tscreen><verb>
1725         .charmap        $41, $61        ; Map 'A' to 'a'
1726   </verb></tscreen>
1727
1728
1729 <sect1><tt>.CODE</tt><label id=".CODE"><p>
1730
1731   Switch to the CODE segment. The name of the CODE segment is always
1732   "CODE", so this is a shortcut for
1733
1734   <tscreen><verb>
1735         .segment  "CODE"
1736   </verb></tscreen>
1737
1738   See also the <tt><ref id=".SEGMENT" name=".SEGMENT"></tt> command.
1739
1740
1741 <sect1><tt>.CONDES</tt><label id=".CONDES"><p>
1742
1743   Export a symbol and mark it in a special way. The linker is able to build
1744   tables of all such symbols. This may be used to automatically create a list
1745   of functions needed to initialize linked library modules.
1746
1747   Note: The linker has a feature to build a table of marked routines, but it
1748   is your code that must call these routines, so just declaring a symbol with
1749   <tt/.CONDES/ does nothing by itself.
1750
1751   All symbols are exported as an absolute (16 bit) symbol. You don't need to
1752   use an additional <tt><ref id=".EXPORT" name=".EXPORT"></tt> statement, this
1753   is implied by <tt/.CONDES/.
1754
1755   <tt/.CONDES/ is followed by the type, which may be <tt/constructor/,
1756   <tt/destructor/ or a numeric value between 0 and 6 (where 0 is the same as
1757   specifiying <tt/constructor/ and 1 is equal to specifying <tt/destructor/).
1758   The <tt><ref id=".CONSTRUCTOR" name=".CONSTRUCTOR"></tt> and <tt><ref
1759   id=".DESTRUCTOR" name=".DESTRUCTOR"></tt> commands are actually shortcuts
1760   for <tt/.CONDES/ with a type of <tt/constructor/ resp. <tt/destructor/.
1761
1762   After the type, an optional priority may be specified. Higher numeric values
1763   mean higher priority. If no priority is given, the default priority of 7 is
1764   used. Be careful when assigning priorities to your own module constructors
1765   so they won't interfere with the ones in the cc65 library.
1766
1767   Example:
1768
1769   <tscreen><verb>
1770         .condes         ModuleInit, constructor
1771         .condes         ModInit, 0, 16
1772   </verb></tscreen>
1773
1774   See the <tt><ref id=".CONSTRUCTOR" name=".CONSTRUCTOR"></tt> and <tt><ref
1775   id=".DESTRUCTOR" name=".DESTRUCTOR"></tt> commands and the separate section
1776   <ref id="condes" name="Module constructors/destructors"> explaining the
1777   feature in more detail.
1778
1779
1780 <sect1><tt>.CONSTRUCTOR</tt><label id=".CONSTRUCTOR"><p>
1781
1782   Export a symbol and mark it as a module constructor. This may be used
1783   together with the linker to build a table of constructor subroutines that
1784   are called by the startup code.
1785
1786   Note: The linker has a feature to build a table of marked routines, but it
1787   is your code that must call these routines, so just declaring a symbol as
1788   constructor does nothing by itself.
1789
1790   A constructor is always exported as an absolute (16 bit) symbol. You don't
1791   need to use an additional <tt/.export/ statement, this is implied by
1792   <tt/.constructor/. It may have an optional priority that is separated by a
1793   comma. Higher numeric values mean a higher priority. If no priority is
1794   given, the default priority of 7 is used. Be careful when assigning
1795   priorities to your own module constructors so they won't interfere with the
1796   ones in the cc65 library.
1797
1798   Example:
1799
1800   <tscreen><verb>
1801         .constructor    ModuleInit
1802         .constructor    ModInit, 16
1803   </verb></tscreen>
1804
1805   See the <tt><ref id=".CONDES" name=".CONDES"></tt> and <tt><ref
1806   id=".DESTRUCTOR" name=".DESTRUCTOR"></tt> commands and the separate section
1807   <ref id="condes" name="Module constructors/destructors"> explaining the
1808   feature in more detail.
1809
1810
1811 <sect1><tt>.DATA</tt><label id=".DATA"><p>
1812
1813   Switch to the DATA segment. The name of the DATA segment is always
1814   "DATA", so this is a shortcut for
1815
1816   <tscreen><verb>
1817         .segment  "DATA"
1818   </verb></tscreen>
1819
1820   See also the <tt><ref id=".SEGMENT" name=".SEGMENT"></tt> command.
1821
1822
1823 <sect1><tt>.DBYT</tt><label id=".DBYT"><p>
1824
1825   Define word sized data with the hi and lo bytes swapped (use <tt/.WORD/ to
1826   create word sized data in native 65XX format). Must be followed by a
1827   sequence of (word ranged) expressions.
1828
1829   Example:
1830
1831   <tscreen><verb>
1832         .dbyt   $1234, $4512
1833   </verb></tscreen>
1834
1835   This will emit the bytes
1836
1837   <tscreen><verb>
1838         $12 $34 $45 $12
1839   </verb></tscreen>
1840
1841   into the current segment in that order.
1842
1843
1844 <sect1><tt>.DEBUGINFO</tt><label id=".DEBUGINFO"><p>
1845
1846   Switch on or off debug info generation. The default is off (that is,
1847   the object file will not contain debug infos), but may be changed by the
1848   -g switch on the command line.
1849   The command must be followed by a '+' or '-' character to switch the
1850   option on or off respectively.
1851
1852   Example:
1853
1854   <tscreen><verb>
1855         .debuginfo      +       ; Generate debug info
1856   </verb></tscreen>
1857
1858
1859 <sect1><tt>.DEFINE</tt><label id=".DEFINE"><p>
1860
1861   Start a define style macro definition. The command is followed by an
1862   identifier (the macro name) and optionally by a list of formal arguments
1863   in braces.
1864   See section <ref id="macros" name="Macros">.
1865
1866
1867 <sect1><tt>.DEF, .DEFINED</tt><label id=".DEFINED"><p>
1868
1869   Builtin function. The function expects an identifier as argument in braces.
1870   The argument is evaluated, and the function yields "true" if the identifier
1871   is a symbol that is already defined somewhere in the source file up to the
1872   current position. Otherwise the function yields false. As an example, the
1873   <tt><ref id=".IFDEF" name=".IFDEF"></tt> statement may be replaced by
1874
1875   <tscreen><verb>
1876         .if     .defined(a)
1877   </verb></tscreen>
1878
1879
1880 <sect1><tt>.DESTRUCTOR</tt><label id=".DESTRUCTOR"><p>
1881
1882   Export a symbol and mark it as a module destructor. This may be used
1883   together with the linker to build a table of destructor subroutines that
1884   are called by the startup code.
1885
1886   Note: The linker has a feature to build a table of marked routines, but it
1887   is your code that must call these routines, so just declaring a symbol as
1888   constructor does nothing by itself.
1889
1890   A destructor is always exported as an absolute (16 bit) symbol. You don't
1891   need to use an additional <tt/.export/ statement, this is implied by
1892   <tt/.destructor/. It may have an optional priority that is separated by a
1893   comma. Higher numerical values mean a higher priority. If no priority is
1894   given, the default priority of 7 is used. Be careful when assigning
1895   priorities to your own module destructors so they won't interfere with the
1896   ones in the cc65 library.
1897
1898   Example:
1899
1900   <tscreen><verb>
1901         .destructor     ModuleDone
1902         .destructor     ModDone, 16
1903   </verb></tscreen>
1904
1905   See the <tt><ref id=".CONDES" name=".CONDES"></tt> and <tt><ref
1906   id=".CONSTRUCTOR" name=".CONSTRUCTOR"></tt> commands and the separate
1907   section <ref id="condes" name="Module constructors/destructors"> explaining
1908   the feature in more detail.
1909
1910
1911 <sect1><tt>.DWORD</tt><label id=".DWORD"><p>
1912
1913   Define dword sized data (4 bytes) Must be followed by a sequence of
1914   expressions.
1915
1916   Example:
1917
1918   <tscreen><verb>
1919         .dword  $12344512, $12FA489
1920   </verb></tscreen>
1921
1922
1923 <sect1><tt>.ELSE</tt><label id=".ELSE"><p>
1924
1925   Conditional assembly: Reverse the current condition.
1926
1927
1928 <sect1><tt>.ELSEIF</tt><label id=".ELSEIF"><p>
1929
1930   Conditional assembly: Reverse current condition and test a new one.
1931
1932
1933 <sect1><tt>.END</tt><label id=".END"><p>
1934
1935   Forced end of assembly. Assembly stops at this point, even if the command
1936   is read from an include file.
1937
1938
1939 <sect1><tt>.ENDENUM</tt><label id=".ENDENUM"><p>
1940
1941   End a <tt><ref id=".ENUM" name=".ENUM"></tt> declaration.
1942
1943
1944 <sect1><tt>.ENDIF</tt><label id=".ENDIF"><p>
1945
1946   Conditional assembly: Close a <tt><ref id=".IF" name=".IF..."></tt> or
1947   <tt><ref id=".ELSE" name=".ELSE"></tt> branch.
1948
1949
1950 <sect1><tt>.ENDMAC, .ENDMACRO</tt><label id=".ENDMACRO"><p>
1951
1952   End of macro definition (see section <ref id="macros" name="Macros">).
1953
1954
1955 <sect1><tt>.ENDPROC</tt><label id=".ENDPROC"><p>
1956
1957   End of local lexical level (see <tt><ref id=".PROC" name=".PROC"></tt>).
1958
1959
1960 <sect1><tt>.ENDREP, .ENDREPEAT</tt><label id=".ENDREPEAT"><p>
1961
1962   End a <tt><ref id=".REPEAT" name=".REPEAT"></tt> block.
1963
1964
1965 <sect1><tt>.ENDSCOPE</tt><label id=".ENDSCOPE"><p>
1966
1967   End of local lexical level (see <tt/<ref id=".SCOPE" name=".SCOPE">/).
1968
1969
1970 <sect1><tt>.ENDSTRUCT</tt><label id=".ENDSTRUCT"><p>
1971
1972   Ends a struct definition. See the <tt/<ref id=".STRUCT" name=".STRUCT">/
1973   command and the separate section named <ref id="structs" name="&quot;Structs
1974   and unions&quot;">.
1975
1976
1977 <sect1><tt>.ENUM</tt><label id=".ENUM"><p>
1978
1979   Start an enumeration. This directive is very similar to the C <tt/enum/
1980   keyword. If a name is given, a new scope is created for the enumeration,
1981   otherwise the enumeration members are placed in the enclosing scope.
1982
1983   In the enumeration body, symbols are declared. The first symbol has a value
1984   of zero, and each following symbol will get the value of the preceeding plus
1985   one. This behaviour may be overriden by an explicit assignment. Two symbols
1986   may have the same value.
1987
1988   Example:
1989
1990   <tscreen><verb>
1991         .enum   errorcodes
1992                 no_error
1993                 file_error
1994                 parse_error
1995         .endenum
1996   </verb></tscreen>
1997
1998   Above example will create a new scope named <tt/errorcodes/ with three
1999   symbols in it that get the values 0, 1 and 2 respectively. Another way
2000   to write this would have been:
2001
2002   <tscreen><verb>
2003         .scope  errorcodes
2004                 no_error        = 0
2005                 file_error      = 1
2006                 parse_error     = 2
2007         .endscope
2008   </verb></tscreen>
2009
2010   Please note that explicit scoping must be used to access the identifiers:
2011
2012   <tscreen><verb>
2013         .word   errorcodes::no_error
2014   </verb></tscreen>
2015
2016   A more complex example:
2017
2018   <tscreen><verb>
2019         .enum
2020                 EUNKNOWN        = -1
2021                 EOK
2022                 EFILE
2023                 EBUSY
2024                 EAGAIN
2025                 EWOULDBLOCK     = EAGAIN
2026         .endenum
2027   </verb></tscreen>
2028
2029   In this example, the enumeration does not have a name, which means that the
2030   members will be visible in the enclosing scope and can be used in this scope
2031   without explicit scoping. The first member (<tt/EUNKNOWN/) has the value -1.
2032   The value for the following members is incremented by one, so <tt/EOK/ would
2033   be zero and so on. <tt/EWOULDBLOCK/ is an alias for <tt/EGAIN/, so it has an
2034   override for the value using an already defined symbol.
2035
2036
2037 <sect1><tt>.ERROR</tt><label id=".ERROR"><p>
2038
2039   Force an assembly error. The assembler will output an error message
2040   preceeded by "User error" and will <em/not/ produce an object file.
2041
2042   This command may be used to check for initial conditions that must be
2043   set before assembling a source file.
2044
2045   Example:
2046
2047   <tscreen><verb>
2048         .if     foo = 1
2049         ...
2050         .elseif bar = 1
2051         ...
2052         .else
2053         .error  "Must define foo or bar!"
2054         .endif
2055   </verb></tscreen>
2056
2057   See also the <tt><ref id=".WARNING" name=".WARNING"></tt> and <tt><ref
2058   id=".OUT" name=".OUT"></tt> directives.
2059
2060
2061 <sect1><tt>.EXITMAC, .EXITMACRO</tt><label id=".EXITMACRO"><p>
2062
2063   Abort a macro expansion immidiately. This command is often useful in
2064   recursive macros. See separate section <ref id="macros" name="Macros">.
2065
2066
2067 <sect1><tt>.EXPORT</tt><label id=".EXPORT"><p>
2068
2069   Make symbols accessible from other modules. Must be followed by a comma
2070   separated list of symbols to export, with each one optionally followed by
2071   an address specification. The default is to export the symbol with the
2072   address size it actually has. The assembler will issue a warning, if the
2073   symbol is exported with an address size smaller than the actual address
2074   size.
2075
2076   Example:
2077
2078   <tscreen><verb>
2079         .export foo
2080         .export bar: far
2081   </verb></tscreen>
2082
2083   See: <tt><ref id=".EXPORTZP" name=".EXPORTZP"></tt>
2084
2085
2086 <sect1><tt>.EXPORTZP</tt><label id=".EXPORTZP"><p>
2087
2088   Make symbols accessible from other modules. Must be followed by a comma
2089   separated list of symbols to export. The exported symbols are explicitly
2090   marked as zero page symols.
2091
2092   Example:
2093
2094   <tscreen><verb>
2095         .exportzp  foo, bar
2096   </verb></tscreen>
2097
2098   See: <tt><ref id=".EXPORT" name=".EXPORT"></tt>
2099
2100
2101 <sect1><tt>.FARADDR</tt><label id=".FARADDR"><p>
2102
2103   Define far (24 bit) address data. The command must be followed by a
2104   sequence of (not necessarily constant) expressions.
2105
2106   Example:
2107
2108   <tscreen><verb>
2109         .faraddr        DrawCircle, DrawRectangle, DrawHexagon
2110   </verb></tscreen>
2111
2112   See: <tt><ref id=".ADDR" name=".ADDR"></tt>
2113
2114
2115 <sect1><tt>.FEATURE</tt><label id=".FEATURE"><p>
2116
2117   This directive may be used to enable one or more compatibility features
2118   of the assembler. While the use of <tt/.FEATURE/ should be avoided when
2119   possible, it may be useful when porting sources written for other
2120   assemblers. There is no way to switch a feature off, once you have
2121   enabled it, so using
2122
2123   <tscreen><verb>
2124         .FEATURE        xxx
2125   </verb></tscreen>
2126
2127   will enable the feature until end of assembly is reached.
2128
2129   The following features are available:
2130
2131   <descrip>
2132
2133   <tag><tt>at_in_identifiers</tt></tag>
2134
2135     Accept the at character (`@') as a valid character in identifiers. The
2136     at character is not allowed to start an identifier, even with this
2137     feature enabled.
2138
2139   <tag><tt>dollar_in_identifiers</tt></tag>
2140
2141     Accept the dollar sign (`&dollar;') as a valid character in identifiers. The
2142     at character is not allowed to start an identifier, even with this
2143     feature enabled.
2144
2145   <tag><tt>dollar_is_pc</tt></tag>
2146
2147     The dollar sign may be used as an alias for the star (`*'), which
2148     gives the value of the current PC in expressions.
2149     Note: Assignment to the pseudo variable is not allowed.
2150
2151   <tag><tt>labels_without_colons</tt></tag>
2152
2153     Allow labels without a trailing colon. These labels are only accepted,
2154     if they start at the beginning of a line (no leading white space).
2155
2156   <tag><tt>leading_dot_in_identifiers</tt></tag>
2157
2158     Accept the dot (`.') as the first character of an identifier. This may be
2159     used for example to create macro names that start with a dot emulating
2160     control directives of other assemblers. Note however, that none of the
2161     reserved keywords built into the assembler, that starts with a dot, may be
2162     overridden. When using this feature, you may also get into trouble if
2163     later versions of the assembler define new keywords starting with a dot.
2164
2165   <tag><tt>loose_char_term</tt></tag>
2166
2167     Accept single quotes as well as double quotes as terminators for char
2168     constants.
2169
2170   <tag><tt>loose_string_term</tt></tag>
2171
2172     Accept single quotes as well as double quotes as terminators for string
2173     constants.
2174
2175   <tag><tt>missing_char_term</tt></tag>
2176
2177     Accept single quoted character constants where the terminating quote is
2178     missing.
2179     <tscreen><verb>
2180         lda     #'a
2181     </verb></tscreen>
2182     <bf/Note:/ This does not work in conjunction with <tt/.FEATURE
2183     loose_string_term/, since in this case the input would be ambigous.
2184
2185   <tag><tt>pc_assignment</tt></tag>
2186
2187     Allow assignments to the PC symbol (`*' or `&dollar;' if <tt/dollar_is_pc/
2188     is enabled). Such an assignment is handled identical to the <tt><ref
2189     id=".ORG" name=".ORG"></tt> command (which is usually not needed, so just
2190     removing the lines with the assignments may also be an option when porting
2191     code written for older assemblers).
2192
2193   <tag><tt>ubiquitous_idents</tt></tag>
2194
2195     Allow the use of instructions names as names for macros and symbols. This
2196     makes it possible to "overload" instructions by defining a macro with the
2197     same name. This does also make it possible to introduce hard to find errors
2198     in your code, so be careful!
2199
2200   </descrip>
2201
2202   It is also possible to specify features on the command line using the
2203   <tt><ref id="option--feature" name="--feature"></tt> command line option.
2204   This is useful when translating sources written for older assemblers, when
2205   you don't want to change the source code.
2206
2207   As an example, to translate sources written for Andre Fachats xa65
2208   assembler, the features
2209
2210   <verb>
2211         labels_without_colons, pc_assignment, loose_char_term
2212   </verb>
2213
2214   may be helpful. They do not make ca65 completely compatible, so you may not
2215   be able to translate the sources without changes, even when enabling these
2216   features. However, I have found several sources that translate without
2217   problems when enabling these features on the command line.
2218
2219
2220 <sect1><tt>.FILEOPT, .FOPT</tt><label id=".FOPT"><p>
2221
2222   Insert an option string into the object file. There are two forms of
2223   this command, one specifies the option by a keyword, the second
2224   specifies it as a number. Since usage of the second one needs knowledge
2225   of the internal encoding, its use is not recommended and I will only
2226   describe the first form here.
2227
2228   The command is followed by one of the keywords
2229
2230   <tscreen><verb>
2231         author
2232         comment
2233         compiler
2234   </verb></tscreen>
2235
2236   a comma and a string. The option is written into the object file
2237   together with the string value. This is currently unidirectional and
2238   there is no way to actually use these options once they are in the
2239   object file.
2240
2241   Examples:
2242
2243   <tscreen><verb>
2244         .fileopt        comment, "Code stolen from my brother"
2245         .fileopt        compiler, "BASIC 2.0"
2246         .fopt           author, "J. R. User"
2247   </verb></tscreen>
2248
2249
2250 <sect1><tt>.FORCEIMPORT</tt><label id=".FORCEIMPORT"><p>
2251
2252   Import an absolute symbol from another module. The command is followed by a
2253   comma separated list of symbols to import. The command is similar to <tt>
2254   <ref id=".IMPORT" name=".IMPORT"></tt>, but the import reference is always
2255   written to the generated object file, even if the symbol is never referenced
2256   (<tt><ref id=".IMPORT" name=".IMPORT"></tt> will not generate import
2257   references for unused symbols).
2258
2259   Example:
2260
2261   <tscreen><verb>
2262         .forceimport    needthisone, needthistoo
2263   </verb></tscreen>
2264
2265   See: <tt><ref id=".IMPORT" name=".IMPORT"></tt>
2266
2267
2268 <sect1><tt>.GLOBAL</tt><label id=".GLOBAL"><p>
2269
2270   Declare symbols as global. Must be followed by a comma separated list of
2271   symbols to declare. Symbols from the list, that are defined somewhere in the
2272   source, are exported, all others are imported. Additional <tt><ref
2273   id=".IMPORT" name=".IMPORT"></tt> or <tt><ref id=".EXPORT"
2274   name=".EXPORT"></tt> commands for the same symbol are allowed.
2275
2276   Example:
2277
2278   <tscreen><verb>
2279         .global foo, bar
2280   </verb></tscreen>
2281
2282
2283 <sect1><tt>.GLOBALZP</tt><label id=".GLOBALZP"><p>
2284
2285   Declare symbols as global. Must be followed by a comma separated list of
2286   symbols to declare. Symbols from the list, that are defined somewhere in the
2287   source, are exported, all others are imported. Additional <tt><ref
2288   id=".IMPORTZP" name=".IMPORTZP"></tt> or <tt><ref id=".EXPORTZP"
2289   name=".EXPORTZP"></tt> commands for the same symbol are allowed. The symbols
2290   in the list are explicitly marked as zero page symols.
2291
2292   Example:
2293
2294   <tscreen><verb>
2295         .globalzp foo, bar
2296   </verb></tscreen>
2297
2298
2299 <sect1><tt>.I16</tt><label id=".I16"><p>
2300
2301   Valid only in 65816 mode. Switch the index registers to 16 bit.
2302
2303   Note: This command will not emit any code, it will tell the assembler to
2304   create 16 bit operands for immediate operands.
2305
2306   See also the <tt><ref id=".I8" name=".I8"></tt> and <tt><ref id=".SMART"
2307   name=".SMART"></tt> commands.
2308
2309
2310 <sect1><tt>.I8</tt><label id=".I8"><p>
2311
2312   Valid only in 65816 mode. Switch the index registers to 8 bit.
2313
2314   Note: This command will not emit any code, it will tell the assembler to
2315   create 8 bit operands for immediate operands.
2316
2317   See also the <tt><ref id=".I16" name=".I16"></tt> and <tt><ref id=".SMART"
2318   name=".SMART"></tt> commands.
2319
2320
2321 <sect1><tt>.IF</tt><label id=".IF"><p>
2322
2323   Conditional assembly: Evalute an expression and switch assembler output
2324   on or off depending on the expression. The expression must be a constant
2325   expression, that is, all operands must be defined.
2326
2327   A expression value of zero evaluates to FALSE, any other value evaluates
2328   to TRUE.
2329
2330
2331 <sect1><tt>.IFBLANK</tt><label id=".IFBLANK"><p>
2332
2333   Conditional assembly: Check if there are any remaining tokens in this line,
2334   and evaluate to FALSE if this is the case, and to TRUE otherwise. If the
2335   condition is not true, further lines are not assembled until an <tt><ref
2336   id=".ELSE" name=".ESLE"></tt>, <tt><ref id=".ELSEIF" name=".ELSEIF"></tt> or
2337   <tt><ref id=".ENDIF" name=".ENDIF"></tt> directive.
2338
2339   This command is often used to check if a macro parameter was given. Since an
2340   empty macro parameter will evaluate to nothing, the condition will evaluate
2341   to FALSE if an empty parameter was given.
2342
2343   Example:
2344
2345   <tscreen><verb>
2346         .macro     arg1, arg2
2347         .ifblank   arg2
2348                    lda     #arg1
2349         .else
2350                    lda     #arg2
2351         .endif
2352         .endmacro
2353   </verb></tscreen>
2354
2355   See also: <tt><ref id=".BLANK" name=".BLANK"></tt>
2356
2357
2358 <sect1><tt>.IFCONST</tt><label id=".IFCONST"><p>
2359
2360   Conditional assembly: Evaluate an expression and switch assembler output
2361   on or off depending on the constness of the expression.
2362
2363   A const expression evaluates to to TRUE, a non const expression (one
2364   containing an imported or currently undefined symbol) evaluates to
2365   FALSE.
2366
2367   See also: <tt><ref id=".CONST" name=".CONST"></tt>
2368
2369
2370 <sect1><tt>.IFDEF</tt><label id=".IFDEF"><p>
2371
2372   Conditional assembly: Check if a symbol is defined. Must be followed by
2373   a symbol name. The condition is true if the the given symbol is already
2374   defined, and false otherwise.
2375
2376   See also: <tt><ref id=".DEFINED" name=".DEFINED"></tt>
2377
2378
2379 <sect1><tt>.IFNBLANK</tt><label id=".IFNBLANK"><p>
2380
2381   Conditional assembly: Check if there are any remaining tokens in this line,
2382   and evaluate to TRUE if this is the case, and to FALSE otherwise. If the
2383   condition is not true, further lines are not assembled until an <tt><ref
2384   id=".ELSE" name=".ELSE"></tt>, <tt><ref id=".ELSEIF" name=".ELSEIF"></tt> or
2385   <tt><ref id=".ENDIF" name=".ENDIF"></tt> directive.
2386
2387   This command is often used to check if a macro parameter was given.
2388   Since an empty macro parameter will evaluate to nothing, the condition
2389   will evaluate to FALSE if an empty parameter was given.
2390
2391   Example:
2392
2393   <tscreen><verb>
2394         .macro     arg1, arg2
2395                    lda     #arg1
2396         .ifnblank  arg2
2397                    lda     #arg2
2398         .endif
2399         .endmacro
2400   </verb></tscreen>
2401
2402   See also: <tt><ref id=".BLANK" name=".BLANK"></tt>
2403
2404
2405 <sect1><tt>.IFNDEF</tt><label id=".IFNDEF"><p>
2406
2407   Conditional assembly: Check if a symbol is defined. Must be followed by
2408   a symbol name. The condition is true if the the given symbol is not
2409   defined, and false otherwise.
2410
2411   See also: <tt><ref id=".DEFINED" name=".DEFINED"></tt>
2412
2413
2414 <sect1><tt>.IFNREF</tt><label id=".IFNREF"><p>
2415
2416   Conditional assembly: Check if a symbol is referenced. Must be followed
2417   by a symbol name. The condition is true if if the the given symbol was
2418   not referenced before, and false otherwise.
2419
2420   See also: <tt><ref id=".REFERENCED" name=".REFERENCED"></tt>
2421
2422
2423 <sect1><tt>.IFP02</tt><label id=".IFP02"><p>
2424
2425   Conditional assembly: Check if the assembler is currently in 6502 mode
2426   (see <tt><ref id=".P02" name=".P02"></tt> command).
2427
2428
2429 <sect1><tt>.IFP816</tt><label id=".IFP816"><p>
2430
2431   Conditional assembly: Check if the assembler is currently in 65816 mode
2432   (see <tt><ref id=".P816" name=".P816"></tt> command).
2433
2434
2435 <sect1><tt>.IFPC02</tt><label id=".IFPC02"><p>
2436
2437   Conditional assembly: Check if the assembler is currently in 65C02 mode
2438   (see <tt><ref id=".PC02" name=".PC02"></tt> command).
2439
2440
2441 <sect1><tt>.IFPSC02</tt><label id=".IFPSC02"><p>
2442
2443   Conditional assembly: Check if the assembler is currently in 65SC02 mode
2444   (see <tt><ref id=".PSC02" name=".PSC02"></tt> command).
2445
2446
2447 <sect1><tt>.IFREF</tt><label id=".IFREF"><p>
2448
2449   Conditional assembly: Check if a symbol is referenced. Must be followed
2450   by a symbol name. The condition is true if if the the given symbol was
2451   referenced before, and false otherwise.
2452
2453   This command may be used to build subroutine libraries in include files
2454   (you may use separate object modules for this purpose too).
2455
2456   Example:
2457
2458   <tscreen><verb>
2459         .ifref  ToHex                   ; If someone used this subroutine
2460         ToHex:  tay                     ; Define subroutine
2461                 lda     HexTab,y
2462                 rts
2463         .endif
2464   </verb></tscreen>
2465
2466   See also: <tt><ref id=".REFERENCED" name=".REFERENCED"></tt>
2467
2468
2469 <sect1><tt>.IMPORT</tt><label id=".IMPORT"><p>
2470
2471   Import a symbol from another module. The command is followed by a comma
2472   separated list of symbols to import, with each one optionally followed by
2473   an address specification.
2474
2475   Example:
2476
2477   <tscreen><verb>
2478         .import foo
2479         .import bar: zeropage
2480   </verb></tscreen>
2481
2482   See: <tt><ref id=".IMPORTZP" name=".IMPORTZP"></tt>
2483
2484
2485 <sect1><tt>.IMPORTZP</tt><label id=".IMPORTZP"><p>
2486
2487   Import a symbol from another module. The command is followed by a comma
2488   separated list of symbols to import. The symbols are explicitly imported
2489   as zero page symbols (that is, symbols with values in byte range).
2490
2491   Example:
2492
2493   <tscreen><verb>
2494         .importzp       foo, bar
2495   </verb></tscreen>
2496
2497   See: <tt><ref id=".IMPORT" name=".IMPORT"></tt>
2498
2499
2500 <sect1><tt>.INCBIN</tt><label id=".INCBIN"><p>
2501
2502   Include a file as binary data. The command expects a string argument
2503   that is the name of a file to include literally in the current segment.
2504   In addition to that, a start offset and a size value may be specified,
2505   separated by commas. If no size is specified, all of the file from the
2506   start offset to end-of-file is used. If no start position is specified
2507   either, zero is assumed (which means that the whole file is inserted).
2508
2509   Example:
2510
2511   <tscreen><verb>
2512         ; Include whole file
2513         .incbin         "sprites.dat"
2514
2515         ; Include file starting at offset 256
2516         .incbin         "music.dat", $100
2517
2518         ; Read 100 bytes starting at offset 200
2519         .incbin         "graphics.dat", 200, 100
2520   </verb></tscreen>
2521
2522
2523 <sect1><tt>.INCLUDE</tt><label id=".INCLUDE"><p>
2524
2525   Include another file. Include files may be nested up to a depth of 16.
2526
2527   Example:
2528
2529   <tscreen><verb>
2530         .include        "subs.inc"
2531   </verb></tscreen>
2532
2533
2534 <sect1><tt>.LINECONT</tt><label id=".LINECONT"><p>
2535
2536   Switch on or off line continuations using the backslash character
2537   before a newline. The option is off by default.
2538   Note: Line continuations do not work in a comment. A backslash at the
2539   end of a comment is treated as part of the comment and does not trigger
2540   line continuation.
2541   The command must be followed by a '+' or '-' character to switch the
2542   option on or off respectively.
2543
2544   Example:
2545
2546   <tscreen><verb>
2547         .linecont       +               ; Allow line continuations
2548
2549         lda     \
2550                 #$20                    ; This is legal now
2551   </verb></tscreen>
2552
2553
2554 <sect1><tt>.LIST</tt><label id=".LIST"><p>
2555
2556   Enable output to the listing. The command must be followed by a boolean
2557   switch ("on", "off", "+" or "-") and will enable or disable listing
2558   output.
2559   The option has no effect if the listing is not enabled by the command line
2560   switch -l. If -l is used, an internal counter is set to 1. Lines are output
2561   to the listing file, if the counter is greater than zero, and suppressed if
2562   the counter is zero. Each use of <tt/.LIST/ will increment or decrement the
2563   counter.
2564
2565   Example:
2566
2567   <tscreen><verb>
2568         .list   on              ; Enable listing output
2569   </verb></tscreen>
2570
2571
2572 <sect1><tt>.LISTBYTES</tt><label id=".LISTBYTES"><p>
2573
2574   Set, how many bytes are shown in the listing for one source line. The
2575   default is 12, so the listing will show only the first 12 bytes for any
2576   source line that generates more than 12 bytes of code or data.
2577   The directive needs an argument, which is either "unlimited", or an
2578   integer constant in the range 4..255.
2579
2580   Examples:
2581
2582   <tscreen><verb>
2583         .listbytes      unlimited       ; List all bytes
2584         .listbytes      12              ; List the first 12 bytes
2585         .incbin         "data.bin"      ; Include large binary file
2586   </verb></tscreen>
2587
2588
2589 <sect1><tt>.LOCAL</tt><label id=".LOCAL"><p>
2590
2591   This command may only be used inside a macro definition. It declares a
2592   list of identifiers as local to the macro expansion.
2593
2594   A problem when using macros are labels: Since they don't change their name,
2595   you get a "duplicate symbol" error if the macro is expanded the second time.
2596   Labels declared with <tt><ref id=".LOCAL" name=".LOCAL"></tt> have their
2597   name mapped to an internal unique name (<tt/___ABCD__/) with each macro
2598   invocation.
2599
2600   Some other assemblers start a new lexical block inside a macro expansion.
2601   This has some drawbacks however, since that will not allow <em/any/ symbol
2602   to be visible outside a macro, a feature that is sometimes useful. The
2603   <tt><ref id=".LOCAL" name=".LOCAL"></tt> command is in my eyes a better way
2604   to address the problem.
2605
2606   You get an error when using <tt><ref id=".LOCAL" name=".LOCAL"></tt> outside
2607   a macro.
2608
2609
2610 <sect1><tt>.LOCALCHAR</tt><label id=".LOCALCHAR"><p>
2611
2612   Defines the character that start "cheap" local labels. You may use one
2613   of '@' and '?' as start character. The default is '@'.
2614
2615   Cheap local labels are labels that are visible only between two non
2616   cheap labels. This way you can reuse identifiers like "<tt/loop/" without
2617   using explicit lexical nesting.
2618
2619   Example:
2620
2621   <tscreen><verb>
2622         .localchar      '?'
2623
2624         Clear:  lda     #$00            ; Global label
2625         ?Loop:  sta     Mem,y           ; Local label
2626                 dey
2627                 bne     ?Loop           ; Ok
2628                 rts
2629         Sub:    ...                     ; New global label
2630                 bne     ?Loop           ; ERROR: Unknown identifier!
2631   </verb></tscreen>
2632
2633
2634 <sect1><tt>.MACPACK</tt><label id=".MACPACK"><p>
2635
2636   Insert a predefined macro package. The command is followed by an
2637   identifier specifying the macro package to insert. Available macro
2638   packages are:
2639
2640   <tscreen><verb>
2641         generic         Defines generic macros like add and sub.
2642         longbranch      Defines conditional long jump macros.
2643         cbm             Defines the scrcode macro
2644         cpu             Defines constants for the .CPU variable
2645   </verb></tscreen>
2646
2647   Including a macro package twice, or including a macro package that
2648   redefines already existing macros will lead to an error.
2649
2650   Example:
2651
2652   <tscreen><verb>
2653         .macpack        longbranch      ; Include macro package
2654
2655                 cmp     #$20            ; Set condition codes
2656                 jne     Label           ; Jump long on condition
2657   </verb></tscreen>
2658
2659   Macro packages are explained in more detail in section <ref
2660   id="macropackages" name="Macro packages">.
2661
2662
2663 <sect1><tt>.MAC, .MACRO</tt><label id=".MAC"><p>
2664
2665   Start a classic macro definition. The command is followed by an identifier
2666   (the macro name) and optionally by a comma separated list of identifiers
2667   that are macro parameters.
2668
2669   See section <ref id="macros" name="Macros">.
2670
2671
2672 <sect1><tt>.ORG</tt><label id=".ORG"><p>
2673
2674   Start a section of absolute code. The command is followed by a constant
2675   expression that gives the new PC counter location for which the code is
2676   assembled. Use <tt><ref id=".RELOC" name=".RELOC"></tt> to switch back to
2677   relocatable code.
2678
2679   Please note that you <em/do not need/ this command in most cases. Placing
2680   code at a specific address is the job of the linker, not the assembler, so
2681   there is usually no reason to assemble code to a specific address.
2682
2683   You may not switch segments while inside a section of absolute code.
2684
2685   Example:
2686
2687   <tscreen><verb>
2688         .org    $7FF            ; Emit code starting at $7FF
2689   </verb></tscreen>
2690
2691
2692 <sect1><tt>.OUT</tt><label id=".OUT"><p>
2693
2694   Output a string to the console without producing an error. This command
2695   is similiar to <tt/.ERROR/, however, it does not force an assembler error
2696   that prevents the creation of an object file.
2697
2698   Example:
2699
2700   <tscreen><verb>
2701         .out    "This code was written by the codebuster(tm)"
2702   </verb></tscreen>
2703
2704   See also the <tt><ref id=".WARNING" name=".WARNING"></tt> and <tt><ref
2705   id=".ERROR" name=".ERROR"></tt> directives.
2706
2707
2708 <sect1><tt>.P02</tt><label id=".P02"><p>
2709
2710   Enable the 6502 instruction set, disable 65SC02, 65C02 and 65816
2711   instructions. This is the default if not overridden by the
2712   <tt><ref id="option--cpu" name="--cpu"></tt> command line option.
2713
2714   See: <tt><ref id=".PC02" name=".PC02"></tt>, <tt><ref id=".PSC02"
2715   name=".PSC02"></tt> and <tt><ref id=".P816" name=".P816"></tt>
2716
2717
2718 <sect1><tt>.P816</tt><label id=".P816"><p>
2719
2720   Enable the 65816 instruction set. This is a superset of the 65SC02 and
2721   6502 instruction sets.
2722
2723   See: <tt><ref id=".P02" name=".P02"></tt>, <tt><ref id=".PSC02"
2724   name=".PSC02"></tt> and <tt><ref id=".PC02" name=".PC02"></tt>
2725
2726
2727 <sect1><tt>.PAGELEN, .PAGELENGTH</tt><label id=".PAGELENGTH"><p>
2728
2729   Set the page length for the listing. Must be followed by an integer
2730   constant. The value may be "unlimited", or in the range 32 to 127. The
2731   statement has no effect if no listing is generated. The default value is -1
2732   (unlimited) but may be overridden by the <tt/--pagelength/ command line
2733   option. Beware: Since ca65 is a one pass assembler, the listing is generated
2734   after assembly is complete, you cannot use multiple line lengths with one
2735   source. Instead, the value set with the last <tt/.PAGELENGTH/ is used.
2736
2737   Examples:
2738
2739   <tscreen><verb>
2740         .pagelength     66              ; Use 66 lines per listing page
2741
2742         .pagelength     unlimited       ; Unlimited page length
2743   </verb></tscreen>
2744
2745
2746 <sect1><tt>.PC02</tt><label id=".PC02"><p>
2747
2748   Enable the 65C02 instructions set. This instruction set includes all
2749   6502 and 65SC02 instructions.
2750
2751   See: <tt><ref id=".P02" name=".P02"></tt>, <tt><ref id=".PSC02"
2752   name=".PSC02"></tt> and <tt><ref id=".P816" name=".P816"></tt>
2753
2754
2755 <sect1><tt>.POPSEG</tt><label id=".POPSEG"><p>
2756
2757   Pop the last pushed segment from the stack, and set it.
2758
2759   This command will switch back to the segment that was last pushed onto the
2760   segment stack using the <tt><ref id=".PUSHSEG" name=".PUSHSEG"></tt>
2761   command, and remove this entry from the stack.
2762
2763   The assembler will print an error message if the segment stack is empty
2764   when this command is issued.
2765
2766   See: <tt><ref id=".PUSHSEG" name=".PUSHSEG"></tt>
2767
2768
2769 <sect1><tt>.PROC</tt><label id=".PROC"><p>
2770
2771   Start a nested lexical level with the given name and adds a symbol with this
2772   name to the enclosing scope. All new symbols from now on are in the local
2773   lexical level and are accessible from outside only via <ref id="scopesyntax"
2774   name="explicit scope specification">. Symbols defined outside this local
2775   level may be accessed as long as their names are not used for new symbols
2776   inside the level. Symbols names in other lexical levels do not clash, so you
2777   may use the same names for identifiers. The lexical level ends when the
2778   <tt><ref id=".ENDPROC" name=".ENDPROC"></tt> command is read. Lexical levels
2779   may be nested up to a depth of 16 (this is an artificial limit to protect
2780   against errors in the source).
2781
2782   Note: Macro names are always in the global level and in a separate name
2783   space. There is no special reason for this, it's just that I've never
2784   had any need for local macro definitions.
2785
2786   Example:
2787
2788   <tscreen><verb>
2789         .proc   Clear           ; Define Clear subroutine, start new level
2790                 lda     #$00
2791         L1:     sta     Mem,y   ; L1 is local and does not cause a
2792                                 ; duplicate symbol error if used in other
2793                                 ; places
2794                 dey
2795                 bne     L1      ; Reference local symbol
2796                 rts
2797         .endproc                ; Leave lexical level
2798   </verb></tscreen>
2799
2800   See: <tt/<ref id=".ENDPROC" name=".ENDPROC">/ and <tt/<ref id=".SCOPE"
2801   name=".SCOPE">/
2802
2803
2804 <sect1><tt>.PSC02</tt><label id=".PSC02"><p>
2805
2806   Enable the 65SC02 instructions set. This instruction set includes all
2807   6502 instructions.
2808
2809   See: <tt><ref id=".P02" name=".P02"></tt>, <tt><ref id=".PC02"
2810   name=".PC02"></tt> and <tt><ref id=".P816" name=".P816"></tt>
2811
2812
2813 <sect1><tt>.PUSHSEG</tt><label id=".PUSHSEG"><p>
2814
2815   Push the currently active segment onto a stack. The entries on the stack
2816   include the name of the segment and the segment type. The stack has a size
2817   of 16 entries.
2818
2819   <tt/.PUSHSEG/ allows together with <tt><ref id=".POPSEG" name=".POPSEG"></tt>
2820   to switch to another segment and to restore the old segment later, without
2821   even knowing the name and type of the current segment.
2822
2823   The assembler will print an error message if the segment stack is already
2824   full, when this command is issued.
2825
2826   See: <tt><ref id=".POPSEG" name=".POPSEG"></tt>
2827
2828
2829 <sect1><tt>.REPEAT</tt><label id=".REPEAT"><p>
2830
2831   Repeat all commands between <tt/.REPEAT/ and <tt><ref id=".ENDREPEAT"
2832   name=".ENDREPEAT"></tt> constant number of times. The command is followed by
2833   a constant expression that tells how many times the commands in the body
2834   should get repeated. Optionally, a comma and an identifier may be specified.
2835   If this identifier is found in the body of the repeat statement, it is
2836   replaced by the current repeat count (starting with zero for the first time
2837   the body is repeated).
2838
2839   <tt/.REPEAT/ statements may be nested. If you use the same repeat count
2840   identifier for a nested <tt/.REPEAT/ statement, the one from the inner
2841   level will be used, not the one from the outer level.
2842
2843   Example:
2844
2845   The following macro will emit a string that is "encrypted" in that all
2846   characters of the string are XORed by the value $55.
2847
2848   <tscreen><verb>
2849         .macro  Crypt   Arg
2850                 .repeat .strlen(Arg), I
2851                 .byte   .strat(Arg, I) ^ $55
2852                 .endrep
2853         .endmacro
2854   </verb></tscreen>
2855
2856   See: <tt><ref id=".ENDREPEAT" name=".ENDREPEAT"></tt>
2857
2858
2859 <sect1><tt>.RELOC</tt><label id=".RELOC"><p>
2860
2861   Switch back to relocatable mode. See the <tt><ref id=".ORG"
2862   name=".ORG"></tt> command.
2863
2864
2865 <sect1><tt>.RES</tt><label id=".RES"><p>
2866
2867   Reserve storage. The command is followed by one or two constant
2868   expressions. The first one is mandatory and defines, how many bytes of
2869   storage should be defined. The second, optional expression must by a
2870   constant byte value that will be used as value of the data. If there
2871   is no fill value given, the linker will use the value defined in the
2872   linker configuration file (default: zero).
2873
2874   Example:
2875
2876   <tscreen><verb>
2877         ; Reserve 12 bytes of memory with value $AA
2878         .res    12, $AA
2879   </verb></tscreen>
2880
2881
2882 <sect1><tt>.RODATA</tt><label id=".RODATA"><p>
2883
2884   Switch to the RODATA segment. The name of the RODATA segment is always
2885   "RODATA", so this is a shortcut for
2886
2887   <tscreen><verb>
2888         .segment  "RODATA"
2889   </verb></tscreen>
2890
2891   The RODATA segment is a segment that is used by the compiler for
2892   readonly data like string constants.
2893
2894   See also the <tt><ref id=".SEGMENT" name=".SEGMENT"></tt> command.
2895
2896
2897 <sect1><tt>.SCOPE</tt><label id=".SCOPE"><p>
2898
2899   Start a nested lexical level with the given name. All new symbols from now
2900   on are in the local lexical level and are accessible from outside only via
2901   <ref id="scopesyntax" name="explicit scope specification">. Symbols defined
2902   outside this local level may be accessed as long as their names are not used
2903   for new symbols inside the level. Symbols names in other lexical levels do
2904   not clash, so you may use the same names for identifiers. The lexical level
2905   ends when the <tt><ref id=".ENDSCOPE" name=".ENDSCOPE"></tt> command is
2906   read. Lexical levels may be nested up to a depth of 16 (this is an
2907   artificial limit to protect against errors in the source).
2908
2909   Note: Macro names are always in the global level and in a separate name
2910   space. There is no special reason for this, it's just that I've never
2911   had any need for local macro definitions.
2912
2913   Example:
2914
2915   <tscreen><verb>
2916         .scope  Error                   ; Start new scope named Error
2917                 None = 0                ; No error
2918                 File = 1                ; File error
2919                 Parse = 2               ; Parse error
2920         .endproc                        ; Close lexical level
2921
2922                 ...
2923                 lda #Error::File        ; Use symbol from scope Error
2924   </verb></tscreen>
2925
2926   See: <tt/<ref id=".ENDSCOPE" name=".ENDSCOPE">/ and <tt/<ref id=".PROC"
2927   name=".PROC">/
2928
2929
2930 <sect1><tt>.SEGMENT</tt><label id=".SEGMENT"><p>
2931
2932   Switch to another segment. Code and data is always emitted into a
2933   segment, that is, a named section of data. The default segment is
2934   "CODE". There may be up to 254 different segments per object file
2935   (and up to 65534 per executable). There are shortcut commands for
2936   the most common segments ("CODE", "DATA" and "BSS").
2937
2938   The command is followed by a string containing the segment name (there are
2939   some constraints for the name - as a rule of thumb use only those segment
2940   names that would also be valid identifiers). There may also be an optional
2941   address size separated by a colon. See the section covering <tt/<ref
2942   id="address-sizes" name="address sizes">/ for more information.
2943
2944   The default address size for a segment depends on the memory model specified
2945   on the command line. The default is "absolute", which means that you don't
2946   have to use an address size modifier in most cases.
2947
2948   "absolute" means that the is a segment with 16 bit (absolute) addressing.
2949   That is, the segment will reside somewhere in core memory outside the zero
2950   page. "zeropage" (8 bit) means that the segment will be placed in the zero
2951   page and direct (short) addressing is possible for data in this segment.
2952
2953   Beware: Only labels in a segment with the zeropage attribute are marked
2954   as reachable by short addressing. The `*' (PC counter) operator will
2955   work as in other segments and will create absolute variable values.
2956
2957   Please note that a segment cannot have two different address sizes. A
2958   segment specified as zeropage cannot be declared as being absolute later.
2959
2960   Examples:
2961
2962   <tscreen><verb>
2963         .segment "ROM2"                 ; Switch to ROM2 segment
2964         .segment "ZP2": zeropage        ; New direct segment
2965         .segment "ZP2"                  ; Ok, will use last attribute
2966         .segment "ZP2": absolute        ; Error, redecl mismatch
2967   </verb></tscreen>
2968
2969   See: <tt><ref id=".BSS" name=".BSS"></tt>, <tt><ref id=".CODE"
2970   name=".CODE"></tt>, <tt><ref id=".DATA" name=".DATA"></tt> and <tt><ref
2971   id=".RODATA" name=".RODATA"></tt>
2972
2973
2974 <sect1><tt>.SETCPU</tt><label id=".SETCPU"><p>
2975
2976   Switch the CPU instruction set. The command is followed by a string that
2977   specifies the CPU. Possible values are those that can also be supplied to
2978   the <tt><ref id="option--cpu" name="--cpu"></tt> command line option,
2979   namely: 6502, 6502X, 65SC02, 65C02, 65816 and sunplus. Please note that
2980   support for the sunplus CPU is not available in the freeware version,
2981   because the instruction set of the sunplus CPU is "proprietary and
2982   confidential".
2983
2984   See: <tt><ref id=".CPU" name=".CPU"></tt>,
2985        <tt><ref id=".IFP02" name=".IFP02"></tt>,
2986        <tt><ref id=".IFP816" name=".IFP816"></tt>,
2987        <tt><ref id=".IFPC02" name=".IFPC02"></tt>,
2988        <tt><ref id=".IFPSC02" name=".IFPSC02"></tt>,
2989        <tt><ref id=".P02" name=".P02"></tt>,
2990        <tt><ref id=".P816" name=".P816"></tt>,
2991        <tt><ref id=".PC02" name=".PC02"></tt>,
2992        <tt><ref id=".PSC02" name=".PSC02"></tt>
2993
2994
2995 <sect1><tt>.SMART</tt><label id=".SMART"><p>
2996
2997   Switch on or off smart mode. The command must be followed by a '+' or
2998   '-' character to switch the option on or off respectively. The default
2999   is off (that is, the assembler doesn't try to be smart), but this
3000   default may be changed by the -s switch on the command line.
3001
3002   In smart mode the assembler will do the following:
3003
3004   <itemize>
3005   <item>Track usage of the <tt/REP/ and <tt/SEP/ instructions in 65816 mode
3006         and update the operand sizes accordingly. If the operand of such an
3007         instruction cannot be evaluated by the assembler (for example, because
3008         the operand is an imported symbol), a warning is issued. Beware: Since
3009         the assembler cannot trace the execution flow this may lead to false
3010         results in some cases. If in doubt, use the <tt/.Inn/ and <tt/.Ann/
3011         instructions to tell the assembler about the current settings.
3012   <item>In 65816 mode, replace a <tt/RTS/ instruction by <tt/RTL/ if it is
3013         used within a procedure declared as <tt/far/, or if the procedure has
3014         no explicit address specification, but it is <tt/far/ because of the
3015         memory model used.
3016   </itemize>
3017
3018   Example:
3019
3020   <tscreen><verb>
3021         .smart                          ; Be smart
3022         .smart  -                       ; Stop being smart
3023   </verb></tscreen>
3024
3025   See: <tt><ref id=".A16" name=".A16"></tt>,
3026        <tt><ref id=".A8" name=".A8"></tt>,
3027        <tt><ref id=".I16" name=".I16"></tt>,
3028        <tt><ref id=".I8" name=".I8"></tt>
3029
3030
3031 <sect1><tt>.STRUCT</tt><label id=".STRUCT"><p>
3032
3033   Starts a struct definition. Structs are covered in a separate section named
3034   <ref id="structs" name="&quot;Structs and unions&quot;">.
3035
3036   See: <tt><ref id=".ENDSTRUCT" name=".ENDSTRUCT"></tt>
3037
3038
3039 <sect1><tt>.SUNPLUS</tt><label id=".SUNPLUS"><p>
3040
3041   Enable the SunPlus instructions set. This command will not work in the
3042   freeware version of the assembler, because the instruction set is
3043   "proprietary and confidential".
3044
3045   See: <tt><ref id=".P02" name=".P02"></tt>, <tt><ref id=".PSC02"
3046   name=".PSC02"></tt>, <tt><ref id=".PC02" name=".PC02"></tt>, and
3047   <tt><ref id=".P816" name=".P816"></tt>
3048
3049
3050 <sect1><tt>.TAG</tt><label id=".TAG"><p>
3051
3052   Allocate space for a struct or union.
3053
3054   Example:
3055
3056   <tscreen><verb>
3057         .struct Point
3058                 xcoord  .word
3059                 ycoord  .word
3060         .endstruct
3061
3062         .bss
3063                 .tag    Point           ; Allocate 4 bytes
3064   </verb></tscreen>
3065
3066
3067 <sect1><tt>.WARNING</tt><label id=".WARNING"><p>
3068
3069   Force an assembly warning. The assembler will output a warning message
3070   preceeded by "User warning". This warning will always be output, even if
3071   other warnings are disabled with the <tt><ref id="option-W" name="-W0"></tt>
3072   command line option.
3073
3074   This command may be used to output possible problems when assembling
3075   the source file.
3076
3077   Example:
3078
3079   <tscreen><verb>
3080         .macro  jne     target
3081                 .local L1
3082                 .ifndef target
3083                 .warning "Forward jump in jne, cannot optimize!"
3084                 beq     L1
3085                 jmp     target
3086         L1:
3087                 .else
3088                 ...
3089                 .endif
3090         .endmacro
3091   </verb></tscreen>
3092
3093   See also the <tt><ref id=".ERROR" name=".ERROR"></tt> and <tt><ref id=".OUT"
3094   name=".OUT"></tt> directives.
3095
3096
3097 <sect1><tt>.WORD</tt><label id=".WORD"><p>
3098
3099   Define word sized data. Must be followed by a sequence of (word ranged,
3100   but not necessarily constant) expressions.
3101
3102   Example:
3103
3104   <tscreen><verb>
3105         .word   $0D00, $AF13, _Clear
3106   </verb></tscreen>
3107
3108
3109 <sect1><tt>.ZEROPAGE</tt><label id=".ZEROPAGE"><p>
3110
3111   Switch to the ZEROPAGE segment and mark it as direct (zeropage) segment.
3112   The name of the ZEROPAGE segment is always "ZEROPAGE", so this is a
3113   shortcut for
3114
3115   <tscreen><verb>
3116         .segment  "ZEROPAGE", zeropage
3117   </verb></tscreen>
3118
3119   Because of the "zeropage" attribute, labels declared in this segment are
3120   addressed using direct addressing mode if possible. You <em/must/ instruct
3121   the linker to place this segment somewhere in the address range 0..$FF
3122   otherwise you will get errors.
3123
3124   See: <tt><ref id=".SEGMENT" name=".SEGMENT"></tt>
3125
3126
3127
3128 <sect>Macros<label id="macros"><p>
3129
3130
3131 <sect1>Introduction<p>
3132
3133 Macros may be thought of as "parametrized super instructions". Macros are
3134 sequences of tokens that have a name. If that name is used in the source
3135 file, the macro is "expanded", that is, it is replaced by the tokens that
3136 were specified when the macro was defined.
3137
3138
3139 <sect1>Macros without parameters<p>
3140
3141 In it's simplest form, a macro does not have parameters. Here's an
3142 example:
3143
3144 <tscreen><verb>
3145         .macro  asr             ; Arithmetic shift right
3146                 cmp     #$80    ; Put bit 7 into carry
3147                 ror             ; Rotate right with carry
3148         .endmacro
3149 </verb></tscreen>
3150
3151 The macro above consists of two real instructions, that are inserted into
3152 the code, whenever the macro is expanded. Macro expansion is simply done
3153 by using the name, like this:
3154
3155 <tscreen><verb>
3156         lda     $2010
3157         asr
3158         sta     $2010
3159 </verb></tscreen>
3160
3161
3162 <sect1>Parametrized macros<p>
3163
3164 When using macro parameters, macros can be even more useful:
3165
3166 <tscreen><verb>
3167         .macro  inc16   addr
3168                 clc
3169                 lda     addr
3170                 adc     #$01
3171                 sta     addr
3172                 lda     addr+1
3173                 adc     #$00
3174                 sta     addr+1
3175         .endmacro
3176 </verb></tscreen>
3177
3178 When calling the macro, you may give a parameter, and each occurence of
3179 the name "addr" in the macro definition will be replaced by the given
3180 parameter. So
3181
3182 <tscreen><verb>
3183         inc16   $1000
3184 </verb></tscreen>
3185
3186 will be expanded to
3187
3188 <tscreen><verb>
3189                 clc
3190                 lda     $1000
3191                 adc     #$01
3192                 sta     $1000
3193                 lda     $1000+1
3194                 adc     #$00
3195                 sta     $1000+1
3196 </verb></tscreen>
3197
3198 A macro may have more than one parameter, in this case, the parameters
3199 are separated by commas. You are free to give less parameters than the
3200 macro actually takes in the definition. You may also leave intermediate
3201 parameters empty. Empty parameters are replaced by empty space (that is,
3202 they are removed when the macro is exanded). If you have a look at our
3203 macro definition above, you will see, that replacing the "addr" parameter
3204 by nothing will lead to wrong code in most lines. To help you, writing
3205 macros with a variable parameter list, there are some control commands:
3206
3207 <tt><ref id=".IFBLANK" name=".IFBLANK"></tt> tests the rest of the line and
3208 returns true, if there are any tokens on the remainder of the line. Since
3209 empty parameters are replaced by nothing, this may be used to test if a given
3210 parameter is empty. <tt><ref id=".IFNBLANK" name=".IFNBLANK"></tt> tests the
3211 opposite.
3212
3213 Look at this example:
3214
3215 <tscreen><verb>
3216         .macro  ldaxy   a, x, y
3217         .ifnblank       a
3218                 lda     #a
3219         .endif
3220         .ifnblank       x
3221                 ldx     #x
3222         .endif
3223         .ifnblank       y
3224                 ldy     #y
3225         .endif
3226         .endmacro
3227 </verb></tscreen>
3228
3229 This macro may be called as follows:
3230
3231 <tscreen><verb>
3232         ldaxy   1, 2, 3         ; Load all three registers
3233
3234         ldaxy   1, , 3          ; Load only a and y
3235
3236         ldaxy   , , 3           ; Load y only
3237 </verb></tscreen>
3238
3239 There's another helper command for determining, which macro parameters are
3240 valid: <tt><ref id=".PARAMCOUNT" name=".PARAMCOUNT"></tt> This command is
3241 replaced by the parameter count given, <em/including/ intermediate empty macro
3242 parameters:
3243
3244 <tscreen><verb>
3245         ldaxy   1               ; .PARAMCOUNT = 1
3246         ldaxy   1,,3            ; .PARAMCOUNT = 3
3247         ldaxy   1,2             ; .PARAMCOUNT = 2
3248         ldaxy   1,              ; .PARAMCOUNT = 2
3249         ldaxy   1,2,3           ; .PARAMCOUNT = 3
3250 </verb></tscreen>
3251
3252 Macro parameters may optionally be enclosed into curly braces. This allows the
3253 inclusion of tokens that would otherwise terminate the parameter (the comma in
3254 case of a macro parameter).
3255
3256 <tscreen><verb>
3257         .macro  foo     arg1, arg2
3258                 ...
3259         .endmacro
3260
3261                 foo     ($00,x)         ; Two parameters passed
3262                 foo     {($00,x)}       ; One parameter passed
3263 </verb></tscreen>
3264
3265 In the first case, the macro is called with two parameters: '<tt/(&dollar;00/'
3266 and 'x)'. The comma is not passed to the macro, since it is part of the
3267 calling sequence, not the parameters.
3268
3269 In the second case, '(&dollar;00,x)' is passed to the macro, this time
3270 including the comma.
3271
3272
3273 <sect1>Detecting parameter types<p>
3274
3275 Sometimes it is nice to write a macro that acts differently depending on the
3276 type of the argument supplied. An example would be a macro that loads a 16 bit
3277 value from either an immediate operand, or from memory. The <tt/<ref
3278 id=".MATCH" name=".MATCH">/ and <tt/<ref id=".XMATCH" name=".XMATCH">/
3279 functions will allow you to do exactly this:
3280
3281 <tscreen><verb>
3282         .macro  ldax    arg
3283                 .if (.match (.left (1, {arg}), #))
3284                     ; immediate mode
3285                     lda     #<(.right (.tcount ({arg})-1, {arg}))
3286                     ldx     #>(.right (.tcount ({arg})-1, {arg}))
3287                 .else
3288                     ; assume absolute or zero page
3289                     lda     arg
3290                     ldx     1+({arg})
3291                 .endif
3292         .endmacro
3293 </verb></tscreen>
3294
3295 Using the <tt/<ref id=".MATCH" name=".MATCH">/ function, the macro is able to
3296 check if its argument begins with a hash mark. If so, two immediate loads are
3297 emitted, Otherwise a load from an absolute zero page memory location is
3298 assumed. Please note how the curly braces are used to enclose parameters to
3299 pseudo functions handling token lists. This is necessary, because the token
3300 lists may include commas or parens, which would be treated by the assembler
3301 as end-of-list.
3302
3303 The macro can be used as
3304
3305 <tscreen><verb>
3306         foo:    .word   $5678
3307         ...
3308                 ldax    #$1234          ; X=$12, A=$34
3309         ...
3310                 ldax    foo             ; X=$56, A=$78
3311 </verb></tscreen>
3312
3313
3314 <sect1>Recursive macros<p>
3315
3316 Macros may be used recursively:
3317
3318 <tscreen><verb>
3319         .macro  push    r1, r2, r3
3320                 lda     r1
3321                 pha
3322         .if     .paramcount > 1
3323                 push    r2, r3
3324         .endif
3325         .endmacro
3326 </verb></tscreen>
3327
3328 There's also a special macro to help writing recursive macros: <tt><ref
3329 id=".EXITMACRO" name=".EXITMACRO"></tt> This command will stop macro expansion
3330 immidiately:
3331
3332 <tscreen><verb>
3333         .macro  push    r1, r2, r3, r4, r5, r6, r7
3334         .ifblank        r1
3335                 ; First parameter is empty
3336                 .exitmacro
3337         .else
3338                 lda     r1
3339                 pha
3340         .endif
3341                 push    r2, r3, r4, r5, r6, r7
3342         .endmacro
3343 </verb></tscreen>
3344
3345 When expanding this macro, the expansion will push all given parameters
3346 until an empty one is encountered. The macro may be called like this:
3347
3348 <tscreen><verb>
3349         push    $20, $21, $32           ; Push 3 ZP locations
3350         push    $21                     ; Push one ZP location
3351 </verb></tscreen>
3352
3353
3354 <sect1>Local symbols inside macros<p>
3355
3356 Now, with recursive macros, <tt><ref id=".IFBLANK" name=".IFBLANK"></tt> and
3357 <tt><ref id=".PARAMCOUNT" name=".PARAMCOUNT"></tt>, what else do you need?
3358 Have a look at the inc16 macro above. Here is it again:
3359
3360 <tscreen><verb>
3361         .macro  inc16   addr
3362                 clc
3363                 lda     addr
3364                 adc     #$01
3365                 sta     addr
3366                 lda     addr+1
3367                 adc     #$00
3368                 sta     addr+1
3369         .endmacro
3370 </verb></tscreen>
3371
3372 If you have a closer look at the code, you will notice, that it could be
3373 written more efficiently, like this:
3374
3375 <tscreen><verb>
3376         .macro  inc16   addr
3377                 inc     addr
3378                 bne     Skip
3379                 inc     addr+1
3380         Skip:
3381         .endmacro
3382 </verb></tscreen>
3383
3384 But imagine what happens, if you use this macro twice? Since the label
3385 "Skip" has the same name both times, you get a "duplicate symbol" error.
3386 Without a way to circumvent this problem, macros are not as useful, as
3387 they could be. One solution is, to start a new lexical block inside the
3388 macro:
3389
3390 <tscreen><verb>
3391         .macro  inc16   addr
3392         .proc
3393                 inc     addr
3394                 bne     Skip
3395                 inc     addr+1
3396         Skip:
3397         .endproc
3398         .endmacro
3399 </verb></tscreen>
3400
3401 Now the label is local to the block and not visible outside. However,
3402 sometimes you want a label inside the macro to be visible outside. To make
3403 that possible, there's a new command that's only usable inside a macro
3404 definition: <tt><ref id=".LOCAL" name=".LOCAL"></tt>. <tt/.LOCAL/ declares one
3405 or more symbols as local to the macro expansion. The names of local variables
3406 are replaced by a unique name in each separate macro expansion. So we could
3407 also solve the problem above by using <tt/.LOCAL/:
3408
3409 <tscreen><verb>
3410         .macro  inc16   addr
3411                 .local  Skip            ; Make Skip a local symbol
3412                 clc
3413                 lda     addr
3414                 adc     #$01
3415                 sta     addr
3416                 bcc     Skip
3417                 inc     addr+1
3418         Skip:                           ; Not visible outside
3419         .endmacro
3420 </verb></tscreen>
3421
3422
3423 <sect1>C style macros<p>
3424
3425 Starting with version 2.5 of the assembler, there is a second macro type
3426 available: C style macros using the <tt/.DEFINE/ directive. These macros are
3427 similar to the classic macro type described above, but behaviour is sometimes
3428 different:
3429
3430 <itemize>
3431
3432 <item>  Macros defined with <tt><ref id=".DEFINE" name=".DEFINE"></tt> may not
3433         span more than a line. You may use line continuation (see <tt><ref
3434         id=".LINECONT" name=".LINECONT"></tt>) to spread the definition over
3435         more than one line for increased readability, but the macro itself
3436         may not contain an end-of-line token.
3437
3438 <item>  Macros defined with <tt><ref id=".DEFINE" name=".DEFINE"></tt> share
3439         the name space with classic macros, but they are detected and replaced
3440         at the scanner level. While classic macros may be used in every place,
3441         where a mnemonic or other directive is allowed, <tt><ref id=".DEFINE"
3442         name=".DEFINE"></tt> style macros are allowed anywhere in a line. So
3443         they are more versatile in some situations.
3444
3445 <item>  <tt><ref id=".DEFINE" name=".DEFINE"></tt> style macros may take
3446         parameters. While classic macros may have empty parameters, this is
3447         not true for <tt><ref id=".DEFINE" name=".DEFINE"></tt> style macros.
3448         For this macro type, the number of actual parameters must match
3449         exactly the number of formal parameters.
3450
3451         To make this possible, formal parameters are enclosed in braces when
3452         defining the macro. If there are no parameters, the empty braces may
3453         be omitted.
3454
3455 <item>  Since <tt><ref id=".DEFINE" name=".DEFINE"></tt> style macros may not
3456         contain end-of-line tokens, there are things that cannot be done. They
3457         may not contain several processor instructions for example. So, while
3458         some things may be done with both macro types, each type has special
3459         usages. The types complement each other.
3460
3461 </itemize>
3462
3463 Let's look at a few examples to make the advantages and disadvantages
3464 clear.
3465
3466 To emulate assemblers that use "<tt/EQU/" instead of "<tt/=/" you may use the
3467 following <tt/.DEFINE/:
3468
3469 <tscreen><verb>
3470         .define EQU     =
3471
3472         foo     EQU     $1234           ; This is accepted now
3473 </verb></tscreen>
3474
3475 You may use the directive to define string constants used elsewhere:
3476
3477 <tscreen><verb>
3478         ; Define the version number
3479         .define VERSION         "12.3a"
3480
3481         ; ... and use it
3482         .asciiz VERSION
3483 </verb></tscreen>
3484
3485 Macros with parameters may also be useful:
3486
3487 <tscreen><verb>
3488         .define DEBUG(message)  .out    message
3489
3490         DEBUG   "Assembling include file #3"
3491 </verb></tscreen>
3492
3493 Note that, while formal parameters have to be placed in braces, this is
3494 not true for the actual parameters. Beware: Since the assembler cannot
3495 detect the end of one parameter, only the first token is used. If you
3496 don't like that, use classic macros instead:
3497
3498 <tscreen><verb>
3499         .macro  message
3500                 .out    message
3501         .endmacro
3502 </verb></tscreen>
3503
3504 (This is an example where a problem can be solved with both macro types).
3505
3506
3507 <sect1>Characters in macros<p>
3508
3509 When using the <ref id="option-t" name="-t"> option, characters are translated
3510 into the target character set of the specific machine. However, this happens
3511 as late as possible. This means that strings are translated if they are part
3512 of a <tt><ref id=".BYTE" name=".BYTE"></tt> or <tt><ref id=".ASCIIZ"
3513 name=".ASCIIZ"></tt> command. Characters are translated as soon as they are
3514 used as part of an expression.
3515
3516 This behaviour is very intuitive outside of macros but may be confusing when
3517 doing more complex macros. If you compare characters against numeric values,
3518 be sure to take the translation into account.
3519
3520
3521
3522
3523 <sect>Macro packages<label id="macropackages"><p>
3524
3525 Using the <tt><ref id=".MACPACK" name=".MACPACK"></tt> directive, predefined
3526 macro packages may be included with just one command. Available macro packages
3527 are:
3528
3529
3530 <sect1><tt>.MACPACK generic</tt><p>
3531
3532 This macro package defines macros that are useful in almost any program.
3533 Currently, two macros are defined:
3534
3535 <tscreen><verb>
3536         .macro  add     Arg
3537                 clc
3538                 adc     Arg
3539         .endmacro
3540
3541         .macro  sub     Arg
3542                 sec
3543                 sbc     Arg
3544         .endmacro
3545 </verb></tscreen>
3546
3547
3548 <sect1><tt>.MACPACK longbranch</tt><p>
3549
3550 This macro package defines long conditional jumps. They are named like the
3551 short counterpart but with the 'b' replaced by a 'j'. Here is a sample
3552 definition for the "<tt/jeq/" macro, the other macros are built using the same
3553 scheme:
3554
3555 <tscreen><verb>
3556         .macro  jeq     Target
3557                 .if     .def(Target) .and ((*+2)-(Target) <= 127)
3558                 beq     Target
3559                 .else
3560                 bne     *+5
3561                 jmp     Target
3562                 .endif
3563         .endmacro
3564 </verb></tscreen>
3565
3566 All macros expand to a short branch, if the label is already defined (back
3567 jump) and is reachable with a short jump. Otherwise the macro expands to a
3568 conditional branch with the branch condition inverted, followed by an absolute
3569 jump to the actual branch target.
3570
3571 The package defines the following macros:
3572
3573 <tscreen><verb>
3574         jeq, jne, jmi, jpl, jcs, jcc, jvs, jvc
3575 </verb></tscreen>
3576
3577
3578
3579 <sect1><tt>.MACPACK cbm</tt><p>
3580
3581 The cbm macro package will define a macro named <tt/scrcode/. It takes a
3582 string as argument and places this string into memory translated into screen
3583 codes.
3584
3585
3586 <sect1><tt>.MACPACK cpu</tt><p>
3587
3588 This macro package does not define any macros but constants used to examine
3589 the value read from the <tt/<ref id=".CPU" name=".CPU">/ pseudo variable. For
3590 each supported CPU a constant similar to
3591
3592 <tscreen><verb>
3593     CPU_6502
3594     CPU_65SC02
3595     CPU_65C02
3596     CPU_65816
3597     CPU_SUNPLUS
3598 </verb></tscreen>
3599
3600 is defined. These constants may be used to determine the exact type of the
3601 currently enabled CPU. In addition to that, for each CPU instruction set,
3602 another constant is defined:
3603
3604 <tscreen><verb>
3605     CPU_ISET_6502
3606     CPU_ISET_65SC02
3607     CPU_ISET_65C02
3608     CPU_ISET_65816
3609     CPU_ISET_SUNPLUS
3610 </verb></tscreen>
3611
3612 The value read from the <tt/<ref id=".CPU" name=".CPU">/ pseudo variable may
3613 be checked with <tt/<ref id="operators" name=".BITAND">/ to determine if the
3614 currently enabled CPU supports a specific instruction set. For example the
3615 65C02 supports all instructions of the 65SC02 CPU, so it has the
3616 <tt/CPU_ISET_65SC02/ bit set in addition to its native <tt/CPU_ISET_65C02/
3617 bit. Using
3618
3619 <tscreen><verb>
3620         .if (.cpu .bitand CPU_ISET_65SC02)
3621                 lda     (sp)
3622         .else
3623                 ldy     #$00
3624                 lda     (sp),y
3625         .endif
3626 </verb></tscreen>
3627
3628 it is possible to determine if the
3629
3630 <tscreen><verb>
3631                 lda     (sp)
3632 </verb></tscreen>
3633
3634 instruction is supported, which is the case for the 65SC02, 65C02 and 65816
3635 CPUs (the latter two are upwards compatible to the 65SC02).
3636
3637
3638
3639 <sect>Structs and unions<label id="structs"><p>
3640
3641 Structs and unions are special forms of <ref id="scopes" name="scopes">.  They
3642 are to some degree comparable to their C counterparts. Both have a list of
3643 members. Each member allocates storage and may optionally have a name, which,
3644 in case of a struct, is the offset from the beginning and, in case of a union,
3645 is always zero.
3646
3647 Here is an example for a very simple struct with two members and a total size
3648 of 4 bytes:
3649
3650 <tscreen><verb>
3651       .struct Point
3652               xcoord  .word
3653               ycoord  .word
3654       .endstruct
3655 </verb></tscreen>
3656
3657 A union shares the total space between all its members, its size is the same
3658 as that of the largest member.
3659
3660 A struct or union must not necessarily have a name. If it is anonymous, no
3661 local scope is opened, the identifiers used to name the members are placed
3662 into the current scope instead.
3663
3664 A struct may contain unnamed members and definitions of local structs. The
3665 storage allocators may contain a multiplier, as in the example below:
3666
3667 <tscreen><verb>
3668       .struct Circle
3669               .struct Point
3670                       .word   2         ; Allocate two words
3671               .endstruct
3672               Radius  .word
3673       .endstruct
3674 </verb></tscreen>
3675
3676 Using the <ref id=".TAG" name=".TAG"> keyword, it is possible to embedd
3677 already defined structs or unions in structs:
3678
3679 <tscreen><verb>
3680       .struct Point
3681               xcoord  .word
3682               ycoord  .word
3683       .endstruct
3684
3685       .struct Circle
3686               Origin  .tag    Point
3687               Radius  .byte
3688       .endstruct
3689 </verb></tscreen>
3690
3691 Space for a struct or union may be allocated using the <ref id=".TAG"
3692 name=".TAG"> directive.
3693
3694 <tscreen><verb>
3695         C:      .tag    Circle
3696 </verb></tscreen>
3697
3698 Currently, members are just offsets from the start of the struct or union. To
3699 access a field of a struct, the member offset has to be added to the address
3700 of the struct itself:
3701
3702 <tscreen><verb>
3703         lda     C+Circle::Radius        ; Load circle radius into A
3704 </verb></tscreen>
3705
3706 This may change in a future version of the assembler.
3707
3708
3709 <sect>Module constructors/destructors<label id="condes"><p>
3710
3711 <em>Note:</em> This section applies mostly to C programs, so the explanation
3712 below uses examples from the C libraries. However, the feature may also be
3713 useful for assembler programs.
3714
3715
3716 <sect1>Module overview<p>
3717
3718 Using the <tt><ref id=".CONSTRUCTOR" name=".CONSTRUCTOR"></tt> and <tt><ref
3719 id=".DESTRUCTOR" name=".DESTRUCTOR"></tt> keywords it it possible to export
3720 functions in a special way. The linker is able to generate tables with all
3721 functions of a specific type. Such a table will <em>only</em> include symbols
3722 from object files that are linked into a specific executable. This may be used
3723 to add initialization and cleanup code for library modules.
3724
3725 The C heap functions are an example where module initialization code is used.
3726 All heap functions (<tt>malloc</tt>, <tt>free</tt>, ...) work with a few
3727 variables that contain the start and the end of the heap, pointers to the free
3728 list and so on. Since the end of the heap depends on the size and start of the
3729 stack, it must be initialized at runtime. However, initializing these
3730 variables for programs that do not use the heap are a waste of time and
3731 memory.
3732
3733 So the central module defines a function that contains initialization code and
3734 exports this function using the <tt/.CONSTRUCTOR/ statement. If (and only if)
3735 this module is added to an executable by the linker, the initialization
3736 function will be placed into the table of constructors by the linker. The C
3737 startup code will call all constructors before <tt/main/ and all destructors
3738 after <tt/main/, so without any further work, the heap initialization code is
3739 called once the module is linked in.
3740
3741 While it would be possible to add explicit calls to initialization functions
3742 in the startup code, the new approach has several advantages:
3743
3744 <enum>
3745 <item>
3746 If a module is not included, the initialization code is not linked in and not
3747 called. So you don't pay for things you don't need.
3748
3749 <item>
3750 Adding another library that needs initialization does not mean that the
3751 startup code has to be changed. Before we had module constructors and
3752 destructors, the startup code for all systems had to be adjusted to call the
3753 new initialization code.
3754
3755 <item>
3756 The feature saves memory: Each additional initialization function needs just
3757 two bytes in the table (a pointer to the function).
3758
3759 </enum>
3760
3761
3762 <sect1>Calling order<p>
3763
3764 Both, constructors and destructors are sorted in increasing priority order by
3765 the linker when using one of the builtin linker configurations, so the
3766 functions with lower priorities come first and are followed by those with
3767 higher priorities. The C library runtime subroutine that walks over the
3768 constructor and destructor tables calls the functions starting from the top of
3769 the table - which means that functions with a high priority are called first.
3770
3771 So when using the C runtime, both constructors and destructors are called with
3772 high priority functions first, followed by low priority functions.
3773
3774
3775 <sect1>Pitfalls<p>
3776
3777 When creating and using module constructors and destructors, please take care
3778 of the following:
3779
3780 <itemize>
3781
3782 <item>
3783 The linker will only generate function tables, it will not generate code to
3784 call these functions. If you're using the feature in some other than the
3785 existing C environments, you have to write code to call all functions in a
3786 linker generated table yourself. See the <tt>condes</tt> module in the C
3787 runtime for an example on how to do this.
3788
3789 <item>
3790 The linker will only add addresses of functions that are in modules linked to
3791 the executable. This means that you have to be careful where to place the
3792 condes functions. If initialization is needed for a group of functions, be
3793 sure to place the initialization function into a module that is linked in
3794 regardless of which function is called by the user.
3795
3796 <item>
3797 The linker will generate the tables only when requested to do so by the
3798 <tt/FEATURE CONDES/ statement in the linker config file. Each table has to
3799 be requested separately.
3800
3801 <item>
3802 Constructors and destructors may have priorities. These priorities determine
3803 the order of the functions in the table. If your intialization or cleanup code
3804 does depend on other initialization or cleanup code, you have to choose the
3805 priority for the functions accordingly.
3806
3807 <item>
3808 Besides the <tt><ref id=".CONSTRUCTOR" name=".CONSTRUCTOR"></tt> and <tt><ref
3809 id=".DESTRUCTOR" name=".DESTRUCTOR"></tt> statements, there is also a more
3810 generic command: <tt><ref id=".CONDES" name=".CONDES"></tt>. This allows to
3811 specify an additional type. Predefined types are 0 (constructor) and 1
3812 (destructor). The linker generates a separate table for each type on request.
3813
3814 </itemize>
3815
3816
3817 <sect>Porting sources from other assemblers<p>
3818
3819 Sometimes it is necessary to port code written for older assemblers to ca65.
3820 In some cases, this can be done without any changes to the source code by
3821 using the emulation features of ca65 (see <tt><ref id=".FEATURE"
3822 name=".FEATURE"></tt>). In other cases, it is necessary to make changes to the
3823 source code.
3824
3825 Probably the biggest difference is the handling of the <tt><ref id=".ORG"
3826 name=".ORG"></tt> directive. ca65 generates relocatable code, and placement is
3827 done by the linker. Most other assemblers generate absolute code, placement is
3828 done within the assembler and there is no external linker.
3829
3830 In general it is not a good idea to write new code using the emulation
3831 features of the assembler, but there may be situations where even this rule is
3832 not valid.
3833
3834 <sect1>TASS<p>
3835
3836 You need to use some of the ca65 emulation features to simulate the behaviour
3837 of such simple assemblers.
3838
3839 <enum>
3840 <item>Prepare your sourcecode like this:
3841
3842 <tscreen><verb>
3843         ; if you want TASS style labels without colons
3844         .feature labels_without_colons
3845
3846         ; if you want TASS style character constants
3847         ; ("a" instead of the default 'a')
3848         .feature loose_char_term
3849
3850                 .word *+2       ; the cbm load address
3851
3852                 [yourcode here]
3853 </verb></tscreen>
3854
3855 notice that the two emulation features are mostly useful for porting
3856 sources originally written in/for TASS, they are not needed for the
3857 actual "simple assembler operation" and are not recommended if you are
3858 writing new code from scratch.
3859
3860 <item>Replace all program counter assignments (which are not possible in ca65
3861 by default, and the respective emulation feature works different from what
3862 you'd expect) by another way to skip to another memory location, for example
3863 the <tt><ref id=".RES" name=".RES"></tt>directive.
3864
3865 <tscreen><verb>
3866         ; *=$2000
3867         .res $2000-*    ; reserve memory up to $2000
3868 </verb></tscreen>
3869
3870 notice that other than the original TASS, ca65 can never move the
3871 programmcounter backwards - think of it as if you are assembling to disc with
3872 TASS.
3873
3874 <item>Conditional assembly (<tt/.ifeq//<tt/.endif//<tt/.goto/ etc.) must be
3875 rewritten to match ca65 syntax. Most importantly notice that due to the lack
3876 of <tt/.goto/, everything involving loops must be replaced by
3877 <tt><ref id=".REPEAT" name=".REPEAT"></tt>.
3878
3879 <item>To assemble code to a different address than it is executed at, use the
3880 <tt><ref id=".ORG" name=".ORG"></tt> directive instead of
3881 <tt/.offs/-constructs.
3882
3883 <tscreen><verb>
3884         .org $1800
3885
3886         [floppy code here]
3887
3888         .reloc  ; back to normal
3889 </verb></tscreen>
3890
3891 <item>Then assemble like this:
3892
3893 <tscreen><verb>
3894         cl65 --start-addr 0x0ffe -t none myprog.s -o myprog.prg
3895 </verb></tscreen>
3896
3897 notice that you need to use the actual start address minus two, since two
3898 bytes are used for the cbm load address.
3899
3900 </enum>
3901
3902
3903 <sect>Bugs/Feedback<p>
3904
3905 If you have problems using the assembler, if you find any bugs, or if
3906 you're doing something interesting with the assembler, I would be glad to
3907 hear from you. Feel free to contact me by email
3908 (<htmlurl url="mailto:uz@cc65.org" name="uz@cc65.org">).
3909
3910
3911
3912 <sect>Copyright<p>
3913
3914 ca65 (and all cc65 binutils) are (C) Copyright 1998-2003 Ullrich von
3915 Bassewitz. For usage of the binaries and/or sources the following
3916 conditions do apply:
3917
3918 This software is provided 'as-is', without any expressed or implied
3919 warranty.  In no event will the authors be held liable for any damages
3920 arising from the use of this software.
3921
3922 Permission is granted to anyone to use this software for any purpose,
3923 including commercial applications, and to alter it and redistribute it
3924 freely, subject to the following restrictions:
3925
3926 <enum>
3927 <item>  The origin of this software must not be misrepresented; you must not
3928         claim that you wrote the original software. If you use this software
3929         in a product, an acknowledgment in the product documentation would be
3930         appreciated but is not required.
3931 <item>  Altered source versions must be plainly marked as such, and must not
3932         be misrepresented as being the original software.
3933 <item>  This notice may not be removed or altered from any source
3934         distribution.
3935 </enum>
3936
3937
3938
3939 </article>
3940
3941
3942