1RGBASM(5)                   BSD File Formats Manual                  RGBASM(5)
2

NAME

4     rgbasm — language documentation
5

DESCRIPTION

7     This is the full description of the language used by rgbasm(1).  The de‐
8     scription of the instructions supported by the Game Boy CPU is in
9     gbz80(7).
10
11     It is strongly recommended to have some familiarity with the Game Boy
12     hardware before reading this document.  RGBDS is specifically targeted at
13     the Game Boy, and thus a lot of its features tie directly to its con‐
14     cepts.  This document is not intended to be a Game Boy hardware refer‐
15     ence.
16
17     Generally, “the linker” will refer to rgblink(1), but any program that
18     processes RGBDS object files (described in rgbds(5)) can be used in its
19     place.
20

SYNTAX

22     The syntax is line-based, just as in any other assembler, meaning that
23     you do one instruction or directive per line:
24
25           [label] [instruction] [; comment]
26
27     Example:
28
29           John: ld a,87 ;Weee
30
31     All reserved keywords (directives, mnemonics, registers, etc.) are case-
32     insensitive; all identifiers (symbol names) are case-sensitive.
33
34     Comments are used to give humans information about the code, such as ex‐
35     planations.  The assembler always ignores comments and their contents.
36
37     There are two syntaxes for comments.  The most common is that anything
38     that follows a semicolon ‘;’ not inside a string, is a comment until the
39     end of the line.  The second is a block comment, beginning with ‘/*’ and
40     ending with ‘*/’.  It can be split across multiple lines, or occur in the
41     middle of an expression:
42
43           X = /* the value of x
44                  should be 3 */ 3
45
46     Sometimes lines can be too long and it may be necessary to split them.
47     To do so, put a backslash at the end of the line:
48
49               DB 1, 2, 3, \
50                  4, 5, 6, \ ; Put it before any comments
51                  7, 8, 9
52
53     This works anywhere in the code except inside of strings.  To split
54     strings it is needed to use STRCAT() like this:
55
56               db STRCAT("Hello ", \
57                         "world!")
58

EXPRESSIONS

