Skip to main content

Crate ratslang

Crate ratslang 

Source
Expand description

§Ratslang

A compact configuration language for physical systems with native support for time and length units.

Ratslang solves the unit conversion problem that plagues physical system configuration, while keeping the implementation simple and declarative. Physical units are stored directly as uom types (Length and Time) for full type-safety and precision.

§Features

  • Time units: ns, us, ms, s, min, h, d, a (year), shake (and SI prefixes, see Supported Time Units)
  • Length units: nm, um, mm, cm, m (see Supported Length Units)
  • Ranges: 1mm..100m, 5s.., ..10m, ..
  • Namespaces: Dot notation (sensor.range) or blocks
  • Includes: Compose configuration files with namespace scoping
  • Annotations: Mark configuration sections with # @annotation_name for selective filtering and extraction
  • Types: Booleans, integers, floats, strings, paths, arrays
  • Type-safe units: Values stored directly as uom types - no conversion or rounding

§Example

use ratslang::compile_code;

let source = r#"
    distance = 100mm..2m
    scan_rate = 10.5s
     
    sensor {
        type = Lidar
        enabled = true
    }
"#;

let result = compile_code(source).unwrap();
let distance = result.vars.resolve("distance").unwrap();

§Usage

Compile and resolve variables:

use ratslang::{compile_code, Rhs, Val, NumVal};

let code = r#"
    timeout = 5000
    sensor.type = Lidar
    sensor.range = 10
"#;

let ast = compile_code(code).unwrap();

// Manual resolution
let timeout = ast.vars.resolve("timeout").unwrap().unwrap();
assert_eq!(timeout, Rhs::Val(Val::NumVal(NumVal::Integer(5000))));

let name = ast.vars.resolve("sensor.type").unwrap().unwrap();
assert_eq!(name, Rhs::Val(Val::StringVal("Lidar".to_string())));

// Filter namespace
let sensor = ast.vars.filter_ns(&["sensor"]);
let range = sensor.resolve("range").unwrap().unwrap();
assert_eq!(range, Rhs::Val(Val::NumVal(NumVal::Integer(10))));

Note: Ratslang is deliberately simple—no arithmetic, loops, or conditionals.

§Serde

Enable features = ["serde"] for ratslang::from_str and ratslang::to_string. This also enables the uom integration feature. Mark typed quantity fields with #[serde(with = "ratslang::serde::length")] or ratslang::serde::time to preserve dimensions and emit readable units such as 1um and 250ms. See the serde module for a complete example and supported data types. serde::Quantity<Length> and serde::Quantity<Time> work in arrays, vectors, matrices, optional fields, and ranges without per-field adapters. Use serde::case_insensitive for derived unit enums and their Serde aliases. Use ratslang::serde::Document<T> to preserve source comments and annotations when round-tripping a configuration through serde. If the configuration is already compiled, use ratslang::from_evaluated to deserialize it directly, retaining its include resolution and usage tracking.

§Type and value constraints

Comments directly above assignments can declare # @enum CPU, Backend, # @type integer, # @min 0, and # @max 64. Enum choices match strings, identifiers, or paths exactly. Bounds are inclusive; physical quantities compare across units, so # @min 1mm accepts 50cm. The compiler validates final values after includes, references, and overrides. Serde also applies default configuration constraints to user overrides. See constraints for examples and the supported type declarations.

§Syntax Highlighting

Syntax highlighting is available with this tree-sitter grammar or this VS Code extension.

§Annotations

Annotations allow you to mark sections of configuration for selective extraction and filtering. Use # @annotation_name to mark lines or entire blocks that you want to extract later.

§Syntax

Annotate a single line:

ⓘ
timeout = 5000

Annotate an entire namespace block:

ⓘ
sensor {
    type = Lidar
    range = 100m
}

§Usage

Extract annotated configuration (see also: Evaluated::to_string_filtered):

use ratslang::compile_code;

let source = r#"
timeout = 5000

sensor {
    type = Lidar
}

sensor.range = 100m
"#;

let ast = compile_code(source).unwrap();
let minimal_config = ast.to_string_filtered("minimal").unwrap();
println!("{}", minimal_config);

