\begin{savequote}
\sffamily
``Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.''
\qauthor{Martin Golding}


\end{savequote}


\chapter{Source Code}
\index{Source Code}
\label{changelog:20200908source}

\section{Encoding}
\index{Source Code!Format!Encoding}

Source code files are written as plain-text (generally ASCII encoding) files.

\index{Source Code!Format!End-of-Line}
Both Windows-style (carriage-return, line-feed) and Unix-style (line-feed) line endings are supported by \dasm.

\section{Comments}
\index{Comments}
\index{Source Code!Comments}
\label{changelog:20200909comment}

\dasm supports two different comment styles: traditional assembler single-line semicolon-delimited comments, and C-style ``\mono{/* ... */}'' delimited multiline comments.

\index{Source Code!Format!Unicode}
Note that comments may contain Unicode characters, as \dasm effectively ignores the contents of comments, but assembled code cannot contain Unicode.

An open comment directive anywhere on a line ("\mono{;}" or "\mono{/*}") terminates \dasm's label/directive/instruction parser for the rest of that line.

\subsection{Assembler-style Comments: ;...}
\index{Source Code!Comments!Assembler-style}
\index{Comments!Assembler-style}

The presence of a semicolon at any character in a line will flag the rest of that line (semicolon included) as a comment. It is common when writing code to place a semicolon at the beginning of lines to disable them from being assembled.

There may be valid labels, directives, and/or instructions before the comment. These will be correctly assembled.

\subsubsection{Examples}
\index{Examples!Comment Styles}
\begin{code}
; this is a comment
      ; and so is this
label ; this is a label followed by a comment
;label   this is a comment, NOT a label
  lda #2 ; <-- this instruction IS assembled
  ;lda #2   <-- this instruction is NOT assembled
\end{code}

\begin{code}
  MAC TEST ;{1}=value  <-- a comment showing params
  ENDM
\end{code}  

\subsection{C-style Comments: /* ... */ }
\index{Source Code!Comments!C-style}
\index{Comments!C-style}

C-style comments mark all text between and including \mono{/*} and \mono{*/} as a comment.

C-style comments make it easy to disable the assembly of blocks of code spanning multiple lines.

\subsubsection{Correct Examples}
\begin{code}
/* This single line comment is valid */
 lda #1 /* And this comment is valid too */

/* And so is this
Multiline comment */


\end{code}

It can sometimes be useful to enable/disable multi-line comments with a semicolon...

\begin{code}
;/*
 lda #2  ;<-- comment disabled. This IS assembled
;*/

/*
 lda #2  ;<-- comment enabled. This is NOT assembled
 */
\end{code}

\subsection{Commenting Out Large Blocks}
\index{Source Code!Comments!Disabling Large Blocks}
\index{Comments!Disabling Large Blocks}

There are several ways to disable ("comment-out") large parts of the source code.

\begin{itemize}
\item Place a semicolon at the start of every line of the code to disable (Assembler-style)
\item Bracket the part to disable with \mono{/*} and \mono{*/}  (C-style)
\item Surround the block with the conditionals "\mono{IF 0}" at the start, followed by "\mono{ENDIF}" at the end. To re-enable the code, change the \mono{0} to \mono{1}. Note that this method is may fail if the enclosed code has conditionals.
\end{itemize}



\chapter{Command-Line}
\index{Command Line}
%\index{AUV!\emph{dasm}}
%\label{chap:Starbug}

%\lstset{basicstyle=\linespread{0.5}}

%	{\centering
%	\fbox{\includegraphics[width=5in]{dasm-logo.png}}}




\section{Usage}
\index{Command Line!Usage}
\dasm is a command-line tool. It parses the command-line for the input source file, which must be present, and optional assemble-time options, assembles the source file, and produces outputs as specified in the options. The source file must be ASCII-encoded, but comments may contain Unicode characters.

One option you are most likely to need is \nameref{flag:outputfile} to specify the binary file for output.

The assembler will return 0 on successful compilation, 1 otherwise.

\begin{usage}
dasm
dasm sourcefile
dasm sourcefile [option ...]
\end{usage}

\label{changelog:20200824sourcefile}
If no \mono{sourcefile} is given, then \dasm will output a short help message, and exit with an assembly error. Otherise, the \mono{sourcefile} becomes the file that \dasm will assemble, and any further parameters are parsed as options.

\label{changelog:20200831help}
\begin{outputx2}
% ./dasm
DASM 2.20.14
Copyright (c) 1988-2020 by the DASM team.
License GPLv2+: GNU GPL version 2 or later (see file LICENSE).
DASM is free software: you are free to change and redistribute it.
There is ABSOLUTELY NO WARRANTY, to the extent permitted by law.

Usage: dasm sourcefile [options]

-f#      output format 1-3 (default 1)
-oname   output file name (else a.out)
-lname   list file name (else none generated)
-Lname   list file, containing all passes
-sname   symbol dump file name (else none generated)
-v#      verboseness 0-4 (default 0)
-d       debug mode (for developers)
-Dsymbol              define symbol, set to 0
-Dsymbol=expression   define symbol, set to expression
-Msymbol=expression   define symbol using EQM (same as -D)
-Idir    search directory for INCLUDE and INCBIN
-p#      maximum number of passes
-P#      maximum number of passes, with fewer checks
-T#      symbol table sorting
         (default 0 = alphabetical, 1 = address/value)
-E#      error format (default 0 = MS, 1 = Dillon, 2 = GNU)
-S       strict syntax checking
-R       remove binary output-file in case of errors
-m#      max. allowed file-size in kB

Report bugs on https://github.com/dasm-assembler/dasm please!


Fatal assembly error: Check command-line format.
\end{outputx2}





\section{Format}
\index{Command Line!Format}
\subsection{Spaces in Filenames}
\label{changelog:20200906spaces}
\index{Command Line!Spaces in Filenames}

If a filename (source, output, listing file) contains spaces, the whole filename may be surrounded with quotes, or the spaces may be escaped with a backslash character - depending on your OS support for these.

\begin{usage}
dasm "source file.asm"
dasm source\ file.asm
\end{usage}



\subsection{Options}

Options are specified on the command-line, after the source file. There may be zero or more options each separated by whitespace. Some options require their own parameters. Default values (where an option is not explicitly defined) are described with each option below.

An option is prefixed by a dash ``\mono{-}'' or a slash ``\mono{/}'' prefix, and followed by the option letter and then the parameter (if there is one). There must be no whitespace between the prefix, option letter or the parameter.

\subsubsection{Example}
\index{Examples!Command Line}
\begin{outputx}
> dasm source.asm -f2 -oout.bin -llist.txt -v3 -DVER=4
\end{outputx}

This example will assemble the file \mono{source.asm}, using output format \mono{2} (random access segments). The resultant binary will be saved to the file \mono{out.bin} and a listing file written to \mono{list.txt}. During the assembly, verbosity of the output is set to \mono{3} (unresolved and unreferenced symbols displayed every pass). The value of the symbol (which will be available in the source code) \mono{VER} is set to \mono{4}.

\section{Options}
\index{Command Line!Options}
\subsection{\texttt{-d Debug}}
\index{Command Line!Options!Debug}
\begin{usage}
-d
\end{usage}

\label{changelog:20200824developers}
This option is for \dasm's developers, and is essentially inactive in release versions.
\\
\hrule

\subsection{\texttt{-D Define Symbol}}
\label{flag:definesymbol}
\index{Command Line!Options!Define Symbol}
\begin{usage}
-Dsymbol=exp
\end{usage}

Defines a symbol and sets it to the expression \mono{exp}.

Can be used to set values for symbols used inside the code.

See \nameref{flag:definesymbolF}, \nameref{flag:definesymbolM}.

\subsubsection{Example}

\begin{outputx}
> dasm source.asm -DSPEED=40
\end{outputx}

\begin{code}
  lda #SPEED       ; will load 40
  sta velocity
\end{code}

\begin{code}
; Use the symbol to assemble different code
  IF SPEED < 30
    jsr FastDraw   ; not assembled
  ELSE
    jsr SlowDraw   ; is assembled
  ENDIF
\end{code}


\hrule

\subsection{\texttt{-E Error Format}}
\index{Command Line!Options!Error Format}
\begin{usage}
-Eformat
\end{usage}

Sets the format of the output of error information. Many programmers' editing environments (IDEs) are able to monitor the output from tools such as \dasm and parse it for information about errors and warnings. If an IDE is able to resolve file names and line numbers for these errors, then the IDE can provide quick-links to the user to allow ease of editing.

This option switches the format of error/warning output of \dasm between several ``standard'' formats.

\begin{table}[H]
\begin{tabularx}{\linewidth}{cl}
\toprule
\mono{\textbf{format}}&\textbf{Result}\\
\hline
\\
\mono{0}&Microsoft (\mono{default})\\
\mono{1}&Dillon\\
\mono{2}&GNU\\
\\
\bottomrule
\end{tabularx}
\end{table}

\subsection{\texttt{-f Output Format}}
\label{flag:outputformat}
\index{Command Line!Options!Output Format}

\begin{usage}
-fvalue
\end{usage}

Defines the format used in the binary output file generated by \dasm.

\begin{table}[H]
	\begin{tabularx}{\textwidth}{cp{12cm}}

\toprule
\textbf{value} & \textbf{Function}\\
\hline

\\

\label{changelog:20200824org}
		\mono{1} & \mono{default}. The output file contains a two byte origin in little-endian order, then
data until the end of the file. Any instructions which generate output (within an initialised segment) must do so with an ascending \mono{ORG} address (this address being the offset in the binary/ROM where the output is placed, as opposed to the \mono{RORG} which is the address to which the code is assembled).  Initialised segments must occur in ascending order. \\