60     An expression can be composed of many things.  Numerical expressions are
61     always evaluated using signed 32-bit math.  Zero is considered to be the
62     only "false" number, all non-zero numbers (including negative) are
63     "true".
64
65     An expression is said to be "constant" if rgbasm knows its value.  This
66     is generally always the case, unless a label is involved, as explained in
67     the SYMBOLS section.
68
69     The instructions in the macro-language generally require constant expres‐
70     sions.
71
72   Numeric Formats
73     There are a number of numeric formats.
74
75           Format type             Prefix    Accepted characters
76           Hexadecimal             $         0123456789ABCDEF
77           Decimal                 none      0123456789
78           Octal                   &         01234567
79           Binary                  %         01
80           Fixed point (Q16.16)    none      01234.56789
81           Character constant      none      "ABYZ"
82           Gameboy graphics        `         0123
83
84     Underscores are also accepted in numbers, except at the beginning of one.
85
86     The "character constant" form yields the value the character maps to in
87     the current charmap.  For example, by default (refer to ascii(7)) ‘"A"’
88     yields 65.  See Character maps for information on charmaps.
89
90     The last one, Gameboy graphics, is quite interesting and useful.  After
91     the backtick, 8 digits between 0 and 3 are expected, corresponding to
92     pixel values.  The resulting value is the two bytes of tile data that
93     would produce that row of pixels.  For example, ‘`01012323’ is equivalent
94     to ‘$0F55’.
95
96     You can also use symbols, which are implicitly replaced with their value.
97
98   Operators
99     A great number of operators you can use in expressions are available
100     (listed from highest to lowest precedence):
101
102           Operator           Meaning
103           ( )                Precedence override
104           FUNC()             Built-in function call
105           **                 Exponent
106           ~ + -              Unary complement/plus/minus
107           * / %              Multiply/divide/modulo
108           << >>              Shift left/right
109           & | ^              Binary and/or/xor
110           + -                Add/subtract
111           != == <= >= < >    Comparison
112           && ||              Boolean and/or
113           !                  Unary not
114
115     ~ complements a value by inverting all its bits.
116
117     % is used to get the remainder of the corresponding division, so that ‘a
118     / b * b + a % b == a’ is always true.  The result has the same sign as
119     the divisor.  This makes ‘a % b’.  equal to ‘(a + b) % b’ or ‘(a - b) %
120     b’.
121
122     Shifting works by shifting all bits in the left operand either left
123     (‘<<’) or right (‘>>’) by the right operand's amount.  When shifting
124     left, all newly-inserted bits are reset; when shifting right, they are
125     copies of the original most significant bit instead.  This makes ‘a << b’
126     and ‘a >> b’ equivalent to multiplying and dividing by 2 to the power of
127     b, respectively.
128
129     Comparison operators return 0 if the comparison is false, and 1 other‐
130     wise.
131
132     Unlike in a lot of languages, and for technical reasons, rgbasm still
133     evaluates both operands of ‘&&’ and ‘||’.
134
135     ! returns 1 if the operand was 0, and 0 otherwise.
136
137   Fixed-point Expressions
138     Fixed-point numbers are basically normal (32-bit) integers, which count
139     65536ths instead of entire units, offering better precision than integers
140     but limiting the range of values.  The upper 16 bits are used for the in‐
141     teger part and the lower 16 bits are used for the fraction (65536ths).
142     Since they are still akin to integers, you can use them in normal integer
143     expressions, and some integer operators like ‘+’ and ‘-’ don't care
144     whether the operands are integers or fixed-point.  You can easily trun‐
145     cate a fixed-point number into an integer by shifting it right by 16
146     bits.  It follows that you can convert an integer to a fixed-point number
147     by shifting it left.
148
149     The following functions are designed to operate with fixed-point numbers:
150     delim $$
151
152           Name           Operation
153           DIV(x, y)      $x ÷ y$
154           MUL(x, y)      $x × y$
155           POW(x, y)      $x$ to the $y$ power
156           LOG(x, y)      Logarithm of $x$ to the base $y$
157           ROUND(x)       Round $x$ to the nearest integer
158           CEIL(x)        Round $x$ up to an integer
159           FLOOR(x)       Round $x$ down to an integer
160           SIN(x)         Sine of $x$
161           COS(x)         Cosine of $x$
162           TAN(x)         Tangent of $x$
163           ASIN(x)        Inverse sine of $x$
164           ACOS(x)        Inverse cosine of $x$
165           ATAN(x)        Inverse tangent of $x$
166           ATAN2(x, y)    Angle between $( x, y )$ and $( 1, 0 )$
167     delim off
168
169     The trigonometry functions ( SIN, COS, TAN, etc) are defined in terms of
170     a circle divided into 65535.0 degrees.
171
172     These functions are useful for automatic generation of various tables.
173     For example:
174
175           ; Generate a 256-byte sine table with values in the range [0, 128]
176           ; (shifted and scaled from the range [-1.0, 1.0])
177           ANGLE = 0.0
178               REPT 256
179                   db (MUL(64.0, SIN(ANGLE)) + 64.0) >> 16
180           ANGLE = ANGLE + 256.0 ; 256.0 = 65536 degrees / 256 entries
181               ENDR
182
183   String Expressions
184     The most basic string expression is any number of characters contained in
185     double quotes (‘"for instance"’).  The backslash character ‘\’ is special
186     in that it causes the character following it to be “escaped”, meaning
187     that it is treated differently from normal.  There are a number of escape
188     sequences you can use within a string:
189
190           String                 Meaning
191           ‘\\                    Produces a backslash’
192           ‘\"                    Produces a double quote without terminating’
193           ‘\{                    Curly bracket left’
194           ‘\}                    Curly bracket right’
195           ‘\n                    Newline ($0A)’
196           ‘\r                    Carriage return ($0D)’
197           ‘\t                    Tab ($09)’
198           "\1" – "\9"            Macro argument (Only in the body of a macro;
199                                  see Invoking macros)
200           ‘\#                    All _NARG macro arguments, separated by
201                                  commas (Only in the body of a macro)’
202           ‘\@                    Label name suffix (Only in the body of a
203                                  macro or a REPT block)’
204     (Note that some of those can be used outside of strings, when noted fur‐
205     ther in this document.)
206
207     Multi-line strings are contained in triple quotes (‘"""for instance"""’).
208     Escape sequences work the same way in multi-line strings; however, lit‐
209     eral newline characters will be included as-is, without needing to escape
210     them with ‘\r’ or ‘\n’.
211
212     A funky feature is ‘{symbol}’ within a string, called “symbol
213     interpolation”.  This will paste the contents of ‘symbol’ as if they were
214     part of the source file.  If it's a string symbol, its characters are
215     simply inserted.  If it's a numerical symbol, its value is converted to
216     hexadecimal notation with a dollar sign ‘$’ prepended.
217
218     Symbols can be interpolated even in the contexts that disable expansion
219     of string equates: ‘DEF({name})’, ‘DEF {name} EQU/SET/EQUS/etc ...’,
220     ‘PURGE {name}’, and ‘MACRO {name}’ will all interpolate the contents of
221     ‘{name}’.
222
223     Symbol interpolations can be nested, too!
224
225           DEF topic EQUS "life, the universe, and \"everything\""
226           DEF meaning EQUS "answer"
227           ; Defines answer = 42
228           DEF {meaning} = 42
229           ; Prints "The answer to life, the universe, and "everything" is 42"
230           PRINTLN "The {meaning} to {topic} is {d:{meaning}}"
231           PURGE topic, meaning, {meaning}
232
233     It's possible to change the way symbols are converted by specifying a
234     print format like so: ‘{fmt:symbol}’.  The ‘fmt’ specifier consists of
235     parts ‘<sign><prefix><align><pad><width><frac><type>’.  These parts are:
236
237     Part        Meaning
238     ‘<sign>     May be’ ‘+’ or ‘ ’.  If specified, prints this character in
239                 front of non-negative numbers.
240     ‘<prefix>   May be’ ‘#’.  If specified, prints the appropriate prefix for
241                 numbers, ‘$’, ‘&’, or ‘%’.
242     ‘<align>    May be’ ‘-’.  If specified, aligns left instead of right.
243     ‘<pad>      May be’ ‘0’.  If specified, pads right-aligned numbers with
244                 zeros instead of spaces.
245     ‘<width>    May be one or more’ ‘0’ – ‘9’.  If specified, pads the value
246                 to this width, right-aligned with spaces by default.
247     ‘<frac>     May be’ ‘.’ followed by one or more ‘0’ – ‘9’.  If specified,
248                 prints this many digits of a fixed-point fraction.  Defaults
249                 to 5 digits, maximum 255 digits.
250     ‘<type>     Specifies the type of value.’
251
252     All the format specifier parts are optional except the ‘<type>’.  Valid
253     print types are:
254
255           Print type    Format                   Example
256           ‘d            Signed decimal           -42’
257           ‘u            Unsigned decimal         42’
258           ‘x            Lowercase hexadecimal    2a’
259           ‘X            Uppercase hexadecimal    2A’
260           ‘b            Binary                   101010’
261           ‘o            Octal                    52’
262           ‘f            Fixed-point              1234.56789’
263           ‘s            String                   "example"’
264
265     Examples:
266
267           ; Prints "%0010 + $3 == 5"
268           PRINTLN STRFMT("%#05b + %#x == %d", 2, 3, 2+3)
269           ; Prints "32% of 20 = 6.40"
270           PRINTLN STRFMT("%d%% of %d = %.2f", 32, 20, MUL(20.0, 0.32))
271           ; Prints "Hello world!"
272           PRINTLN STRFMT("Hello %s!", STRLWR("WORLD"))
273
274     HINT: The {symbol} construct can also be used outside strings.  The sym‐
275     bol's value is again inserted directly.
276
277           def NAME equs "ITEM"
278           def FMT equs "d"
279           def ZERO_NUM equ 0
280           def ZERO_STR equs "0"
281           ; Defines INDEX as 100
282           INDEX = 1{ZERO_STR}{{FMT}:ZERO_NUM}
283           ; Defines ITEM_100 as "\"hundredth\""
284           def {NAME}_{d:INDEX} equs "\"hundredth\""
285           ; Prints "ITEM_100 is hundredth"
286           PRINTLN STRCAT("{NAME}_{d:INDEX} is ", {NAME}_{d:INDEX})
287           ; Purges ITEM_100
288           PURGE {NAME}_{d:INDEX}
289
290     The following functions operate on string expressions.  Most of them re‐
291     turn a string, however some of these functions actually return an integer
292     and can be used as part of an integer expression!
293
294     Name                     Operation
295     STRLEN(str)              Returns the number of characters in str.
296     STRCAT(strs...)          Concatenates strs.
297     STRCMP(str1, str2)       Returns -1 if str1 is alphabetically lower than
298                              str2 , zero if they match, 1 if str1 is greater
299                              than str2.
300     STRIN(str1, str2)        Returns the first position of str2 in str1 or
301                              zero if it's not present (first character is
302                              position 1).
303     STRRIN(str1, str2)       Returns the last position of str2 in str1 or
304                              zero if it's not present (first character is
305                              position 1).
306     STRSUB(str, pos, len)    Returns a substring from str starting at pos
307                              (first character is position 1, last is position
308                              -1) and len characters long. If len is not
309                              specified the substring continues to the end of
310                              str.
311     STRUPR(str)              Returns str with all letters in uppercase.
312     STRLWR(str)              Returns str with all letters in lowercase.
313     STRRPL(str, old, new)    Returns str with each non-overlapping occurrence
314                              of the substring old replaced with new.
315     STRFMT(fmt, args...)     Returns the string fmt with each
316     CHARLEN(str)             Returns the number of charmap entries in str
317                              with the current charmap.
318     CHARSUB(str, pos)        Returns the substring for the charmap entry at
319                              pos in str (first character is position 1, last
320                              is position -1) with the current charmap.
321                              ‘%spec’ pattern replaced by interpolating the
322                              format spec with its corresponding argument in
323                              args (‘%%’ is replaced by the ‘%’ character).
324
325   Character maps
326     When writing text strings that are meant to be displayed on the Game Boy,
327     the character encoding in the ROM may need to be different than the
328     source file encoding.  For example, the tiles used for uppercase letters
329     may be placed starting at tile index 128, which differs from ASCII start‐
330     ing at 65.
331
332     Character maps allow mapping strings to arbitrary 8-bit values:
333
334           CHARMAP "<LF>", 10
335           CHARMAP "&iacute", 20
336           CHARMAP "A", 128
337     This would result in ‘db "Amen<LF>"’ being equivalent to ‘db 128, 109,
338     101, 110, 10’.
339
340     Any characters in a string without defined mappings will be copied di‐
341     rectly, using the source file's encoding of characters to bytes.
342
343     It is possible to create multiple character maps and then switch between
344     them as desired.  This can be used to encode debug information in ASCII
345     and use a different encoding for other purposes, for example.  Initially,
346     there is one character map called ‘main’ and it is automatically selected
347     as the current character map from the beginning.  There is also a charac‐
348     ter map stack that can be used to save and restore which character map is
349     currently active.
350
351     Command                      Meaning
352     NEWCHARMAP name              Creates a new, empty character map called
353                                  name and switches to it.
354     NEWCHARMAP name, basename    Creates a new character map called name,
355                                  copied from character map basename, and
356                                  switches to it.
357     SETCHARMAP name              Switch to character map name.
358     PUSHC                        Push the current character map onto the
359                                  stack.
360     POPC                         Pop a character map off the stack and switch
361                                  to it.
362
363     Note: Modifications to a character map take effect immediately from that
364     point onward.
365
366   Other functions
367     There are a few other functions that do various useful things:
368
369     Name           Operation
370     BANK(arg)      Returns a bank number. If arg is the symbol @, this func‐
371                    tion returns the bank of the current section.  If arg is a
372                    string, it returns the bank of the section that has that
373                    name.  If arg is a label, it returns the bank number the
374                    label is in.  The result may be constant if rgbasm is able
375                    to compute it.
376     SIZEOF(arg)    Returns the size of the section named arg.  The result is
377                    not constant, since only RGBLINK can compute its value.
378     STARTOF(arg)   Returns the starting address of the section named arg.
379                    The result is not constant, since only RGBLINK can compute
380                    its value.
381     DEF(symbol)    Returns TRUE (1) if symbol has been defined, FALSE (0)
382                    otherwise.  String equates are not expanded within the
383                    parentheses.
384     HIGH(arg)      Returns the top 8 bits of the operand if arg is a label or
385                    constant, or the top 8-bit register if it is a 16-bit
386                    register.
387     LOW(arg)       Returns the bottom 8 bits of the operand if arg is a label
388                    or constant, or the bottom 8-bit register if it is a
389                    16-bit register (AF isn't a valid register for this
390                    function).
391     ISCONST(arg)   Returns 1 if arg's value is known by RGBASM (e.g. if it
392                    can be an argument to IF), or 0 if only RGBLINK can com‐
393                    pute its value.
394