§Use Cases

  • Minimal configurations: Mark only essential parameters with @minimal for deployment or documentation
  • Feature flags: Use @feature_name to extract configurations for specific features
  • Environment-specific: Use @prod, @dev, @test for environment-specific settings
  • Documentation: Mark parameters with @documented for user-facing config examples

§Supported Time Units

§Base Units

  • SI Prefixes: fs (femto), ps (pico), ns (nano), us (micro), ms (milli), s (second), min (minute), h (hour), d (day), ks (kilo)

§Common Units

  • s – second (base unit)
  • min – minute (60 seconds)
  • h – hour (3600 seconds)
  • d – day (86400 seconds)

§Astronomical and Special Units

  • a – year (365 days, matching uom)
  • shake – 10 nanoseconds (unit used in nuclear physics)
  • sidereal_year – sidereal year (365.256363004 days)
  • tropical_year – tropical year (365.242190402 days)

§Notes

  • SI prefixes combine with base units: ms, us, ns, ps, fs
  • All time values are stored internally as uom::si::f64::Time with no conversion loss
  • Ranges work with all time units: 100ms..5s, 1h.., ..30s

§Supported Length Units

§SI Prefixes

  • pm (pico), nm (nano), um (micro), mm (milli), cm (centi), m (meter), km (kilo), Mm (mega), Gm (giga), Tm (tera), Pm (peta), Em (exa), Zm (zetta), Ym (yotta)

§Imperial Units

  • in or inch – inch (25.4 mm)
  • ft or foot – foot (304.8 mm)
  • yd or yard – yard (914.4 mm)
  • mi or mile – mile (1609.344 m)

§Astronomical Units

  • au or AU – astronomical unit (~149.6 million km)
  • ly or light_year – light-year (~9.46 trillion km)
  • pc or parsec – parsec (~30.86 trillion km)

§Nautical Units

  • nmi or nautical_mile – nautical mile (1852 m)
  • fathom – fathom (1.8288 m, nautical depth measurement)

§Small Units

  • angstrom – 10^-10 meters (used in atomic physics and chemistry)
  • bohr_radius – Bohr radius (~0.529 Ångströms, atomic unit)
  • fermi – femtometer (10^-15 m, nuclear unit)

§Notes

  • Ranges work with all length units: 1mm..100m, 5ft.., ..10mi
  • Mixed units in expressions are not supported; each value must use consistent units

Re-exports§

pub use constraints::Constraints;
pub use constraints::ValueType;
pub use crate::serde::from_evaluated;
pub use crate::serde::from_str;
pub use crate::serde::to_ast;
pub use crate::serde::to_string;
pub use uom;

Modules§

constraints
Type and value constraints declared in comments above assignments.
serde
Serde support for ratslang configurations.
tooling
Schema validation, source-preserving edits, and layered configuration tooling.

Macros§

release_schema_url
Where the calling crate’s release publishes its defaults schema: <repository>/releases/download/v<version>/default.rl, from the crate’s own repository and version in Cargo.toml, so every binary names the schema of exactly its release. The release has to attach the defaults file under that name; pass another asset name as the argument.
resolve_bool
Resolves a boolean value from user or default configuration.
resolve_float
Resolves a floating-point value from user or default configuration.
resolve_float_force_range
Resolves a numeric range, converting integers to floats if needed.
resolve_float_range
Resolves a floating-point range without implicit integer conversion.
resolve_int
Resolves an integer value from user or default configuration.
resolve_int_range
Resolves an integer range without type conversion.
resolve_length_range_meters_float
Resolves a length range from millimeters to meters as f32.
resolve_path
Resolves a path value from user or default configuration.
resolve_string
Resolves a string value from user or default configuration.
resolve_time_range_seconds_float
Resolves a time range from milliseconds to seconds as f32.
resolve_var
Resolves a variable from user or default configuration.

Structs§