\\
\mono{2} & \mono{RAS} (Random Access Segment). The output file contains one or more hunks.  Each hunk consists of a 2 byte origin (little-endian), 2 byte length (little-endian), and that number of data bytes.  The hunks occur in the same order as initialized segments in the assembly.  There are no restrictions to segment ordering (i.e. reverse indexed ORG statements are allowed).  The next hunk begins after the previous hunk's data, until the end of the file.\\

\\
\mono{3} & \mono{RAW}. The output file contains data only (format \#1 without the 2 byte
header).  Restrictions are the same as for format \#1.
\textbf{No} header origin is generated.  You get
nothing but data.\\

\\
\bottomrule
	\end{tabularx}
\end{table}

It is a \textbf{common problem} to forget the format option on the command line, especially if you are expecting a pure binary ROM without a header. Use \mono{-f3} if you are assembling ROMs.

%\hrule
\subsection{\texttt{-F Define Symbol}}
\label{flag:definesymbolF}
\index{Command Line!Options!Define Symbol}

\begin{usage}
-Fsymbol
\end{usage}

Define a symbol and set its value to 0.

This symbol is then usable in the source code as if it were a part of the code itself. This can be useful for controlling the conditional assembly of parts of code.

See related options \nameref{flag:definesymbol} and \nameref{flag:definesymbolM}.

\subsubsection{Example}

\begin{outputx}
> dasm source.asm -FTEST
\end{outputx}

\begin{code}
  IFCONST TEST
    ; code here only assembled when TEST is defined
  ENDIF
\end{code}

\hrule
\subsection{\texttt{-I Include Directory}}
\label{flag:includedirectory}
\index{Command Line!Options!Include Directory}

\begin{usage}
-Idirectory
\end{usage}

This adds the \mono{directory} to the search path \dasm uses when looking for files when it encounters \nameref{pseudoop:include} and \nameref{pseudoop:incbin} directives. Use of this option on the command line is equivalent to an \nameref{pseudoop:incdir} directive placed at the beginning of the source file.

See \nameref{pseudoop:incdir} for the format of the directory name.\\

\hrule

\subsection{\texttt{-l Listing Filename}}
\index{Command Line!Options!Listing}
\label{flag:listing}

\begin{usage}
-lfilename
\end{usage}

\dasm is able to produce a comprehensive and extremely useful listing of the assembled source code. This file includes symbol values, code locations, and the source code itself. To enable generation of a listing file, use the \mono{-l} option.

See alternate: \nameref{flag:listingall}.\\

\hrule
\subsection{\texttt{-L Listing Filename (all Passes)}}
\label{flag:listingall}
\index{Command Line!Options!Listing (all)}

\begin{usage}
-Lfilename
\end{usage}

This option behaves the same as \nameref{flag:listing}, but lists the code on every pass. Warning: this can lead to some very big listings if \dasm needs to perform many passes on your code!

See alternate: \nameref{flag:listing}.

\subsection{\texttt{-M Define Symbol}}
\label{flag:definesymbolM}
\index{Command Line!Options!Define Symbol}
\begin{usage}
-Msymbol=exp
\end{usage}

Deprecated.

Defines a symbol and sets it to the expression \mono{exp]}.

See similar: \nameref{flag:definesymbol}, \nameref{flag:definesymbolF}.\\

\hrule

\subsection{\texttt{-m Maximum Output File Size}}
\label{flag:maximum}
\index{Command Line!Options!Maximum Output Size}
\begin{usage}
-msize
\end{usage}

\label{changelog:20200908optionm}

The \mono{-m} switch is not intended to limit the size of the created binary. Instead, it provides a safety-halting mechanism to prevent erroneous/recursive code from creating huge binaries, in situations that may not otherwise be detected.

The \mono{size} parameter is the halting condition. \dasm will halt with an error if the size of the generated binary exceeds this value. The default maximum size is \mono{640 KiB}.

This switch is generally useful for architectures with more than \mono{10} memory banks. It can be used in conjunction with \nameref{flag:remove} to detect assembly anomalies and clean-up afterwards.

\subsubsection{Example}
\begin{outputx}
> dasm source.asm -orom.bin -m128
\end{outputx}

This example will assemble the file \mono{source.asm} and write the file \mono{rom.bin}, halting with an error if the output binary exceeds \mono{128 KiB} (an indication of a potential recursion error in the code generation).

See aslo \nameref{flag:remove}.\\

\hrule


\subsection{\texttt{-o Output File}}
\label{flag:outputfile}
\index{Command Line!Options!Output File}

\begin{usage}
-ofilename
\end{usage}

Set the name of the filename for the output binary result of the assembly. If no name is specified, \dasm will write to the file ``\mono{a.out}''. See \nameref{flag:outputformat} for the format of the output file. If you want a pure binary output file without headers, you \textbf{must} add option \mono{-f3}.

\subsubsection{Example}
\begin{outputx}
> dasm source.asm -orom.bin -f3
\end{outputx}

This example will assemble the file \mono{source.asm} and write the file \mono{rom.bin} with the binary results of the assembly, without header information.\\


\hrule
\subsection{\texttt{-p Number of Passes}}
\label{flag:passes}
\index{Command Line!Options!Passes}
\begin{usage}
-pvalue
\end{usage}

Sets the maximum number of passes performed by \dasm to \mono{value}.

\dasm will keep performing passes until all references are resolved, or until the maximum number of passes is reached (in which case it will exit with an unresolved symbol error). Typically on machines these days, \dasm is so fast that a high number of passes is acceptable.

\label{changelog:20200824passes}
The default number of pases is 3.

See \nameref{flag:passes2}.\\

\hrule
\subsection{\texttt{-P Number of Passes (Fewer Checks)}}
\label{flag:passes2}
\index{Command Line!Options!Passes (Fewer Checks)}

\begin{usage}
-pvalue
\end{usage}

Sets the maximum number of passes performed by \dasm to \mono{value}.

This is the same as \nameref{flag:passes}, but instructs \dasm to perform fewer checks.

\label{todo}
{\color{red}And these are...?}

See \nameref{flag:passes}.\\

\hrule


\subsection{\texttt{-R Remove Output File}}
\label{flag:remove}
\index{Command Line!Options!Remove Output}
\begin{usage}
-R
\end{usage}

\label{changelog:20200908optionR}
Removes the binary output file if \dasm encounters an error during assembly.\\

Can be used in conjunction with \nameref{flag:maximum} to remove erroneous binaries, for example if a ROM size limit is exceeded.

See aslo \nameref{flag:maximum}.
\\


\hrule

\subsection{\texttt{-s Symbol Table File}}
\label{flag:symboltable}
\index{Command Line!Options!Symbol Table File}

\begin{usage}
-sfilename
\end{usage}

At the conclusion of assembly, the \mono{-s} option directs \dasm to save a symbol table to the specified file. A symbol table is a table listing all the symbols encountered during an assembly, and their values if known. By default, no symbol table file is generated.

The symbol table may be sorted alphabetically or numerically with the \nameref{flag:symboltablesort} option.


\subsubsection{Example}

\begin{outputx}
> dasm source.asm -ssource.sym
\end{outputx}

After the execution of the above, the file \mono{source.sym} would contain the symbol table in the format as shown in the example below. Each line gives a symbol name, its final resolved address/value, and a flag field. In the flag field,  \mono{(R )} indicates the symbol has been used/referenced and not just defined.

\begin{code}
--- Symbol List (sorted by symbol)
AUDC0                    0015                  
StartAddress             1000              (R )
TIA_BASE_ADDRESS         0000              (R )
TIM1T                    0294                  
TIM64T                   0296                  
TIM8T                    0295                  
TIMINT                   0285                  
var1                     0080                  
var2                     0081                  
varn                     008b                  
VBLANK                   0001                  
VERSION_VCS              0069                  
WSYNC                    0002                  
--- End of Symbol List.
\end{code}
\\
\\
\hrule

\subsection{\texttt{-S Strict Syntax Checking}}
\label{flags:strictsyntax}
\index{Command Line!Options!Strict Syntax Checking}

\begin{usage}
-S
\end{usage}

This option switches on more stringent checking of source code issues. 

Duplicate macro definitions are flagged as errors.

\index{todo}
{\color{red}TODO complete list of strict checks}\\

\hrule

\subsection{\texttt{-T Sort Symbol Table}}
\label{flag:symboltablesort}
\index{Command Line!Options!Sort Symbol Table}
\begin{usage}
-Tvalue
\end{usage}

Controls the sorting of lines in the symbol table.

See \nameref{flag:symboltable} to enable symbol table output.


\begin{table}[H]
\begin{tabularx}{\textwidth}{cl}
\toprule
\mono{\textbf{value}}&\textbf{Sort By}\\
\hline
\\
\mono{0}&Symbol Alphabetically (default)\\
\mono{1}&Address/Value\\
\\
\bottomrule
\end{tabularx}
\end{table}


\subsection{\texttt{-v Verbosity Level}}
\index{Command Line!Options!Verbosity Level}
\label{flag:verbosity}

\begin{usage}
-vvalue
\end{usage}

The \mono{-v} option controls the amount of information output by \dasm while it is assembling your code. This information includes warnings, errors, a segement table, a symbol table, unresolved and unreferenced symbols, and reasons for performing extra passes. Use of the \mono{-v} option can assist with diagnosing anomalous behaviour.

\begin{table}[H]
\begin{tabularx}{\textwidth}{cl}
\toprule
\mono{\textbf{value}}&\textbf{Result}\\
\hline
\\
\mono{0}&Only warnings and errors (default)\\
\\
\mono{1}&Segment table information generated after each pass\\
&Include file names are displayed\\
&Item statistics on why the assembler is going to make another pass\\
&R1,R2 reason code: R3\\
&where R1 is the number of times the assembler encountered\\
&something requiring another pass to resolve.  R2 is the\\
&number of references to unknown symbols which occured in the\\
&pass (but only R1 determines the need for another pass).  R3\\
&is a BITMASK of the reasons why another pass is required.\\