SECTIONS

396     Before you can start writing code, you must define a section.  This tells
397     the assembler what kind of information follows and, if it is code, where
398     to put it.
399
400           SECTION name, type
401           SECTION name, type, options
402           SECTION name, type[addr]
403           SECTION name, type[addr], options
404
405     name is a string enclosed in double quotes, and can be a new name or the
406     name of an existing section.  If the type doesn't match, an error occurs.
407     All other sections must have a unique name, even in different source
408     files, or the linker will treat it as an error.
409
410     Possible section types are as follows:
411
412     ROM0    A ROM section.  addr can range from $0000 to $3FFF, or $0000 to
413             $7FFF if tiny ROM mode is enabled in the linker.
414
415     ROMX    A banked ROM section.  addr can range from $4000 to $7FFF.  bank
416             can range from 1 to 511.  Becomes an alias for ROM0 if tiny ROM
417             mode is enabled in the linker.
418
419     VRAM    A banked video RAM section.  addr can range from $8000 to $9FFF.
420             bank can be 0 or 1, but bank 1 is unavailable if DMG mode is en‐
421             abled in the linker.
422
423     SRAM    A banked external (save) RAM section.  addr can range from $A000
424             to $BFFF.  bank can range from 0 to 15.
425
426     WRAM0   A general-purpose RAM section.  addr can range from $C000 to
427             $CFFF, or $C000 to $DFFF if WRAM0 mode is enabled in the linker.
428
429     WRAMX   A banked general-purpose RAM section.  addr can range from $D000
430             to $DFFF.  bank can range from 1 to 7.  Becomes an alias for
431             WRAM0 if WRAM0 mode is enabled in the linker.
432
433     OAM     An object attribute RAM section.  addr can range from $FE00 to
434             $FE9F.
435
436     HRAM    A high RAM section.  addr can range from $FF80 to $FFFE.
437
438             Note: While rgbasm will automatically optimize ld instructions to
439             the smaller and faster ldh (see gbz80(7)) whenever possible, it
440             is generally unable to do so when a label is involved.  Using the
441             ldh instruction directly is recommended.  This forces the assem‐
442             bler to emit a ldh instruction and the linker to check if the
443             value is in the correct range.
444
445     Since RGBDS produces ROMs, code and data can only be placed in ROM0 and
446     ROMX sections.  To put some in RAM, have it stored in ROM, and copy it to
447     RAM.
448
449     options are comma-separated and may include:
450
451     BANK[bank]
452             Specify which bank for the linker to place the section in.  See
453             above for possible values for bank, depending on type.
454
455     ALIGN[align, offset]
456             Place the section at an address whose align least-significant
457             bits are equal to offset.  (Note that ALIGN[align] is a shorthand
458             for ALIGN[align, 0]).  This option can be used with [addr], as
459             long as they don't contradict eachother.  It's also possible to
460             request alignment in the middle of a section, see Requesting
461             alignment below.
462
463     If [addr] is not specified, the section is considered “floating”; the
464     linker will automatically calculate an appropriate address for the sec‐
465     tion.  Similarly, if BANK[bank] is not specified, the linker will auto‐
466     matically find a bank with enough space.
467
468     Sections can also be placed by using a linker script file.  The format is
469     described in rgblink(5).  They allow the user to place floating sections
470     in the desired bank in the order specified in the script.  This is useful
471     if the sections can't be placed at an address manually because the size
472     may change, but they have to be together.
473
474     Section examples:
475
476
477           SECTION "Cool Stuff",ROMX
478     This switches to the section called “CoolStuff”, creating it if it
479     doesn't already exist.  It can end up in any ROM bank.  Code and data may
480     follow.
481
482     If it is needed, the the base address of the section can be specified:
483
484           SECTION "Cool Stuff",ROMX[$4567]
485
486     An example with a fixed bank:
487
488           SECTION "Cool Stuff",ROMX[$4567],BANK[3]
489
490     And if you want to force only the section's bank, and not its position
491     within the bank, that's also possible:
492
493           SECTION "Cool Stuff",ROMX,BANK[7]
494
495     Alignment examples: The first one could be useful for defining an OAM
496     buffer to be DMA'd, since it must be aligned to 256 bytes.  The second
497     could also be appropriate for GBC HDMA, or for an optimized copy code
498     that requires alignment.
499
500           SECTION "OAM Data",WRAM0,ALIGN[8] ; align to 256 bytes
501           SECTION "VRAM Data",ROMX,BANK[2],ALIGN[4] ; align to 16 bytes
502
503   Section Stack
504     POPS and PUSHS provide the interface to the section stack.  The number of
505     entries in the stack is limited only by the amount of memory in your ma‐
506     chine.
507
508     PUSHS will push the current section context on the section stack.  POPS
509     can then later be used to restore it.  Useful for defining sections in
510     included files when you don't want to override the section context at the
511     point the file was included.
512
513   RAM Code
514     Sometimes you want to have some code in RAM.  But then you can't simply
515     put it in a RAM section, you have to store it in ROM and copy it to RAM
516     at some point.
517
518     This means the code (or data) will not be stored in the place it gets ex‐
519     ecuted.  Luckily, LOAD blocks are the perfect solution to that.  Here's
520     an example of how to use them:
521
522           SECTION "LOAD example", ROMX
523           CopyCode:
524               ld de, RAMCode
525               ld hl, RAMLocation
526               ld c, RAMLocation.end - RAMLocation
527           .loop
528               ld a, [de]
529               inc de
530               ld [hli], a
531               dec c
532               jr nz, .loop
533               ret
534
535           RAMCode:
536             LOAD "RAM code", WRAM0
537           RAMLocation:
538               ld hl, .string
539               ld de, $9864
540           .copy
541               ld a, [hli]
542               ld [de], a
543               inc de
544               and a
545               jr nz, .copy
546               ret
547
548           .string
549               db "Hello World!", 0
550           .end
551             ENDL
552
553     A LOAD block feels similar to a SECTION declaration because it creates a
554     new one.  All data and code generated within such a block is placed in
555     the current section like usual, but all labels are created as if they
556     were placed in this newly-created section.
557
558     In the example above, all of the code and data will end up in the "LOAD
559     example" section.  You will notice the ‘RAMCode’ and ‘RAMLocation’ la‐
560     bels.  The former is situated in ROM, where the code is stored, the lat‐
561     ter in RAM, where the code will be loaded.
562
563     You cannot nest LOAD blocks, nor can you change the current section
564     within them.
565
566     LOAD blocks can use the UNION or FRAGMENT modifiers, as described below.
567
568   Unionized Sections
569     When you're tight on RAM, you may want to define overlapping blocks of
570     variables, as explained in the Unions section.  However, the UNION key‐
571     word only works within a single file, which prevents e.g. defining tempo‐
572     rary variables on a single memory area across several files.  Unionized
573     sections solve this problem.  To declare an unionized section, add a
574     UNION keyword after the SECTION one; the declaration is otherwise not
575     different.  Unionized sections follow some different rules from normal
576     sections:
577
578           The same unionized section (= having the same name) can be de‐
579               clared several times per rgbasm invocation, and across several
580               invocations.  Different declarations are treated and merged
581               identically whether within the same invocation, or different
582               ones.
583
584           If one section has been declared as unionized, all sections
585               with the same name must be declared unionized as well.
586
587           All declarations must have the same type.  For example, even if
588               rgblink(1)'s -w flag is used, WRAM0 and WRAMX types are still
589               considered different.
590
591           Different constraints (alignment, bank, etc.) can be specified
592               for each unionized section declaration, but they must all be
593               compatible.  For example, alignment must be compatible with any
594               fixed address, all specified banks must be the same, etc.
595
596           Unionized sections cannot have type ROM0 or ROMX.
597
598     Different declarations of the same unionized section are not appended,
599     but instead overlaid on top of eachother, just like Unions.  Similarly,
600     the size of an unionized section is the largest of all its declarations.
601
602   Section Fragments
603     Section fragments are sections with a small twist: when several of the
604     same name are encountered, they are concatenated instead of producing an
605     error.  This works within the same file (paralleling the behavior "plain"
606     sections has in previous versions), but also across object files.  To de‐
607     clare an section fragment, add a FRAGMENT keyword after the SECTION one;
608     the declaration is otherwise not different.  However, similarly to
609     Unionized Sections, some rules must be followed:
610
611           If one section has been declared as fragment, all sections with
612               the same name must be declared fragments as well.
613
614           All declarations must have the same type.  For example, even if
615               rgblink(1)'s -w flag is used, WRAM0 and WRAMX types are still
616               considered different.
617
618           Different constraints (alignment, bank, etc.) can be specified
619               for each unionized section declaration, but they must all be
620               compatible.  For example, alignment must be compatible with any
621               fixed address, all specified banks must be the same, etc.
622
623           A section fragment may not be unionized; after all, that
624               wouldn't make much sense.
625
626     When RGBASM merges two fragments, the one encountered later is appended
627     to the one encountered earlier.
628
629     When RGBLINK merges two fragments, the one whose file was specified last
630     is appended to the one whose file was specified first.  For example, as‐
631     suming ‘bar.o’, ‘baz.o’, and ‘foo.o’ all contain a fragment with the same
632     name, the command
633           rgblink -o rom.gb baz.o foo.o bar.o
634     would produce the fragment from ‘baz.o’ first, followed by the one from
635     ‘foo.o’, and the one from ‘bar.o’ last.
636

