Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/dml/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: dml
description: >-
Reference and guide for understanding Device Modeling Language (DML 1.4 & 1.2) syntax,
formal grammar, object model, templates, and standard library specifications. Use whenever
analyzing, writing, parsing, or formatting DML code, modifying pkg/dmlex/dml.g4, or implementing
analyzing, writing, parsing, or formatting DML code, modifying grammar/dml/dml.g4, or implementing
AST and printer features in dmlint.
---

Expand Down
4 changes: 2 additions & 2 deletions .agents/skills/dml_printer_feature_bootstrap/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ description: A workflow for scaffolding new DML printer features from grammar ru
This skill outlines a systematic, scalable approach to adding new formatting structures to the `dmlint` printer package after a grammar update in `dml.g4`. It enforces test-driven development, strict mapping to ANTLR contexts, and proactive error suppression.

## 1. Plan & Research
- **Analyze Grammar:** Inspect `pkg/dmlex/dml.g4` to identify the new rules to be implemented. Trace down dependencies and nested structures (e.g., initializers, statements, expressions).
- **Analyze Grammar:** Inspect `grammar/dml/dml.g4` to identify the new rules to be implemented. Trace down dependencies and nested structures (e.g., initializers, statements, expressions).
- User may provide some pseudo g4 code with annotation:
- \n - means force wrap
- \r - optional wrap
- Check potential optimization of the `pkg/dmlex/dml.g4` file (Group similar rules). Any changes to the file has to be appoved by user.
- Check potential optimization of the `grammar/dml/dml.g4` file (Group similar rules). Any changes to the file has to be appoved by user.
- **Propose Implementation:** Draft a plan that clarifies any formatting ambiguity with the user. Specifically ask about:
- Line wrapping strategies (e.g. keeping elements on a single line if they fit post-wrap).
- Trailing comma or specific grammar symbol handling (e.g., `...`).
Expand Down
14 changes: 14 additions & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ builds:
- -X main.GitCommit={{.Commit}}
- -X main.BuildDate={{.Date}}

- id: dmlsp-debug
dir: .
main: ./cmd/dmlsp
binary: dmlsp
targets:
- linux_amd64
env:
- CGO_ENABLED=0
ldflags:
- -X main.Version={{.Version}}
- -X main.GitCommit={{.Commit}}
- -X main.BuildDate={{.Date}}

- id: dml-web-format
dir: .
main: ./cmd/dml-web-format
Expand Down Expand Up @@ -88,6 +101,7 @@ archives:
ids:
- dmlfmt-debug
- dmlast-debug
- dmlsp-debug
formats:
- tar.gz
name_template: "dmltools-debug_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
Expand Down
136 changes: 72 additions & 64 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,77 +1,85 @@
# dmlint Agent Instructions
# AGENTS.md

## Architecture & Boundaries
- **Module Name:** The Go module is `github.com/timoschenko/dmltools` (not `dmlint`). Internal imports must use `github.com/timoschenko/dmltools/pkg/...` or `github.com/timoschenko/dmltools/cmd/...`.
- **Primary Branch:** `master`.
- **Entrypoints (`cmd/`):**
- `cmd/dmlfmt`: Main DML formatter CLI (`dmlfmt [options] [src]...`).
- `cmd/dmlast`: AST dump tool emitting JSON.
- `cmd/dml-web-format`: WebAssembly formatter demo (`make build-wasm`, `make web` on port 8080).
- **Core Packages (`pkg/`):**
- `pkg/dmlex`: Lexer/parser generated from ANTLR4 grammar (`grammar/dml/dml.g4`), decomposed via `tools/baker` into per-rule context files (`dml_parser_*_context.go`).
- `pkg/printer`: Formatter visitor traversing DML AST nodes (`// g4-tag: <rule>`).
- `pkg/printer/layout`: Line wrapping, indentation, conflict resolution, token buffering (`layout.Engine`).
- `pkg/printer/format`: Unified Formatting Flags (`format.FormatFlag`), break priorities, separators, `TokenMap`.
- `pkg/printer/dml_defaults`: Default token format maps (cdecl, expression, tokens).
- `pkg/fs` & `pkg/fs/stream`: File system abstraction, caching (`FsCache`), and streaming.
- **Package Documentation:** Every package under `pkg/` must include a `doc.go` or package comment starting with `Package <name>`. `test/doc_test.go` and `make doc` enforce this.
## Build, Test & Verification Commands

