2.10. Text Formatting
Text formatting inserts values into a string at placeholders such as {}.
The format string supplies the surrounding text; a separate argument list
supplies the values. DQ uses this text formatting syntax in multiple places,
such as printing or creating exception messages.
DQ aims to be compatible with the brace-based formatting syntax of C++
std::format and Python str.format(). This chapter describes the currently
supported placeholders and options.
2.10.1 Compile-Time String Interpolation
Inside a string literal, \{expression} inserts a constant value. Add a colon
and a format specification to control its presentation:
const NUM : int = 123
const STR : rostr = "\{NUM:5} times..." // " 123 times..."
const HEX : rostr = "\{NUM:04X}" // "007B"
const LABEL : rostr = "\{DQ.PKGNAME:<30}"
const PATH : rostr = "\{DQ.PKGNAME}/arma/rk/impl/hwuart_rk"
Expressions can contain arithmetic, named constants, nested parentheses and strings, and compile-time intrinsics. Supported values are integers, floats, booleans, characters, enums (formatted as their ordinal value), and constant text. Runtime variables and ordinary function calls are rejected, even when the enclosing string is used at runtime.
The compiler uses C++ std::vformat for these specifications: for example,
5 sets a minimum width, <30 left-aligns, 04X zero-pads hexadecimal output,
and .2f selects two fractional digits. DQ's u unsigned-decimal spelling is
also accepted. Characters default to text, including UTF-8 for Unicode
characters; numeric specifications format their character codes. Invalid
specifications produce compile errors. Width and precision must be literal
parts of the specification; nested replacement fields are not supported.
Interpolation works in single-, double-, and triple-quoted literals. Ordinary
braces remain literal; \\{ writes a literal \{. Inserted text is not parsed
again for escapes or interpolation. Multiline indentation is removed from the
source text, preserving whitespace in inserted values.
The result is one compile-time literal, usable in const declarations and
module paths. It requires no runtime formatting or dynamic strings and works
with --no-dynstrings. These interpolations apply to expression strings;
quoted filenames in directives such as #include retain their literal syntax.
2.10.2 Compiler Properties
DQ is a compiler-provided object with read-only compile-time properties.
It has no runtime storage, requires no import, and cannot be shadowed by a
user declaration. Property names are case-sensitive and do not take parentheses.
| Property | Value |
|---|---|
DQ.PKGNAME |
Configured package containing the current source file, without a trailing slash |
DQ.FILENAME |
Source filename including its extension, without directories |
DQ.FILEPATH |
Absolute, lexically normalized source-file path |
DQ.FILEDIR |
Parent directory of that source file |
DQ.LINE |
One-based source line of the DQ token |
DQ.COLUMN |
One-based UTF-8 byte column of the DQ token, matching compiler diagnostics |
DQ.FUNCNAME |
Unqualified name of the enclosing function or method |
Properties are evaluated where they appear. Included fragments use their own source file; returning from an include restores the enclosing source context. Assigning a property to an ordinary constant captures its value at that declaration, even when that constant is later imported by another module.
DQ.PKGNAME requires membership in a configured package, and DQ.FUNCNAME
requires an enclosing function. Using either outside its applicable context is
a compile error. Other file and location properties also work in standalone
source files. DQ itself is not a value that can be assigned or passed around.
const IMPLEMENTATION : rostr = "\{DQ.PKGNAME}/drivers/uart"
const LOCATION : rostr = "\{DQ.FILENAME}:\{DQ.LINE}"
2.10.3 A Simple Print Example
The examples use PrintLn from use print. Unless stated otherwise, they
use these single-letter variables. The type-specific subsections repeat the
relevant declarations so their examples can be read independently.
var i : int = 42
var n : uint = 255
var f : float = 3.5
var s : rostr = "Amy"
var b : bool = true
var c : char = 'A'
var w : wchar = '€'
var p : ^int = %i
PrintLn("Hello, {}!", [s]) // = "Hello, Amy!"
{} is replaced by the first value in [s]. The square brackets belong to
the DQ argument-list expression; they are not printed. PrintLn adds a newline
after the result. Multiple placeholders consume values from left to right:
PrintLn("{} has {} messages.", [s, i]) // = "Amy has 42 messages."
2.10.4 Formatting Arguments: varargs
To print formatted text to the standard output use these functions from the print package:
Print(fmt : strslice, args : varargs)
PrintLn(fmt : strslice, args : varargs)
fmt is the format string. args is a borrowed list of values and their types.
2.10.4.1 Writing the Argument List
Group multiple values in brackets and separate them with commas. The values can have different types, and the caller evaluates them from left to right.
PrintLn("name={}, count={}, active={}", [s, i, b]) // = "name=Amy, count=42, active=true"
Each element can also be an expression:
PrintLn("next={}, doubled={}", [i + 1, i * 2]) // = "next=43, doubled=84"
Pass one value directly or in a one-element list. Use [] for an empty list.
The entire list occupies one argument position.
PrintLn("count={}", i) // = "count=42"
PrintLn("count={}", [i]) // = "count=42"
PrintLn("{} {}", s, i) // ERROR: too many arguments
2.10.4.2 Which Values Can Be Passed?
| Value type | Example argument | Default output with {} |
|---|---|---|
| Signed integers | -7, an int32 or int64 variable |
Signed decimal number |
| Unsigned integers | A uint or uint64 variable |
Unsigned decimal number |
| Floating-point numbers | 3.5, a float32, float64, or float variable |
Decimal number |
| Boolean values | true, false, a comparison |
true or false |
char |
A char variable |
One byte written as a character |
wchar |
'€', a wchar variable |
One Unicode character encoded as UTF-8 |
char16 |
A char16 variable |
One Unicode character; converted to wchar |
| Text | A literal, str, rostr, strslice, embstr(N), or unsized embstr |
The text bytes |
^char |
A pointer to zero-terminated text | The pointed-to text |
| Other typed or generic pointers | A ^int or pointer variable |
Address in hexadecimal with a leading ^ |
| Nil pointer | nil |
^0 |
The formatter preserves the value's type. A text value containing "42" is
still text, and an integer containing 42 is still a number. The placeholder
can choose a representation, but it does not perform arbitrary conversions
between these categories.
PrintLn("{} / {} / {} / {}", [i, f, b, w]) // = "42 / 3.5 / true / €"
Objects, structures, function references, and whole arrays cannot be passed as values for automatic formatting. Select their fields or elements instead.
var a : [3]int = [10, 20, 30]
PrintLn("first={}, count={}", [a[0], a.length]) // = "first=10, count=3"
For a stored anyvalue, pass a value read with an accessor
such as AsInt or AsText.
2.10.4.3 Forwarding Arguments
A function can pass its varargs parameter directly to another formatter.
The list is valid throughout the original call.
func Log(fmt : strslice, args : varargs):
PrintLn(fmt, args)
endfunc
Log("{} has {} messages.", [s, i]) // = "Amy has 42 messages."
2.10.4.4 Matching Values to Format String Placeholders
Each placeholder uses the next value. To print the same value multiple times, include
it in the args multiple times:
PrintLn("{} + {} = {}", [i, i, i + i]) // = "42 + 42 = 84"
One argument is used for each placeholder. There are no named or numbered argument
references. The current formatter writes null for a missing argument and
ignores arguments left over after the last placeholder:
PrintLn("{} / {}", [s]) // = "Amy / null"
PrintLn("{}", [s, i]) // = "Amy"
These mismatches do not generate compile-time or runtime errors.
2.10.5 Format String Placeholders
Ordinary characters in the format string are copied to the output. Each
{...} placeholder inserts the next argument. {} uses the default
representation; a colon introduces formatting options.
2.10.5.1 Main Placeholder Variants
| Form | Accepted values | Meaning |
|---|---|---|
{} / {:?} |
Any supported value | Default representation. Use this for bool types |
{:d} |
Integers, characters | Signed decimal number or character code |
{:u} |
Integers, characters | Unsigned decimal number or character code |
{:x} |
Integers, characters | Lowercase hexadecimal |
{:X} |
Integers, characters | Uppercase hexadecimal |
{:p} |
Pointer values | Hexadecimal address with a leading ^ |
{:s} |
Text, characters | Text bytes or a character |
{:f} |
Floating-point values | Decimal floating-point output |
{{ |
No argument | Literal { |
}} |
No argument | Literal } |
2.10.5.2 Signed Integers: {:d}
Use {:d} for signed decimal output. {} gives the same result for a signed
integer.
var i : int = 42
PrintLn("{:d}", [i]) // = "42"
PrintLn("[{:6d}]", [i]) // = "[ 42]": minimum width
PrintLn("{:06d}", [i]) // = "000042": zero padding
PrintLn("{:+d}", [i]) // = "+42": explicit sign
PrintLn("{:+06d}", [i]) // = "+00042": sign followed by zero padding
PrintLn("[{: d}]", [i]) // = "[ 42]": reserve a sign position
PrintLn("{:06d}", [-i]) // = "-00042": negative sign before the zeros
PrintLn("[{:<6d}]", [i]) // = "[42 ]": left alignment
2.10.5.3 Unsigned Integers: {:u}
Use {:u} for unsigned decimal output, including the full range of uint.
var n : uint = 255
PrintLn("{:u}", [n]) // = "255"
PrintLn("[{:6u}]", [n]) // = "[ 255]"
PrintLn("{:06u}", [n]) // = "000255"
PrintLn("[{:<6u}]", [n]) // = "[255 ]"
2.10.5.4 Hexadecimal Integers: {:x} and {:X}
Use x for lowercase digits and X for uppercase digits. These formats accept
signed and unsigned integers.
var n : uint = 255
PrintLn("{:x}", [n]) // = "ff"
PrintLn("{:X}", [n]) // = "FF"
PrintLn("{:08X}", [n]) // = "000000FF": zero-padded hexadecimal
PrintLn("0x{:x}", [n]) // = "0xff": add the prefix as literal text
2.10.5.5 Floating-Point Numbers: {:f}
Use {:f} for decimal floating-point output.
var f : float = 3.5
PrintLn("{:f}", [f]) // = "3.5"
PrintLn("{:.2f}", [f]) // = "3.50": two fractional digits
PrintLn("{:.0f}", [f]) // = "4": rounded to a whole number
PrintLn("[{:8.2f}]", [f]) // = "[ 3.50]": width includes the decimal point
PrintLn("{:+.2f}", [f]) // = "+3.50"
PrintLn("{:+08.2f}", [f]) // = "+0003.50"
PrintLn("[{:<8.2f}]", [f]) // = "[3.50 ]"
An explicit precision fixes the number of digits after the decimal point,
rounding as needed and retaining trailing zeros. The decimal separator is a
dot. Without explicit precision, {} and {:f} use up to 15 fractional digits
and remove trailing zeros. Explicit precision is limited to 18 fractional digits.
The f placeholder requires a floating-point value; it does not convert an
integer to a float.
2.10.5.6 Text: {:s}
Use {:s} or {} for text. The same formats accept the other supported
string types and ^char. Here, t contains ten characters.
var s : rostr = "Amy"
var t : rostr = "abcdefghij"
PrintLn("{:s}", [s]) // = "Amy"
PrintLn("[{:8s}]", [s]) // = "[ Amy]": right alignment is the default
PrintLn("[{:<8s}]", [s]) // = "[Amy ]": left-aligned text column
PrintLn("[{:>8s}]", [s]) // = "[ Amy]": explicit right alignment
PrintLn("[{:^8s}]", [s]) // = "[ Amy ]": centered text
PrintLn("[{:8s}]", [t]) // = "[abcdefghij]": longer text is not truncated
The s kind is optional: {:8} and {:8s} both reserve a right-aligned field
at least eight Unicode code points wide. Width never truncates longer text.
2.10.5.7 Booleans: {}
Use {} or {:?} for bool; there is no separate Boolean format letter.
var b : bool = true
PrintLn("{}", [b]) // = "true"
PrintLn("{}", [not b]) // = "false"
PrintLn("[{:6}]", [b]) // = "[ true]"
2.10.5.8 Characters: {:s}
Default formatting and {:s} write a character. Explicit numeric formats
write its code.
var c : char = 'A'
var w : wchar = '€'
PrintLn("{}", [c]) // = "A"
PrintLn("{}", [w]) // = "€"
PrintLn("{:s}", [w]) // = "€"
PrintLn("{:d}", [c]) // = "65"
PrintLn("{:u}", [w]) // = "8364"
PrintLn("{:04X}", [c]) // = "0041"
A char writes one byte; a wchar is encoded as UTF-8. A char16 value is
converted to wchar before formatting. A UTF-16 surrogate pair is not combined
automatically when its two code units are passed as two arguments. Convert
UTF-16 text with StrFromUtf16() first. An invalid Unicode character value,
including an isolated surrogate, produces �.
2.10.5.9 Pointers: {:p}
Use {:p} or {} for an address in hexadecimal with a leading ^.
%i takes the address of i. The output below uses an example address;
the actual address varies between runs.
var i : int = 42
var p : ^int = %i
var z : pointer = nil
var pc : ^char = "abc"
PrintLn("{:p}", [p]) // = "^7FFC1234ABCD": address of i
PrintLn("{}", [p]) // = "^7FFC1234ABCD": same address with default formatting
PrintLn("{:p}", [z]) // = "^0": nil pointer
PrintLn("{}", [pc]) // = "abc": ^char is treated as text
PrintLn("{:p}", [pointer(pc)]) // = "^401234": convert to pointer to print the address
2.10.5.10 Missing Arguments and Nil Pointers
A missing argument prints null. A supplied nil pointer prints ^0.
PrintLn("{} / {}", nil) // = "^0 / null"
2.10.5.11 Literal Braces and Escaping
Double each brace in a format string to print one literal brace. Escaped braces
do not consume arguments. In a double-quoted string literal, escape embedded
double quotes as \":
var s : rostr = "Amy"
PrintLn("{{{}}}", [s]) // = "{Amy}"
PrintLn("{{\"name\":\"{}\"}}", [s]) // = '{"name":"Amy"}': escaped double quotes
PrintLn('{{"name":"{}"}}', [s]) // = '{"name":"Amy"}': single outer quotes avoid internal escaping
PrintLn("{{}}", []) // = "{}": just the literal braces
PrintLn("{}") // = "{}": no doubling need at non-formatting print
2.10.6 Width, Fill, Sign, Precision
The type-specific examples above show the common combinations. The supported option order is:
{: [alignment] [sign] [0] [width] [.precision] [kind] }
Spaces and square brackets in this diagram are explanatory; do not write them in the placeholder. Each bracketed part is optional.
| Option | Example | Meaning |
|---|---|---|
< |
{:<8s} |
Left-align within the field |
> |
{:>8s} |
Right-align within the field |
^ |
{:^8s} |
Center within the field |
+ |
{:+d} |
Show + for a non-negative signed number or float |
- |
{:-d} |
Show a sign only for negative values; this is the default |
| Space | {: d} |
Use a leading space for a non-negative signed number or float |
0 |
{:06d} |
Use zeros for right-aligned numeric padding |
| Width | {:8s} |
Reserve a field at least eight Unicode code points wide |
| Precision | {:.2f} |
Write two digits after the decimal point |
Width and alignment work with text, characters, numbers, Boolean values, null,
and pointers. DQ defaults to right alignment for every value type. < pads
on the right, > pads on the left, and ^ divides padding between both sides.
If centering needs an odd number of spaces, the extra space goes on the right.
Width is a minimum, not a maximum: longer values are never truncated to fit.
Width counts Unicode code points, not UTF-8 bytes. For example, € counts
as one code point even though its UTF-8 encoding uses three bytes, and café
counts as four:
var w : wchar = '€'
var s : rostr = "café"
PrintLn("[{:>5s}]", [w]) // = "[ €]": four spaces plus one code point
PrintLn("[{:>6s}]", [s]) // = "[ café]": right alignment
PrintLn("[{:<6s}]", [s]) // = "[café ]": left alignment
PrintLn("[{:^6s}]", [s]) // = "[ café ]": centered text
Combining marks count separately. Width does not measure visual character groups or terminal display columns.
A negative sign is written automatically. + also requests a sign for
non-negative signed numbers and floating-point values. A space sign option
reserves a sign position without writing +. The - option requests the
default sign behavior; use < for left alignment.
Zero padding applies to right-aligned numbers and is written after the sign
or pointer prefix. Left and center alignment use spaces even if 0 is present.
Text and character output also use spaces.
Write alignment first, followed by the sign, zero fill, and width. For example,
{:^+8d} centers a signed number, and {:+08d} enables zero fill with a sign.
The former zero-before-sign spelling {:0+8d} is no longer supported.
2.10.7 Formatting APIs and Destinations
The same placeholders and varargs argument syntax work with each API:
| API | Destination | Availability |
|---|---|---|
Print(fmt, args) / PrintLn(fmt, args) |
Standard output | use print |
Format(fmt, args) |
A new str |
Implicit sys; requires dynamic-string support |
.AddFmt(fmt, args) on str |
Appends to a dynamic string | Requires dynamic-string support |
.AddFmt(fmt, args) on embstr |
Appends to a fixed buffer | Works without dynamic-string support |
Exception(fmt, args) |
Exception message | Requires exception support |
The fmt parameter is strslice: literals, str, rostr, embstr, and
existing slices can be passed directly. Even a substring can be used as the format:
var i : int = 42
var s : rostr = "{} ignored"
PrintLn(s[0:2], [i]) // = "42": only the "{}" slice is parsed
2.10.7.1 Print and PrintLn
Print(text : strslice)
Print(fmt : strslice, args : varargs)
PrintLn()
PrintLn(text : strslice)
PrintLn(fmt : strslice, args : varargs)
Print writes without adding a newline. PrintLn adds a newline, and
PrintLn() writes a blank line.
Print("Hello, {}", [s]) // = "Hello, Amy": without a newline
PrintLn("!") // = "!": followed by a newline
PrintLn() // = "": a blank line
The one-argument form writes its text literally, without interpreting placeholders or escaped braces. Supplying the second argument selects the formatting overload:
PrintLn("{}") // = "{}"
PrintLn("{{}}") // = "{{}}"
PrintLn("{{}}", []) // = "{}"
2.10.7.2 Format
Format(fmt : strslice, args : varargs) -> str
Use Format() when the result should be stored or returned rather than
immediately printed. Format() is included in the implicit sys, which
means it is available without a use declaration.
var s : str = Format("item-{:04d}", [i]) // = "item-0042": contents of s
Format() is also useful when passing formatted text to a function that does
not support formatting itself. For example, a database connection's
.Execute(sql) method takes a complete SQL statement. Here, dbconn is an open
database connection and items is a table with one integer column:
var i : int = 42
dbconn.Execute(Format("INSERT INTO items VALUES ({:d})", [i]))
2.10.7.3 .AddFmt
.AddFmt(fmt : strslice, args : varargs)
.AddFmt() appends to the existing contents of the str or embstr.
str and embstr(n) declarations without initializers initialize the string
variables empty, so .AddFmt() can be called immediately (calling.Clear()
before is not necessary):
var ds : str
ds.AddFmt("Order {}: {} items", [i, n]) // = "Order 42: 255 items": contents of s
var es : embstr(32)
es.AddFmt("mask = {:04X}", [n]) // = "mask = 00FF": contents of s
A str grows as needed by re-allocating its storage memory. An embstr(N) keeps its fixed buffer, including space
for the terminating zero, so formatting can truncate the result:
var es : embstr(8)
es.AddFmt("{}", ["abcdefghij"]) // = "abcdefg": contents of s; seven bytes plus the terminator fit
Repeated .AddFmt() calls can assemble a larger message. Reserve space with
.Reserve() first when the expected size of a dynamic string is known. This
avoids repeated buffer growth and can reduce heap fragmentation.
The following example reserves 50000 bytes, enough for the numbers 1 through 10000, each followed by a space:
use print
func AppendNumbers(s : ref str):
for i : int = 1 to 10000:
s.AddFmt("{:d} ", [i])
endfor
endfunc
func *Main():
var s : str
s.Reserve(50000)
AppendNumbers(s)
PrintLn("String length: {}", [s.length]) // = "String length: 48894"
endfunc
2.10.7.4 Exception Messages
The text formatting can be used at rising exceptions too:
var i : int = -42
if i < 1:
raise Exception("invalid count: {}", [i]) // = "invalid count: 42"
endif
See Exceptions and Error Handling for raising, catching, and inspecting exceptions.
2.10.8 Argument and Error Rules
Formatting uses the stored value's type. For example, {:f} requires a float,
while {:d} expects an integer or a character code. Convert the value explicitly
before formatting when another category is needed:
PrintLn("{:.2f}", [float(i)]) // = "42.00"
PrintLn("{:d}", [StrToInt("42")]) // = "42"
A type/format mismatch produces a diagnostic marker instead of throwing a formatting exception:
PrintLn("{:f}", [i]) // = "<i-f!>": an integer with a float placeholder
PrintLn("{:d}", [s]) // = "<s-f!>": text with a numeric placeholder
PrintLn("{:d}", [b]) // = "<b-f!>": a Boolean with a numeric placeholder
2.10.8.1 Low-Level Formatter Flags
Format(), .AddFmt(), and the print helpers do not return a formatting status.
For direct control, rtl/textformat exposes OTextFormatter, which writes
through an OTextSink such as OTextSinkEmbStr, OTextSinkStr, or
OTextSinkStdOut. Its .flags records DQFMT_FMT_ERROR for malformed braces
or unsupported format options, and DQFMT_ARG_ERROR for incompatible value
types or invalid Unicode characters. Each formatting call resets the flags.
With use rtl/textformat, let t be an OTextFormatter connected to the
desired sink:
t.Format("{:f}", [i]) // = "<i-f!>": sets t.flags to DQFMT_ARG_ERROR
The runtime also defines DQFMT_TRUNCATED and DQFMT_SINK_ERROR, but the current
built-in sinks do not set them when a fixed buffer fills. Keep the destination
capacity in mind when complete output is required.