SYMBOLS

638     RGBDS supports several types of symbols:
639
640     Label   Numerical symbol designating a memory location.  May or may not
641             have a value known at assembly time.
642
643     Constant Numerical symbol whose value has to be known at assembly time.
644
645     Macro   A block of rgbasm code that can be invoked later.
646
647     String equate A text string that can be expanded later, similarly to a
648             macro.
649
650     Symbol names can contain letters, numbers, underscores ‘_’, hashes ‘#’
651     and at signs ‘@’.  However, they must begin with either a letter or an
652     underscore.  Periods ‘.’ are allowed exclusively in labels, as described
653     below.  A symbol cannot have the same name as a reserved keyword.
654
655   Label declaration
656     One of the assembler's main tasks is to keep track of addresses for you,
657     so you can work with meaningful names instead of "magic" numbers.
658
659     This can be done in a number of ways:
660
661           GlobalLabel:
662           AnotherGlobal:
663           .locallabel
664           .another_local:
665           AnotherGlobal.with_another_local:
666           ThisWillBeExported:: ; Note the two colons
667           ThisWillBeExported.too::
668
669     Any label whose name does not contain a period is a global label.
670     Declaring a global label sets it as the current scoped label, until the
671     next global one.  Global labels must be followed by one or two colons.
672
673     Any label whose name contains a single period is a local label.  Label
674     names cannot contain more than one period.  If the period is the first
675     character, it will have the current scoped label's name implicitly
676     prepended.  Local labels may optionally be followed by one or two colons.
677     Local labels can be declared as ‘scoped.local’ or simply as ‘.local’.  If
678     the former notation is used, then ‘scoped’ must actually be the current
679     scoped label.
680
681     Declaring a label (global or local) with two colons ‘::’ will EXPORT and
682     define it at the same time.  (See Exporting and importing symbols below).
683
684     Anonymous labels are useful for short blocks of code.  They are defined
685     like normal labels, but without a name before the colon.  Anonymous la‐
686     bels are independent of label scoping, so defining one does not change
687     the scoped label, and referencing one is not affected by the current
688     scoped label.
689
690     Anonymous labels are referenced using a colon ‘:’ followed by pluses ‘+’
691     or minuses ‘-’.  Thus :+ references the next one after the expression,
692     :++ the one after that; :- references the one before the expression; and
693     so on.
694
695               ld hl, :++
696           :   ld a, [hli] ; referenced by "jr nz"
697               ldh [c], a
698               dec c
699               jr nz, :-
700               ret
701
702           :   ; referenced by "ld hl"
703               dw $7FFF, $1061, $03E0, $58A5
704
705     A label's location (and thus value) is usually not determined until the
706     linking stage, so labels usually cannot be used as constants.  However,
707     if the section in which the label is declared has a fixed base address,
708     its value is known at assembly time.
709
710     rgbasm is able to compute the subtraction of two labels either if both
711     are constant as described above, or if both belong to the same section.
712
713   Immutable constants
714     EQU is used to define numerical constant symbols.  Unlike SET below, con‐
715     stants defined this way cannot be redefined.  These constants can be used
716     for unchanging values such as properties of the hardware.
717
718           def SCREEN_WIDTH  equ 160 ; In pixels
719           def SCREEN_HEIGHT equ 144
720
721     Note that colons ‘:’ following the name are not allowed.
722
723     If you really need to, the REDEF keyword will define or redefine a con‐
724     stant symbol.  This can be used, for example, to update a constant using
725     a macro, without making it mutable in general.
726
727               def NUM_ITEMS equ 0
728           MACRO add_item
729               redef NUM_ITEMS equ NUM_ITEMS + 1
730               def ITEM_{02x:NUM_ITEMS} equ 1
731           ENDM
732               add_item 1
733               add_item 4
734               add_item 9
735               add_item 16
736               assert NUM_ITEMS == 4
737               assert ITEM_04 == 16
738
739   Mutable constants
740     SET, or its synonym =, is used to define numerical symbols like EQU, but
741     these symbols can be redefined.  This is useful for variables in macros,
742     for counters, etc.
743
744           DEF ARRAY_SIZE EQU 4
745           DEF   COUNT SET 2
746           DEF   COUNT SET 3
747           REDEF COUNT SET ARRAY_SIZE+COUNT
748           COUNT = COUNT*2
749           ; COUNT now has the value 14
750
751     Note that colons ‘:’ following the name are not allowed.
752
753   Offset constants
754     The RS group of commands is a handy way of defining structure offsets:
755
756                          RSRESET
757           DEF str_pStuff RW   1
758           DEF str_tData  RB   256
759           DEF str_bCount RB   1
760           DEF str_SIZEOF RB   0
761
762     The example defines four constants as if by:
763
764           DEF str_pStuff EQU 0
765           DEF str_tData  EQU 2
766           DEF str_bCount EQU 258
767           DEF str_SIZEOF EQU 259
768
769     There are five commands in the RS group of commands:
770
771     Command            Meaning
772     RSRESET            Equivalent to ‘RSSET 0’.
773     RSSET constexpr    Sets the _RS counter to constexpr.
774     RB constexpr       Sets the preceding symbol to _RS and adds constexpr to
775                        _RS.
776     RW constexpr       Sets the preceding symbol to _RS and adds constexpr *
777                        2 to _RS.
778     RL constexpr       Sets the preceding symbol to _RS and adds constexpr *
779                        4 to _RS.
780
781     If the argument to RB, RW, or RL is omitted, it's assumed to be 1.
782
783     Note that colons ‘:’ following the name are not allowed.
784
785   String equates
786     EQUS is used to define string equate symbols.  Wherever the assembler
787     reads a string equate, it gets expanded: the symbol's name is replaced
788     with its contents.  If you are familiar with C, you can think of it as
789     similar to #define .
790     This expansion is disabled in a few contexts: ‘DEF(name)’, ‘DEF name
791     EQU/SET/EQUS/etc ...’, ‘PURGE name’, and ‘MACRO name’ will not expand
792     string equates in their names.
793
794           DEF COUNTREG EQUS "[hl+]"
795               ld a,COUNTREG
796
797           DEF PLAYER_NAME EQUS "\"John\""
798               db PLAYER_NAME
799
800     This will be interpreted as:
801
802               ld a,[hl+]
803               db "John"
804
805     String equates can also be used to define small one-line macros:
806
807           DEF pusha EQUS "push af\npush bc\npush de\npush hl\n"
808
809     Note that colons ‘:’ following the name are not allowed.
810
811     String equates can't be exported or imported.
812
813     String equates, like EQU constants, cannot be redefined.  However, the
814     REDEF keyword will define or redefine a string symbol.  For example:
815
816           DEF s EQUS "Hello, "
817           REDEF s EQUS "{s}world!"
818           ; prints "Hello, world!"
819           PRINTLN "{s}0
820
821     Important note: An EQUS can be expanded to a string that contains another
822     EQUS and it will be expanded as well.  If this creates an infinite loop,
823     rgbasm will error out once a certain depth is reached.  See the -r com‐
824     mand-line option in rgbasm(1).  Also, a macro can contain an EQUS which
825     calls the same macro, which causes the same problem.
826
827     The examples above for ‘EQU’, ‘SET’ or ‘=’, ‘RB’, ‘RW’, ‘RL’, and ‘EQUS’
828     all start with ‘DEF’.  (A ‘SET’ or ‘=’ definition may start with ‘REDEF’
829     instead, since they are redefinable.)  You may use the older syntax with‐
830     out ‘DEF’, but then the name being defined must not have any whitespace
831     before it; otherwise rgbasm will treat it as a macro invocation.  Fur‐
832     thermore, without the ‘DEF’ keyword, string equates may be expanded for
833     the name.  This can lead to surprising results:
834
835           X EQUS "Y"
836           ; this defines Y, not X!
837           X EQU 42
838           ; prints "Y $2A"
839           PRINTLN "{X} {Y}"
840
841   Macros
842     One of the best features of an assembler is the ability to write macros
843     for it.  Macros can be called with arguments, and can react depending on
844     input using IF constructs.
845
846           MACRO MyMacro
847                    ld a, 80
848                    call MyFunc
849           ENDM
850
851     The example above defines ‘MyMacro’ as a new macro.  String equates are
852     not expanded within the name of the macro.  You may use the older syntax
853     ‘MyMacro: MACRO’ instead of ‘MACRO MyMacro’, with a single colon ‘:’ fol‐
854     lowing the macro's name.  With the older syntax, string equates may be
855     expanded for the name.
856
857     Macros can't be exported or imported.
858
859     Plainly nesting macro definitions is not allowed, but this can be worked
860     around using EQUS.  So this won't work:
861
862           MACRO outer
863               MACRO inner
864                   PRINTLN "Hello!"
865               ENDM
866           ENDM
867
868     But this will:
869
870           MACRO outer
871           DEF definition EQUS "MACRO inner\nPRINTLN \"Hello!\"\nENDM"
872               definition
873               PURGE definition
874           ENDM
875
876     Macro arguments support all the escape sequences of strings, as well as
877     ‘\,’ to escape commas, as well as ‘\(’ and ‘\)’ to escape parentheses,
878     since those otherwise separate and enclose arguments, respectively.
879
880   Exporting and importing symbols
881     Importing and exporting of symbols is a feature that is very useful when
882     your project spans many source files and, for example, you need to jump
883     to a routine defined in another file.
884
885     Exporting of symbols has to be done manually, importing is done automati‐
886     cally if rgbasm finds a symbol it does not know about.
887
888     The following will cause symbol1, symbol2 and so on to be accessible to
889     other files during the link process:
890           EXPORT symbol1 [, symbol2, ...]
891
892     For example, if you have the following three files:
893
894     ‘a.asm’:
895     SECTION "a", WRAM0
896     LabelA:
897
898     ‘b.asm’:
899     SECTION "b", WRAM0
900     ExportedLabelB1::
901     ExportedLabelB2:
902             EXPORT ExportedLabelB2
903
904     ‘c.asm’:
905     SECTION "C", ROM0[0]
906             dw LabelA
907             dw ExportedLabelB1
908             dw ExportedLabelB2
909
910     Then ‘c.asm’ can use ‘ExportedLabelB1’ and ‘ExportedLabelB2’, but not
911     ‘LabelA’, so linking them together will fail:
912
913     $ rgbasm -o a.o a.asm
914     $ rgbasm -o b.o b.asm
915     $ rgbasm -o c.o c.asm
916     $ rgblink a.o b.o c.o
917     error: c.asm(2): Unknown symbol "LabelA"
918     Linking failed with 1 error
919
920     Note also that only exported symbols will appear in symbol and map files
921     produced by rgblink(1).
922
923   Purging symbols
924     PURGE allows you to completely remove a symbol from the symbol table as
925     if it had never existed.  USE WITH EXTREME CAUTION!!! I can't stress this
926     enough, you seriously need to know what you are doing.  DON'T purge a
927     symbol that you use in expressions the linker needs to calculate.  When
928     not sure, it's probably not safe to purge anything other than string sym‐
929     bols, macros, and constants.
930
931           DEF Kamikaze EQUS  "I don't want to live anymore"
932           DEF AOLer    EQUS  "Me too"
933                    PURGE Kamikaze, AOLer
934
935     String equates are not expanded within the symbol names.
936
937   Predeclared Symbols
938     The following symbols are defined by the assembler:
939
940           Name    Type                  Contents
941           @       EQU                   PC value (essentially, the current
942                                         memory address)
943           _RS     SET                   _RS Counter
944           _NARG   EQU                   Number of arguments passed to macro,
945                                         updated by SHIFT
946           __LINE__                      EQUThe current line number
947           __FILE__                      EQUSThe current filename
948           __DATE__                      EQUSToday's date
949           __TIME__                      EQUSThe current time
950           __ISO_8601_LOCAL__            EQUSISO 8601 timestamp (local)
951           __ISO_8601_UTC__              EQUSISO 8601 timestamp (UTC)
952           __UTC_YEAR__                  EQUToday's year
953           __UTC_MONTH__                 EQUToday's month number, 1–12
954           __UTC_DAY__                   EQUToday's day of the month, 1–31
955           __UTC_HOUR__                  EQUCurrent hour, 0–23
956           __UTC_MINUTE__                EQUCurrent minute, 0–59
957           __UTC_SECOND__                EQUCurrent second, 0–59
958           __RGBDS_MAJOR__               EQUMajor version number of RGBDS
959           __RGBDS_MINOR__               EQUMinor version number of RGBDS
960           __RGBDS_PATCH__               EQUPatch version number of RGBDS
961           __RGBDS_RC__                  EQURelease candidate ID of RGBDS, not
962                                         defined for final releases
963           __RGBDS_VERSION__             EQUSVersion of RGBDS, as printed by
964                                         ‘rgbasm --version’
965
966     The current time values will be taken from the SOURCE_DATE_EPOCH environ‐
967     ment variable if that is defined as a UNIX timestamp.  Refer to the spec
968     at https://reproducible-builds.org/docs/source-date-epoch/
969