\mono{2}&Mismatches between program labels and symbols are displayed\\
&on every pass (usually none occur in the first pass unless you\\
&have re-declared a symbol name).\\
\\
&Displayed information for symbols:\\
\\
&~~\mono{????} = unknown value\\
&~~\mono{str}  = symbol is a string\\
&~~\mono{eqm}  = symbol is an eqm macro\\
&~~\mono{(R)}  = symbol has been referenced\\
&~~\mono{(s)}  = symbol created with \nameref{pseudoop:set} or \nameref{pseudoop:eqm} directive\\
\\

\mono{3}&Unresolved and unreferenced symbols are displayed every pass\\
\mono{4}&Symbol table displayed to \mono{STDOUT} every pass\\
\\
\bottomrule
\end{tabularx}
\end{table}


\begin{savequote}
\sffamily
``If you have the words, there's always a chance that you'll find the way.''
\qauthor{Seamus Heaney}
\end{savequote}

\chapter{Numbers, Expressions and Operators}
\index{Expressions}
\index{Numbers}
\index{Operators}

\section{Constants}
\label{section:numberformat}
\index{Expressions!Constants}
\index{Number Format}
\index{Bases!2 binary}
\index{Bases!8 octal}
\index{Bases!10 decimal}
\index{Bases!16 hexadecimal}

\label{changelog:20200905range}
\subsection{Magnitude}
\index{Numbers!Magnitude}
All numbers and addresses in \dasm are represented internally as signed 32-bit values.

\index{Numbers!Range Checking}
Numbers are range-checked at point of usage. Byte values should be between \mono{\$80} (\mono{-128}) and \mono{\$FF} (\mono{255}) inclusive, as these values are the extremes of what can be represented with signed and unsigned 8-bit values. Word values should be between \mono{\$8000} (\mono{-32768}) and \mono{\$FFFF} (\mono{65535}) as these are the extremes of signed and unigned 16-bit values.

Note that the assembler cannot tell the difference between the representation (in 8 and 16 bits) of signed/unsigned representation of negative and positive numbers, as they share the same bit patterns. 

\begin{code}
 lda #%11111111  ; is this 255 or -1?
\end{code}

The answer to the above question is that it depends on what the programmer does with the value, as in signed 8-bit arithmetic, \mono{\%11111111} is \mono{-1}, and in unsigned 8-bit arithmetic it is \mono{255}. This is not as confusing as it sounds, as the assembler works in signed 32-bit arithmetic and the signedness of these values (particularly when taking the low byte/word) is unambiguous.

It is common for programmers who want all bits set to simply use \mono{-1}.

\subsection{Base Representation}
\index{Numbers!Bases}
\index{Bases}

Values in \dasm can be specified in base 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal), or as ASCII characters. It doesn't matter to \dasm which format you use, so use what makes the most sense in your code. The interpretation of the value is determined by the prefix and digits used, as shown in the following table.

