Tweag tools: Topiary universal code formatter and Nickel configuration language

version
0.1.5
GitHub stars
27

Install

/plugin install tweag@vinnie357

Run it inside Claude Code after adding the marketplace with /plugin marketplace add vinnie357/claude-skills.

Contents

Discovered from source

Skills 2

Nickel Configuration Language

Nickel is a configuration language designed to automate generation of static configuration files (JSON, YAML, TOML, XML). It combines gradual typing with runtime contracts to provide both static checking for complex logic and flexible validation for configuration data.

Key Concepts

Gradual Typing

Nickel supports both static and dynamic typing. Mix typed and untyped code within the same configuration:

  • Typed regions: Functions with static type checking for complex logic
  • Dynamic regions: Flexible configuration values validated at runtime with contracts
  • Types are optional—choose when to use them

Contracts

Contracts are runtime assertions that validate values satisfy specific properties. They act as schemas:

  • Built-in contracts: Number, String, Bool, Dyn, Array, record contracts
  • Custom contracts: Functions that check predicates and return values or errors
  • Composition: Combine multiple contracts with boolean logic (std.contract.one_of, std.contract.all_of)
  • Metadata: Contracts attach to fields using the | operator

Merge System

The & operator merges records with symmetric semantics:

  • Symmetric merging: Both sides contribute to the result
  • Recursive merging: Nested records merge recursively
  • Metadata composition: Documentation, defaults, and contracts merge together
  • Priorities and defaults: Control override behavior with metadata

Installation

Using mise

Add to mise.toml:

[tools]
nickel = "latest"

[tasks.validate-config]
script = "nickel eval config.ncl"

[tasks.export-config]
script = "nickel export --format json config.ncl"

Using Cargo

cargo install nickel-lang-cli

CLI Usage

Evaluate Nickel Files

nickel eval config.ncl
nickel eval config.ncl --output result.json

Export to Different Formats

# Export to JSON
nickel export config.ncl --format json

# Export to YAML
nickel export config.ncl --format yaml

# Export to TOML
nickel export config.ncl --format toml

# Merge and export
nickel export base.json overrides.ncl --format yaml

Format Code

nickel format config.ncl
nickel format --check config.ncl  # Check without modifying

Interactive REPL

nickel repl

Basic Syntax

Records (Objects)

{
  field1 = "value",
  field2 = 42,
  nested = {
    key = "data",
  }
}

String Interpolation

let name = "app" in
let port = 8080 in
"Starting %{name} on port %{port}"

Arrays

let ports = [8000, 8001, 8002] in
ports

Functions

let add = fun x y => x + y in
let result = add 2 3 in
result

Let Bindings

let base_port = 8000 in
let debug = true in
{
  port = base_port,
  debug = debug,
}

Contracts and Validation

Applying Contracts with the Pipe Operator

Attach contracts to fields using |:

{
  port | Number = 8080,
  name | String = "my-service",
  debug | Bool = false,
}

Built-in Contracts

Nickel provides contracts for basic types:

# Number contract
value | Number

# String contract
value | String

# Boolean contract
value | Bool

# Dyn (dynamic) contract - never fails
value | Dyn

# Array contract
items | Array Number  # Array of numbers

# Record contract
config | {port: Number, host: String}

Custom Contracts

Define contracts as functions that validate and return values:

# Port number validation (1-65535)
let Port = std.contract.from_predicate (
  fun x => x >= 1 && x <= 65535
) in
{
  port | Port = 8080,
}

Contract with Error Messages

let LogLevel =
  fun label value =>
    if std.array.elem value ["debug", "info", "warn", "error"]
    then value
    else std.contract.blame label
in
{
  log_level | LogLevel = "info",
}

Combining Contracts

Use boolean contract combinators from std.contract:

# One of multiple contracts must match
value | std.contract.one_of [Contract1, Contract2]

# All contracts must match
value | std.contract.all_of [Contract1, Contract2]

# Negation
value | std.contract.not SomeContract

Importing and Validating Formats

Import YAML

let config = import "config.yaml" in
config

Import JSON

let data = import "data.json" in
data

Import TOML

let settings = import "settings.toml" in
settings

Apply Validation Contract to Import

let AppConfig = {
  port | Number,
  name | String,
  debug | Bool,
} in

(import "app.yaml") | AppConfig

Full Validation Workflow

# Define schema
let ConfigSchema = {
  app_name | String,
  port | Number,
  log_level | String,
  database = {
    host | String,
    port | Number,
  }
} in

# Import and validate
let imported = import "config.yaml" in
let validated = imported | ConfigSchema in

# Export as JSON
validated

Merge System

Basic Merge

let base = {
  app_name = "service",
  port = 8080,
} in

let overrides = {
  port = 443,
} in

# Result: port = 443 (overrides takes precedence)
base & overrides

Recursive Merge

let base = {
  database = {
    host = "localhost",
    port = 5432,
  }
} in

let env_overrides = {
  database = {
    host = "prod.example.com",
  }
} in

# Nested database.host overridden, port preserved
base & env_overrides

Defaults and Optional Fields