DEFINING DATA

971   Declaring variables in a RAM section
972     DS allocates a number of empty bytes.  This is the preferred method of
973     allocating space in a RAM section.  You can also use DB, DW and DL with‐
974     out any arguments instead (see Defining constant data below).
975
976           DS 42 ; Allocates 42 bytes
977
978     Empty space in RAM sections will not be initialized.  In ROM sections, it
979     will be filled with the value passed to the -p command-line option, ex‐
980     cept when using overlays with -O.
981
982   Defining constant data
983     DB defines a list of bytes that will be stored in the final image.  Ideal
984     for tables and text.
985
986           DB 1,2,3,4,"This is a string"
987
988     Alternatively, you can use DW to store a list of words (16-bit) or DL to
989     store a list of double-words/longs (32-bit).
990
991     Strings are handled a little specially: they first undergo charmap con‐
992     version (see Character maps), then each resulting character is output in‐
993     dividually.  For example, under the default charmap, the following two
994     lines are identical:
995
996           DW "Hello!"
997           DW "H", "e", "l", "l", "o", "!"
998
999     If you do not want this special handling, enclose the string in parenthe‐
1000     ses.
1001
1002     DS can also be used to fill a region of memory with some repeated values.
1003     For example:
1004
1005           ; outputs 3 bytes: $AA, $AA, $AA
1006           DS 3, $AA
1007           ; outputs 7 bytes: $BB, $CC, $BB, $CC, $BB, $CC, $BB
1008           DS 7, $BB, $CC
1009
1010     You can also use DB, DW and DL without arguments.  This works exactly
1011     like DS 1, DS 2 and DS 4 respectively.  Consequently, no-argument DB, DW
1012     and DL can be used in a WRAM0 / WRAMX / HRAM / VRAM / SRAM section.
1013
1014   Including binary files
1015     You probably have some graphics, level data, etc. you'd like to include.
1016     Use INCBIN to include a raw binary file as it is.  If the file isn't
1017     found in the current directory, the include-path list passed to rgbasm(1)
1018     (see the -i option) on the command line will be searched.
1019
1020           INCBIN "titlepic.bin"
1021           INCBIN "sprites/hero.bin"
1022
1023     You can also include only part of a file with INCBIN.  The example below
1024     includes 256 bytes from data.bin, starting from byte 78.
1025
1026           INCBIN "data.bin",78,256
1027
1028     The length argument is optional.  If only the start position is speci‐
1029     fied, the bytes from the start position until the end of the file will be
1030     included.
1031
1032   Unions
1033     Unions allow multiple memory allocations to overlap, like unions in C.
1034     This does not increase the amount of memory available, but allows re-us‐
1035     ing the same memory region for different purposes.
1036
1037     A union starts with a UNION keyword, and ends at the corresponding ENDU
1038     keyword.  NEXTU separates each block of allocations, and you may use it
1039     as many times within a union as necessary.
1040
1041               ; Let's say PC = $C0DE here
1042               UNION
1043               ; Here, PC = $C0DE
1044           Name: ds 8
1045               ; PC = $C0E6
1046           Nickname: ds 8
1047               ; PC = $C0EE
1048               NEXTU
1049               ; PC is back to $C0DE
1050           Health: dw
1051               ; PC = $C0E0
1052           Something: ds 6
1053               ; And so on
1054           Lives: db
1055               NEXTU
1056           VideoBuffer: ds 19
1057               ENDU
1058
1059     In the example above, ‘Name, Health, VideoBuffer’ all have the same
1060     value, as do ‘Nickname’ and ‘Lives’.  Thus, keep in mind that ld
1061     [Health], a is identical to ld [Name], a.
1062
1063     The size of this union is 19 bytes, as this is the size of the largest
1064     block (the last one, containing ‘VideoBuffer’).  Nesting unions is possi‐
1065     ble, with each inner union's size being considered as described above.
1066
1067     Unions may be used in any section, but inside them may only be DS - like
1068     commands (see Declaring variables in a RAM section).
1069