\label{changelog:20200824const}
\begin{table}[H]
\begin{tabularx}{\linewidth}{lll}
\toprule
\textbf{Type}&\textbf{Format}&\textbf{Content}\\
\hline
\\
\mono{Binary}       &\mono{\%}n        & \mono{0-1}\\
\\
\mono{Octal}        &\mono{0}n         & \mono{0-7}\\
\\
\mono{Decimal}      &\mono{n}                   & \mono{0-9}, first digit non-\mono{0}\\
\\
\mono{Hexadecimal}  &\mono{\$}n        &case insensitive \mono{0-9,A-F}\\
\\
\mono{Character}    &\mono{'c}         &\mono{ASCII} character\\
\\
\mono{String}       &\mono{``cc..''}   & zero-terminated ASCII character string\\
					&                           & \textbf{not} zero-terminated when used in \mono{DC}/\mono{DS}/\mono{DV}.\\
\\					
					&\mono{[exp]d}     & The constant expressions is evaluated and its\\
					&                           &decimal result converted into an ASCII string.\\
					&                           &Useful in conjunction with ECHO diagnostic output.\\
\\
\bottomrule
\end{tabularx}
\end{table}

Even though decimal numbers can't start with \mono{0}, as that describes an octal number, the octal \mono{0} is equivalent. In other words, \mono{0\textsubscript{10}} = \mono{0\textsubscript{8}}.

Negative signs are placed before the number prefix (e.g., \mono{-\$123}).

\subsubsection{Examples}

\begin{code}
 lda #%101          ; binary = 5 decimal
 lda #%10101010     ; binary = 170 decimal
 lda #015           ; octal = 13 decimal
 lda #$FF           ; hexadecimal = 255 decimal (unsigned)
                    ;             = -1 decimal (signed)
 lda #'A            ; ASCII character = 65 decimal
 lda #'A'           ; ERROR - no trailing quote allowed!
\end{code}

\begin{code}
VAL = -129
 lda #VAL           ; ERROR - outside byte range
\end{code}



\begin{code}
; A great approximation for Pi is 355/113
PIDIGITS = 1000000 * 355/113
  ECHO "PI DIGITS: ", PIDIGITS    ; obscure
  ECHO "PI DIGITS: ",[PIDIGITS]d  ; aha!
\end{code}

\begin{outputx}
 PI DIGITS:  $2fefd8
 PI DIGITS:  3141592
 \end{outputx}




\hrule
\index{Expressions}
\index{Operators}

\index{Expressions!Brackets}
\index{Expressions!\mono{[ ]}}
\index{Expressions!\mono{( )}}

\section{Expressions}

Expressions are calculations involving symbols and numbers. These calculations are performed by \dasm during the assembly process. Often, symbols will have unkonwn values during an assembly pass, and thus an expression cannot be evaluated. \dasm will, in these cases, perform another assembly pass - often, unknown values are resolved later in the assembly.  A successful assembly is one where no errors have been detected, and all referenced symbols have been resolved.

\subsection{Brackets}
\label{changelog:20200908brackets}
\index{Brackets}
\index{Expressions!Brackets}

The precedence of operators is the same as for the C-language in almost all respects.  

Either square brackets \mono{[]} or round brackets \mono{()} may be used to group expressions and to clarify/adjust precedence, depending on which \nameref{pseudoop:processor} is in effect for the assembly. Differences are related to the use of round brackets in assembler instructions. 

\subsubsection{F8 and Other Processors}
\index{Expressions!Brackets!F8 and Other}
Either bracket type may be used in all situatinos.

\subsubsection{6502 Processor}
\index{Expressions!Brackets!6502}

Use square brackets \mono{[]} when you are unsure. The reason round brackets \mono{()} cannot be used to
group expressions is due to a conflict with 6502 assembly language which use them to specifiy indirect memory access (for example, ``\mono{lda (zp),y}'').

It is possible to use round brackets \mono{()} instead of square brackets \mono{[]} in expressions following directives, but not following mnemonics.

So this works:

\begin{code}[caption=Valid Bracket Usage]
    IF target & (pet3001 | pet4001) ; OK
\end{code}

but this doesn't:

\begin{code}[caption=Invalid Bracket Usage]
    lda #target & (pet3001 | pet4001) ; fails
\end{code}

\section{Operators}
\index{Operators}
\index{Operators!Logical!OR}
\index{Operators!Logical!NOT}
\index{Operators!\mono{< LSB}}
\index{Operators!\mono{> MSB}}
	
Some operators, such as \mono{||} (logical-OR), can return a resolved value even if
one of the expressions is not resolved.
 
\subsection{Operator Precedence}
\index{Operators!Precedence}

Operators in any expression are evaluated in order of precedence. The following tables list the various operators, their function, and precedence (PR). Operators are handled in precedence order high to low.


\subsubsection{Unary Operators}
\label{operators:unary}
\index{Operators!Unary}

\label{changelog:alternateunary}
\noindent
\begin{table}[H]
	\begin{tabularx}{\textwidth}{cllr}
		\toprule
		\textbf{Operator} &\textbf{Alternate} & \textbf{Function} & \textbf{PR}\\
		\hline
		\\
		\mono{$\sim$exp}&\mono{exp\textasciicircum -1}&one's complement & 20\\
		\mono{-exp}&\mono{[exp\textasciicircum -1]+1}&    mathematical negation & 20\\
		\mono{!exp}&\mono{exp==0}&   logical \mono{NOT}& 20\\
		&&(0 if \mono{exp} is non-zero, 1 if \mono{exp} is zero)&\\
		\mono{<exp}&\mono{exp\&\$FF}&    take \mono{LSB} of the low word& 20\\
		\mono{>exp}&\mono{[exp>\,>8]\&\$FF}&take \mono{MSB} of the low word& 20\\
		\\
		\bottomrule
		\end{tabularx}
\caption{\label{tab:unaryoperators}Unary Operators}
\end{table}

\label{operators:specialcase}
\subsubsection{Special Case}
\index{Operators!Unary!Special Case}
\label{changelog:specialcase}

Some operations will result in non-byte values when a byte value was wanted.	For example: \mono{$\sim$1} is not \mono{\$FF}, but instead \mono{\$FFFFFFFF}. Preceding it with a \mono{<} (take LSB of) will solve the problem.

However, there is a special-case for negative numbers used in operands. Although internally 32-bit, numbers in the range -1 to -128 are treated as two's complement 8-bit numbers in this situation. Another way of thinking of this - it is not necessary to take the \mono{LSB} of the number if it is in the range -128 to 255, as \dasm will recognise this as a valid signed/unsigned 8-bit number and do this automatically.

\label{changelog:20200824rangebug}
\index{Bugs!Range}{\color{bug}Bug: Currently \dasm allows values in the range \mono{-\$FF} to \mono{+\$FF}. This is incorrect. The correct range is \mono{-\$80} to \mono{+\$FF}}.

\subsubsection{Examples}

\begin{code}
; Special case handling of 8-bit negatives
  lda #-1           ; OK
  lda #$FF          ; same as -1
  lda #-129         ; ERROR - outside 8-bit size
\end{code}

\begin{code}
; Extracting low and high byte of value
  lda #<addr        ; low byte of symbol address/value
  lda #>$12345678   ; =  $56, the high byte of the low word
\end{code}



\subsubsection{Binary Operators}
\index{Operators!Binary}

\label{changelog:20200824arithmetic}
\begin{table}[H]
	\begin{tabularx}{\textwidth}{clr}
		
\toprule
\textbf{Operator} & \textbf{Function} & \textbf{PR}\\
\hline
\\
\mono{*}&	    Multiplication &19\\
\mono{/}&	    Division &19\\
\mono{\%}&	    Modulus &19\\
\mono{+}&	    Addition &18\\
\mono{-}&	    Subtraction &18\\
\mono{\textgreater\,\textgreater}&   Aritmetic shift right & 17\\
\mono{<\,<}& Arithmetic shift left &17\\
\mono{>}& Greater than & 16\\
\mono{>=}& Greater than or equal to &16\\
\mono{<} & Less than & 16\\
\mono{<=}& Less than or equal to&16\\
\mono{==}&	    Logical equal to.&15\\
\mono{=}&	    Logical equal to. Deprecated! (use `\mono{==}')&15\\
\mono{!=}&	    Not equal to &15\\
\mono{\&}	&    Arithmetic \mono{AND} &14\\
\mono{\^}&	    Arithmetic exclusive-\mono{OR} &13\\
\mono{|}&	    Arithmetic \mono{OR} &12\\
\mono{\&\&}&	    Logical \mono{AND}. Evaluates as 0 or 1&11\\
\mono{||}&	    Logical \mono{OR}. Evaluates as 0 or 1&10\\
\mono{?}&	    If the left expression is \mono{TRUE}, result is the right&9\\
&expression, else result is \mono{0}. \mono{[10?20]} returns \mono{20}.&\\
&The function of the C conditional operator \mono{a?b:c}&\\
&  can be achieved by using \mono{[a?b-c]+c}.&\\
\mono{[ ]}&	    Group expressions &8\\
\mono{,}&	    Separates expressions in list (also used in &7\\
&addressing mode resolution, so be careful! &\\
\\
\bottomrule
\end{tabularx}
\caption{\label{tab:binaryoperators}Binary Operators}
\end{table}


\section{Symbols}

\renewcommand{\arraystretch}{1.1}
\begin{table}[H]
	\begin{tabularx}{\textwidth}{cl}
\toprule
\textbf{Symbol} & \textbf{Meaning}\\
\hline
\\
\index{Symbol!...}
\index{Symbol!checksum}
\mono{...} & Checksum so far (of actually-generated data)\\
\mono{..} & Evaluated value in \nameref{pseudoop:dv} directive \\
\mono{.} & Current program counter\\
\mono{*} & Synonym for `\mono{.}' when not confused as an operator.\\
\mono{.name} & Represents a local label name. Local labels may be reused\\
& inside \mono{MACRO}s and between \nameref{pseudoop:subroutine} directives, but may not be \\
& referenced across \mono{MACRO} or \mono{SUBROUTINE} scope.\\
& (as of the beginning of the instruction)\\
\mono{name} & Represents a global symbol name. Beginning with an alpha\\
&character and containing letters, numbers, or  underscores.\\
& Symbol definitions may end with a colon, but reference must\\
& omit the colon.\\
\mono{nnn\$} & Local label, much like `\mono{.name}', except that defining\\
& a non-local label has the effect that \mono{SUBROUTINE} has on`\mono{.name}'.\\
& They are unique within \mono{MACRO}s, like `\mono{.name}'.\\
& Note that `\mono{0\$}' and \mono{00\$} are distinct, as are \mono{8\$} and \mono{010\$}\\
	& (mainly for compatibility with other assemblers).\\
	\\
\bottomrule
\end{tabularx}
\caption{\label{tab:symbols}Symbols}
\end{table}


\section{Why-Codes}

\dasm can display the reason (via \nameref{flag:verbosity}) it needs to do another pass. Internally, these reasons are stored in the ``why'' word.

The list of available reasons include:

\begin{table}[H]
\begin{tabularx}{\textwidth}{cl}
	\toprule
	\textbf{Bit} & \textbf{Usage}\\
	\hline
	\\
\mono{0}&   expression in mnemonic not resolved\\
\mono{1}&   -\\
\mono{2}&   expression in a \mono{DC} not resolved\\
\mono{3}&   expression in a \mono{DV} not resolved (probably in \mono{DV}'s \mono{EQM} symbol)\\
\mono{4}&   expression in a \mono{DV} not resolved (could be in \mono{DV}'s \mono{EQM} symbol)\\
\mono{5}&   expression in a \mono{DS} not resolved\\
\mono{6}&   expression in an \mono{ALIGN} not resolved\\
\mono{7}&   \mono{ALIGN}: Relocatable origin not known (if in \mono{RORG} at the time)\\
\mono{8}&   \mono{ALIGN}: Normal origin not known	(if in \mono{ORG} at the time)\\
\mono{9}&   \mono{EQU}:   expression not resolved\\
\mono{10}&  \mono{EQU}:   value mismatch from previous pass (phase error)\\
\mono{11}&  \mono{IF}:     expression not resolved\\
\mono{12}&  \mono{REPEAT}: expression not resolved\\

\mono{13}&  a program label has been defined after it has been\\
&referenced (forward reference) and thus we need another pass\\
\mono{14}&  a program label's value is different from that of the\\
&previous pass (phase error)\\
\\
\bottomrule
\end{tabularx}
%\caption{\label{tab:constants}WHY Codes}
\end{table}

\label{changelog:20200824error}
There are three types of error; those that cause the assembly to abort immediately, those that complete the current pass and then abort assembly, and those that allow another assembly pass in the hope that the error will self-correct.

\begin{savequote}
\sffamily
``No symbols where none intended.''
\qauthor{Samuel Beckett}
\end{savequote}

\chapter{Symbols and Labels}

\section{Labels}
\index{Labels}
\index{Labels!Global}

\index{Symbols}

The terms symbols and labels are synonymous. However, common usage is to use ``label'' for a symbol referring to a memory address, and that convention is generally used in this document. Otherwise, it is referred to as a symbol.

Labels are and symbols assigned addresses or values by \dasm. These values are calculated during the assembly process by resolving the location or value of expressions defining the label. Often this may take multiple assembly passes to resolve.

Label definitions start at the beginning of a line and are encoded in ASCII; they must start with a letter or \mono{@} or {\_}, and can include letters, numbers, and some symbols.




\label{changelog:20200823colon}
\subsubsection{Colon Usage}
\index{Labels!Use of Colon in}
Label definitions can end with a colon, but the usage of the label must not include the colon. This can be helpful when you are editing your code if you want to search for your label definition \mono{label:} which will return just one result (unless it's a local label, which may be duplicated), or \mono{label} which will return all instances.

\subsubsection{Examples}
\begin{code}
; Usage of colon in label names
loop:       jmp loop    ; OK
            jmp loop:   ; error: Illegal character ':'
\end{code}


\begin{code}[caption=Global Label Definitions]
; Examples of label/symbol definitions
Label1               ; standard
Label2:              ; optional colon
lab3 = %101010       ; life, the universe, and everything
LAB4 SETSTR "Hello"  ; allocated as string
.lab6                ; local
lab,{1}              ; dynamic, inside macro
lab@                 ; some symbols are valid too
 labWhoops           ; invalid - not in 1st column
lab SET -INFINITY    ; SET: initial definition
lab SET 0            ; SET: and re-use!
\end{code}


\section{Local Labels}
\index{Labels!Local}
\label{locallabels}

Local labels begin with a dot ``\mono{.}''. They are local to the scope of the current \nameref{pseudoop:subroutine} directive boundary, and may be re-used in other subroutine scopes. Note that the usage of the term subroutine can be misleading; local labels are local to blocks defined by usage of the directive \nameref{pseudoop:subroutine}, not to code-subroutines.

Usually local labels are used in macros and within actual code subroutines. This is handy where simple names such as `\mono{.loop}' can be re-used many times. It is particularly useful in macros, where global labels are problematic due to the inability to declare a global label more than once.

\subsubsection{Example}
\begin{code}[caption=Scope of Local Labels]
    ; Define macro

    MAC DO
        ; Implicit SUBROUTINE inserted here!
.mac    jmp .mac       ; OK - local macro label       
    ENDM
    
    ; elsewhere in the code...
    
.local  jmp .local     ; OK - local label
global  jmp global     ; OK - global label

        DO             ; use macro

    ; implicit new scope has happened
    ; after macro instantiated

        jmp global     ; OK - global scope
        jmp .local     ; error - outside scope
        jmp .mac       ; error - outside scope

\end{code}

The example above shows the result of the use of local and global labels, and the effects of implicit \nameref{pseudoop:subroutine} as a result of a macro instance.

\section{Dynamic Labels}
\index{Labels!Dynamic}
\label{todo}

When used in a symbol name, the ``\mono{,}'' operator indicates one or more
arguments that follow should be evaluated, and the resulting values 
should be concatenated to the label, to create a dynamic symbol name. 

\begin{usage}
symbol,arg1[,argn...]
\end{usage}

String literals in arguments must be specified with quotes around the string
text.  Expression operators can also be used, but due to label
parsing constraints, they should not contain spacing.

The concat-eval ``\mono{,}'' operator also works on the expression side
of \mono{EQU/SET} directives, so dynamic labels can be used with opcodes. 

\subsubsection{Examples}

\begin{code}
; define and use a dynamic label
CON,"cat"               ; define label
        jmp CONcat      ; use the generated label
\end{code}

\begin{code}
; Use a dynamic label inside a macro

N SET 0         ; instance number

  MAC dynm      ; {1}=base name
{1},"_",N       ; define label using {1} and instance #
N SET N+1
  ENDM

  dynm fna
  jmp fna_0     ; OK

  dynm fna
  jmp fna_1     ; OK
  
  dynm fnb
  jmp fnb_2     ; OK
  jmp fnb_0     ; ERROR - does not exist
\end{code}

\section{Deprecated Form}
\label{changelog:20200907deprecated}
\dasm currently supports labels defined as per the following...

\begin{usage}
[]...^[]...label
\end{usage}

That might look a bit weird because, basically, it is. Essentially, whitespace carat whitespace and then the label name. This is a \textbf{deprecated} format that may not be supported by future versions of \dasm. Do not use.

\begin{code}
   ^ weirdLabel  ; this is a weird way to define a label
 normalLabel     ; this is a normal way
\end{code}



\begin{savequote}
\sffamily
``Success is often the result of taking a misstep in the right direction.''
\qauthor{Al Bernstein}
\end{savequote}

\chapter{Directives}



\label{chapter:pseudoops}
\index{Directives}

Also known as pseudo-ops, directives appear in the source code. They instruct \dasm what to do during assembly. These are distinct from the mnemonics in the source code, which contains the human-readable instructions for the microprocessor itself. Directives include macros, segment definitions, setting the origin/location of code, etc. They are not case-sensitive.

There must be whitespace before a directive. Thus, directives must not appear in the first column of any line. Directives are not case-sensitive, but in this document they are shown in uppercase.

Some directives cannot have labels on the same line - for example, those where there is no possibility of evaluating a label's value because no origin/segment has yet been defined. For directives where a label is illegal, or does not make sense, this is explicitly stated.

If a label is present, then its value will be set to the current \nameref{pseudoop:org}/\nameref{pseudoop:rorg} either before or after
a directive is processed.  Most of the time, the label to the left of a
directive is set to the current \nameref{pseudoop:org}/\nameref{pseudoop:rorg}. The following directives' labels are given their value {\bf after} execution of the directive: \nameref{pseudoop:seg}, \nameref{pseudoop:org}, \nameref{pseudoop:rorg}, \nameref{pseudoop:rend}, \nameref{pseudoop:align}.

All directives (and incidentally also the mnemonics) can be prefixed with a dot ``\mono{.}'' or a crosshatch ``\mono{\#}'' for compatibility with other assemblers. So, ``\mono{.IF}'' is the same as ``\mono{IF}'' and ``\mono{\#IF}''. In the case of the dot, this works only because unattached, lone \mono{.FORCE} extensions are meaningless.

\section{Includes}
\subsection{\texttt{INCBIN}}
\label{pseudoop:incbin}
\index{Directives!Includes!\texttt{INCBIN}}

\begin{usage}
  INCBIN "filename"
\end{usage}

Include the binary contents of another file literally in the output.\\
\hrule

\subsection{\texttt{INCDIR}}
\label{pseudoop:incdir}
\index{Directives!Includes!\texttt{INCDIR}}

\begin{usage}
  INCDIR "directory"
\end{usage}

Add the given directory name to the list of places where
\nameref{pseudoop:include} and \nameref{pseudoop:incbin} search their files. Multiple directories can be added through multiple \nameref{pseudoop:incdir} commands. When the other includes directives look for files, first the names are tried relative to the current directory, if that fails and
the name is not an absolute pathname, the directory list is tried.
You can optionally end the directory name with a ``\mono{/}''. 

\index{todo}
{\color{todo}AmigaDOS filename conventions imply that two slashes at the end of a directory indicates the parent directory, and so this does an \nameref{pseudoop:include}~\mono{"/directory"}}
	
The command-line option \mono{-Idirectory} is equivalent to an \nameref{pseudoop:incdir}~\mono{"directory"} directive placed at the beginning of the source file.

The directory list is not cleared between passes, but each exact directory name is added to the list only once.
\\
\hrule
\subsection{\texttt{INCLUDE}}
\label{pseudoop:include}
\index{Directives!Includes!\texttt{INCLUDE}}


\begin{usage}
  INCLUDE "file name"
\end{usage}

Effectively inserts the contents of another file at the point of the \nameref{pseudoop:include} and continues assembling the original as if it were one merged file.

\subsubsection{Example}

\begin{code}[caption=Declaring the Platform]
; Typical first few lines in an Atari 2600 program...
   processor 6502
   include "vcs.h"
   include "macro.h"
\end{code}\\

\hrule
%-------------------------------------------------------------------------------

\section{Assigments}

\subsection{\texttt{EQU}, \texttt{=}}
\label{pseudoop:equ}
\label{pseudoop:=}
\index{Directives!Assignments!\texttt{EQU}}
\index{Directives!Assignments!\texttt{=}}


\begin{usage}
symbol EQU exp
symbol = exp
\end{usage}

The expression is evaluated and the result assigned to
\mono{symbol}.

\nameref{pseudoop:equ} are equivalent.

You can use the common idiom of ``\mono{.=.+3}'' - in other words, you can assign to ``.'' or ``\text{*}'' directly, instead of using an \nameref{pseudoop:org} or \nameref{pseudoop:rorg} directive.

More formally, a directive of the form ``\mono{.~EQU~exp}'' is
interpreted as if it were written ``\nameref{pseudoop:org} \mono{exp}'' or  ``\nameref{pseudoop:rorg} \mono{exp}''.
The \nameref{pseudoop:rorg} is used if a relocatable origin is already in effect,
otherwise \nameref{pseudoop:org} is used. Note that the first example is \textbf{not}
equivalent to ``\nameref{pseudoop:ds} \mono{3}'' when the \nameref{pseudoop:rorg} is in effect.

A symbol can also be defined through the command-line options \nameref{flag:definesymbol}, \nameref{flag:definesymbolF} and \nameref{flag:definesymbolM}.\\

\hrule
\subsection{\texttt{EQM}}
\label{pseudoop:eqm}
\index{Directives!Assignments!\texttt{EQM}}

\begin{usage}
symbol EQM exp
\end{usage}

The string representing the expression is assigned to the
symbol.  Occurrences of the label in later expressions causes
the string to be evaluated for each occurrence.  Also used in
conjuction with the \nameref{pseudoop:dv} psuedo-op.\\

\hrule
\subsection{\texttt{SET}}
\label{pseudoop:set}
\index{Directives!Assignments!\texttt{SET}}

\begin{usage}
symbol SET exp
\end{usage}


Same as \nameref{pseudoop:equ}, but the symbol may be reassigned later.\\

\subsubsection{Example}

\begin{code}
; Using SET to do calcualtions
N SET 1 
SUM SET 0
  REPEAT 10
SUM SET SUM+N
N SET N+1
  REPEND
  ECHO "Sum of 1 to 10 is", [SUM]d
\end{code}

\begin{outputx}
Sum of 1 to 10 is 55
\end{outputx}


\hrule
\subsection{\texttt{SETSTR}}
\label{pseudoop:setstr}
\index{Directives!Assignments!\texttt{SETSTR}}

\begin{usage}
symbol SETSTR exp
\end{usage}

The expression is converted to a string, and assigned to the
symbol. Typical use-case is within a macro, to allow the
macro to echo or otherwise use the name of an argument.

\subsubsection{Example}

\begin{code}[caption=Use of SETSTR to Display Function Name]
; Use SETSTR to output a parameter as a string
    MAC CALL    ; {1} = function name
.FNAME  SETSTR {1}
        ECHO "This is the function name:", .FNAME
    ENDM
    
    CALL HelloWorld        ; test it...
\end{code}

\begin{outputx}
This is the function name: HelloWorld
\end{outputx}



\section{Data}
\subsection{\texttt{DC}}
\label{pseudoop:dc}
\index{Directives!Data!\texttt{DC}}

\begin{usage}
   DC[{.B|.W|.L|.S}] exp,...
\end{usage}
\label{changelog:20200915endian}
Declare data in the current segment.  No output is generated if within a uninitialised \mono{.U} segment. The byte ordering (the endian order) for the selected processor is used for each entry. It is possible to "swap endianness" (the byte order of wide-characters) using \mono{DC.s}

The default size extension (\mono{.B}, \mono{.W}, \mono{.L}) is \mono{.B} (byte).

\subsubsection{Alternates}
\begin{usage}
   BYTE exp,...
   WORD exp,...
   LONG exp,...
\end{usage}

\subsubsection{Examples}

\begin{code}[caption=Data Generation]
; various ways of defining data...
  DC 0,1,2,3
  BYTE -1,1,2,3, <Value
  .WORD 100,1000,10000, VectorTable
  LONG 100000, 50*50*50
  dc 'a'  ; ERROR - should be 'a
  dc.s "unicode"   ; endian-swapped character words
\end{code}

\begin{code}[caption=Data Declaration using REPEAT Loop]
; generate the bytes 0 to 9 inclusive
VAL SET 0
    REPEAT 10
        .byte VAL
VAL SET VAL + 1
    REPEND
\end{code}\\




\hrule
\subsection{\texttt{DS}}
\label{pseudoop:ds}
\index{Directives!Data!\texttt{DS}}

\emph{Not available for the F8 processor - use \nameref{pseudoop:res}}

\begin{usage}
  DS[{.B|.W|.L}] exp[,fillvalue]
\end{usage}

Declare space and fill with a fillvalue (if specificed, otherwise default is 0). The optional size extender (\mono{.B}, \mono{.W}, \mono{.L}) defines the data size (1, 2 or 4) bytes. Data is not generated if within an uninitialized segment, but the origin still changes accordingly (this is very useful for defining variables).  The number of bytes generated is \mono{exp} $\times$ data size (1, 2, or 4)

The default size extension is a byte.

The fill value is not related to the fill value used by \nameref{pseudoop:org}.




\subsubsection{Examples}

\begin{code}[caption=Declaring Space]
 ds 2     ; 2 bytes of default value 0
 ds 2,10  ; 2 bytes of value 10
 ds 10,2  ; 10 bytes of value 2
 ds.w 2   ; 4 bytes (2 words) of default value 0
 ds.l 0   ; define no space at all
 \end{code}

\begin{code}[caption=Declaring Variables]
; Declare some zero page variables
; in an uninitialised segment
    SEG.U variables
    ORG $80
var1          ds 2      ; 2 bytes             @ $80-$81
var2          ds.w 10   ; 20 bytes (10 words) @ $82-$8B
varn          ds.w 2    ; 4 bytes (2 longs)   @ $8C-$8F
\end{code}\\

\hrule
\subsection{\texttt{DV}}
\label{pseudoop:dv}
\index{Directives!Data!\texttt{DV}}

\begin{usage}
  DV[{.B|.W|.L}] eqmlabel exp,...
\end{usage}

This is equivalent to \nameref{pseudoop:dc}, but each \mono{exp} in the list is passed
through the symbolic expression specified by the \mono{eqmlabel}.
The expression is held in a special symbol dotdot '\mono{..}' on each
call to the \mono{eqmlabel}.

See \nameref{pseudoop:eqm}.\\

\hrule

\subsection{\texttt{HEX}}
\label{pseudoop:hex}
\index{Directives!Data!\texttt{HEX}}

\begin{usage}
  HEX {hh...}
\end{usage}

This sets down raw hexadecimal data.  Whitespace is optional between each \mono{hh} byte.
No expressions are allowed.  Note that you do NOT place a ``\$''
in front of the hexadecimal digits.  This is a short form for creating
tables compactly.  Data is always layed down on a byte-by-byte
basis.

\subsubsection{Example}
\begin{code}
 HEX 1A45 45 13254F 3E12
\end{code}

produces the following sequence of decimal values in the binary...

\begin{outputx}
26 69 69 19 37 79 62 18
\end{outputx}
	
\hrule
	
	
\subsection{\texttt{RES}}
\label{changelog:20200906res}
\label{pseudoop:res}	
	
\emph{Not available for 6502 - use \nameref{pseudoop:ds}}
	
\emph{Since \mono{DS} is an F8 instruction (decrement scratchpad register),
the \mono{DS} directive isn't available anymore if \dasm assembles
F8 code, and this \mono{RES} directive is provided as an alternative.
}


\begin{usage}
  RES[{.B|.W|.L}] exp[,fillvalue]
\end{usage}

Declare space and fill with a fillvalue (if specificed, otherwise default is 0). The optional size extender (\mono{.B}, \mono{.W}, \mono{.L}) defines the data size (1, 2 or 4) bytes. Data is not generated if within an uninitialized segment, but the origin still changes accordingly (this is very useful for defining variables).  The number of bytes generated is \mono{exp} $\times$ data size (1, 2, or 4)

The default size extension is a byte.

The fill value is not related to the fill value used by \nameref{pseudoop:org}.


\subsubsection{Examples}

\begin{code}[caption=Declaring Space]
 res 2     ; 2 bytes of default value 0
 res 2,10  ; 2 bytes of value 10
 res 10,2  ; 10 bytes of value 2
 res.w 2   ; 4 bytes (2 words) of default value 0
 res.l 0   ; define no space at all
 \end{code}

	
\section{Conditionals}
\label{conditionals}


Conditionals allow selected selections of code to be assembled.\\


\subsection{\texttt{IFCONST}}
\label{pseudoop:ifconst}
\index{Directives!Conditionals!\texttt{IFCONST}}

\begin{usage}
  IFCONST exp
\end{usage}

A useful method is to use \nameref{pseudoop:ifconst} or \nameref{pseudoop:ifnconst} to check for the definition of a symbol and then conditionally assemble code based on the result. This can be especially useful with symbols defined via the command-line.

\subsubsection{Examples}

\begin{code}
  IFCONST PI
    IF PI=3
      ECHO "Are you sure?"
    ENDIF
  ENDIF
\end{code}\\

\begin{outputx}
> dasm source.asm -DPI=3
Are you sure?
\end{outputx}


Is \mono{TRUE} if the expression result is defined, \mono{FALSE} otherwise
and no error is generated if the expression is undefined.

\subsubsection{Example}
\begin{code}
symbol  ; defined!
    IFCONST symbol
        ECHO "Defined!"  ; we'll see this!
    ENDIF
\end{code}\\

\hrule
\subsection{\texttt{IFNCONST}}
\label{pseudoop:ifnconst}
\index{Directives!Conditionals!\texttt{IFNCONST}}

\begin{usage}
  IFNCONST exp
\end{usage}

\subsubsection{Example}
\begin{code}
IFNCONST symbol
    ECHO "Not defined!"  ; we'll see this!
ENDIF
\end{code}\\



\hrule
\subsection{\texttt{IF}}
\label{pseudoop:if}
\index{Directives!Conditionals!\texttt{IF}}

\begin{usage}
  IF exp
    ; block TRUE
  [ELSE
    ; block FALSE
  ]
  ENDIF
\end{usage}

Evaluates \mono{exp} and if \mono{TRUE} (\mono{exp} is defined and non-zero) will insert the following block of code.


Neither \nameref{pseudoop:if} nor \nameref{pseudoop:else} will be executed if the expression result
is undefined.  In that case, another assembly
pass is performed and phase errors (in the next pass only) will not
be reported unless the verbosity is set to 1 or more.

\subsubsection{Examples}

\nameref{pseudoop:if} is a handy way to comment out large sections of code or text. There is a caveat to this method - the code is still parsed by \dasm while looking for the \nameref{pseudoop:endif}, so this can have some unexpected side-effects if further conditionals are encountered.

\begin{code}
  IF 0
    ; disabled block that won't assemble
  ENDIF
\end{code}\\



Paired with \nameref{pseudoop:endif}, \nameref{pseudoop:else}.\\

\hrule

\subsection{\texttt{ELSE}}
\label{pseudoop:else}
\index{Directives!Conditionals!\texttt{ELSE}}

\begin{usage}
  ELSE
\end{usage}

Begin an \nameref{pseudoop:else} block for the current conditional.

If the current conditional is \nameref{pseudoop:if} and \mono{exp} is undefined, the \nameref{pseudoop:else} will not be executed.

Paired with \nameref{pseudoop:if}, \nameref{pseudoop:ifconst}, \nameref{pseudoop:ifnconst}.\\


\hrule


\subsection{\texttt{ENDIF}, \texttt{EIF}}
\label{pseudoop:endif}
\label{pseudoop:eif}
\index{Directives!Conditionals!\texttt{ENDIF}}
\index{Directives!Conditionals!\texttt{EIF}}

\begin{usage}
  ENDIF
  EIF
\end{usage}

Terminate a conditional block.

\nameref{pseudoop:endif} are equivalent.

Paired with \nameref{pseudoop:if}, \nameref{pseudoop:ifconst}, \nameref{pseudoop:ifnconst}.\\

\hrule


\section{Code Generation}

There are two sets of directives that provide ways to insert meta-blocks of code and/or data. These are the \nameref{pseudoop:repeat}/\nameref{pseudoop:repend} pair, and \nameref{pseudoop:macro}s, which are described in their own chapter.

See \nameref{pseudoop:macro}.

\subsection{\texttt{REPEAT}}
\label{pseudoop:repeat}
\index{Directives!Code Generation!\texttt{REPEAT}}

\begin{usage}
  REPEAT exp
    ;body...
  REPEND
\end{usage}

\mono{exp} copies of the body are inserted at the current location, and assembled.

This looks like a loop, but it isn't. It's a text-insert of \mono{exp} blocks of code, so beware of code bloat when using this construct.  \nameref{pseudoop:repeat}/\nameref{pseudoop:repend} can be very useful for data table generation.

If \mono{exp==0}, the body is ignored.

If \mono{exp<0}, a warning ``\mono{REPEAT parameter < 0 (ignored)}'' is output and the body is ignored.

\subsubsection{Example}

\begin{code}[caption=Data Generation Using Nested Repeat Loops]
YV  SET 2
    REPEAT 2
XV  SET 2
      REPEAT 4
        .byte XV, YV, XV*YV
XV  SET XV+1
      REPEND
YV  SET YV+1
    REPEND
\end{code}

The above example generates the following code, which is then assembled:

\begin{code}
 .byte 2, 2, 4
 .byte 3, 2, 6
 .byte 4, 2, 8
 .byte 5, 2, 10
 .byte 2, 3, 6
 .byte 3, 3, 9
 .byte 4, 3, 12
 .byte 5, 3, 15
\end{code}

Labels within a \nameref{pseudoop:repeat} block should be local labels, preceeded by a
\nameref{pseudoop:subroutine} directive to keep them unique.

\subsubsection{Example}
\begin{code}
; Use SUBROUTINE to delineate local label usage
VAL SET 0
  REPEAT 4
  SUBROUTINE
    cmp #VAL
    bne .reused     ; reused local label
    ; do something here
    jmp .exit
.reused
VAL SET VAL+1
  REPEND    
.exit
\end{code}

The above example generates 4 blocks of code, each comparing with a specific immediate value and branching to a re-used local label which is made distinct by the use of the \nameref{pseudoop:subroutine} directive.

Paired with \nameref{pseudoop:repend}.\\

\hrule

\subsection{\texttt{REPEND}}
\label{pseudoop:repend}
\index{Directives!Code Generation!\texttt{REPEND}}

\begin{usage}
 REPEND
\end{usage}

Bottom or a \nameref{pseudoop:repeat}/\nameref{pseudoop:repend} block. They must be in matched pairs.

Any label to the left of a \nameref{pseudoop:repend} is assigned \textbf{after} the complete text insert for the \nameref{pseudoop:repeat}/\nameref{pseudoop:repend} block has finished.

Paired with \nameref{pseudoop:repeat}.\\


\hrule

\section{Structure}

\subsection{\texttt{ORG}}
\label{pseudoop:org}
\index{Directives!Control!\texttt{ORG}}

\begin{usage}
  ORG exp[,fill]
\end{usage}  
 
This directive sets the current origin.  You can also set the
global default fill character (a byte value) with this
directive.  No filler data are generated until the first
data-generating opcode/directive is encountered after this one.

Sequences like:

\begin{code}
    org  0,255
    org  100,0
    org  200
    dc   23
\end{code}

... will result in 200 zeroes and a 23. This allows you to specify
some \nameref{pseudoop:org}, then change your mind and specify some other (lower
address) \nameref{pseudoop:org} without causing an error (assuming nothing is
generated in-between).

Normally, \nameref{pseudoop:ds} and \nameref{pseudoop:align} are used to generate specific filler
values.

Any label on the \nameref{pseudoop:org} line will be allocated its value after the directive is processed.\\

\hrule



\subsection{\texttt{RORG}}
\label{pseudoop:rorg}
\index{Directives!Control!\texttt{RORG}}

\begin{usage}
  RORG exp
\end{usage}

This activates the relocatable origin.  All generated
addresses, including `.', although physically placed at the
true origin, will use values from the relocatable origin.
While in effect both the physical origin and relocatable origin
are updated.

The relocatable origin can skip around (no limitations).  The
relocatable origin is a function of the segment.  That is, you
can still \nameref{pseudoop:seg} to another segment that does not have a
relocatable origin activated, do other (independant) stuff
there, and then switch back to the current segment and continue
where you left off.

Any label on the \nameref{pseudoop:rorg} line will be allocated its value after the directive is processed.


\subsection{\texttt{REND}}
\label{pseudoop:rend}
\index{Directives!Control!\texttt{REND}}

\begin{usage}
  REND
\end{usage}


Deactivate the relocatable origin for the current segment.
Generation uses the real origin for reference.

Any label on the \nameref{pseudoop:rend} line will be allocated its value after the directive is processed.\\

\hrule



\subsection{\texttt{SEG}}
\label{pseudoop:seg}
\index{Directives!Control!\texttt{SEG}}

\begin{usage}
  SEG[.U] [name]
\end{usage}

This switches to a new segment, creating it if neccessary.  If the optional \mono{.U} extension is present, the segment is an \textbf{uninitialised} segment. Segments may be defined in parts; the \mono{.U} is not needed when going back to an already created uninitialized segment, though it makes the code more readable.

Unitialised segments are particularly useful for declaring variable locations without writing data to the binary output. They have no origin restrictions. This is useful for determining the size of a certain assembly sequence without generating code, and for assigning RAM addresses to labels.

An uninitialised segment with a \mono{name} will result in the generation of a warning for a \mono{reference to an unkonwn symbol}. This is harmless, but a good reason not to name uninitialised segments.

For segments which are not uninitialised, the segment name is used when producing the diagnostic output at the end of each pass to indicate the memory usage of the named segments. For uninitialised segments, use of a segment name will generate a ``reference to undefined symbol'' warning that can be ignored.

Any label on the \mono{SEG} line will be allocated its value after the directive is processed.

The following should be considered when generating ROMs:

\begin{itemize}
	\item The default fill character when using \nameref{pseudoop:org} (and \nameref{flag:definesymbolF} \mono{-f1} or \mono{-f3}) to
	skip forward in segments is 0. This is a \textbf{global} default and affects all segments.
	\item The fill value for \nameref{pseudoop:ds} has nothing to do with segment space padding, so don't confuse them!
\end{itemize}

\subsubsection{Example}

\begin{code}[caption=Declaration of Variables]		
; Declaration of zero page variables
  SEG.U variables
  ORG $80
foo1          ds 1
bar2          ds 10
varn          ds 2
\end{code}

In the example shown above, the \mono{variables} segment is unitialised. The zero-page variables (starting at location \mono{\$80}) \mono{foo1}, \mono{bar2}, and \mono{varn} are declared using \mono{DS} directive to ``reserve/allocate'' appropriate amounts of memory. Their addresses are automatically calculated by \dasm. The relevant part of the symbol table is shown below, to make clear that although the segment is unitialised, the labels/variables have correct values.

\begin{outputx}
foo1                     0080                  
bar2                     0081                  
varn                     008b                  
\end{outputx}\\

\hrule

\subsection{\texttt{ALIGN}}
\label{pseudoop:align}
\index{Directives!Control!\texttt{ALIGN}}

\begin{usage}
  ALIGN n[,fill]
\end{usage}

Align the current program counter to an n-byte boundry.	If the \mono{fill} option is present, then that value will be used to fill the space generated. The default fill value is \mono{0}. The \nameref{pseudoop:align} default value should not be confused with the \nameref{pseudoop:org} 
directive's default fill value.

Any label on the \nameref{pseudoop:align} line will be associated its value after the directive is processed.

\subsubsection{Example}

\begin{code}
; using ALIGN to move to 256-byte page boundary
  ORG $1000
  DS 10
  ; origin now $100A
  ALIGN 256
  ; origin now $1100
\end{code}\\

\hrule




\section{Control}


\subsection{\texttt{PROCESSOR}}
\label{changelog:20200824processor}
\label{pseudoop:processor}
\index{Directives!Control!\texttt{PROCESSOR}}
\index{Processor}

\begin{usage}
  PROCESSOR type
\end{usage}

\dasm needs to know the target microprocessor for which it is assembling the code.

This is indicated via the \nameref{pseudoop:processor} directive, which should
be the first line (other than whitespace and comments) in your source code file.
Only one \nameref{pseudoop:processor} directive may be declared in the entire assembly.

	
	The \nameref{pseudoop:processor} directive appears in the source code before the declaration of code origin, and thus any label present on the same line will remain unresolved at the end of assembly, causing an error.
	
	Thus, do not place a label on the \nameref{pseudoop:processor} line.
	
\subsubsection{Supported Microprocessors}	
\index{Processor!Supported Microprocessors}	
\begin{table}[H]
\begin{tabularx}{\textwidth}{llll}
\toprule
\textbf{\mono{type}}&\textbf{Identity}&\textbf{Endian}&\textbf{Byte Order}\\
\hline
\\
\nameref{processor:6502}      &MOS Technology 6502   &little-endian  &\mono{LSB}, \mono{MSB}\\
\nameref{processor:68HC11}    &Motorola 68HC11       &big-endian     &\mono{MSB}, \mono{LSB}\\
\nameref{processor:68705}     &Motorola 68705        &big-endian     &\mono{MSB}, \mono{LSB}\\
\nameref{processor:6803}      &Motorola 6803         &big-endian     &\mono{MSB}, \mono{LSB}\\
\nameref{processor:6303}    &Hitachi HD6303        &big-endian     &\mono{MSB}, \mono{LSB}\\
\nameref{processor:f8}        &Fairchild F8          &big-endian     &\mono{MSB}, \mono{LSB}\\
\nameref{processor:MC68HC908} &Motorola MC68HC908&big-endian& \mono{MSB}, \mono{LSB}\\
\\
\bottomrule
\end{tabularx}
\end{table}
	
\subsubsection{Example}
\begin{code}
  PROCESSOR 6502
\end{code}	

\index{Processor!Atari 2600}
For the \mono{6507} microprocessor (as used in the Atari 2600 machine), use ``\nameref{pseudoop:processor} \mono{6502}'' as these two microprocessors are identical except for their addressing range.
	
Different processor	models use different endianness (byte ordering of word values, being little-endian or big-endian). The processor's endiannessdoes not affect the header in the output files (\mono{-f1} and \mono{-f2}), which are always little-endian (\mono{LSB}, \mono{MSB}).  The processor byte ordering affects all address, word, andlong values.\\

\hrule

\subsection{\texttt{ECHO}}
\label{pseudoop:echo}
\index{Directives!Control!\texttt{ECHO}}

\begin{usage}
  ECHO exp[,exp...]
\end{usage}

The expressions (which may also be strings), are echoed on the
screen and into the list file.\\

\index{Number Format!Decimal Display of}
To output values in decimal use the format \mono{[exp]d}

\subsubsection{Example}

\begin{code}
answer = 42
  ECHO "Hex=",answer,"Decimal=",[answer]d
\end{code}

\begin{outputx}
Hex= $2a Decimal= 42
\end{outputx}

\hrule

\subsection{\texttt{SUBROUTINE}}
\label{pseudoop:subroutine}
\index{Directives!Control!\texttt{SUBROUTINE}}

\begin{usage}
  SUBROUTINE [name]
\end{usage}

This isn't really a subroutine, but a boundary that resets the scope of \nameref{locallabels}. Those which are defined before the \nameref{pseudoop:subroutine} directive are not visible after it.

\index{Labels!Scope}
\index{Scope!Local Labels}
Local labels must be unique within the scope of the subroutine in which they are defined, and cannot be accessed outside of that scope. Local label names do not need to be unique, provided that they are not duplicated within a single scope. In other words, names can be re-used.

\index{Macros!Scope}
\index{Scope!Macros}
Macros implicitly define a new subroutine scope both at their beginning, and end. Local labels defined inside a macro are not avalable outside it, and local labels defined before a macro usage instance are also no longer visible after the instantiation. Automatic new local label scope boundries occur for each macro level.


\subsubsection{Example}

\begin{code}
Fn10
            SUBROUTINE
.loop       dex           ; 1st definition of .loop
            bne .loop     ; branches to 1st .loop
.exit       rts

Fn20        SUBROUTINE

  ; new scope here because of the SUBROUTINE directive
  ; previous local labels are no longer reachable

.loop       dex           ; 2nd definition of .loop
            bne .loop     ; branches to 2nd .loop
            
            jmp .exit     ; ERROR - out of scope
            
\end{code}

The above example defines two functions (\mono{Fn10}, \mono{Fn20}) which both use the local label \mono{.loop}. The correct label for each is used by the branch, by way of the \nameref{pseudoop:subroutine} directive  setting local scope.  If the second \nameref{pseudoop:subroutine} directive  was removed, the assembler would generate an error because of the duplicate label.

Note that the function name label can be on the same line as the directive, if desired.

\index{Scope!Implicit}
An implicit \nameref{pseudoop:subroutine} scope is in effect when \nameref{macros} are instantiated, so local labels cannot be accessed spanning a macro instantiation.\\

\subsubsection{Example}

\begin{code}
  MAC DO
  ; body
  ENDM

.lab
  jmp .lab     ; OK
  
  DO  ; instantiate macro
  
  jmp .lab     ; ERROR
\end{code}

See \nameref{pseudoop:mac}.


\hrule
\subsection{\texttt{ERR}}
\label{pseudoop:err}
\index{Directives!Control!\texttt{ERR}}

\begin{usage}
  ERR
\end{usage}

Abort assembly. Useful in conjunction with \nameref{conditionals} to end an essembly if required.

\subsubsection{Example}

\begin{code}
  MAC CALL ; function name
    IFNCONST {1}
FNAME SETSTR {1}
      ECHO FNAME," does not exist!"
      ERR
    ELSE
      jsr {1}
    ENDIF
  ENDM

test

  CALL test         ; OK
  CALL test2        ; "test2 does not exist!" then halts
\end{code}

\begin{outputx}
test2 does not exist!
source.asm (37): error: ERR pseudo-op encountered
\end{outputx}

\hrule



\subsection{\texttt{LIST}}
\label{pseudoop:list}
\index{Directives!Control!\texttt{LIST ON}}
\index{Directives!Control!\texttt{LIST OFF}}

\begin{usage}
  LIST ON|OFF
\end{usage}

Globally turns listing on or off, starting with the current
line.

When you use \nameref{pseudoop:list} the effect is local to the
current macro or included file. For a line to be listed both
the global and local list switches must be on.\\

\hrule


\subsection{\texttt{.FORCE}}
\label{pseudoop:force}
\index{Directives!\texttt{[.FORCE]}}
\index{Addressing!.0 Implied}
\index{Addressing!.0x Implied (0,x)}
\index{Addressing!.0y Implied, (0,y)}
\index{Addressing!.a Absolute}
\index{Addressing!.b Byte}
\index{Addressing!.bx Byte Address  Indexed,  x}

\begin{usage}
  mnemonic[.force]
\end{usage}

FORCE extensions (placed after a mnemonic) are used to force an addressing mode.  In some cases,
you can optimize the assembly to take fewer passes by telling it the
addressing mode.  Force extensions are also used with \mono{DS},\mono{DC}, and \mono{DV}
to determine the element size.

\textbf{Not all extensions are available for all processor types.}

\begin{table}[H]
\begin{tabularx}{\linewidth}{cl}
\toprule
\textbf{Extension} & \textbf{Function}\\
\hline
\\
\mono{.0}   &Implied\\
\mono{.0x}  &Implied indexing \mono{(0,x)}\\
\mono{.0y}  &Implied indexing \mono{(0,y)}\\
\mono{.a}   &Absolute (equivalent to \mono{.e}, \mono{.w})\\
\mono{.b}   &\mono{byte} (equivalent to \mono{.d}, \mono{.z})\\
\mono{.bx}  &\mono{byte} address indexed \mono{x}\\
\mono{.by}  &\mono{byte} address indexed \mono{y}\\
\mono{.d}   &Direct (equivalent to \mono{.b}, \mono{.z})\\
\mono{.e}   &Extended (equivalent to \mono{.a}, \mono{.w})\\
\mono{.i}   &Implied\\
\mono{.ind} &Indirect \mono{word}\\
\mono{.l}   &\mono{long word} (4 bytes) (\mono{DS}/\mono{DC}/\mono{DV})\\
\mono{.r}   &Relative\\
\mono{.u}   &Uninitialized (\nameref{pseudoop:seg})\\
\mono{.w}   &\mono{word} address (equivalent to \mono{.a}, \mono{.e})\\
\mono{.wx}  &\mono{word} address indexed \mono{x}\\
\mono{.wy}  &\mono{word} address indexed \mono{y}\\
\mono{.z}   &Zero page (equivalent to \mono{.b}, \mono{.d})\\
\\
\bottomrule
\end{tabularx}
\end{table}


\label{changelog:20200829substitutions}
First character equivalent substitutions:

\begin{table}[H]
\begin{tabularx}{\linewidth}{cccl}
\toprule
\textbf{Orig}&\textbf{Alt}&\textbf{Alt}&\textbf{Meaning}\\
\hline
\\
	\mono{b} &\mono{z} &\mono{d}	&    byte, zeropage, direct\\
	\mono{w} &\mono{e} &\mono{a}	&    word, extended, absolute\\
\bottomrule
\end{tabularx}
\end{table}



\begin{savequote}
\sffamily
``Everyone is against micro managing but macro managing means you're working at the big picture but don't know the details.''
\qauthor{Henry Mintzberg}
\end{savequote}

\chapter{Macros}
\label{macros}
\index{Macros}

Macros are user-defined \nameref{chapter:pseudoops}, and when used well they can provide extremely powerful code constructs and simplify programming.

A macro is effectively a text-substitution template. Wherever the name of a macro is used, the body of the macro is inserted. During the insertion, parameters passed to the macro may be substituted inside the body as specified by the macro definition.

\includegraphics[width=1cm]{important}Macros automatically generate an implicit \nameref{pseudoop:subroutine} when instantiated, which guarantees distinct local labels for that macro instance.

This can sometimes be inconvenient, as it can ``hide'' local labels in code using the macro, but there is currently no way known to prevent this.

\section{Usage}

\subsection{\texttt{MAC}, \texttt{MACRO}}
\label{pseudoop:mac}
\label{pseudoop:macro}
\index{Macros}
\index{Macros!\texttt{MAC}}
\index{Macros!\texttt{MACRO}}
%\index{Directives!Macros!\texttt{MAC}}
%\index{Directives!Macros!\texttt{MACRO}}

\begin{usage}
; Declaration
; parameters available as {1}, {2}, etc.
; {0} = full instantiation line
  MAC name
    ; body line 1
    ; ...
    ; body line n
  ENDM
\end{usage}

\begin{usage}
; Instantiation
  name param1, param2, ...
\end{usage}
	
	\nameref{pseudoop:mac} are equivalent.

	
	Source code lines between \nameref{pseudoop:mac} and \nameref{pseudoop:endm} are the macro's body.
	You cannot recursively declare a macro.  You can, however, recursively
	use a macro (reference a macro in a macro).
		
No label is allowed on the macro declaration line.

The macro name is not case-sensitive, either in declaration or use.

Macros can be redefined, so beware of potential issues related to unexpected usage.

You should always use \nameref{locallabels} (e.g., \mono{.loop}) inside macros which you use
more than once.
	
Macros are instantiated by using the macro's name (case-insensitive), followed by an optional list of arguments. The body of the macro definition can refer to arguments passed with the format ``\mono{\{\#\}}'', where \mono{\#} is replaced by the argument number. The first argument passed to a macro is therefore \mono{\{1\}}. \mono{\{0\}} represents an exact substitution of the entire instantiation line.
	
	\subsubsection{Examples}
	
\begin{code}[caption=Vector Table Generation using a MACRO]
; Generate low/high tables pointing to functions

; Uses a macro to contain the list of functions,
; and the parameter to declare low byte or high byte
	
  MAC VECTORS
  ; usage: {1} is < or >
    .byte {1}Routine1
    .byte {1}Routine2
    .byte {1}Routine3
  ENDM
	
LoTable VECTORS <
HiTable VECTORS > 
\end{code}
	
In the above example, a list of pointers to functions is generated in two tables (one containing the low addresses of the functions, and the other the high addresses). These two tables are always in-synch (no extra or missing entries) through the single-point definitino in the macro itself.

The two calls to the macro generate the low bytes and the high bytes into two separate tables. This will result in the following code being generated, and then inserted into the source code in place of the macro calls...
	
\begin{code}[caption=Output]
LoTable
	.byte <Routine1
	.byte <Routine2
	.byte <Routine3
HiTable
	.byte >Routine1
	.byte >Routine2
	.byte >Routine3
	
	\end{code}
		
\subsubsection{Example}

\begin{code}
; Inserts a page break if the object would overlap a page

  MAC OPTIONAL_PAGEBREAK ; { labelString, size }
    IF (>( * + {2} -1 )) > ( >* )
.EARLY_LOCATION  SET *
      ALIGN 256
        ECHO "Page break for", {1}
        ECHO "wasted", [* - .EARLY_LOCATION]d, "bytes"
    ENDIF
  ENDM
\end{code}		
		
		
		
Paired with \nameref{pseudoop:endm}.\\

\hrule

	
\subsection{\texttt{ENDM}}
\label{pseudoop:endm}
%\index{Directives!Macros!\texttt{ENDM}}
\index{Macros!\texttt{ENDM}}
	
\begin{usage}
  ENDM
\end{usage}
		
		End of macro definition.
		
		\textbf{No label is allowed to the left of the directive.}

Paired with \nameref{pseudoop:mac}.\\
		
\hrule
		
\subsection{\texttt{MEXIT}}
\index{Macros}
%\index{Directives!Macros!\texttt{MEXIT}}
\index{Macros!\texttt{MEXIT}}

\begin{usage}
  MEXIT
\end{usage}

Used in conjuction with conditionals.  Exits the current macro level.

See \nameref{conditionals}.