let defaults = {
  port | default = 8080,
  log_level | default = "info",
} in

let user_config = {
  port = 3000,
} in

defaults & user_config  # port = 3000, log_level = "info"

Anti-Fabrication Notes

When using Nickel configurations:

  • Verify contract behavior by running nickel eval file.ncl to confirm validation works as expected
  • Test import validation using nickel eval with actual data files to ensure format imports succeed
  • Validate merge results by examining output with nickel export --format json to confirm merge semantics
  • Check CLI flags against current Nickel version documentation, as CLI may have changed since this skill was written

Ecosystem Tools

json-schema-to-nickel

Convert JSON Schema specifications to Nickel contracts:

# Generates Nickel contract from JSON Schema
json-schema-to-nickel schema.json > schema.ncl

Topiary Integration

Nickel is Topiary's configuration language. Topiary's language configuration uses languages.ncl:

# Topiary language configuration with Nickel
{
  language = "rust",
  formatting_rules = {
    indent = 2,
  }
}

mise Task Examples

Define validation and export tasks in mise.toml:

[tasks.config:validate]
description = "Validate configuration against schema"
script = "nickel eval config.ncl --output /dev/null && echo 'Valid'"

[tasks.config:export-json]
description = "Export configuration as JSON"
script = "nickel export config.ncl --format json --output config.json"

[tasks.config:export-all]
description = "Export in all formats"
script = """
nickel export config.ncl --format json --output config.json
nickel export config.ncl --format yaml --output config.yaml
nickel export config.ncl --format toml --output config.toml
"""

References

  • references/contract-patterns.md — contract annotation syntax and the validation patterns used for configuration schemas. Read when writing or debugging a contract.
  • references/import-export.md — converting between config formats and validating imported data. Read when moving data in or out of Nickel.

Additional Resources

Topiary

Topiary is a universal code formatter that uses Tree-sitter grammars and queries to define formatting rules. Rather than implementing language-specific formatting logic, Topiary uses declarative Tree-sitter query files (.scm) to specify how code should be formatted.

Key Concepts

Tree-Sitter Queries

Tree-sitter is a parser generator that creates language parsers from grammar definitions. Topiary uses Tree-sitter queries to analyze code structures and apply formatting rules. Queries match patterns in the syntax tree using S-expression syntax and decorate matched nodes with capture names (prefixed with @) that describe formatting actions.

Query Files and Capture Names

Language formatting is defined in .scm (Scheme) query files. Each capture name instructs Topiary how to format the matched node:

  • Line breaks: @prepend_hardline, @append_hardline (always insert newline), @prepend_empty_softline, @append_empty_softline (newline or nothing), @prepend_spaced_softline, @append_spaced_softline (newline or space)
  • Indentation: @prepend_indent_start, @append_indent_start, @prepend_indent_end, @append_indent_end (mark indentation scopes)
  • Spacing: @prepend_space, @append_space (add single space)
  • Control: @delete (remove matched node), @do_nothing (suppress default behavior), @leaf (prevent formatting within node)
  • Input-aware: @prepend_input_softline, @append_input_softline (preserve original line break presence)

Idempotency

Topiary formatting is idempotent—running the formatter repeatedly on already-formatted code produces identical output. This guarantee allows safe integration into version control hooks and CI pipelines.

Author Intent Preservation

Topiary respects the structural intent of code by preserving language-specific semantics. It focuses on whitespace, indentation, and line breaks rather than restructuring code. This approach works especially well with languages whose semantics are simple and whitespace-independent.

Installation

Via Mise

Add Topiary to your mise.toml:

[tools]
topiary = "latest"

[tasks]
fmt = "topiary fmt"
fmt:check = "topiary fmt --check"

Via Cargo

Install directly from crates.io:

cargo install topiary-cli

Verify Installation

Check the installed version and available languages:

topiary --version
topiary config show-sources

CLI Usage

Format Files

Format files in place by detected file extension:

topiary fmt src/main.ml
topiary fmt config.json
topiary fmt *.toml

Add --check to verify formatting without modifications:

topiary fmt --check src/

Format Standard Input

Format piped input by specifying language and optional query file:

echo '{"name":"example"}' | topiary format --language json
cat script.sh | topiary format --language bash

Visualize Parse Trees

Use visualise to debug queries by inspecting the syntax tree:

topiary visualise script.json
topiary visualise --language bash script.sh

This outputs the Tree-sitter parse tree, useful for understanding node structure when writing .scm queries.

Query Configuration

Override the default query file for a language:

topiary fmt --language nickel --query custom.scm script.ncl

Show Current Configuration

Display the active configuration including registered languages and indentation settings:

topiary config show-sources

Configuration

languages.ncl Format

Create a .topiary/languages.ncl file in your project root to customize language registration, indentation, and grammar sources. This file uses Nickel syntax:

{
  languages = {
    json = {
      extensions = ["json"],
      indent = "  ",
    },
    bash = {
      extensions = ["sh", "bash"],
      indent = "  ",
    }
  }
}

Configuration Search Order