## Developer Commands
- **Default verification before finishing a task**:
1. `go test -timeout 60s ./test/... ./cmd/... ./pkg/...` (debug assertions enabled)
2. `go test -tags dmltools.ndebug -timeout 60s ./test/... ./cmd/... ./pkg/...` (release mode / `NDEBUG`)
3. `golangci-lint run`
4. `make license-check`
- **Do NOT run `go test ./...` from the repo root**: It scans `./venv` and standalone sub-modules under `./tools/`. Always pass `./test/... ./cmd/... ./pkg/...`.
- **Single test / package iteration**:
- `go test -v ./test/printer -run TestAssertStatement`
- Most unit and integration suites live under `./test/{dmlex,printer,lsp,fs}`, not alongside `./pkg/`.
- **Standalone tool modules**: `tools/baker` and `tools/licensecheck` have their own `go.mod` files. Test them via `make test-tools`.
- **`make` & ANTLR gotcha (`SKIP_ANTLR=1`)**:
- Makefile build/test targets (`make test`, `make release`, `make debug`) depend on `build-gocache`, which triggers `make generate` (requiring Java 11+, `curl`, and `stringer`) whenever `build/env/*.flag` files are missing or older than `grammar/dml/dml.g4`.
- Use `go test` directly or pass `SKIP_ANTLR=1` (e.g., `make test SKIP_ANTLR=1`, `make build/bin/dmlfmt SKIP_ANTLR=1`) to avoid triggering ANTLR codegen.
- Makefile also overrides `GOCACHE` to `build/cache/golang` unless `GOCACHE` is already set in the environment.
- **Full CI pipeline order** (`.github/workflows/pre-commit.yml`):
`make test-tools` -> `make generate` -> `make release` -> `make test` -> `make test-ndebug` -> `pre-commit run --all-files` (`golangci-lint`) -> `make license-check`.

```bash
# Full test suite (builds gocache, runs tests across all valid packages)
make test
## Grammar & Codegen Pipeline (`grammar/dml/dml.g4` -> `pkg/dmlex/`)

# Fast focused testing (bypasses ANTLR codegen)
go test ./test/printer/...
go test -v ./test/printer -run TestAssertStatement
go test ./test/... ./cmd/... ./pkg/... # Never run 'go test ./...' from root (scans ./venv)
- **Approval required**: **Never** modify `grammar/dml/dml.g4` or run `make generate` without explicit user approval.
- **What `make generate` does** (when approved):
1. Formats `grammar/dml/dml.g4` using the cached ANTLR formatter JAR (`make format`).
2. Runs ANTLR 4.13.2 to produce intermediate Go parser/lexer files in `grammar/dml/`.
3. Runs `tools/baker` to split monolithic `dml_parser.go` into per-rule context files (`pkg/dmlex/dml_parser_*_context.go`) and removes `grammar/dml/dml_*.go`.
4. Runs `go generate ./pkg/dmlex/...` (`stringer -type=TokenType` -> `pkg/dmlex/tokentype_string.go`).
- **Generated vs. hand-written files in `pkg/dmlex/`**:
- **Generated (never edit manually)**: `dml_parser_*.go`, `dml_lexer.go`, `dml_listener.go`, `dml_base_listener.go`, `tokentype_string.go`.
- **Hand-written (safe to edit)**: `file.go`, `porting.go`, `expression.go`, `cdecl.go`, `method.go`, `imports.go`, `synthetic_token.go`, `error_listener.go`, `version.go`, `doc.go`.

# Build binaries (outputs to build/bin/dmlfmt, build/bin/dmlast)
make build/bin/dmlfmt
make release
## Architecture & Package Map

# Build/test without Java/ANTLR runtime (uses committed parser sources)
make test SKIP_ANTLR=1
make build/bin/dmlfmt SKIP_ANTLR=1
- **Entrypoints (`cmd/`)**:
- `cmd/dmlfmt`: CLI code formatter (`build/bin/dmlfmt`). Note: sets `antlr.CommonTokenFactoryDEFAULT = antlr.NewCommonTokenFactory(true)` in `init()` so tokens retain zero-copy string slices backed by `stream.HashedBuffer`.
- `cmd/dmlast`: AST dumper CLI (`build/bin/dmlast`).
- `cmd/dmlsp`: LSP 3.17 server over stdio (`build/bin/dmlsp`).
- `cmd/dml-web-format`: WebAssembly formatter playground (`make build-wasm` -> `cmd/dml-web-format/main.wasm`).
- **Core Packages (`pkg/`)**:
- `pkg/dmlex`: ANTLR4 lexer/parser wrapper, AST rule contexts, `TokenType` enum, import resolution helpers (`imports.go`), and DML version detection (`version.go`).
- `pkg/printer`: AST traversal (`dml_*.go`), scoped `PrintContext` hierarchy, and Unified Formatting Flags (`pkg/printer/format`, 32-bit `FormatFlag`), backed by default token maps (`pkg/printer/dml_defaults`) and the line-wrapping engine (`pkg/printer/layout`).
- `pkg/lsp`: LSP server (`Server`), in-memory overlay/AST/symbol cache (`FsCache`), syntax diagnostics, and go-to-definition (`definition.go`, `symbols.go`).
- **UTF-16 vs. byte offset gotcha**: LSP `protocol.Position.Character` is in UTF-16 code units, whereas ANTLR and Go strings use UTF-8 byte/rune offsets. Always convert positions via `LineAndByteCol` / `utf16ColToByteCol` (`pkg/lsp/cache.go`).
- `pkg/fs`: Atomic file replacement (`ReplaceFileAtomically`), path normalization, `pkg/fs/stream` (`HashedBuffer` lazy UTF-8 `antlr.CharStream` + 192-bit composite hash), and `pkg/fs/lookup` (stat-validated file discovery, `.gitignore`/`.editorconfig` chain lookup).

# Linting and formatting Go code
golangci-lint run # Enforces gofmt and golines (max-len: 80, tab-len: 4)
golangci-lint fmt # Automatically format Go code
## Printer Constraints (`pkg/printer`)

# Grammar & codegen
make format # Format grammar/dml/dml.g4
make generate # Format grammar + ANTLR codegen + baker split + go generate
make doc # Verify package doc coverage across pkg/
make clean # Clear Go build, test, fuzz, and coverage caches
```
- **Delegate all layout to `layout.Engine`**: AST visitor methods in `pkg/printer/dml_*.go` **must not** perform manual string length math, manual spacing, or manual line wrapping. Push tokens via `processToken`, `pushTokenRange`, `pushTokenRangeFromRightiest`, or `pushTokenWithCustomFormat` inside scoped `PrintContext` overrides (`p.newContext(...)` / `defer p.freeContext()`).
- **Sole newline exception**: Blank lines between top-level/block statements are emitted via `writeNewLines()` at statement boundaries (`pkg/printer/statement_spacing.go`).
- **Rule annotations & passthrough**:
- Prefix every grammar rule visitor method with `// g4-tag: <ruleName>`.
- Unimplemented grammar rules must call `p.printUnimplemented(node)` for raw source passthrough.
- **No unauthorized workarounds**: **Never** add new AST/token workarounds to `pkg/printer/workarounds.go` without explicit user approval. Fix the root cause in `pkg/printer` or `pkg/printer/layout`, or ask first.
- **Debug assertions**: `assert()` and `assertLazy()` in `pkg/printer/debug.go` panic during normal tests (`!dmltools.ndebug`) and compile to no-ops under `-tags dmltools.ndebug`.

