Skip to main content

Code Formatting System

The code formatting system is the runtime object serialization and code formatting mechanism of the Alia language. It supports converting any object into a readable structural description or into executable code, and supports ANSI colored output.

1. Runtime Serialization Methods​

Every built-in Alia type implements four core methods for converting objects into strings in different formats.

Method overview​

MethodPurposeOutput format
toDescription()Structural descriptionString "hello" / Number 42 / Object *[...]
toColoredDescription()Colored structural descriptionColoredString object
toCode()Executable code"hello" / 42 / *[key: value]
toColoredCode()Colored executable codeColoredString object

Standard structural description format​

The output of toDescription() follows a unified standard structural description paradigm:

Objects​

Object *[
String name: "Alice",
Number age: 30,
Object address: *[
String city: "Beijing",
Number zip: 100000
],
Array tags: [String "admin", String "user"]
]

Arrays​

Array [Number 1, String "hello", Boolean true]

Value types​

String "Hello World"
Number 42
Boolean true
Null null

The Alias type​

Alias(greet)
Alias(add)

Type color mapping​

TypeColor
StringGreen #00FF00
NumberMagenta #FF00FF
BooleanYellow #FFFF00
ObjectCyan #00FFFF
ArrayBlue #0000FF
AliasBright magenta #DA77F2
NullGray #808080
ErrorRed #FF0000

2. Code Formatting API​

Formatting and highlighting are provided by the host interface; both accept an Alia code string and an optional configuration object:

MethodInputOutput
formatAlia code string, configuration objectThe formatted code string
colorAlia code string, configuration objectA position-preserving ANSI-highlighted string

Configuration options:

OptionTypeDefaultDescription
indentSizeNumber2Number of spaces per indentation level
useTabsBooleanfalseWhether to indent with tabs
compactBooleanfalseCompact mode: removes spaces inside Stacks/collections, leaves no space after colons, and separates elements with ,
quoteStyleString'single'String quote style: 'single' / 'double'
bracketSpacingBooleantrueWhether to keep spaces inside braces when a Stack is collapsed onto one line ({ a } / {a})
collectionSpacingBooleanfalseWhether to keep spaces inside array/object literal brackets ([a, b] / [ a, b ])
emptyCollectionSpacingBooleantrueWhether empty collections keep their inner spaces ({ } / {}, [ ] / [])
endOfLineString'lf'Line ending: 'lf' / 'crlf' / 'cr'
insertFinalNewlineBooleanfalseWhether to append a newline at the end of the output
forceMultilineBooleanfalseForces a Stack containing a single instruction to expand onto multiple lines
keepColorDirectivesBooleantrueWhether to keep color declaration directives such as @colorAlias and @colorClass in the output

Host invocation example (JavaScript):

const Alia = require('./Base/Executor')
const alia = new Alia()

alia.format('alias greet <String name> { print name }', { indentSize: 4 })
alia.color('alias greet <String name> { print name }')

The configuration object is only passed when the host calls format or color; there is no corresponding call syntax in Alia code.

3. Color Declaration Directives​

Color configuration is declared in Alia source code via @-prefixed directives; these directives are automatically collected and applied during code formatting.

Color.set​

Color.set registers color names. The output of color() is rendered as position-preserving pure highlighting, distinguishing the following color categories; the default color of any category can be overridden via Color.set:

CategoryDefault colorMeaning
DeclKeywordBright redDeclaration keywords (const, let, class, alias, new, import, export, type, typify, test, remove, enable, disable, mut)
KeywordBright yellowControl-flow keywords (print, if, each, return, call, assert, etc.) and statement-level operators (=, +=, ++)
OperatorBright whiteArithmetic/comparison operators within expressions (+, <=, etc.)
VariableBright greenRegular variable identifiers
ConstVariableBright cyanConstants declared by const and their references
KeyArgumentBright blueKey arguments in calls and alias parameters
AliasBright magentaAlias names, alias pattern literals (such as and) and class methods
TypeCyanType names (String, Number, etc.)
PropertyBlueClass body / object literal member keys and member accesses (self.name, obj.key)

Syntax:

Color.set <String name> to <Color color>

Color.set registers a color name in the color name registry; afterwards the color can be referenced with new Color ['registered name', 'Name']. If the registered name shares its name with one of the color categories above, that category's default color is overridden.

Example:

~ Register the color name Accent
Color.set 'Accent' to new Color ['#FF0000', 'Hex']

~ Reference a registered color name
const accent = new Color ['Accent', 'Name']

~ Override the Keyword category with red
Color.set 'Keyword' to new Color ['#FF0000', 'Hex']

@colorAlias​

Sets the colors of the embedded keywords within an alias pattern.

Syntax:

@colorAlias <Keys aliasPattern> -> <Sheet keyAndColorMap>

The color map uses the new Sheet [['keyword', 'color'], ...] two-dimensional table form (Sheet allows duplicate keys).

Example:

~ Set a color for an alias containing the embedded keyword and
@colorAlias add <Number a> and <Number b> -> new Sheet [['and', '#00FF00']]

During formatting, embedded keywords such as and in an add 1 and 1 call are rendered with the predefined color from the map; embedded keywords not present in the map, and the syntax keywords themselves, keep the same Alias color category.

@colorClass​

Sets the colors of the members within a class.

Syntax:

@colorClass <Key className> -> <Object everyClassItemColorMap>

The color map uses the *[ <Key member>: <Color color>, ... ] object literal form, with each member mapping to a Color object.

Example:

~ Set colors for the properties of the Person class
@colorClass Person -> *[name: new Color ['#FFFF00', 'Hex'], age: new Color ['#FF00FF', 'Hex'], address: new Color ['#00FFFF', 'Hex']]

During formatting, member keys in construction statements such as const Alice = new Person *[name: 'Alice', age: 21] keep the default colors, while member names in member accesses such as Alice.name are rendered with the predefined colors.

Collection mechanism​

Color.set statements and the @colorAlias, @colorClass color declaration directives are automatically collected during formatting and registered in the ColorRegistry, affecting all colored output within that formatting session. color() performs position-preserving pure highlighting of the source code: it only inserts ANSI escape codes into the input code, without changing any character positions.

4. Intermediate Representation: ColoredString​

Colored output uniformly uses the ColoredString object as its intermediate representation:

const red = new Color ['#FF0000', 'Hex']
const cs = new ColoredString ['Hello World']
cs.color red at [0, 5] ~ colors "Hello" red
print call cs.toTerminal ~ prints the ANSI colored string

ColoredString is converted into an ANSI escape code string via the toTerminal method, supporting TrueColor output.

5. Best Practices​

Prefer standard structural descriptions​

For debugging and logging output, prefer toDescription() to obtain a standard structural description with type prefixes:

print call someValue.toDescription
~:
Object *[
String name: "Alice",
Number age: 30
]
:~

Custom color themes​

Declare the color theme uniformly at the project entry point:

~ my-theme.alia
Color.set 'String' to new Color ['#E06C75', 'Hex']
Color.set 'Number' to new Color ['#56B6C2', 'Hex']
Color.set 'Boolean' to new Color ['#E5C07B', 'Hex']
Color.set 'Object' to new Color ['#61AFEF', 'Hex']
Color.set 'Array' to new Color ['#C678DD', 'Hex']
export this

Next Steps​