THE MACRO LANGUAGE

1071   Invoking macros
1072     You execute the macro by inserting its name.
1073
1074                    add a,b
1075                    ld sp,hl
1076                    MyMacro ; This will be expanded
1077                    sub a,87
1078
1079     It's valid to call a macro from a macro (yes, even the same one).
1080
1081     When rgbasm sees MyMacro it will insert the macro definition (the code
1082     enclosed in MACRO / ENDM).
1083
1084     Suppose your macro contains a loop.
1085
1086           MACRO LoopyMacro
1087                       xor  a,a
1088           .loop       ld   [hl+],a
1089                       dec  c
1090                       jr   nz,.loop
1091           ENDM
1092
1093     This is fine, but only if you use the macro no more than once per scope.
1094     To get around this problem, there is the escape sequence \@ that expands
1095     to a unique string.
1096
1097     \@ also works in REPT blocks.
1098
1099           MACRO LoopyMacro
1100                       xor  a,a
1101           .loop\@     ld   [hl+],a
1102                       dec  c
1103                       jr   nz,.loop\@
1104           ENDM
1105
1106     Important note: Since a macro can call itself (or a different macro that
1107     calls the first one), there can be circular dependency problems.  If this
1108     creates an infinite loop, rgbasm will error out once a certain depth is
1109     reached.  See the -r command-line option in rgbasm(1).  Also, a macro can
1110     have inside an EQUS which references the same macro, which has the same
1111     problem.
1112
1113     It's possible to pass arguments to macros as well!  You retrieve the ar‐
1114     guments by using the escape sequences \1 through \9, \1 being the first
1115     argument specified on the macro invocation.
1116
1117           MACRO LoopyMacro
1118                       ld   hl,\1
1119                       ld   c,\2
1120                       xor  a,a
1121           .loop\@     ld   [hl+],a
1122                       dec  c
1123                       jr   nz,.loop\@
1124                       ENDM
1125
1126     Now you can call the macro specifying two arguments, the first being the
1127     address and the second being a byte count.  The generated code will then
1128     reset all bytes in this range.
1129
1130           LoopyMacro MyVars,54
1131
1132     Arguments are passed as string equates, although there's no need to en‐
1133     close them in quotes.  Thus, an expression will not be evaluated first
1134     but kind of copy-pasted.  This means that it's probably a very good idea
1135     to use brackets around \1 to \9 if you perform further calculations on
1136     them.  For instance, consider the following:
1137
1138           MACRO print_double
1139               PRINTLN \1 * 2
1140           ENDM
1141               print_double 1 + 2
1142
1143     The PRINTLN statement will expand to ‘PRINTLN 1 + 2 * 2’, which will
1144     print 5 and not 6 as you might have expected.
1145
1146     Line continuations work as usual inside macros or lists of macro argu‐
1147     ments.  However, some characters need to be escaped, as in the following
1148     example:
1149
1150           MACRO PrintMacro1
1151               PRINTLN STRCAT(\1)
1152           ENDM
1153               PrintMacro1 "Hello "\, \
1154                                  "world"
1155           MACRO PrintMacro2
1156               PRINT \1
1157           ENDM
1158               PrintMacro2 STRCAT("Hello ", \
1159                                  "world\n")
1160
1161     The comma in ‘PrintMacro1’ needs to be escaped to prevent it from start‐
1162     ing another macro argument.  The comma in ‘PrintMacro2’ does not need es‐
1163     caping because it is inside parentheses, similar to macro arguments in C.
1164     The backslash in ‘\n’ also does not need escaping because string literals
1165     work as usual inside macro arguments.
1166
1167     Since there are only nine digits, you can only access the first nine
1168     macro arguments like this.  To use the rest, you need to put the multi-
1169     digit argument number in angle brackets, like ‘\<10>’.  This bracketed
1170     syntax supports decimal numbers and numeric symbol names.  For example,
1171     ‘\<_NARG>’ will get the last argument.
1172
1173     Other macro arguments and symbol interpolations will be expanded inside
1174     the angle brackets.  For example, if ‘\1’ is ‘13’, then ‘\<\1>’ will ex‐
1175     pand to ‘\<13>’.  Or if ‘v10 = 42’ and ‘x = 10’, then ‘\<v{d:x}>’ will
1176     expand to ‘\<42>’.
1177
1178     Another way to access more than nine macro arguments is the SHIFT com‐
1179     mand, a special command only available in macros.  It will shift the ar‐
1180     guments by one to the left, and decrease _NARG by 1.  \1 will get the
1181     value of \2, \2 will get the value of \3, and so forth.
1182
1183     SHIFT can optionally be given an integer parameter, and will apply the
1184     above shifting that number of times.  A negative parameter will shift the
1185     arguments in reverse.
1186
1187     SHIFT is useful in REPT blocks to repeat the same commands with multiple
1188     arguments.
1189
1190   Printing things during assembly
1191     The PRINT and PRINTLN commands print text and values to the standard out‐
1192     put.  Useful for debugging macros, or wherever you may feel the need to
1193     tell yourself some important information.
1194
1195           PRINT "Hello world!\n"
1196           PRINTLN "Hello world!"
1197           PRINT _NARG, " arguments\n"
1198           PRINTLN "sum: ", 2+3, " product: ", 2*3
1199           PRINTLN "Line #", __LINE__
1200           PRINTLN STRFMT("E = %f", 2.718)
1201
1202     PRINT prints out each of its comma-separated arguments.  Numbers are
1203     printed as unsigned uppercase hexadecimal with a leading $.  For differ‐
1204     ent formats, use STRFMT.
1205
1206     PRINTLN prints out each of its comma-separated arguments, if any, fol‐
1207     lowed by a line feed (‘\n’).
1208
1209   Automatically repeating blocks of code
1210     Suppose you want to unroll a time consuming loop without copy-pasting it.
1211     REPT is here for that purpose.  Everything between REPT and the matching
1212     ENDR will be repeated a number of times just as if you had done a
1213     copy/paste operation yourself.  The following example will assemble ‘add
1214     a,c’ four times:
1215
1216           REPT 4
1217             add  a,c
1218           ENDR
1219
1220     You can also use REPT to generate tables on the fly:
1221
1222           ; Generate a 256-byte sine table with values in the range [0, 128]
1223           ; (shifted and scaled from the range [-1.0, 1.0])
1224           ANGLE = 0.0
1225               REPT 256
1226                   db (MUL(64.0, SIN(ANGLE)) + 64.0) >> 16
1227           ANGLE = ANGLE + 256.0 ; 256.0 = 65536 degrees / 256 entries
1228               ENDR
1229
1230     As in macros, you can also use the escape sequence \@.  REPT blocks can
1231     be nested.
1232
1233     A common pattern is to repeat a block for each value in some range.  FOR
1234     is simpler than REPT for that purpose.  Everything between FOR and the
1235     matching ENDR will be repeated for each value of a given symbol.  String
1236     equates are not expanded within the symbol name.  For example, this code
1237     will produce a table of squared values from 0 to 255:
1238
1239           FOR N, 256
1240                 dw N * N
1241           ENDR
1242
1243     It acts just as if you had done:
1244
1245          N = 0
1246                dw N * N
1247          N = 1
1248                dw N * N
1249          N = 2
1250                dw N * N
1251          ; ...
1252          N = 255
1253                dw N * N
1254          N = 256
1255
1256     You can customize the range of FOR values:
1257
1258     Code                        Range
1259     FOR V, stop                 V increments from 0 to stop
1260     FOR V, start, stop          V increments from start to stop
1261     FOR V, start, stop, step    V goes from start to stop by step
1262
1263     The FOR value will be updated by step until it reaches or exceeds stop.
1264     For example:
1265
1266           FOR V, 4, 25, 5
1267                 PRINT "{d:V} "
1268           ENDR
1269                 PRINTLN "done {d:V}"
1270     This will print:
1271
1272           4 9 14 19 24 done 29
1273
1274     Just like with REPT blocks, you can use the escape sequence \@ inside of
1275     FOR blocks, and they can be nested.
1276
1277     You can stop a repeating block with the BREAK command.  A BREAK inside of
1278     a REPT or FOR block will interrupt the current iteration and not repeat
1279     any more.  It will continue running code after the block's ENDR.  For ex‐
1280     ample:
1281
1282           FOR V, 1, 100
1283                 PRINT "{d:V}"
1284                 IF V == 5
1285                     PRINT " stop! "
1286                     BREAK
1287                 ENDC
1288                 PRINT ", "
1289           ENDR
1290                 PRINTLN "done {d:V}"
1291     This will print:
1292
1293           1, 2, 3, 4, 5 stop! done 5
1294
1295   Aborting the assembly process
1296     FAIL and WARN can be used to print errors and warnings respectively dur‐
1297     ing the assembly process.  This is especially useful for macros that get
1298     an invalid argument.  FAIL and WARN take a string as the only argument
1299     and they will print this string out as a normal error with a line number.
1300
1301     FAIL stops assembling immediately while WARN shows the message but con‐
1302     tinues afterwards.
1303
1304     If you need to ensure some assumption is correct when compiling, you can
1305     use ASSERT and STATIC_ASSERT.  Syntax examples are given below:
1306
1307           Function:
1308                 xor a
1309           ASSERT LOW(Variable) == 0
1310                 ld h, HIGH(Variable)
1311                 ld l, a
1312                 ld a, [hli]
1313                 ; You can also indent this!
1314                 ASSERT BANK(OtherFunction) == BANK(Function)
1315                 call OtherFunction
1316           ; Lowercase also works
1317           assert Variable + 1 == OtherVariable
1318                 ld c, [hl]
1319                 ret
1320           .end
1321                 ; If you specify one, a message will be printed
1322                 STATIC_ASSERT .end - Function < 256, "Function is too large!"
1323
1324     First, the difference between ASSERT and STATIC_ASSERT is that the former
1325     is evaluated by RGBASM if it can, otherwise by RGBLINK; but the latter is
1326     only ever evaluated by RGBASM.  If RGBASM cannot compute the value of the
1327     argument to STATIC_ASSERT, it will produce an error.
1328
1329     Second, as shown above, a string can be optionally added at the end, to
1330     give insight into what the assertion is checking.
1331
1332     Finally, you can add one of WARN, FAIL or FATAL as the first optional ar‐
1333     gument to either ASSERT or STATIC_ASSERT.  If the assertion fails, WARN
1334     will cause a simple warning (controlled by rgbasm(1) flag -Wassert) to be
1335     emitted; FAIL (the default) will cause a non-fatal error; and FATAL imme‐
1336     diately aborts.
1337
1338   Including other source files
1339     Use INCLUDE to process another assembler file and then return to the cur‐
1340     rent file when done.  If the file isn't found in the current directory,
1341     the include path list (see the -i option in rgbasm(1)) will be searched.
1342     You may nest INCLUDE calls infinitely (or until you run out of memory,
1343     whichever comes first).
1344
1345               INCLUDE "irq.inc"
1346
1347   Conditional assembling
1348     The four commands IF, ELIF, ELSE, and ENDC let you have rgbasm skip over
1349     parts of your code depending on a condition.  This is a powerful feature
1350     commonly used in macros.
1351
1352           IF NUM < 0
1353             PRINTLN "NUM < 0"
1354           ELIF NUM == 0
1355             PRINTLN "NUM == 0"
1356           ELSE
1357             PRINTLN "NUM > 0"
1358           ENDC
1359
1360     The ELIF (standing for "else if") and ELSE blocks are optional.  IF /
1361     ELIF / ELSE / ENDC blocks can be nested.
1362
1363     Note that if an ELSE block is found before an ELIF block, the ELIF block
1364     will be ignored.  All ELIF blocks must go before the ELSE block.  Also,
1365     if there is more than one ELSE block, all of them but the first one are
1366     ignored.
1367

