commit
First real release
diff --git a/Cargo.lock b/Cargo.lock
index 13c78b2..373bb74 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -19,11 +19,12 @@ checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "c4d"
-version = "1.0.0-alpha-2"
+version = "1.0.0"
dependencies = [
"jpcl",
"proc-macro2",
"regex",
+ "serde",
"serde_json",
"syn 2.0.117",
"tempfile",
diff --git a/Cargo.toml b/Cargo.toml
index 896db26..05e1f99 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -2,7 +2,7 @@
[package]
name = "c4d"
-version = "1.0.0-alpha-2"
+version = "1.0.0"
edition = "2024"
rust-version = "1.85"
description = "Local source-code formatting and accessibility checks"
@@ -21,8 +21,7 @@ include = [
jpcl = "=2.0.0"
proc-macro2 = { version = "=1.0.106", features = ["span-locations"] }
regex = "=1.12.3"
+serde_json = "=1.0.149"
+serde = "=1.0.229"
syn = { version = "=2.0.117", features = ["full", "visit"] }
tempfile = "=3.27.0"
-
-[dev-dependencies]
-serde_json = "=1.0.149"
diff --git a/README.md b/README.md
index 17037a8..88a65f2 100644
--- a/README.md
+++ b/README.md
@@ -173,13 +173,18 @@ set `color` under `[overrides.rust.terminal]`.
## Supported sources
-The initial adapter handles UTF-8 Rust files (`.rs`, case-insensitive).
-TypeScript, Python, and other file types are skipped. The adapter uses
-[syn](https://docs.rs/syn/2.0.117/syn/) for the syntax tree and
+C4D supports UTF-8 Rust (`.rs`), Go (`.go`), Python (`.py` and `.pyi`),
+JSON (`.json`), and JSON with comments (`.jsonc`). Their configuration
+identifiers are `rust`, `go`, `python`, `json`, and `jsonc`. Extensions are
+case-insensitive. TypeScript and JavaScript files are skipped.
+
+### Rust
+
+The Rust adapter uses [syn](https://docs.rs/syn/2.0.117/syn/) for the syntax tree and
[proc-macro2](https://docs.rs/proc-macro2/1.0.106/proc_macro2/struct.Span.html)
for source token spans.
-### Formatting
+#### Rust formatting
- `indentSize` controls leading spaces on lines that begin with a token.
Each active multiline brace, bracket, or parenthesis group contributes
@@ -203,7 +208,7 @@ attributes, or expand macros. Some macro-expanded code and compiler features
are opaque to the tool. Formatting can shift source locations observed
indirectly through macros, compiler diagnostics, or caller metadata.
-### File path headers
+#### File path headers
Enable this option in `.c4d/config.jp` to have `c4d format` add a comment
such as `// src/main.rs`. The option defaults to `false`.
@@ -220,7 +225,7 @@ An exact matching path in the leading comments counts as an existing header.
`c4d check` reports missing headers and `c4d format --check` previews them.
Files with explicit `line!()` or `column!()` calls also skip header insertion.
-### Naming
+#### Rust naming
| Option | Rust declarations checked |
| --- | --- |
@@ -233,6 +238,65 @@ against that convention's ASCII letters, digits, and underscore pattern.
A Rust raw identifier prefix `r#` is ignored for matching. Diagnostics
never change the identifier.
+### JSON and JSONC
+
+C4D validates files before applying whitespace edits. JSON uses strict JSON
+syntax. JSONC also accepts line comments, block comments, and trailing commas.
+The extension selects the syntax. A `.json` file containing comments reports
+a syntax error.
+
+- `indentSize` sets the leading spaces per open object or array. A line that
+ starts with a closing delimiter uses the enclosing level.
+- `newLineSize` applies between siblings on separate lines when either value
+ is an object or array. A gap containing a comment is left intact.
+- Strings, number spellings, duplicate keys, key order, and comment contents
+ keep their original bytes. The JSON adapters skip file path headers and
+ naming checks.
+
+### Python
+
+Python formatting requires CPython 3.11 or newer as `python3` on PATH.
+C4D uses it to parse and tokenize source without executing it. The installed
+Python version determines which syntax is supported. The adapter accepts
+UTF-8 source with LF or CRLF line endings.
+
+- `indentSize` sets spaces per indentation level on logical statement lines.
+ Continuation lines, comments, and multiline string contents keep their
+ original spacing.
+- `newLineSize` sets the spacing between statements in the same suite when
+ either is a compound statement such as a definition, loop, or conditional.
+ Gaps containing comments keep their existing spacing.
+- `filePathHeader` adds a `# path/to/file.py` comment after any shebang and
+ encoding declaration.
+- Naming checks cover function and class definitions, parameters, and simple
+ name bindings. Checks report diagnostics without renaming anything.
+
+Before writing, C4D reparses the proposed result and compares the two syntax
+trees. Formatting can still shift source line numbers used by tracebacks or
+inspection tools.
+
+### Go
+
+Go formatting requires Go 1.21 or newer as `go` on PATH. C4D starts one
+helper per invocation using Go's standard parser and scanner. The helper
+builds locally with the installed toolchain and uses its normal build cache.
+C4D parses the source without building or executing the Go files you pass in.
+
+- `indentSize` sets spaces per open brace, bracket, or parenthesis. Lines
+ beginning with a closing delimiter use the enclosing level.
+- `newLineSize` applies between sibling declarations or statements on
+ different lines when one is a logical block. These include functions,
+ type declarations, grouped declarations, loops, conditionals, switches,
+ selects, and standalone blocks. Gaps with comments keep their spacing.
+- `filePathHeader` inserts a standalone `// path/to/file.go` comment above
+ the source. Files with Go line directives keep their position and spacing.
+- Naming checks cover functions and methods, named types, named parameters
+ and results, const and var declarations, and names on the left of `:=`.
+
+Before writing, C4D reparses the result and compares token kinds and spellings,
+including implicit semicolons. Literals and existing comments keep their
+bytes. Syntax checking uses Go's parser and skips package type checking.
+
### Discovery
Directories are traversed in name order. The tool skips symlinks, non-source
@@ -255,7 +319,8 @@ editing of the same file.
## Contributing
Run `cargo fmt --check`, `cargo clippy --locked --all-targets -- -D warnings`,
-and `cargo test --locked` before submitting a change. When adding a language,
+and `cargo test --locked` before submitting a change. The Python and Go integration
+tests use `python3` and `go` respectively. When adding a language,
register its adapter in `src/language.rs` and add representative fixtures
covering syntax-sensitive whitespace, literals, comments, and repeat runs.
Keep transformations constrained to the spans that the adapter can verify.
diff --git a/src/adapter_protocol.rs b/src/adapter_protocol.rs
new file mode 100644
index 0000000..82403f9
--- /dev/null
+++ b/src/adapter_protocol.rs
@@ -0,0 +1,89 @@
+// src/adapter_protocol.rs
+
+use std::borrow::Cow;
+
+use serde_json::{Value, json};
+
+use crate::config::{CLASSES, Effective, FUNCTIONS, VARIABLES};
+use crate::language::{Analysis, Diagnostic};
+
+pub fn runtime(message: impl Into<String>) -> Diagnostic {
+ Diagnostic {
+ offset: 0,
+ rule: "runtime",
+ message: message.into(),
+ }
+}
+
+pub fn request(source: &str, path: &str, settings: &Effective, naming: bool) -> Value {
+ json!({
+ "source": source,
+ "path": path,
+ "indent": settings.indent_size(),
+ "newlines": settings.newline_size(),
+ "header": settings.file_path_header(),
+ "names": naming,
+ })
+}
+
+pub fn decode<'source>(source: &'source str, settings: &Effective, response: &Value) -> Result<Analysis<'source>, Diagnostic> {
+ if let Some(message) = response["error"].as_str() {
+ let line = response["line"].as_u64().unwrap_or(1).saturating_sub(1) as usize;
+ let column = response["column"].as_u64().unwrap_or(1).saturating_sub(1) as usize;
+ let mut offset = if let Some(offset) = response["offset"].as_u64() {
+ (offset as usize).min(source.len())
+ } else if let Some(text) = source.split_inclusive('\n').nth(line) {
+ let start = text.as_ptr() as usize - source.as_ptr() as usize;
+ start + text.char_indices().nth(column).map_or(text.trim_end_matches(['\r', '\n']).len(), |(offset, _)| offset)
+ } else {
+ source.len()
+ };
+
+ while !source.is_char_boundary(offset) {
+ offset -= 1;
+ }
+
+ return Err(Diagnostic { offset, rule: "syntax", message: message.to_owned() });
+ }
+
+ let formatted = response["formatted"].as_str().ok_or_else(|| runtime("Language adapter returned no source"))?;
+ let mut issues = Vec::new();
+
+ for entry in response["issues"].as_array().ok_or_else(|| runtime("Language adapter returned no diagnostics"))? {
+ let rule = match entry["rule"].as_str() {
+ Some("formatting.indentSize") => "formatting.indentSize",
+ Some("formatting.newLineSize") => "formatting.newLineSize",
+ Some("formatting.filePathHeader") => "formatting.filePathHeader",
+ _ => return Err(runtime("Unknown language formatting rule")),
+ };
+ issues.push(Diagnostic {
+ offset: entry["offset"].as_u64().unwrap_or_default() as usize,
+ rule,
+ message: entry["message"].as_str().unwrap_or_default().to_owned(),
+ });
+ }
+
+ for entry in response["names"].as_array().ok_or_else(|| runtime("Language adapter returned no names"))? {
+ let rule = match entry[1].as_str() {
+ Some("functions") => FUNCTIONS,
+ Some("variables") => VARIABLES,
+ Some("classes") => CLASSES,
+ _ => return Err(runtime("Unknown language naming rule")),
+ };
+ let name = entry[2].as_str().unwrap_or_default();
+ let convention = settings.convention(rule);
+
+ if !convention.matches(name) {
+ issues.push(Diagnostic {
+ offset: entry[0].as_u64().unwrap_or_default() as usize,
+ rule,
+ message: format!("“{name}” should use {}", convention.label()),
+ });
+ }
+ }
+
+ issues.sort_by_key(|issue| issue.offset);
+
+ let formatted = if formatted == source { Cow::Borrowed(source) } else { Cow::Owned(formatted.to_owned()) };
+ Ok(Analysis { formatted, issues })
+}
diff --git a/src/go_adapter.go b/src/go_adapter.go
new file mode 100644
index 0000000..d3b4821
--- /dev/null
+++ b/src/go_adapter.go
@@ -0,0 +1,389 @@
+// src/go_adapter.go
+
+package main
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/scanner"
+ "go/token"
+ "io"
+ "os"
+ "sort"
+ "strings"
+)
+
+type request struct {
+ Source, Path string
+ Indent, Newlines int
+ Header, Names bool
+}
+
+type issue struct {
+ Offset int `json:"offset"`
+ Rule string `json:"rule"`
+ Message string `json:"message"`
+}
+
+type result struct {
+ Formatted string `json:"formatted"`
+ Issues []issue `json:"issues"`
+ Names [][3]any `json:"names"`
+ Error string `json:"error,omitempty"`
+ Offset int `json:"offset,omitempty"`
+}
+
+type edit struct {
+ start, end int
+ replacement, rule, message string
+}
+
+type scanned struct {
+ offset int
+ kind token.Token
+ literal string
+}
+
+func scan(source string) []scanned {
+ files := token.NewFileSet()
+ file := files.AddFile("", -1, len(source))
+ var lexer scanner.Scanner
+ lexer.Init(file, []byte(source), nil, scanner.ScanComments)
+ var tokens []scanned
+
+ for {
+ position, kind, literal := lexer.Scan()
+
+ if kind == token.EOF {
+ return tokens
+ }
+
+ tokens = append(tokens, scanned{file.Offset(position), kind, literal})
+ }
+}
+
+func sameTokens(original, proposed []scanned) bool {
+ if len(original) != len(proposed) {
+ return false
+ }
+
+ for index, before := range original {
+ after := proposed[index]
+
+ if before.kind != after.kind || before.literal != after.literal {
+ return false
+ }
+ }
+
+ return true
+}
+
+func spacing[T ast.Node](source string, file *token.File, nodes []T, width int, edits *[]edit) {
+ for index := 1; index < len(nodes); index++ {
+ left, right := nodes[index-1], nodes[index]
+
+ if !logicalBlock(left) && !logicalBlock(right) {
+ continue
+ }
+
+ start := file.Offset(left.End())
+ rightOffset := file.Offset(right.Pos())
+ // Preserve comment attachment, including documentation and compiler directives.
+ end := file.Offset(file.LineStart(file.PositionFor(file.Pos(rightOffset), false).Line))
+
+ if end <= start {
+ continue
+ }
+
+ gap := source[start:end]
+ count := strings.Count(gap, "\n")
+
+ if count == width || strings.Trim(gap, " \t\r\n") != "" {
+ continue
+ }
+
+ first := strings.IndexByte(gap, '\n')
+ ending := "\n"
+
+ if first > 0 && gap[first-1] == '\r' {
+ ending = "\r\n"
+ }
+
+ *edits = append(*edits, edit{
+ start, end, strings.Repeat(ending, width), "formatting.newLineSize",
+ fmt.Sprintf("Expected %d newline character(s) between logical blocks", width),
+ })
+ }
+}
+
+func logicalBlock(node ast.Node) bool {
+ switch node := node.(type) {
+ case *ast.FuncDecl, *ast.BlockStmt, *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt,
+ *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
+ return true
+ case *ast.GenDecl:
+ return node.Tok == token.TYPE || node.Lparen.IsValid()
+ default:
+ return false
+ }
+}
+
+func indentation(source string, file *token.File, tokens []scanned, width, bom int, edits *[]edit) {
+ depth := 0
+ previousLine := -1
+
+ for _, entry := range tokens {
+ if entry.kind == token.COMMENT || (entry.kind == token.SEMICOLON && entry.literal == "\n") {
+ continue
+ }
+
+ switch entry.kind {
+ case token.RBRACE, token.RBRACK, token.RPAREN:
+ depth--
+ }
+
+ line := file.PositionFor(file.Pos(entry.offset), false).Line
+ lineStart := max(bom, file.Offset(file.LineStart(line)))
+
+ if lineStart != previousLine {
+ prefix := source[lineStart:entry.offset]
+ wanted := depth * width
+
+ if strings.Trim(prefix, " \t") == "" && (len(prefix) != wanted || strings.ContainsRune(prefix, '\t')) {
+ *edits = append(*edits, edit{
+ lineStart, entry.offset, strings.Repeat(" ", wanted), "formatting.indentSize",
+ fmt.Sprintf("Expected %d space(s) of indentation", wanted),
+ })
+ }
+ }
+
+ previousLine = lineStart
+
+ switch entry.kind {
+ case token.LBRACE, token.LBRACK, token.LPAREN:
+ depth++
+ }
+ }
+}
+
+func header(source, path string, bom int, edits *[]edit) {
+ if strings.HasPrefix(path, "+build ") || strings.HasPrefix(path, "+build\t") {
+ path = "./" + path
+ }
+
+ comment := "// " + path
+
+ for _, line := range strings.Split(source[bom:], "\n") {
+ text := strings.TrimSpace(line)
+
+ if text == comment {
+ return
+ }
+
+ if text != "" && !strings.HasPrefix(text, "//") {
+ break
+ }
+ }
+
+ ending := "\n"
+
+ if first, _, _ := strings.Cut(source, "\n"); strings.HasSuffix(first, "\r") {
+ ending = "\r\n"
+ }
+
+ *edits = append(*edits, edit{
+ bom, bom, comment + ending + ending, "formatting.filePathHeader",
+ "Expected file path header " + comment,
+ })
+}
+
+func names(node ast.Node, add func(*ast.Ident, string)) {
+ switch node := node.(type) {
+ case *ast.FuncDecl:
+ add(node.Name, "functions")
+ case *ast.TypeSpec:
+ add(node.Name, "classes")
+ case *ast.ValueSpec:
+ for _, name := range node.Names {
+ add(name, "variables")
+ }
+ case *ast.FuncType:
+ for _, fields := range []*ast.FieldList{node.Params, node.Results} {
+ if fields == nil {
+ continue
+ }
+
+ for _, field := range fields.List {
+ for _, name := range field.Names {
+ add(name, "variables")
+ }
+ }
+ }
+ case *ast.AssignStmt:
+ if node.Tok == token.DEFINE {
+ for _, expr := range node.Lhs {
+ if ident, ok := expr.(*ast.Ident); ok {
+ add(ident, "variables")
+ }
+ }
+ }
+ case *ast.RangeStmt:
+ if node.Tok == token.DEFINE {
+ for _, expr := range []ast.Expr{node.Key, node.Value} {
+ if ident, ok := expr.(*ast.Ident); ok {
+ add(ident, "variables")
+ }
+ }
+ }
+ }
+}
+
+func analyze(input request) result {
+ output := result{
+ Formatted: input.Source,
+ Issues: []issue{},
+ Names: [][3]any{},
+ }
+ files := token.NewFileSet()
+ mode := parser.ParseComments | parser.AllErrors | parser.SkipObjectResolution
+ tree, err := parser.ParseFile(files, "", input.Source, mode)
+
+ if err != nil {
+ var list scanner.ErrorList
+
+ if errors.As(err, &list) && len(list) != 0 {
+ output.Error, output.Offset = list[0].Msg, list[0].Pos.Offset
+ } else {
+ output.Error = err.Error()
+ }
+
+ return output
+ }
+
+ file := files.File(tree.Pos())
+ var edits []edit
+ tokens := scan(input.Source)
+ preserve := false
+
+ for _, entry := range tokens {
+ if entry.kind == token.COMMENT && (strings.HasPrefix(entry.literal, "//line ") || strings.HasPrefix(entry.literal, "/*line ")) {
+ preserve = true
+ break
+ }
+ }
+
+ newlines := input.Newlines
+
+ if preserve {
+ newlines = 0
+ }
+
+ if newlines != 0 {
+ spacing(input.Source, file, tree.Decls, newlines, &edits)
+ }
+
+ ast.Inspect(tree, func(node ast.Node) bool {
+ if input.Names {
+ names(node, func(name *ast.Ident, category string) {
+ if name.Name != "_" {
+ output.Names = append(output.Names, [3]any{file.Offset(name.Pos()), category, name.Name})
+ }
+ })
+ }
+
+ if newlines != 0 {
+ switch section := node.(type) {
+ case *ast.BlockStmt:
+ spacing(input.Source, file, section.List, newlines, &edits)
+ case *ast.CaseClause:
+ spacing(input.Source, file, section.Body, newlines, &edits)
+ case *ast.CommClause:
+ spacing(input.Source, file, section.Body, newlines, &edits)
+ }
+ }
+
+ return true
+ })
+
+ bom := 0
+
+ if strings.HasPrefix(input.Source, "\ufeff") {
+ bom = len("\ufeff")
+ }
+
+ if !preserve && input.Indent != 0 {
+ indentation(input.Source, file, tokens, input.Indent, bom, &edits)
+ }
+
+ if !preserve && input.Header {
+ header(input.Source, input.Path, bom, &edits)
+ }
+
+ // Keep zero-length header insertions before any indentation replacement at the same offset.
+ sort.SliceStable(edits, func(left, right int) bool {
+ first, second := edits[left], edits[right]
+ return first.start < second.start || (first.start == second.start && first.end < second.end)
+ })
+ var candidate strings.Builder
+ cursor := 0
+
+ for _, change := range edits {
+ if change.start < cursor {
+ return result{Error: "Go formatting produced overlapping edits"}
+ }
+
+ candidate.WriteString(input.Source[cursor:change.start])
+ candidate.WriteString(change.replacement)
+ cursor = change.end
+ output.Issues = append(output.Issues, issue{change.start, change.rule, change.message})
+ }
+
+ if len(edits) != 0 {
+ candidate.WriteString(input.Source[cursor:])
+ proposal := candidate.String()
+
+ if _, err := parser.ParseFile(token.NewFileSet(), "", proposal, mode); err != nil {
+ return result{Error: "Formatting would make the Go source invalid"}
+ }
+
+ verified := scan(proposal)
+
+ if input.Header && len(verified) == len(tokens)+1 && verified[0].kind == token.COMMENT {
+ verified = verified[1:]
+ }
+
+ if !sameTokens(tokens, verified) {
+ return result{Error: "Formatting would change the Go token stream"}
+ }
+
+ output.Formatted = proposal
+ }
+
+ return output
+}
+
+func main() {
+ input := json.NewDecoder(os.Stdin)
+ output := json.NewEncoder(os.Stdout)
+
+ for {
+ var request request
+
+ if err := input.Decode(&request); err != nil {
+ if err == io.EOF {
+ return
+ }
+
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+
+ if err := output.Encode(analyze(request)); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+ }
+}
diff --git a/src/go_source.rs b/src/go_source.rs
new file mode 100644
index 0000000..24f381a
--- /dev/null
+++ b/src/go_source.rs
@@ -0,0 +1,106 @@
+// src/go_source.rs
+
+use std::cell::RefCell;
+use std::io::{BufRead, BufReader, Write};
+use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
+
+use serde_json::Value;
+use tempfile::{Builder, NamedTempFile};
+
+use crate::adapter_protocol::{decode, request, runtime};
+use crate::config::Effective;
+use crate::language::{Analysis, Diagnostic};
+
+const ADAPTER: &str = include_str!("go_adapter.go");
+
+struct Worker {
+ child: Child,
+ stdin: Option<ChildStdin>,
+ stdout: BufReader<ChildStdout>,
+ _source: NamedTempFile,
+}
+
+thread_local! {
+ static WORKER: RefCell<Option<Worker>> = const { RefCell::new(None) };
+}
+
+impl Worker {
+ fn start() -> Result<Self, String> {
+ let mut source = Builder::new()
+ .prefix("c4d-go-")
+ .suffix(".go")
+ .tempfile()
+ .map_err(|error| error.to_string())?;
+ source.write_all(ADAPTER.as_bytes()).map_err(|error| error.to_string())?;
+ let mut child = Command::new("go")
+ .arg("run")
+ .arg(source.path())
+ .env("GO111MODULE", "off")
+ .env("CGO_ENABLED", "0")
+ .env("GOENV", "off")
+ .env("GOFLAGS", "")
+ .env_remove("GOOS")
+ .env_remove("GOARCH")
+ .env("GOPROXY", "off")
+ .env("GOSUMDB", "off")
+ .env("GOTELEMETRY", "off")
+ .env("GOTOOLCHAIN", "local")
+ .env("GOWORK", "off")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .spawn()
+ .map_err(|error| format!("Go support needs go on PATH: {error}"))?;
+ let stdin = child.stdin.take().expect("piped Go input");
+ let stdout = child.stdout.take().expect("piped Go output");
+
+ Ok(Self {
+ child,
+ stdin: Some(stdin),
+ stdout: BufReader::new(stdout),
+ _source: source,
+ })
+ }
+
+ fn ask(&mut self, request: &Value) -> Result<Value, String> {
+ let stdin = self.stdin.as_mut().expect("open Go input");
+ writeln!(stdin, "{request}").map_err(|error| error.to_string())?;
+ let mut line = String::new();
+ let count = self.stdout.read_line(&mut line).map_err(|error| error.to_string())?;
+
+ if count == 0 {
+ return Err("Go adapter stopped without returning a result".into());
+ }
+
+ serde_json::from_str(&line).map_err(|error| error.to_string())
+ }
+}
+
+impl Drop for Worker {
+ fn drop(&mut self) {
+ drop(self.stdin.take());
+ let _ = self.child.wait();
+ }
+}
+
+pub fn analyze<'source>(
+ source: &'source str,
+ path: &str,
+ settings: &Effective,
+ naming: bool,
+) -> Result<Analysis<'source>, Diagnostic> {
+ let answer = WORKER.with_borrow_mut(|slot| {
+ if slot.is_none() {
+ *slot = Some(Worker::start()?);
+ }
+
+ let answer = slot.as_mut().expect("started Go adapter").ask(&request(source, path, settings, naming));
+
+ if answer.is_err() {
+ slot.take();
+ }
+
+ answer
+ }).map_err(runtime)?;
+
+ decode(source, settings, &answer)
+}
diff --git a/src/json_source.rs b/src/json_source.rs
new file mode 100644
index 0000000..0726684
--- /dev/null
+++ b/src/json_source.rs
@@ -0,0 +1,284 @@
+// src/json_source.rs
+
+use std::borrow::Cow;
+use std::ops::Range;
+
+use serde::de::IgnoredAny;
+
+use crate::config::Effective;
+use crate::language::{Analysis, Diagnostic};
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Kind {
+ Open,
+ Close,
+ Comma,
+ Colon,
+ Value,
+}
+
+struct Token {
+ kind: Kind,
+ span: Range<usize>,
+}
+
+fn syntax(offset: usize, message: impl Into<String>) -> Diagnostic {
+ Diagnostic {
+ offset,
+ rule: "syntax",
+ message: message.into(),
+ }
+}
+
+fn lex(source: &str, comments: bool) -> Result<(Vec<Token>, Vec<Range<usize>>), Diagnostic> {
+ let bytes = source.as_bytes();
+ let mut offset = 0;
+ let mut tokens = Vec::new();
+ let mut masks = Vec::new();
+
+ while offset < bytes.len() {
+ let start = offset;
+ offset += 1;
+
+ let kind = match bytes[start] {
+ b' ' | b'\t' | b'\r' | b'\n' => continue,
+ b'{' | b'[' => Kind::Open,
+ b'}' | b']' => Kind::Close,
+ b',' => Kind::Comma,
+ b':' => Kind::Colon,
+ b'"' => {
+ while offset < bytes.len() {
+ let byte = bytes[offset];
+ offset += 1;
+
+ if byte == b'"' {
+ break;
+ }
+
+ if byte == b'\\' && offset < bytes.len() {
+ offset += 1;
+ }
+ }
+
+ Kind::Value
+ }
+ b'/' if comments && bytes.get(offset) == Some(&b'/') => {
+ offset = source[start..].find(['\r', '\n']).map_or(bytes.len(), |end| start + end);
+ masks.push(start..offset);
+ continue;
+ }
+ b'/' if comments && bytes.get(offset) == Some(&b'*') => {
+ offset = source[offset + 1..]
+ .find("*/")
+ .map(|end| offset + 1 + end + 2)
+ .ok_or_else(|| syntax(start, "Unterminated block comment"))?;
+ masks.push(start..offset);
+ continue;
+ }
+ _ => {
+ while bytes.get(offset).is_some_and(|&byte| {
+ !matches!(byte, b' ' | b'\t' | b'\r' | b'\n' | b'{' | b'[' | b'}' | b']' | b':' | b',' | b'"' | b'/')
+ }) {
+ offset += 1;
+ }
+
+ Kind::Value
+ }
+ };
+
+ tokens.push(Token {
+ kind,
+ span: start..offset,
+ });
+ }
+
+ Ok((tokens, masks))
+}
+
+fn validate(
+ source: &str,
+ tokens: &[Token],
+ mut masks: Vec<Range<usize>>,
+ comments: bool,
+ lines: &[usize],
+) -> Result<(), Diagnostic> {
+ if comments {
+ // Mask commas only after a value and immediately before a closing delimiter.
+ for triple in tokens.windows(3) {
+ if matches!(triple[0].kind, Kind::Value | Kind::Close)
+ && triple[1].kind == Kind::Comma && triple[2].kind == Kind::Close
+ {
+ masks.push(triple[1].span.clone());
+ }
+ }
+ }
+
+ let mut masked;
+ let input = if masks.is_empty() {
+ source.as_bytes()
+ } else {
+ masked = source.as_bytes().to_vec();
+
+ for range in masks {
+ for byte in &mut masked[range] {
+ if !matches!(*byte, b'\r' | b'\n') {
+ *byte = b' ';
+ }
+ }
+ }
+
+ &masked
+ };
+
+ serde_json::from_slice::<IgnoredAny>(input).map_err(|error| {
+ let line = lines[error.line().saturating_sub(1).min(lines.len() - 1)];
+ let mut offset = (line + error.column().saturating_sub(1)).min(source.len());
+
+ while !source.is_char_boundary(offset) {
+ offset -= 1;
+ }
+
+ syntax(offset, error.to_string())
+ })?;
+ Ok(())
+}
+
+struct Edit {
+ span: Range<usize>,
+ replacement: String,
+ issue: Diagnostic,
+}
+
+fn edit(span: Range<usize>, replacement: String, rule: &'static str, message: String) -> Edit {
+ Edit {
+ issue: Diagnostic {
+ offset: span.start,
+ rule,
+ message,
+ },
+ span,
+ replacement,
+ }
+}
+
+pub fn analyze<'source, const COMMENTS: bool>(
+ source: &'source str,
+ _: &str,
+ settings: &Effective,
+ _: bool,
+) -> Result<Analysis<'source>, Diagnostic> {
+ let code = source.strip_prefix('\u{feff}').unwrap_or(source);
+ let header = source.len() - code.len();
+ let lines: Vec<_> = std::iter::once(0)
+ .chain(code.match_indices('\n').map(|(offset, _)| offset + 1))
+ .collect();
+ let result = lex(code, COMMENTS).and_then(|(tokens, masks)| {
+ validate(code, &tokens, masks, COMMENTS, &lines)?;
+ Ok(tokens)
+ });
+ let tokens = result.map_err(|mut issue| {
+ issue.offset += header;
+ issue
+ })?;
+
+ let mut edits = Vec::new();
+ let mut depth: usize = 0;
+ let mut previous_line = None;
+
+ for (index, token) in tokens.iter().enumerate() {
+ let line = lines.partition_point(|offset| *offset <= token.span.start) - 1;
+
+ if token.kind == Kind::Close {
+ depth = depth.saturating_sub(1);
+ }
+
+ let indent = settings.indent_size();
+
+ if indent != 0 && previous_line != Some(line) {
+ let prefix = &code.as_bytes()[lines[line]..token.span.start];
+ let width = depth * indent;
+
+ if prefix.iter().all(|byte| matches!(byte, b' ' | b'\t'))
+ && (prefix.len() != width || prefix.contains(&b'\t'))
+ {
+ edits.push(edit(
+ lines[line]..token.span.start,
+ " ".repeat(width),
+ "formatting.indentSize",
+ format!("Expected {width} space(s) of indentation"),
+ ));
+ }
+ }
+
+ previous_line = Some(line);
+
+ if token.kind == Kind::Open {
+ depth += 1;
+ }
+
+ let newlines = settings.newline_size();
+
+ if newlines == 0 || token.kind != Kind::Comma || index == 0 {
+ continue;
+ }
+
+ let Some(right) = tokens.get(index + 1).filter(|next| next.kind != Kind::Close) else {
+ continue;
+ };
+ let nested_right = right.kind == Kind::Open
+ || (tokens.get(index + 2).is_some_and(|next| next.kind == Kind::Colon)
+ && tokens.get(index + 3).is_some_and(|next| next.kind == Kind::Open));
+
+ if tokens[index - 1].kind != Kind::Close && !nested_right {
+ continue;
+ }
+
+ let between = &code[token.span.end..right.span.start];
+
+ if !between.bytes().all(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) {
+ continue;
+ }
+
+ let count = between.bytes().filter(|&byte| byte == b'\n').count();
+
+ if count != 0 && count != newlines {
+ let first = between.find('\n').unwrap();
+ let last = between.rfind('\n').unwrap();
+ let ending = if between[..first].ends_with('\r') { "\r\n" } else { "\n" };
+ edits.push(edit(
+ token.span.end..token.span.end + last + 1,
+ ending.repeat(newlines),
+ "formatting.newLineSize",
+ format!("Expected {newlines} newline character(s) between structured values"),
+ ));
+ }
+ }
+
+ if edits.is_empty() {
+ return Ok(Analysis {
+ formatted: Cow::Borrowed(source),
+ issues: Vec::new(),
+ });
+ }
+
+ let mut output = String::with_capacity(source.len());
+ let mut issues = Vec::with_capacity(edits.len());
+ output.push_str(&source[..header]);
+
+ let mut cursor = 0;
+
+ for Edit { span, replacement, mut issue } in edits {
+ output.push_str(&code[cursor..span.start]);
+ output.push_str(&replacement);
+ cursor = span.end;
+ issue.offset += header;
+ issues.push(issue);
+ }
+
+ output.push_str(&code[cursor..]);
+
+ Ok(Analysis {
+ formatted: Cow::Owned(output),
+ issues,
+ })
+}
diff --git a/src/language.rs b/src/language.rs
index b3eb8aa..3dd1e17 100644
--- a/src/language.rs
+++ b/src/language.rs
@@ -18,7 +18,7 @@ pub struct Analysis<'source> {
pub struct Language {
pub id: &'static str,
- pub extension: &'static str,
+ pub extensions: &'static [&'static str],
pub generated_header: fn(&str, &str) -> bool,
pub analyze: for<'source> fn(
&'source str,
@@ -28,16 +28,42 @@ pub struct Language {
) -> Result<Analysis<'source>, Diagnostic>,
}
-pub static LANGUAGES: &[Language] = &[Language {
- id: "rust",
- extension: "rs",
- generated_header: crate::rust_source::generated_header,
- analyze: crate::rust_source::analyze,
- }];
+pub static LANGUAGES: &[Language] = &[
+ Language {
+ id: "rust",
+ extensions: &["rs"],
+ generated_header: crate::rust_source::generated_header,
+ analyze: crate::rust_source::analyze,
+ },
+ Language {
+ id: "json",
+ extensions: &["json"],
+ generated_header: |_, _| false,
+ analyze: crate::json_source::analyze::<false>,
+ },
+ Language {
+ id: "jsonc",
+ extensions: &["jsonc"],
+ generated_header: crate::rust_source::generated_header,
+ analyze: crate::json_source::analyze::<true>,
+ },
+ Language {
+ id: "python",
+ extensions: &["py", "pyi"],
+ generated_header: crate::python_source::generated_header,
+ analyze: crate::python_source::analyze,
+ },
+ Language {
+ id: "go",
+ extensions: &["go"],
+ generated_header: crate::rust_source::generated_header,
+ analyze: crate::go_source::analyze,
+ },
+];
pub fn detect(path: &Path) -> Option<&'static Language> {
let extension = path.extension()?.to_str()?;
LANGUAGES
.iter()
- .find(|language| extension.eq_ignore_ascii_case(language.extension))
+ .find(|language| language.extensions.iter().any(|candidate| extension.eq_ignore_ascii_case(candidate)))
}
diff --git a/src/main.rs b/src/main.rs
index 4b312bd..77c294a 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,11 +1,19 @@
// src/main.rs
+mod adapter_protocol;
+
mod config;
mod discovery;
+mod go_source;
+
+mod json_source;
+
mod language;
+mod python_source;
+
mod rust_source;
mod terminal;
@@ -56,7 +64,7 @@ fn report(path: &Path, source: &str, issues: &[Diagnostic], terminal: &Terminal)
}
let column = source[line_start..issue.offset].chars().count() + 1;
- let tone = if issue.rule == "syntax" {
+ let tone = if matches!(issue.rule, "syntax" | "runtime") {
Tone::Error
} else {
Tone::Notice
diff --git a/src/python_adapter.py b/src/python_adapter.py
new file mode 100644
index 0000000..4f42c09
--- /dev/null
+++ b/src/python_adapter.py
@@ -0,0 +1,224 @@
+# src/python_adapter.py
+
+import ast
+import codecs
+import io
+import json
+import re
+import sys
+import tokenize
+
+if sys.version_info < (3, 11):
+ raise SystemExit("C4D requires Python 3.11 or newer")
+
+INDENT = "formatting.indentSize"
+NEWLINES = "formatting.newLineSize"
+HEADER = "formatting.filePathHeader"
+COMPOUND = (
+ ast.FunctionDef,
+ ast.AsyncFunctionDef,
+ ast.ClassDef,
+ ast.If,
+ ast.For,
+ ast.AsyncFor,
+ ast.While,
+ ast.Try,
+ ast.TryStar,
+ ast.With,
+ ast.AsyncWith,
+ ast.Match,
+)
+ENCODING = re.compile(r"^[ \t\f]*#.*?coding[:=][ \t]*[-\w.]+")
+
+def document_lines(source):
+ # CPython normalizes physical CRLF line endings on parsing.
+ return re.findall(r"[^\n]*\n|[^\n]+$", source)
+
+def indentation(tokens, lines, starts, width):
+ depth = 0
+ at_start = True
+
+ for token in tokens:
+ kind = token.type
+
+ if kind == tokenize.INDENT:
+ depth += 1
+ elif kind == tokenize.DEDENT:
+ depth -= 1
+ elif kind == tokenize.NEWLINE:
+ at_start = True
+ elif kind in (tokenize.NL, tokenize.COMMENT, tokenize.ENCODING, tokenize.ENDMARKER):
+ continue
+ elif at_start:
+ at_start = False
+ row, column = token.start
+ start = starts[row - 1]
+ prefix = lines[row - 1][:column]
+ wanted = " " * (depth * width)
+
+ if prefix != wanted and not prefix.strip(" \t"):
+ yield (start, start + column, wanted, INDENT, f"Expected {len(wanted)} space(s) of indentation")
+
+def statement_start(statement):
+ decorators = getattr(statement, "decorator_list", ())
+ return min((decorator.lineno for decorator in decorators), default=statement.lineno)
+
+def block_spacing(tree, source, starts, width):
+ for node in ast.walk(tree):
+ for _, field in ast.iter_fields(node):
+ if not isinstance(field, list) or not field or not isinstance(field[0], ast.stmt):
+ continue
+
+ for left, right in zip(field, field[1:]):
+ if not isinstance(left, COMPOUND) and not isinstance(right, COMPOUND):
+ continue
+
+ right_line = statement_start(right)
+
+ if left.end_lineno >= right_line:
+ continue
+
+ line_start = starts[left.end_lineno - 1]
+ end = starts[right_line - 1]
+ left_line = source[line_start:starts[left.end_lineno]]
+ start = line_start + len(left_line.encode()[:left.end_col_offset].decode())
+ gap = source[start:end]
+ count = gap.count("\n")
+
+ if count and count != width and not gap.strip(" \t\r\n"):
+ ending = "\r\n" if gap.partition("\n")[0].endswith("\r") else "\n"
+ yield (start, end, ending * width, NEWLINES, f"Expected {width} newline character(s) between logical blocks")
+
+def file_header(lines, starts, path):
+ comment = "# " + path
+
+ if ENCODING.match(comment):
+ comment = comment.replace("coding:", r"coding\:").replace("coding=", r"coding\=")
+
+ for line in lines:
+ text = line.strip()
+
+ if text == comment:
+ return None
+
+ if text and not text.startswith("#"):
+ break
+
+ count = int(bool(lines and lines[0].startswith("#!")))
+
+ for index, line in enumerate(lines[:2]):
+ if ENCODING.match(line) and (index == 0 or lines[0].lstrip().startswith("#") or not lines[0].strip()):
+ count = index + 1
+ break
+
+ leading = "\r\n" if lines and lines[0].endswith("\r\n") else "\n"
+ separation = leading if count and not lines[count - 1].endswith("\n") else ""
+ return (starts[count], starts[count], separation + comment + leading, HEADER, f"Expected file path header {comment}")
+
+def naming(tree, lines, starts, tokens):
+ token_names = {}
+ previous = None
+
+ for token in tokens:
+ if previous and previous.string in ("def", "class") and token.type == tokenize.NAME:
+ row, column = token.start
+ token_names[previous.start[0]] = starts[row - 1] + column
+
+ previous = token
+
+ for node in ast.walk(tree):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ category = "classes" if isinstance(node, ast.ClassDef) else "functions"
+ yield (token_names.get(node.lineno, starts[node.lineno - 1]), category, node.name)
+ elif isinstance(node, ast.arg) or (isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store)):
+ name = node.arg if isinstance(node, ast.arg) else node.id
+ column = len(lines[node.lineno - 1].encode()[:node.col_offset].decode())
+ yield (starts[node.lineno - 1] + column, "variables", name)
+
+def analyze(request):
+ original = request["source"]
+ source = original.removeprefix("\ufeff")
+ bom = original[:len(original) - len(source)]
+
+ if re.search(r"\r(?!\n)", source):
+ raise SyntaxError("Python source must use LF or CRLF line endings")
+
+ raw = original.encode()
+ encoding, _ = tokenize.detect_encoding(io.BytesIO(raw).readline)
+
+ if codecs.lookup(encoding).name not in ("utf-8", "utf-8-sig", "ascii"):
+ raise SyntaxError("C4D supports only UTF-8 Python source")
+
+ tree = ast.parse(raw, type_comments=True)
+ tokens = list(tokenize.tokenize(io.BytesIO(raw).readline))
+ lines = document_lines(source)
+ starts = [0]
+
+ for line in lines:
+ starts.append(starts[-1] + len(line))
+
+ edits = []
+
+ if request["indent"]:
+ edits.extend(indentation(tokens, lines, starts, request["indent"]))
+
+ if request["newlines"]:
+ edits.extend(block_spacing(tree, source, starts, request["newlines"]))
+
+ if request["header"]:
+ header = file_header(lines, starts, request["path"])
+
+ if header:
+ edits.append(header)
+
+ sections = [bom]
+ previous = 0
+
+ for start, end, replacement, _, _ in sorted(edits):
+ sections.extend((source[previous:start], replacement))
+ previous = end
+
+ sections.append(source[previous:])
+ formatted = "".join(sections)
+
+ if edits:
+ proposed = ast.parse(formatted.encode(), type_comments=True)
+
+ for item in (*tree.type_ignores, *proposed.type_ignores):
+ item.lineno = 0
+
+ if ast.dump(tree) != ast.dump(proposed):
+ raise SyntaxError("Formatting would change the Python syntax tree")
+
+ names = list(naming(tree, lines, starts, tokens)) if request["names"] else []
+ positions = {start for start, _, _, _, _ in edits}
+ positions.update(offset for offset, _, _ in names)
+ byte_offsets = {}
+ position = 0
+ total = len(bom.encode())
+
+ for offset in sorted(positions):
+ total += len(source[position:offset].encode())
+ byte_offsets[offset] = total
+ position = offset
+
+ return {
+ "formatted": formatted,
+ "issues": [
+ {"offset": byte_offsets[start], "rule": rule, "message": message}
+ for start, _, _, rule, message in edits
+ ],
+ "names": [
+ (byte_offsets[offset], category, name)
+ for offset, category, name in names
+ ],
+ }
+
+try:
+ print(json.dumps(analyze(json.load(sys.stdin))))
+except (SyntaxError, tokenize.TokenError, UnicodeError) as error:
+ print(json.dumps({
+ "error": getattr(error, "msg", str(error)),
+ "line": getattr(error, "lineno", None) or 1,
+ "column": getattr(error, "offset", None) or 1,
+ }))
diff --git a/src/python_source.rs b/src/python_source.rs
new file mode 100644
index 0000000..925b8c1
--- /dev/null
+++ b/src/python_source.rs
@@ -0,0 +1,61 @@
+// src/python_source.rs
+
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+use serde_json::Value;
+
+use crate::adapter_protocol::{decode, request, runtime};
+use crate::config::Effective;
+use crate::language::{Analysis, Diagnostic};
+
+const ADAPTER: &str = include_str!("python_adapter.py");
+
+pub fn generated_header(source: &str, path: &str) -> bool {
+ let path_comment = format!("# {path}");
+ source.trim_start_matches('\u{feff}')
+ .lines()
+ .map(str::trim)
+ .take_while(|line| line.is_empty() || line.starts_with('#'))
+ .any(|line| {
+ if line == path_comment {
+ return false;
+ }
+
+ let line = line.to_ascii_lowercase();
+ ["@generated", "auto-generated", "autogenerated", "automatically generated", "do not edit"]
+ .iter().any(|marker| line.contains(marker))
+ })
+}
+
+fn response(request: &Value) -> Result<Value, Diagnostic> {
+ let mut child = Command::new("python3")
+ .args(["-I", "-S", "-c", ADAPTER])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .map_err(|error| runtime(format!("Python support needs python3 on PATH: {error}")))?;
+
+ let mut stdin = child.stdin.take().expect("piped Python input");
+ let write = stdin.write_all(request.to_string().as_bytes());
+ drop(stdin);
+ let output = child.wait_with_output().map_err(|error| runtime(error.to_string()))?;
+
+ if !output.status.success() {
+ return Err(runtime(format!("Python adapter failed: {}", String::from_utf8_lossy(&output.stderr).trim())));
+ }
+
+ write.map_err(|error| runtime(error.to_string()))?;
+ serde_json::from_slice(&output.stdout).map_err(|error| runtime(error.to_string()))
+}
+
+pub fn analyze<'source>(
+ source: &'source str,
+ path: &str,
+ settings: &Effective,
+ naming: bool,
+) -> Result<Analysis<'source>, Diagnostic> {
+ let answer = response(&request(source, path, settings, naming))?;
+ decode(source, settings, &answer)
+}
diff --git a/tests/cli.rs b/tests/cli.rs
index 7195629..7c22053 100644
--- a/tests/cli.rs
+++ b/tests/cli.rs
@@ -331,7 +331,7 @@ fn discovery_obeys_ignore_rules_and_skips_non_sources() {
"node_modules/module.rs",
"file.generated.rs",
"code.ts",
- "code.py",
+ "code.lua",
".git/hidden.rs",
"../external/outside.rs",
];
@@ -500,10 +500,8 @@ fn explicit_false_overrides_inherited_headers_and_existing_comments_remain() {
fn unsupported_language_fixtures_are_preserved_byte_for_byte() {
let workspace = Workspace::new();
let examples: &[(&str, &[u8])] = &[
- ("example.py", include_bytes!("fixtures/example.py")),
("example.ts", include_bytes!("fixtures/example.ts")),
("example.js", include_bytes!("fixtures/example.js")),
- ("example.go", include_bytes!("fixtures/example.go")),
];
workspace.write(
@@ -591,3 +589,183 @@ fn config_show_initializes_the_global_file_and_preserves_user_edits() {
);
assert_eq!(fs::read(&global).unwrap(), custom);
}
+
+#[test]
+fn json_adapters_format_whitespace_and_preserve_source_tokens() {
+ let workspace = Workspace::new();
+ let json = include_str!("fixtures/example.json.input");
+ let jsonc = include_str!("fixtures/example.jsonc.input");
+ workspace.write("example.json", json);
+ workspace.write("example.JSONC", jsonc.replace('\n', "\r\n"));
+ workspace.write(
+ ".c4d/config.jp",
+ "[formatting]\nfilePathHeader: true\n[cases]\nvariables: PascalCase\n[overrides.jsonc.formatting]\nindentSize: 2\n",
+ );
+
+ let before = workspace.cli(&["check", "."], 1);
+ let diagnostics = String::from_utf8_lossy(&before.stdout);
+ assert!(diagnostics.contains("formatting.indentSize"));
+ assert!(diagnostics.contains("formatting.newLineSize"));
+ assert!(!diagnostics.contains("cases.variables"));
+ workspace.cli(&["format", "--check", "."], 1);
+ assert_eq!(workspace.read("example.json"), json);
+ workspace.cli(&["format", "."], 0);
+
+ let formatted = workspace.read("example.json");
+ assert!(formatted.starts_with("{\n \"message\""));
+ assert!(formatted.contains("Keep \\\"[ ]\\\" and // inside this string"));
+ assert!(formatted.contains("\n\n \"list\": [\n {\"count\": 1e500, \"count\": -0.0},\n\n 2"));
+ assert!(formatted.contains(" ],\n\n \"done\": true"));
+
+ let formatted = workspace.read("example.JSONC");
+ assert!(formatted.contains(" /* Keep this comment\r\n and its indentation. */"));
+ assert!(formatted.contains(" \"https://example.test/a/*b*/\",\r\n 2,\r\n ],"));
+ assert!(formatted.contains(" // Keep this next to the flag.\r\n \"enabled\": true,"));
+ assert!(!formatted.replace("\r\n", "").contains('\n'));
+ workspace.cli(&["check", "."], 0);
+ workspace.cli(&["format", "--check", "."], 0);
+
+ let effective = workspace.config(&[]);
+ assert_eq!(effective["overrides"]["json"]["formatting"]["indentSize"], 4);
+ assert_eq!(effective["overrides"]["jsonc"]["formatting"]["indentSize"], 2);
+}
+
+#[test]
+fn invalid_json_and_jsonc_are_reported_without_writes() {
+ let workspace = Workspace::new();
+
+ for (path, source) in [
+ ("strict.json", "{\n \"a\": 1,\n}\n"),
+ ("strict.json", "{\n // Comment\n \"a\": 1\n}\n"),
+ ("extended.jsonc", "[\n 1,,\n]\n"),
+ ("extended.jsonc", "{\n \"a\": 1 /* unterminated\n"),
+ ("extended.jsonc", "[\n 01,\n]\n"),
+ ] {
+ workspace.write(path, source);
+ let result = workspace.cli(&["format", path], 2);
+ assert!(String::from_utf8_lossy(&result.stdout).contains(" syntax"));
+ assert_eq!(workspace.read(path), source);
+ }
+}
+
+#[test]
+fn python_format_preserves_suites_literals_comments_and_behaviour() {
+ let workspace = Workspace::new();
+ let source = include_str!("fixtures/layout.py.input").replace('\n', "\r\n");
+ workspace.write("example.py", &source);
+ workspace.write(
+ ".c4d/config.jp",
+ "[formatting]\nfilePathHeader: true\n[cases]\nfunctions: snake_case\nvariables: snake_case\n",
+ );
+ let run = || {
+ let output = Command::new("python3")
+ .args(["-I", "-S", "example.py"])
+ .current_dir(&workspace.project)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
+ output.stdout
+ };
+ let original_output = run();
+
+ let check = workspace.cli(&["check", "."], 1);
+ let diagnostics = String::from_utf8_lossy(&check.stdout);
+ assert!(diagnostics.contains("example.py:6:5 cases.functions"));
+ assert!(diagnostics.contains("example.py:6:20 cases.variables"));
+ assert!(diagnostics.contains("formatting.filePathHeader"));
+ workspace.cli(&["format", "--check", "."], 1);
+ assert_eq!(workspace.read("example.py"), source);
+
+ workspace.cli(&["format", "."], 0);
+ let formatted = workspace.read("example.py");
+ assert!(formatted.starts_with("#!/usr/bin/env python3\r\n# coding: utf-8\r\n# example.py\r\n"));
+ assert!(formatted.contains(" keep these spaces and café\r\nline three"));
+ assert!(formatted.contains("\r\n\r\ndef DescribeStatus"));
+ assert!(formatted.contains(" # Keep the indentation of this comment.\r\n if Ready:"));
+ assert!(formatted.contains(" return (text,\r\n \"ready\")"));
+ assert!(!formatted.replace("\r\n", "").contains('\n'));
+ assert_eq!(run(), original_output);
+ workspace.cli(&["format", "--check", "."], 0);
+ workspace.cli(&["check", "."], 1);
+}
+
+#[test]
+fn python_applies_overrides_to_stubs_and_refuses_invalid_syntax() {
+ let workspace = Workspace::new();
+ workspace.write(
+ ".c4d/config.jp",
+ "[overrides.python.formatting]\nindentSize: 2\nnewLineSize: 0\n",
+ );
+ let source = include_str!("fixtures/example.py");
+ workspace.write("example.PYI", source);
+ workspace.cli(&["format", "example.PYI"], 0);
+ let formatted = workspace.read("example.PYI");
+ assert!(formatted.contains("\n if ready:\n return"));
+ workspace.cli(&["format", "--check", "example.PYI"], 0);
+
+ let invalid = "def broken():\n value = 1\n return value\n";
+ workspace.write("broken.py", invalid);
+ let result = workspace.cli(&["format", "broken.py"], 2);
+ assert!(String::from_utf8_lossy(&result.stdout).contains("broken.py:3:"));
+ assert_eq!(workspace.read("broken.py"), invalid);
+}
+
+#[test]
+fn go_format_preserves_literals_directives_and_program_output() {
+ let workspace = Workspace::new();
+ let source = include_str!("fixtures/layout.go.input").replace('\n', "\r\n");
+ workspace.write("example.go", &source);
+ workspace.write(
+ ".c4d/config.jp",
+ "[formatting]\nfilePathHeader: true\n[overrides.go.formatting]\nindentSize: 2\n[overrides.go.cases]\nfunctions: snake_case\nvariables: snake_case\n",
+ );
+ let run = || {
+ let output = Command::new("go")
+ .args(["run", "example.go"])
+ .env("GOTOOLCHAIN", "local")
+ .env("GO111MODULE", "off")
+ .current_dir(&workspace.project)
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
+ output.stdout
+ };
+ let original = run();
+
+ let check = workspace.cli(&["check", "."], 1);
+ let diagnostics = String::from_utf8_lossy(&check.stdout);
+ assert!(diagnostics.contains("cases.functions"));
+ assert!(diagnostics.contains("cases.variables"));
+ assert!(diagnostics.contains("formatting.filePathHeader"));
+ workspace.cli(&["format", "--check", "."], 1);
+ assert_eq!(workspace.read("example.go"), source);
+
+ workspace.cli(&["format", "."], 0);
+ let formatted = workspace.read("example.go");
+ assert!(formatted.starts_with("// example.go\r\n\r\n//go:build linux\r\n\r\npackage main"));
+ assert!(formatted.contains(" keep these spaces and café\r\nline three`\r\n\r\nfunc"));
+ assert!(formatted.contains("\r\n if Ready {\r\n return text\r\n }\r\n\r\n return"));
+ assert!(!formatted.replace("\r\n", "").contains('\n'));
+ assert_eq!(run(), original);
+ workspace.cli(&["format", "--check", "."], 0);
+}
+
+#[test]
+fn go_preserves_line_directives_and_refuses_invalid_syntax() {
+ let workspace = Workspace::new();
+ let sample = include_str!("fixtures/example.go");
+ workspace.write("sample.GO", sample);
+ workspace.write(".c4d/config.jp", "[formatting]\nfilePathHeader: true\n");
+ let directive = "package test\n\n//line original.go:100\nfunc report() {\n\treturn\n}\n";
+ workspace.write("location.go", directive);
+ workspace.cli(&["format", "."], 0);
+ assert_eq!(workspace.read("location.go"), directive);
+ assert!(workspace.read("sample.GO").starts_with("// sample.GO\n"));
+ assert!(workspace.read("sample.GO").contains(" if ready {"));
+
+ let invalid = "package test\nfunc broken() {\n value :=\n}\n";
+ workspace.write("broken.go", invalid);
+ let result = workspace.cli(&["format", "broken.go"], 2);
+ assert!(String::from_utf8_lossy(&result.stdout).contains(" syntax"));
+ assert_eq!(workspace.read("broken.go"), invalid);
+}
diff --git a/tests/fixtures/example.go b/tests/fixtures/example.go
index e8c5175..b651298 100644
--- a/tests/fixtures/example.go
+++ b/tests/fixtures/example.go
@@ -3,8 +3,9 @@
package fixture
func DescribeStatus(ready bool) string {
- if ready {
- return "ready"
- }
- return "waiting"
+ if ready {
+ return "ready"
+ }
+
+ return "waiting"
}
diff --git a/tests/fixtures/example.json.input b/tests/fixtures/example.json.input
new file mode 100644
index 0000000..1812580
--- /dev/null
+++ b/tests/fixtures/example.json.input
@@ -0,0 +1,8 @@
+{
+ "message": "Keep \"[ ]\" and // inside this string",
+ "list": [
+ {"count": 1e500, "count": -0.0},
+ 2
+ ],
+ "done": true
+}
diff --git a/tests/fixtures/example.jsonc.input b/tests/fixtures/example.jsonc.input
new file mode 100644
index 0000000..ed9b473
--- /dev/null
+++ b/tests/fixtures/example.jsonc.input
@@ -0,0 +1,11 @@
+// tests/fixtures/example.jsonc
+{
+ /* Keep this comment
+ and its indentation. */
+ "options": [
+ "https://example.test/a/*b*/",
+ 2,
+ ],
+ // Keep this next to the flag.
+ "enabled": true,
+}
diff --git a/tests/fixtures/example.py b/tests/fixtures/example.py
index bba3d13..2631c2e 100644
--- a/tests/fixtures/example.py
+++ b/tests/fixtures/example.py
@@ -3,4 +3,5 @@
def describe_status(ready):
if ready:
return "ready"
+
return "waiting"
diff --git a/tests/fixtures/layout.go.input b/tests/fixtures/layout.go.input
new file mode 100644
index 0000000..922e7d3
--- /dev/null
+++ b/tests/fixtures/layout.go.input
@@ -0,0 +1,18 @@
+//go:build linux
+
+package main
+
+import "fmt"
+
+const text = `line one
+ keep these spaces and café
+line three`
+func DescribeStatus(Ready bool) string {
+ if Ready {
+ return text
+ }
+ return "waiting"
+}
+func main() {
+ fmt.Println(DescribeStatus(true))
+}
diff --git a/tests/fixtures/layout.py.input b/tests/fixtures/layout.py.input
new file mode 100644
index 0000000..f72098d
--- /dev/null
+++ b/tests/fixtures/layout.py.input
@@ -0,0 +1,12 @@
+#!/usr/bin/env python3
+# coding: utf-8
+text = """line one
+ keep these spaces and café
+line three"""
+def DescribeStatus(Ready):
+ # Keep the indentation of this comment.
+ if Ready:
+ return (text,
+ "ready")
+ return (text, "waiting")
+print(DescribeStatus(True))