Definition
One assignment before and after reference resolution.
Evaluated
The result of compiling and evaluating ratslang code.
Explanation
The effective definition, earlier assignments, and referenced definitions.
FormatError
An AST value cannot be represented as ratslang source.
Root
The root of the abstract syntax tree.
SourceDiagnostic
A parser diagnostic with a byte range in the input source.
SourceLocation
A byte range and one-based Unicode line/column in the original input.
VariableHistory
Tracks the history of variable definitions and provides resolution capabilities.
angstrom
ångströms
astronomical_unit
astronomical units
attometer
attometers
attosecond
attoseconds
bohr_radius
bohr radiuses
centimeter
centimeters
centisecond
centiseconds
chain
chains
day
days
day_sidereal
days (sidereal)
decameter
decameters
decasecond
decaseconds
decimeter
decimeters
decisecond
deciseconds
degree
degrees
exameter
exameters
exasecond
exaseconds
fathom
fathoms
femtometer
femtometers
femtosecond
femtoseconds
fermi
fermis
foot
feet
gigameter
gigameters
gigasecond
gigaseconds
gram
grams
hectometer
hectometers
hectosecond
hectoseconds
hertz
The hertz is one cycle per second.
hour
hours
hour_sidereal
hours (sidereal)
inch
inches
kilogram
The kilogram is the SI unit of mass. It is defined by taking the fixed numerical value of the Planck constant h to be 6.626 070 15 × 10⁻³⁴ when expressed in the unit J s, which is equal to kg m² s⁻¹, where the meter and the second are defined in terms of c and ∆νCs.
kilometer
kilometers
kilosecond
kiloseconds
light_year
light years
megameter
megameters
megasecond
megaseconds
meter
The meter is the SI unit of length. It is defined by taking the fixed numerical value of the speed of light in vacuum c to be 299 792 458 when expressed in the unit m s⁻¹, where the second is defined in terms of the caesium frequency ∆νCs.
meter_per_second
meters per second
meter_per_second_squared
meters per second squared
microgram
micrograms
microinch
microinches
micrometer
micrometers
micron
microns
microsecond
microseconds
mil
mils
mile
miles
milligram
milligrams
millimeter
millimeters
millisecond
milliseconds
minute
minutes
nanogram
nanograms
nanometer
nanometers
nanosecond
nanoseconds
nautical_mile
nautical miles
ounce
ounces
parsec
parsecs
petameter
petameters
petasecond
petaseconds
picometer
picometers
picosecond
picoseconds
pound
pounds
radian
SI derived unit of angle. It is the angle subtended at the center of a circle by an arc that is equal in length to the radius of the circle.
rod
rods
second
The second is the SI unit of time. It is defined by taking the fixed numerical value of the caesium frequency ∆νCs, the unperturbed ground-state hyperfine transition frequency of the caesium 133 atom, to be 9 192 631 770 when expressed in the unit Hz, which is equal to s⁻¹.
second_sidereal
seconds (sidereal)
shake
shakes
terameter
terameters
terasecond
teraseconds
yard
yards
year
years
year_sidereal
years (sidereal)
year_tropical
years (tropical)
yoctometer
yoctometers
yoctosecond
yoctoseconds
yottameter
yottameters
yottasecond
yottaseconds
zeptometer
zeptometers
zeptosecond
zeptoseconds
zettameter
zettameters
zettasecond
zettaseconds

Enums§

NumVal
Represents a numeric value that can be either a floating-point or integer.
Operator
Rhs
Right-hand side of an assignment, representing various expression types.
Statement
A statement in the language (currently only variable assignments).
StatementKind
StatementKindOwned
StatementKindOwnedPass1
StatementKindPass1
StatementPass1
Unit
Physical unit types supported by the language.
UnitVal
A physical quantity with its unit, using the uom crate for type-safe dimensional analysis.
Val
A value in the language, which can be a number (with or without units), string, or boolean.
Var
A variable reference with optional namespace qualification.

Functions§

compile_code
Compiles ratslang source code from a string.
compile_code_with_state
Compiles ratslang source code with existing variable state.
compile_file
Compiles a ratslang source file.
compile_file_with_state
Compiles a ratslang source file with existing variable state.
syntax_diagnostics
Report syntax errors using the compiler’s parser without resolving includes. This is suitable for editor buffers that may contain incomplete statements.

Type Aliases§

Acceleration
Quantity type alias using the default base units.
Angle
Quantity type alias using the default base units.
Frequency
Quantity type alias using the default base units.
Length
Quantity type alias using the default base units.
Mass
Quantity type alias using the default base units.
Time
Quantity type alias using the default base units.
Velocity
Quantity type alias using the default base units.