MISCELLANEOUS

1369   Changing options while assembling
1370     OPT can be used to change some of the options during assembling from
1371     within the source, instead of defining them on the command-line.
1372
1373     OPT takes a comma-separated list of options as its argument:
1374
1375           PUSHO
1376               OPT g.oOX, Wdiv, L    ; acts like command-line -g.oOX -Wdiv -L
1377               DW `..ooOOXX          ; uses the graphics constant characters from OPT g
1378               PRINTLN $80000000/-1  ; prints a warning about division
1379               LD [$FF88], A         ; encoded as LD, not LDH
1380           POPO
1381               DW `00112233          ; uses the default graphics constant characters
1382               PRINTLN $80000000/-1  ; no warning by default
1383               LD [$FF88], A         ; optimized to use LDH by default
1384
1385     The options that OPT can modify are currently: b, g, p, h, L, and W.  The
1386     Boolean flag options h and L can be negated as ‘OPT !h’ and ‘OPT !L’ to
1387     act like omitting them from the command-line.
1388
1389     POPO and PUSHO provide the interface to the option stack.  PUSHO will
1390     push the current set of options on the option stack.  POPO can then later
1391     be used to restore them.  Useful if you want to change some options in an
1392     include file and you don't want to destroy the options set by the program
1393     that included your file.  The stack's number of entries is limited only
1394     by the amount of memory in your machine.
1395
1396   Requesting alignment
1397     While ALIGN as presented in SECTIONS is often useful as-is, sometimes you
1398     instead want a particular piece of data (or code) in the middle of the
1399     section to be aligned.  This is made easier through the use of mid-sec‐
1400     tion align align, offset.  It will alter the section's attributes to en‐
1401     sure that the location the align directive is at, has its align lower
1402     bits equal to offset.
1403
1404     If the constraint cannot be met (for example because the section is fixed
1405     at an incompatible address), and error is produced.  Note that align
1406     align is a shorthand for align align, 0.
1407

SEE ALSO

1409     rgbasm(1), rgblink(1), rgblink(5), rgbds(5), rgbds(7), gbz80(7)
1410

HISTORY

1412     rgbasm was originally written by Carsten Sørensen as part of the ASMotor
1413     package, and was later packaged in RGBDS by Justin Lloyd.  It is now
1414     maintained by a number of contributors at https://github.com/gbdev/rgbds
1415
1416BSD                             March 28, 2021                             BSD
Impressum