Topiary searches for configuration in this order (first found wins):

  1. --configuration CLI argument
  2. .topiary/languages.ncl in current directory or parent directories
  3. User configuration directory (OS-specific): ~/.config/topiary/languages.ncl (Linux), ~/Library/Application Support/topiary/languages.ncl (macOS), %APPDATA%\topiary\languages.ncl (Windows)
  4. Built-in defaults compiled into Topiary

Custom Grammar Sources

Register custom Tree-sitter grammars by specifying Git source or local path:

{
  languages = {
    my-lang = {
      extensions = ["ml"],
      grammar.source.git = {
        git = "https://github.com/example/tree-sitter-my-lang",
        rev = "abc123def456"
      }
    }
  }
}

Or reference a pre-compiled grammar on disk:

{
  languages = {
    my-lang = {
      extensions = ["ml"],
      grammar.source.path = "./grammars/my-lang.so"
    }
  }
}

Adding Custom Languages

Add formatting support for new languages by following these steps:

Step 1: Register the Grammar

Create .topiary/languages.ncl in your project with the grammar source:

{
  languages = {
    my-lang = {
      extensions = ["ml"],
      indent = "  ",
      grammar.source.git = {
        git = "https://github.com/my-org/tree-sitter-my-lang",
        rev = "main"
      }
    }
  }
}

Verify the grammar source URL points to a valid Tree-sitter grammar repository.

Step 2: Create Query File

Create .topiary/queries/my-lang.scm with formatting rules. Start minimal:

; Format binary operators with surrounding spaces
((binary_op) @op
 (#match? @op "^(+|-|=)$"))
@prepend_space
@append_space

; Hard line after statements
((statement) @stmt)
@append_hardline

Use topiary visualise to inspect the parse tree and understand node names and structure.

Step 3: Test Formatting

Test the formatter on sample files:

topiary fmt --language my-lang test-file.ml
topiary visualise --language my-lang test-file.ml

Iterate on the query file until formatting behaves as expected. Run topiary fmt on actual code to verify formatting is idempotent (run twice, should produce identical output).

Writing Formatting Queries

Query Syntax Overview

Tree-sitter queries use S-expression syntax. A basic query matches nodes and captures them:

; Match a function definition and capture its name
(function_def
  name: (identifier) @func-name)

The @func-name is a capture; function_def, name, and identifier are node types. Field names like name: link to specific children.

Common Capture Patterns

Format operators with spaces on both sides:

((binary_op operator: _ @op))
@prepend_space
@append_space

Indent function bodies:

(function_def
  body: (block) @body)
@append_indent_start
@prepend_indent_end

Insert line breaks between statements:

((statement) @stmt)
@append_hardline

Preserve input line breaks (single line or multi-line lists):

(list
  "[" @open
  _ @item
  "]" @close)
@append_spaced_softline

Predicates and Matching

Use predicates to refine matches:

; Match only specific operators
((binary_op operator: _ @op)
 (#match? @op "^(=|==|!=)$"))
@prepend_space
@append_space

; Match nodes that are NOT in comments
((statement) @stmt
 (#not-eq? @stmt comment))

Available predicates: #match? (regex), #eq? (equality), #not-eq? (inequality).

Supported Languages

Official Languages

Topiary actively maintains formatting for:

  • Bash - Shell scripting
  • JSON - Data serialization
  • Nickel - Configuration language
  • OCaml - Functional programming (implementations and interfaces)
  • OCamllex - Lexer definitions
  • TOML - Configuration file format
  • Tree-sitter Queries - Query file formatting

Community-Contributed Languages

External maintainers provide formatters for:

  • CSS - Stylesheets
  • OpenSCAD - 3D modeling language
  • SDML - Semantic Data Modeling Language
  • WIT - WebAssembly Interface Types

Language Limitations

Topiary works best with languages where formatting is independent of semantics. Whitespace-sensitive languages (Python, Haskell) present challenges and are not officially supported, as formatting changes could alter code meaning.

Mise Task Examples

Define formatting tasks in mise.toml:

[tasks.fmt]
description = "Format all code"
run = """
topiary fmt src/
"""

[tasks.fmt:check]
description = "Check formatting without modifying"
run = """
topiary fmt --check src/
"""

[tasks.fmt:debug]
description = "Visualize parse tree for debugging"
run = """
topiary visualise {file}
"""

Run tasks with:

mise run fmt
mise run fmt:check
mise run fmt:debug -- script.ncl

References

  • references/query-syntax.md — the S-expression query syntax Topiary uses to match code patterns and apply formatting rules. Read when writing or debugging a .scm query file.

Anti-Fabrication Note

Before claiming that Topiary formats a language or query correctly, verify behavior by running topiary fmt on actual code files and inspecting the output. Do not assume query behavior without testing; use topiary visualise to inspect the parse tree and confirm node names and structure match the query. Test idempotency by running the formatter twice and confirming output is identical.

Sponsors

Details

Marketplace
vinnie357/claude-skills
Source
plugins/tools/tweag
Category
Tools
License
MIT
Keywords
tweag, topiary, nickel, formatter, configuration, tree-sitter

More from vinnie357/claude-skills

All 33