## Codegen & Grammar Changes
- **Generated Code:** Never manually edit `pkg/dmlex/dml_*.go`, `pkg/dmlex/*_string.go`, `cmd/dml-web-format/wasm_exec.js`, `*.tokens`, or `*.interp`.
- **Regeneration Requirements:** `make generate` requires:
- Java runtime 11+ (Temurin 21 recommended) to execute ANTLR 4.13.2.
- `stringer` tool: `go install golang.org/x/tools/cmd/stringer@latest`.
- Virtualenv `./venv` (automatically provisioned by Makefile for whitespace/EOF fixers).
- **CI Enforcement:** When `CI=true`, `make generate` verifies generated files match committed files in git and fails if there is any diff. Always run `make generate` and commit all generated files after modifying `grammar/dml/dml.g4`.
## Testing Quirks (`test/printer`)

## Printer Architecture & Constraints
- **Layout Engine Delegation:** AST visitor methods in `pkg/printer/` push `PrintContext` overrides with `FormatFlag`s. Formatting, spacing, and line wrapping decisions must be delegated entirely to `layout.Engine`.
- **No Manual Wrapping:** AST methods must not perform manual string length calculations or manually inject spacing/newlines for line wrapping within statements.
- **Statement Boundary Exception:** `writeNewLines()` is permitted only between top-level statements, as `layout.Engine` operates within statements.
- **Grammar Tagging:** Every AST print method must be tagged with its grammar rule: `// g4-tag: <rule_name>`.
- **Synthetic Tokens (Epic 006):** Do not manually inject synthetic tokens. Use `task006Skip: true` in test cases requiring synthetic parens.
- **Backtick quote substitution**: In `printerTestCase` (`test/printer/testlib_test.go`), all backticks (`` ` ``) in `code`, `expected`, and `masked` strings are automatically converted to double quotes (`"`) before parsing and comparison.
- **Implicit headers & method wrapping**:
- `runPrinterTestCase` auto-prepends `"dml 1.4;\n\n\n"` and strips it from the formatted result unless `expected` already contains a `dml` header.
- `runPrinterMethodTestCase` wraps snippets in `method foo() { ... }` indented by 4 spaces and adds `+4` to `lineCap` (standard test `lineCap` is `40`).
- **Test masking policy (`test/printer/mask_test.go`)**:
- **Never** add new `masked: Mask...` entries or `task006Skip: true` flags to silence failing tests without explicit user approval.
- When fixing a bug covered by an existing mask, remove the mask—if a masked test produces `expected`, the runner fails with `"test case passed but it is still masked"`.

## Testing Harness & Masking (`test/printer/testlib_test.go`)
- **DML Header Preprocessing:** If test input lacks a `dml` header, `dml 1.4;\n\n\n` is automatically prepended and stripped from output.
- **Backtick Normalization:** Backticks (`` ` ``) in test code and expected strings are normalized to double quotes (`"`), allowing raw Go string literals to express DML double quotes cleanly.
- **Masked Tests (`test/printer/mask_test.go`):** Known issues and WIP formatting use typed masks (`MaskIncorrectFormatting`, `MaskSkip`, `MaskSyntaxError`).
- **Mask Removal Gotcha:** When a bugfix causes a masked test to output the correct expected string, the test harness triggers `t.Errorf("test case passed but it is still masked. Consider removing the mask")`. You **must** remove the mask once the test passes.
## Enforced Repo Conventions

## Code Conventions & Workarounds
- **AI Workarounds:** Every temporary fix or workaround must strictly follow the format:
`// TODO: AI WA: <description>` and `// Deprecated: This is workaround`.
- **Workaround Isolation:** Isolate non-trivial workaround logic into dedicated helper functions in `pkg/printer/workarounds.go` or `pkg/printer/layout/workarounds.go`.
- **SPDX License Header (`make license-check`)**: Every non-generated `.go` file and `grammar/dml/dml.g4` must start with:
```go
// SPDX-License-Identifier: GPL-2.0-only
// Copyright (C) 2026 Sergei Timoshchenko
```
(`GPL-2.0-or-later` is explicitly rejected by `tools/licensecheck`). If local untracked directories with third-party `LICENSE` files cause `make license-check` to fail, pass explicit file paths: `(cd tools/licensecheck && go run . -root ../.. <files...>)`.
- **Package documentation (`test/doc_test.go` & `make doc`)**: Every package under `pkg/` containing non-test `.go` files must have a package doc comment (`doc.go`) starting with `"Package <name> ..."`. When adding a new subpackage under `pkg/`, also add it to `TestGoDocCommand` in `test/doc_test.go`.
- **Go formatting & linting (`.golangci.yaml`)**: Formatted with `gofmt` and `golines` (`max-len: 80`).
- **Commit messages (`.goreleaser.yaml`)**: Follow Conventional Commits (`<type>(<scope>): <description>`) using types `feat`, `fix`, `perf`, `docs`, `refactor`, `chore`, `test`, `ci`, `infra`.

## Key Skills & References
- **DML 1.4 / 1.2 Syntax Spec:** Cached in `.docs-cache/dml.wiki` (fetch via `.agents/skills/dml/scripts/fetch_wiki.sh`); guide in `.agents/skills/dml/SKILL.md`.
- **Scaffolding New Printer Rules:** Workflow and checklist in `.agents/skills/dml_printer_feature_bootstrap/SKILL.md`.
## Existing Instruction & Reference Files

- `.agents/skills/dml/SKILL.md`: DML 1.4/1.2 syntax and formal grammar lookup guide (queries `.docs-cache/dml.wiki`, fetched via `./.agents/skills/dml/scripts/fetch_wiki.sh`).
- `.agents/skills/dml_printer_feature_bootstrap/SKILL.md`: TDD workflow for scaffolding new printer rules and tests.
- `doc/format/README.md`, `doc/format/line_wrapping.md`, `doc/format/comments.md`: DML formatter style, wrap-group explosion, and sticky comment rules.
- `doc/lsp/README.md`, `doc/lsp/features.md`, `doc/lsp/compatibility.md`: `dmlsp` capabilities, import resolution, and LSP 3.17 support.
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ $(ANTLR_FORMAT_JAR): | $(BUILD_DEPS_DIR)
BUILD_APPS:=
BUILD_APPS+=dmlast
BUILD_APPS+=dmlfmt
BUILD_APPS+=dmlsp

# Intermediate ANTLR generated files in grammar/dml
G4_GENERATED_FILES:=
Expand Down
Loading
Loading