feat: pattern support args and multiple variants; add zed extension for highlight
All checks were successful
build-dsl-smoke / Build judge (push) Successful in 13s
build-dsl-smoke / debug / clang / linux (push) Successful in 6s
build-dsl-smoke / debug / gcc / linux (push) Successful in 8s
build-dsl-smoke / release / clang / linux (push) Successful in 9s
build-dsl-smoke / release / gcc / linux (push) Successful in 7s
build-dsl-smoke / sanitized / clang / linux (push) Successful in 8s
build-dsl-smoke / sanitized / gcc / linux (push) Successful in 7s
build-dsl-smoke / debug / clang / windows (push) Successful in 16s
build-dsl-smoke / debug-valgrind / gcc / linux (push) Successful in 14s
build-dsl-smoke / debug / msvc / windows (push) Successful in 18s
build-dsl-smoke / release / clang / windows (push) Successful in 17s
build-dsl-smoke / release / msvc / windows (push) Successful in 17s
build-dsl-smoke / SUMMARY (push) Successful in 5s

This commit is contained in:
2026-04-11 14:37:43 +03:00
parent dacae83dc6
commit 7f9f6a0a6e
29 changed files with 11429 additions and 94 deletions

View File

@@ -99,11 +99,7 @@ func main() {
} }
func parseSuite(path string) *dsl.File { func parseSuite(path string) *dsl.File {
src, err := os.ReadFile(path) f, warns, err := dsl.ParseFile(path)
if err != nil {
fatalf("cannot read %q: %v", path, err)
}
f, warns, err := dsl.Parse(string(src))
if err != nil { if err != nil {
fatalf("parse error in %q:\n %v", path, err) fatalf("parse error in %q:\n %v", path, err)
} }

View File

@@ -50,6 +50,8 @@ type Pattern struct {
DirsGlob string DirsGlob string
InputFile string InputFile string
OutputFile string OutputFile string
Args []string
} }
func (p *Pattern) IsDirMode() bool { func (p *Pattern) IsDirMode() bool {

210
dsl/include_test.go Normal file
View File

@@ -0,0 +1,210 @@
package dsl
import (
"os"
"path/filepath"
"strings"
"testing"
)
func writeTempJdg(t *testing.T, dir, name, content string) string {
t.Helper()
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
return path
}
func TestIncludeBasicMerge(t *testing.T) {
dir := t.TempDir()
writeTempJdg(t, dir, "common.jdg", `
toolchains {
gcc { platforms = "linux" }
}
build_defaults {
language = "c"
standard = "c11"
sources = "*.c"
output = "solution"
warnings = strict
}
`)
mainPath := writeTempJdg(t, dir, "main.jdg", `
include "common.jdg"
build "release" { profile = release }
group("g") {
weight = 1.0
test("t") { stdout = "ok\n" }
}
`)
f, _, err := ParseFile(mainPath)
if err != nil {
t.Fatalf("parse: %v", err)
}
if len(f.Toolchains) != 1 || f.Toolchains[0].Name != "gcc" {
t.Errorf("toolchains not merged: %+v", f.Toolchains)
}
if f.BuildDefaults == nil || f.BuildDefaults.Language != "c" {
t.Errorf("build_defaults not merged: %+v", f.BuildDefaults)
}
if len(f.Builds) != 1 || f.Builds[0].Name != "release" {
t.Errorf("local build lost: %+v", f.Builds)
}
}
func TestIncludeLocalOverridesIncluded(t *testing.T) {
dir := t.TempDir()
writeTempJdg(t, dir, "common.jdg", `
build_defaults {
language = "c"
standard = "c11"
warnings = strict
}
`)
mainPath := writeTempJdg(t, dir, "main.jdg", `
include "common.jdg"
build_defaults {
standard = "c17"
}
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
`)
f, _, err := ParseFile(mainPath)
if err != nil {
t.Fatalf("parse: %v", err)
}
if f.BuildDefaults.Standard != "c17" {
t.Errorf("local should override included standard: got %q", f.BuildDefaults.Standard)
}
if f.BuildDefaults.Language != "c" {
t.Errorf("language should survive from include: got %q", f.BuildDefaults.Language)
}
if f.BuildDefaults.Warnings != WarningsStrict {
t.Errorf("warnings should survive from include: got %v", f.BuildDefaults.Warnings)
}
}
func TestIncludeRelativePathResolution(t *testing.T) {
dir := t.TempDir()
writeTempJdg(t, dir, "shared/tools.jdg", `
toolchains {
gcc { platforms = "linux" }
}
`)
mainPath := writeTempJdg(t, dir, "suite/main.jdg", `
include "../shared/tools.jdg"
build "release" {
language = "c"
sources = "solution.c"
output = "solution"
profile = release
}
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
`)
f, _, err := ParseFile(mainPath)
if err != nil {
t.Fatalf("parse: %v", err)
}
if len(f.Toolchains) != 1 {
t.Errorf("relative include failed to resolve: %+v", f.Toolchains)
}
}
func TestIncludeDuplicateToolchainErrors(t *testing.T) {
dir := t.TempDir()
writeTempJdg(t, dir, "common.jdg", `
toolchains {
gcc { platforms = "linux" }
}
`)
mainPath := writeTempJdg(t, dir, "main.jdg", `
include "common.jdg"
toolchains {
gcc { platforms = "linux" }
}
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
`)
_, _, err := ParseFile(mainPath)
if err == nil {
t.Fatal("expected duplicate toolchain error")
}
if !strings.Contains(err.Error(), "duplicate toolchain") {
t.Errorf("error %q does not mention duplicate toolchain", err.Error())
}
}
func TestIncludeCircularDetection(t *testing.T) {
dir := t.TempDir()
aPath := writeTempJdg(t, dir, "a.jdg", `
include "b.jdg"
group("ga") { weight = 1.0 test("t") { stdout = "ok\n" } }
`)
writeTempJdg(t, dir, "b.jdg", `
include "a.jdg"
`)
_, _, err := ParseFile(aPath)
if err == nil {
t.Fatal("expected circular include error")
}
if !strings.Contains(err.Error(), "circular include") {
t.Errorf("error %q does not mention circular include", err.Error())
}
}
func TestIncludeMissingFileErrors(t *testing.T) {
dir := t.TempDir()
mainPath := writeTempJdg(t, dir, "main.jdg", `
include "nonexistent.jdg"
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
`)
_, _, err := ParseFile(mainPath)
if err == nil {
t.Fatal("expected missing include error")
}
if !strings.Contains(err.Error(), "nonexistent.jdg") {
t.Errorf("error %q does not reference the missing path", err.Error())
}
}
func TestParseRejectsIncludeWithoutFileContext(t *testing.T) {
src := `
include "common.jdg"
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
`
_, _, err := Parse(src)
if err == nil {
t.Fatal("expected error: include without file context")
}
if !strings.Contains(err.Error(), "file context") {
t.Errorf("error %q does not mention file context", err.Error())
}
}

81
dsl/merge.go Normal file
View File

@@ -0,0 +1,81 @@
package dsl
import "fmt"
func mergeFiles(dst, src *File) error {
if src.Build != "" {
dst.Build = src.Build
}
if src.BuildLinux != "" {
dst.BuildLinux = src.BuildLinux
}
if src.BuildWindows != "" {
dst.BuildWindows = src.BuildWindows
}
if src.BuildDarwin != "" {
dst.BuildDarwin = src.BuildDarwin
}
if src.BuildDefaults != nil {
if dst.BuildDefaults == nil {
dst.BuildDefaults = &BuildConfig{}
}
dst.BuildDefaults.MergeFrom(src.BuildDefaults)
}
seenTC := map[string]bool{}
for _, t := range dst.Toolchains {
seenTC[t.Name] = true
}
for _, t := range src.Toolchains {
if seenTC[t.Name] {
return fmt.Errorf("duplicate toolchain %q", t.Name)
}
seenTC[t.Name] = true
dst.Toolchains = append(dst.Toolchains, t)
}
seenB := map[string]bool{}
for _, b := range dst.Builds {
seenB[b.Name] = true
}
for _, b := range src.Builds {
if seenB[b.Name] {
return fmt.Errorf("duplicate build %q", b.Name)
}
seenB[b.Name] = true
dst.Builds = append(dst.Builds, b)
}
seenG := map[string]bool{}
for _, g := range dst.Groups {
seenG[g.Name] = true
}
for _, g := range src.Groups {
if seenG[g.Name] {
return fmt.Errorf("duplicate group %q", g.Name)
}
seenG[g.Name] = true
dst.Groups = append(dst.Groups, g)
}
if src.Timeout != 0 {
dst.Timeout = src.Timeout
}
if src.MemoryLimit != 0 {
dst.MemoryLimit = src.MemoryLimit
}
if src.Binary != "" {
dst.Binary = src.Binary
}
if src.Sources != "" {
dst.Sources = src.Sources
}
if src.NormalizeCRLF {
dst.NormalizeCRLF = true
}
if src.TrimTrailingWS {
dst.TrimTrailingWS = true
}
return nil
}

View File

@@ -3,6 +3,8 @@ package dsl
import ( import (
"fmt" "fmt"
"math" "math"
"os"
"path/filepath"
"strconv" "strconv"
"time" "time"
) )
@@ -11,6 +13,8 @@ type Parser struct {
tokens []Token tokens []Token
pos int pos int
warns []string warns []string
includeBaseDir string
visited map[string]bool
} }
func NewParser(tokens []Token) *Parser { func NewParser(tokens []Token) *Parser {
@@ -72,9 +76,67 @@ func Parse(src string) (*File, []string, error) {
if err != nil { if err != nil {
return nil, parser.Warnings(), err return nil, parser.Warnings(), err
} }
if err := parser.finalize(file); err != nil {
return nil, parser.Warnings(), err
}
return file, parser.Warnings(), nil return file, parser.Warnings(), nil
} }
func ParseFile(path string) (*File, []string, error) {
abs, err := filepath.Abs(path)
if err != nil {
return nil, nil, fmt.Errorf("resolve %q: %w", path, err)
}
visited := map[string]bool{}
parser, file, err := parseFileOnDisk(abs, visited)
if err != nil {
var warns []string
if parser != nil {
warns = parser.Warnings()
}
return nil, warns, err
}
if err := parser.finalize(file); err != nil {
return nil, parser.Warnings(), err
}
return file, parser.Warnings(), nil
}
func parseFileOnDisk(absPath string, visited map[string]bool) (*Parser, *File, error) {
if visited[absPath] {
return nil, nil, fmt.Errorf("circular include: %s", absPath)
}
visited[absPath] = true
src, err := os.ReadFile(absPath)
if err != nil {
return nil, nil, fmt.Errorf("read %s: %w", absPath, err)
}
tokens, err := NewLexer(string(src)).Tokenize()
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", absPath, err)
}
p := NewParser(tokens)
p.includeBaseDir = filepath.Dir(absPath)
p.visited = visited
file, err := p.parseFile()
if err != nil {
return p, nil, fmt.Errorf("%s: %w", absPath, err)
}
return p, file, nil
}
func (p *Parser) finalize(f *File) error {
if err := p.validateWeights(f); err != nil {
return err
}
if err := validateBuilds(f); err != nil {
return err
}
return nil
}
func (p *Parser) parseFile() (*File, error) { func (p *Parser) parseFile() (*File, error) {
f := &File{} f := &File{}
@@ -107,7 +169,10 @@ func (p *Parser) parseFile() (*File, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
f.BuildDefaults = bc if f.BuildDefaults == nil {
f.BuildDefaults = &BuildConfig{}
}
f.BuildDefaults.MergeFrom(bc)
case "toolchains": case "toolchains":
p.advance() p.advance()
@@ -115,7 +180,45 @@ func (p *Parser) parseFile() (*File, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
f.Toolchains = specs existing := map[string]bool{}
for _, tc := range f.Toolchains {
existing[tc.Name] = true
}
for _, tc := range specs {
if existing[tc.Name] {
return nil, fmt.Errorf("duplicate toolchain %q", tc.Name)
}
existing[tc.Name] = true
f.Toolchains = append(f.Toolchains, tc)
}
case "include":
p.advance()
s, err := p.expect(TOKEN_STRING)
if err != nil {
return nil, err
}
if p.includeBaseDir == "" {
return nil, fmt.Errorf("%d:%d: `include` requires file context (use ParseFile, not Parse)", s.Line, s.Col)
}
target := s.Value
if !filepath.IsAbs(target) {
target = filepath.Join(p.includeBaseDir, target)
}
abs, err := filepath.Abs(target)
if err != nil {
return nil, fmt.Errorf("%d:%d: resolve include %q: %w", s.Line, s.Col, s.Value, err)
}
childParser, child, err := parseFileOnDisk(abs, p.visited)
if err != nil {
return nil, fmt.Errorf("%d:%d: include %q: %w", s.Line, s.Col, s.Value, err)
}
for _, w := range childParser.Warnings() {
p.warn(w)
}
if err := mergeFiles(f, child); err != nil {
return nil, fmt.Errorf("%d:%d: include %q: %w", s.Line, s.Col, s.Value, err)
}
case "build_linux": case "build_linux":
p.advance() p.advance()
@@ -216,13 +319,6 @@ func (p *Parser) parseFile() (*File, error) {
} }
} }
if err := p.validateWeights(f); err != nil {
return nil, err
}
if err := validateBuilds(f); err != nil {
return nil, err
}
return f, nil return f, nil
} }
@@ -683,25 +779,40 @@ func (p *Parser) parsePattern() (*Pattern, error) {
if _, err := p.expect(TOKEN_ASSIGN); err != nil { if _, err := p.expect(TOKEN_ASSIGN); err != nil {
return nil, err return nil, err
} }
switch t.Value {
case "input":
val, err := p.expect(TOKEN_STRING) val, err := p.expect(TOKEN_STRING)
if err != nil { if err != nil {
return nil, err return nil, err
} }
switch t.Value {
case "input":
if pat.DirsGlob != "" { if pat.DirsGlob != "" {
pat.InputFile = val.Value pat.InputFile = val.Value
} else { } else {
pat.InputGlob = val.Value pat.InputGlob = val.Value
} }
case "output": case "output":
val, err := p.expect(TOKEN_STRING)
if err != nil {
return nil, err
}
if pat.DirsGlob != "" { if pat.DirsGlob != "" {
pat.OutputFile = val.Value pat.OutputFile = val.Value
} else { } else {
pat.OutputGlob = val.Value pat.OutputGlob = val.Value
} }
case "dirs": case "dirs":
val, err := p.expect(TOKEN_STRING)
if err != nil {
return nil, err
}
pat.DirsGlob = val.Value pat.DirsGlob = val.Value
case "args":
xs, err := p.parseStringList()
if err != nil {
return nil, err
}
pat.Args = xs
default: default:
return nil, fmt.Errorf("%d:%d: unknown pattern field %q", t.Line, t.Col, t.Value) return nil, fmt.Errorf("%d:%d: unknown pattern field %q", t.Line, t.Col, t.Value)
} }

17
editor/zed/.gitignore vendored Normal file
View File

@@ -0,0 +1,17 @@
grammars/*.wasm
tree-sitter-jdg/tree-sitter-jdg.wasm
tree-sitter-jdg/node_modules/
tree-sitter-jdg/bindings/
tree-sitter-jdg/binding.gyp
tree-sitter-jdg/Cargo.toml
tree-sitter-jdg/Cargo.lock
tree-sitter-jdg/Makefile
tree-sitter-jdg/Package.swift
tree-sitter-jdg/pyproject.toml
tree-sitter-jdg/setup.py
tree-sitter-jdg/go.mod
tree-sitter-jdg/go.sum
tree-sitter-jdg/bindings.gyp
tree-sitter-jdg/prebuilds/
tree-sitter-jdg/target/

23
editor/zed/extension.toml Normal file
View File

@@ -0,0 +1,23 @@
id = "jdg"
name = "JDG"
version = "0.1.0"
schema_version = 1
description = "Syntax highlighting for the judge DSL (.jdg)"
repository = "https://github.com/Mond1c/judge"
authors = ["judge contributors"]
themes = []
icon_themes = []
languages = ["languages/jdg"]
capabilities = []
[lib]
[grammars.jdg]
repository = "https://github.com/Mond1c/judge"
rev = "main"
[language_servers]
[context_servers]
[slash_commands]

View File

@@ -0,0 +1,2 @@
("{" @open "}" @close)
("(" @open ")" @close)

View File

@@ -0,0 +1,12 @@
name = "JDG"
grammar = "jdg"
path_suffixes = ["jdg"]
line_comments = ["// "]
autoclose_before = ";:.,=}])>"
brackets = [
{ start = "{", end = "}", close = true, newline = true },
{ start = "(", end = ")", close = true, newline = false },
{ start = "\"", end = "\"", close = true, newline = false, not_in = ["string", "comment"] },
]
word_characters = ["_"]
tab_size = 4

View File

@@ -0,0 +1,100 @@
(comment) @comment
[
"include"
"build"
"build_defaults"
"build_linux"
"build_windows"
"build_darwin"
"toolchains"
"binary"
"sources"
"timeout"
"memory_limit"
"group"
"test"
"pattern"
] @keyword
[
"normalize_crlf"
"trim_trailing_ws"
] @keyword
(build_scalar_field name: _ @property)
(build_list_field name: _ @property)
(bool_decl name: _ @property)
(legacy_build_platform keyword: _ @keyword)
[
"profile"
"warnings"
"define"
"platforms"
"binary"
"class"
"weight"
"scoring"
"wrapper"
"env"
"stdin"
"stdout"
"stderr"
"args"
"exitCode"
"file"
"outFile"
"input"
"output"
"dirs"
] @property
[
"linux"
"windows"
"darwin"
] @type.builtin
(profile_value) @constant.builtin
(warnings_value) @constant.builtin
(scoring_value) @constant.builtin
(class_value) @constant.builtin
(bool) @constant.builtin
"of" @keyword.operator
[
"contains"
"matches"
"anyOrder"
] @function.builtin
[
"="
"~"
] @operator
[
"{"
"}"
"("
")"
] @punctuation.bracket
(simple_string) @string
(heredoc_string) @string
(regex_string) @string.regex
(structured_build name: (string) @string.special)
(legacy_build command: (string) @string.special)
(toolchain_entry name: (string) @type)
(toolchain_entry name: (identifier) @type)
(group name: (string) @string.special)
(test name: (string) @string.special)
(include path: (string) @string.special.path)
(define_field key: (string) @constant.macro)
(env_decl key: (string) @constant.macro)
(file_decl key: (string) @string.special.path)
(out_file_decl key: (string) @string.special.path)

View File

@@ -0,0 +1,11 @@
[
(build_block)
(toolchains)
(toolchain_entry)
(group)
(test)
(pattern)
(any_order_matcher)
] @indent
"}" @end

View File

@@ -0,0 +1,7 @@
((comment) @injection.content
(#set! injection.language "comment"))
((regex_matcher
pattern: (regex_string) @injection.content)
(#set! injection.language "regex")
(#set! injection.include-children))

View File

@@ -0,0 +1,23 @@
(structured_build
"build" @context
name: (string) @name) @item
(build_defaults
"build_defaults" @context) @item
(toolchains
"toolchains" @context) @item
(toolchain_entry
name: (_) @name) @item
(group
"group" @context
name: (string) @name) @item
(test
"test" @context
name: (string) @name) @item
(pattern
"pattern" @context) @item

View File

@@ -0,0 +1,39 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.{json,toml,yml,gyp}]
indent_style = space
indent_size = 2
[*.js]
indent_style = space
indent_size = 2
[*.rs]
indent_style = space
indent_size = 4
[*.{c,cc,h}]
indent_style = space
indent_size = 4
[*.{py,pyi}]
indent_style = space
indent_size = 4
[*.swift]
indent_style = space
indent_size = 4
[*.go]
indent_style = tab
indent_size = 8
[Makefile]
indent_style = tab
indent_size = 8

View File

@@ -0,0 +1,11 @@
* text eol=lf
src/*.json linguist-generated
src/parser.c linguist-generated
src/tree_sitter/* linguist-generated
bindings/** linguist-generated
binding.gyp linguist-generated
setup.py linguist-generated
Makefile linguist-generated
Package.swift linguist-generated

38
editor/zed/tree-sitter-jdg/.gitignore vendored Normal file
View File

@@ -0,0 +1,38 @@
# Rust artifacts
Cargo.lock
target/
# Node artifacts
build/
prebuilds/
node_modules/
*.tgz
# Swift artifacts
.build/
# Go artifacts
go.sum
_obj/
# Python artifacts
.venv/
dist/
*.egg-info
*.whl
# C artifacts
*.a
*.so
*.so.*
*.dylib
*.dll
*.pc
# Example dirs
/examples/*/
# Grammar volatiles
*.wasm
*.obj
*.o

View File

@@ -0,0 +1,342 @@
module.exports = grammar({
name: 'jdg',
extras: $ => [/\s+/, $.comment],
word: $ => $.identifier,
conflicts: $ => [],
rules: {
source_file: $ => repeat($._top_statement),
comment: $ => token(seq('//', /[^\n]*/)),
_top_statement: $ => choice(
$.include,
$.toolchains,
$.build_defaults,
$.structured_build,
$.legacy_build_platform,
$.legacy_build,
$.binary_decl,
$.sources_decl,
$.bool_decl,
$.timeout_decl,
$.memory_limit_decl,
$.group,
),
include: $ => seq(
'include',
field('path', $.string)
),
legacy_build: $ => prec(1, seq(
'build',
field('command', $.string)
)),
legacy_build_platform: $ => seq(
field('keyword', choice('build_linux', 'build_windows', 'build_darwin')),
field('command', $.string)
),
structured_build: $ => prec(2, seq(
'build',
field('name', $.string),
field('body', $.build_block)
)),
build_defaults: $ => seq(
'build_defaults',
field('body', $.build_block)
),
build_block: $ => seq(
'{',
repeat($._build_field),
'}'
),
_build_field: $ => choice(
$.build_scalar_field,
$.build_list_field,
$.build_profile_field,
$.build_warnings_field,
$.define_field,
$.os_override,
),
build_scalar_field: $ => seq(
field('name', choice('language', 'standard', 'output', 'wrapper')),
'=',
field('value', $.string)
),
build_list_field: $ => seq(
field('name', choice('sources', 'includes', 'sanitize', 'link', 'extra', 'platforms', 'compilers')),
'=',
field('value', repeat1($.string))
),
build_profile_field: $ => seq(
'profile',
'=',
field('value', $.profile_value)
),
profile_value: $ => choice('release', 'debug', 'sanitized'),
build_warnings_field: $ => seq(
'warnings',
'=',
field('value', $.warnings_value)
),
warnings_value: $ => choice('default', 'strict', 'pedantic'),
define_field: $ => seq(
'define',
'(',
field('key', $.string),
')',
'=',
field('value', $.string)
),
os_override: $ => seq(
field('os', $.os_name),
field('body', $.build_block)
),
os_name: $ => choice('linux', 'windows', 'darwin'),
toolchains: $ => seq(
'toolchains',
'{',
repeat($.toolchain_entry),
'}'
),
toolchain_entry: $ => seq(
field('name', choice($.identifier, $.string)),
'{',
repeat($._toolchain_field),
'}'
),
_toolchain_field: $ => choice(
$.toolchain_platforms_field,
$.toolchain_binary_field,
$.toolchain_class_field,
),
toolchain_platforms_field: $ => seq(
'platforms',
'=',
field('value', repeat1($.string))
),
toolchain_binary_field: $ => seq(
'binary',
'=',
field('value', $.string)
),
toolchain_class_field: $ => seq(
'class',
'=',
field('value', $.class_value)
),
class_value: $ => choice('gnu', 'msvc'),
binary_decl: $ => seq(
'binary',
'=',
field('value', $.string)
),
sources_decl: $ => seq(
'sources',
'=',
field('value', $.string)
),
bool_decl: $ => seq(
field('name', choice('normalize_crlf', 'trim_trailing_ws')),
'=',
field('value', $.bool)
),
timeout_decl: $ => seq(
'timeout',
field('value', $.duration)
),
memory_limit_decl: $ => seq(
'memory_limit',
'=',
field('value', $.size)
),
group: $ => seq(
'group',
'(',
field('name', $.string),
')',
'{',
repeat($._group_field),
'}'
),
_group_field: $ => choice(
$.group_weight_field,
$.group_timeout_field,
$.group_memory_field,
$.group_scoring_field,
$.group_wrapper_field,
$.env_decl,
$.test,
$.pattern,
),
group_weight_field: $ => seq('weight', '=', field('value', $.number)),
group_timeout_field: $ => seq('timeout', '=', field('value', $.duration)),
group_memory_field: $ => seq('memory_limit', '=', field('value', $.size)),
group_scoring_field: $ => seq('scoring', '=', field('value', $.scoring_value)),
scoring_value: $ => choice('partial', 'all_or_none'),
group_wrapper_field: $ => seq('wrapper', '=', field('value', $.string)),
env_decl: $ => seq(
'env',
'(',
field('key', $.string),
')',
'=',
field('value', $.string)
),
test: $ => seq(
'test',
'(',
field('name', $.string),
')',
'{',
repeat($._test_field),
'}'
),
_test_field: $ => choice(
$.test_stdin_field,
$.test_stdout_field,
$.test_stderr_field,
$.test_args_field,
$.test_exit_code_field,
$.test_timeout_field,
$.test_memory_field,
$.test_wrapper_field,
$.env_decl,
$.file_decl,
$.out_file_decl,
),
test_stdin_field: $ => seq('stdin', '=', field('value', $.string)),
test_stdout_field: $ => seq('stdout', $._matcher),
test_stderr_field: $ => seq('stderr', $._matcher),
test_args_field: $ => seq('args', '=', field('value', repeat1($.string))),
test_exit_code_field: $ => seq('exitCode', '=', field('value', $.integer)),
test_timeout_field: $ => seq('timeout', '=', field('value', $.duration)),
test_memory_field: $ => seq('memory_limit', '=', field('value', $.size)),
test_wrapper_field: $ => seq('wrapper', '=', field('value', $.string)),
file_decl: $ => seq(
'file',
'(',
field('key', $.string),
')',
'=',
field('value', $.string)
),
out_file_decl: $ => seq(
'outFile',
'(',
field('key', $.string),
')',
'=',
field('value', $.string)
),
_matcher: $ => choice(
$.exact_matcher,
$.numeric_matcher,
$.contains_matcher,
$.regex_matcher,
$.any_order_matcher,
),
exact_matcher: $ => seq('=', field('value', $.string)),
numeric_matcher: $ => seq(
'~',
field('epsilon', $.number),
'of',
field('value', $.string)
),
contains_matcher: $ => seq('contains', field('value', $.string)),
regex_matcher: $ => seq('matches', field('pattern', $.regex_string)),
any_order_matcher: $ => seq(
'anyOrder',
'{',
repeat1($.string),
'}'
),
pattern: $ => seq(
'pattern',
'{',
repeat($._pattern_field),
'}'
),
_pattern_field: $ => choice(
$.pattern_input_field,
$.pattern_output_field,
$.pattern_dirs_field,
$.pattern_args_field,
),
pattern_input_field: $ => seq('input', '=', field('value', $.string)),
pattern_output_field: $ => seq('output', '=', field('value', $.string)),
pattern_dirs_field: $ => seq('dirs', '=', field('value', $.string)),
pattern_args_field: $ => seq('args', '=', field('value', repeat1($.string))),
bool: $ => choice('true', 'false'),
number: $ => choice($.integer, $.float),
string: $ => choice(
$.heredoc_string,
$.simple_string,
),
simple_string: $ => token(seq(
'"',
repeat(choice(
/[^"\\\n]/,
seq('\\', /./)
)),
'"'
)),
heredoc_string: $ => token(seq(
'"""',
/([^"]|"[^"]|""[^"])*/,
'"""'
)),
regex_string: $ => $.simple_string,
identifier: $ => /[a-zA-Z_][a-zA-Z0-9_]*/,
integer: $ => token(/-?\d+/),
float: $ => token(/-?\d+\.\d+/),
duration: $ => token(/\d+(ms|s|m)/),
size: $ => token(/\d+(KiB|MiB|GiB|KB|MB|GB|B|K|M|G)/),
}
});

View File

@@ -0,0 +1,54 @@
{
"name": "tree-sitter-jdg",
"version": "0.1.0",
"description": "Tree-sitter grammar for the judge DSL (.jdg)",
"main": "bindings/node",
"types": "bindings/node",
"keywords": [
"tree-sitter",
"parser",
"jdg",
"judge"
],
"files": [
"grammar.js",
"binding.gyp",
"prebuilds/**",
"bindings/node/*",
"queries/*",
"src/**"
],
"license": "MIT",
"dependencies": {
"node-addon-api": "^7.1.0",
"node-gyp-build": "^4.8.0"
},
"peerDependencies": {
"tree-sitter": "^0.21.0"
},
"peerDependenciesMeta": {
"tree_sitter": {
"optional": true
}
},
"devDependencies": {
"tree-sitter-cli": "^0.22.0",
"prebuildify": "^6.0.0"
},
"scripts": {
"build": "tree-sitter generate",
"test": "tree-sitter test",
"install": "node-gyp-build",
"prebuildify": "prebuildify --napi --strip"
},
"tree-sitter": [
{
"scope": "source.jdg",
"file-types": [
"jdg"
],
"highlights": "queries/highlights.scm",
"injections": "queries/injections.scm"
}
]
}

1732
editor/zed/tree-sitter-jdg/src/grammar.json generated Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

5922
editor/zed/tree-sitter-jdg/src/parser.c generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,54 @@
#ifndef TREE_SITTER_ALLOC_H_
#define TREE_SITTER_ALLOC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Allow clients to override allocation functions
#ifdef TREE_SITTER_REUSE_ALLOCATOR
extern void *(*ts_current_malloc)(size_t);
extern void *(*ts_current_calloc)(size_t, size_t);
extern void *(*ts_current_realloc)(void *, size_t);
extern void (*ts_current_free)(void *);
#ifndef ts_malloc
#define ts_malloc ts_current_malloc
#endif
#ifndef ts_calloc
#define ts_calloc ts_current_calloc
#endif
#ifndef ts_realloc
#define ts_realloc ts_current_realloc
#endif
#ifndef ts_free
#define ts_free ts_current_free
#endif
#else
#ifndef ts_malloc
#define ts_malloc malloc
#endif
#ifndef ts_calloc
#define ts_calloc calloc
#endif
#ifndef ts_realloc
#define ts_realloc realloc
#endif
#ifndef ts_free
#define ts_free free
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_ALLOC_H_

View File

@@ -0,0 +1,290 @@
#ifndef TREE_SITTER_ARRAY_H_
#define TREE_SITTER_ARRAY_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "./alloc.h"
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
#pragma warning(disable : 4101)
#elif defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#define Array(T) \
struct { \
T *contents; \
uint32_t size; \
uint32_t capacity; \
}
/// Initialize an array.
#define array_init(self) \
((self)->size = 0, (self)->capacity = 0, (self)->contents = NULL)
/// Create an empty array.
#define array_new() \
{ NULL, 0, 0 }
/// Get a pointer to the element at a given `index` in the array.
#define array_get(self, _index) \
(assert((uint32_t)(_index) < (self)->size), &(self)->contents[_index])
/// Get a pointer to the first element in the array.
#define array_front(self) array_get(self, 0)
/// Get a pointer to the last element in the array.
#define array_back(self) array_get(self, (self)->size - 1)
/// Clear the array, setting its size to zero. Note that this does not free any
/// memory allocated for the array's contents.
#define array_clear(self) ((self)->size = 0)
/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is
/// less than the array's current capacity, this function has no effect.
#define array_reserve(self, new_capacity) \
_array__reserve((Array *)(self), array_elem_size(self), new_capacity)
/// Free any memory allocated for this array. Note that this does not free any
/// memory allocated for the array's contents.
#define array_delete(self) _array__delete((Array *)(self))
/// Push a new `element` onto the end of the array.
#define array_push(self, element) \
(_array__grow((Array *)(self), 1, array_elem_size(self)), \
(self)->contents[(self)->size++] = (element))
/// Increase the array's size by `count` elements.
/// New elements are zero-initialized.
#define array_grow_by(self, count) \
do { \
if ((count) == 0) break; \
_array__grow((Array *)(self), count, array_elem_size(self)); \
memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \
(self)->size += (count); \
} while (0)
/// Append all elements from one array to the end of another.
#define array_push_all(self, other) \
array_extend((self), (other)->size, (other)->contents)
/// Append `count` elements to the end of the array, reading their values from the
/// `contents` pointer.
#define array_extend(self, count, contents) \
_array__splice( \
(Array *)(self), array_elem_size(self), (self)->size, \
0, count, contents \
)
/// Remove `old_count` elements from the array starting at the given `index`. At
/// the same index, insert `new_count` new elements, reading their values from the
/// `new_contents` pointer.
#define array_splice(self, _index, old_count, new_count, new_contents) \
_array__splice( \
(Array *)(self), array_elem_size(self), _index, \
old_count, new_count, new_contents \
)
/// Insert one `element` into the array at the given `index`.
#define array_insert(self, _index, element) \
_array__splice((Array *)(self), array_elem_size(self), _index, 0, 1, &(element))
/// Remove one element from the array at the given `index`.
#define array_erase(self, _index) \
_array__erase((Array *)(self), array_elem_size(self), _index)
/// Pop the last element off the array, returning the element by value.
#define array_pop(self) ((self)->contents[--(self)->size])
/// Assign the contents of one array to another, reallocating if necessary.
#define array_assign(self, other) \
_array__assign((Array *)(self), (const Array *)(other), array_elem_size(self))
/// Swap one array with another
#define array_swap(self, other) \
_array__swap((Array *)(self), (Array *)(other))
/// Get the size of the array contents
#define array_elem_size(self) (sizeof *(self)->contents)
/// Search a sorted array for a given `needle` value, using the given `compare`
/// callback to determine the order.
///
/// If an existing element is found to be equal to `needle`, then the `index`
/// out-parameter is set to the existing value's index, and the `exists`
/// out-parameter is set to true. Otherwise, `index` is set to an index where
/// `needle` should be inserted in order to preserve the sorting, and `exists`
/// is set to false.
#define array_search_sorted_with(self, compare, needle, _index, _exists) \
_array__search_sorted(self, 0, compare, , needle, _index, _exists)
/// Search a sorted array for a given `needle` value, using integer comparisons
/// of a given struct field (specified with a leading dot) to determine the order.
///
/// See also `array_search_sorted_with`.
#define array_search_sorted_by(self, field, needle, _index, _exists) \
_array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists)
/// Insert a given `value` into a sorted array, using the given `compare`
/// callback to determine the order.
#define array_insert_sorted_with(self, compare, value) \
do { \
unsigned _index, _exists; \
array_search_sorted_with(self, compare, &(value), &_index, &_exists); \
if (!_exists) array_insert(self, _index, value); \
} while (0)
/// Insert a given `value` into a sorted array, using integer comparisons of
/// a given struct field (specified with a leading dot) to determine the order.
///
/// See also `array_search_sorted_by`.
#define array_insert_sorted_by(self, field, value) \
do { \
unsigned _index, _exists; \
array_search_sorted_by(self, field, (value) field, &_index, &_exists); \
if (!_exists) array_insert(self, _index, value); \
} while (0)
// Private
typedef Array(void) Array;
/// This is not what you're looking for, see `array_delete`.
static inline void _array__delete(Array *self) {
if (self->contents) {
ts_free(self->contents);
self->contents = NULL;
self->size = 0;
self->capacity = 0;
}
}
/// This is not what you're looking for, see `array_erase`.
static inline void _array__erase(Array *self, size_t element_size,
uint32_t index) {
assert(index < self->size);
char *contents = (char *)self->contents;
memmove(contents + index * element_size, contents + (index + 1) * element_size,
(self->size - index - 1) * element_size);
self->size--;
}
/// This is not what you're looking for, see `array_reserve`.
static inline void _array__reserve(Array *self, size_t element_size, uint32_t new_capacity) {
if (new_capacity > self->capacity) {
if (self->contents) {
self->contents = ts_realloc(self->contents, new_capacity * element_size);
} else {
self->contents = ts_malloc(new_capacity * element_size);
}
self->capacity = new_capacity;
}
}
/// This is not what you're looking for, see `array_assign`.
static inline void _array__assign(Array *self, const Array *other, size_t element_size) {
_array__reserve(self, element_size, other->size);
self->size = other->size;
memcpy(self->contents, other->contents, self->size * element_size);
}
/// This is not what you're looking for, see `array_swap`.
static inline void _array__swap(Array *self, Array *other) {
Array swap = *other;
*other = *self;
*self = swap;
}
/// This is not what you're looking for, see `array_push` or `array_grow_by`.
static inline void _array__grow(Array *self, uint32_t count, size_t element_size) {
uint32_t new_size = self->size + count;
if (new_size > self->capacity) {
uint32_t new_capacity = self->capacity * 2;
if (new_capacity < 8) new_capacity = 8;
if (new_capacity < new_size) new_capacity = new_size;
_array__reserve(self, element_size, new_capacity);
}
}
/// This is not what you're looking for, see `array_splice`.
static inline void _array__splice(Array *self, size_t element_size,
uint32_t index, uint32_t old_count,
uint32_t new_count, const void *elements) {
uint32_t new_size = self->size + new_count - old_count;
uint32_t old_end = index + old_count;
uint32_t new_end = index + new_count;
assert(old_end <= self->size);
_array__reserve(self, element_size, new_size);
char *contents = (char *)self->contents;
if (self->size > old_end) {
memmove(
contents + new_end * element_size,
contents + old_end * element_size,
(self->size - old_end) * element_size
);
}
if (new_count > 0) {
if (elements) {
memcpy(
(contents + index * element_size),
elements,
new_count * element_size
);
} else {
memset(
(contents + index * element_size),
0,
new_count * element_size
);
}
}
self->size += new_count - old_count;
}
/// A binary search routine, based on Rust's `std::slice::binary_search_by`.
/// This is not what you're looking for, see `array_search_sorted_with` or `array_search_sorted_by`.
#define _array__search_sorted(self, start, compare, suffix, needle, _index, _exists) \
do { \
*(_index) = start; \
*(_exists) = false; \
uint32_t size = (self)->size - *(_index); \
if (size == 0) break; \
int comparison; \
while (size > 1) { \
uint32_t half_size = size / 2; \
uint32_t mid_index = *(_index) + half_size; \
comparison = compare(&((self)->contents[mid_index] suffix), (needle)); \
if (comparison <= 0) *(_index) = mid_index; \
size -= half_size; \
} \
comparison = compare(&((self)->contents[*(_index)] suffix), (needle)); \
if (comparison == 0) *(_exists) = true; \
else if (comparison < 0) *(_index) += 1; \
} while (0)
/// Helper macro for the `_sorted_by` routines below. This takes the left (existing)
/// parameter by reference in order to work with the generic sorting function above.
#define _compare_int(a, b) ((int)*(a) - (int)(b))
#ifdef _MSC_VER
#pragma warning(default : 4101)
#elif defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_ARRAY_H_

View File

@@ -0,0 +1,265 @@
#ifndef TREE_SITTER_PARSER_H_
#define TREE_SITTER_PARSER_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#define ts_builtin_sym_error ((TSSymbol)-1)
#define ts_builtin_sym_end 0
#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024
#ifndef TREE_SITTER_API_H_
typedef uint16_t TSStateId;
typedef uint16_t TSSymbol;
typedef uint16_t TSFieldId;
typedef struct TSLanguage TSLanguage;
#endif
typedef struct {
TSFieldId field_id;
uint8_t child_index;
bool inherited;
} TSFieldMapEntry;
typedef struct {
uint16_t index;
uint16_t length;
} TSFieldMapSlice;
typedef struct {
bool visible;
bool named;
bool supertype;
} TSSymbolMetadata;
typedef struct TSLexer TSLexer;
struct TSLexer {
int32_t lookahead;
TSSymbol result_symbol;
void (*advance)(TSLexer *, bool);
void (*mark_end)(TSLexer *);
uint32_t (*get_column)(TSLexer *);
bool (*is_at_included_range_start)(const TSLexer *);
bool (*eof)(const TSLexer *);
};
typedef enum {
TSParseActionTypeShift,
TSParseActionTypeReduce,
TSParseActionTypeAccept,
TSParseActionTypeRecover,
} TSParseActionType;
typedef union {
struct {
uint8_t type;
TSStateId state;
bool extra;
bool repetition;
} shift;
struct {
uint8_t type;
uint8_t child_count;
TSSymbol symbol;
int16_t dynamic_precedence;
uint16_t production_id;
} reduce;
uint8_t type;
} TSParseAction;
typedef struct {
uint16_t lex_state;
uint16_t external_lex_state;
} TSLexMode;
typedef union {
TSParseAction action;
struct {
uint8_t count;
bool reusable;
} entry;
} TSParseActionEntry;
typedef struct {
int32_t start;
int32_t end;
} TSCharacterRange;
struct TSLanguage {
uint32_t version;
uint32_t symbol_count;
uint32_t alias_count;
uint32_t token_count;
uint32_t external_token_count;
uint32_t state_count;
uint32_t large_state_count;
uint32_t production_id_count;
uint32_t field_count;
uint16_t max_alias_sequence_length;
const uint16_t *parse_table;
const uint16_t *small_parse_table;
const uint32_t *small_parse_table_map;
const TSParseActionEntry *parse_actions;
const char * const *symbol_names;
const char * const *field_names;
const TSFieldMapSlice *field_map_slices;
const TSFieldMapEntry *field_map_entries;
const TSSymbolMetadata *symbol_metadata;
const TSSymbol *public_symbol_map;
const uint16_t *alias_map;
const TSSymbol *alias_sequences;
const TSLexMode *lex_modes;
bool (*lex_fn)(TSLexer *, TSStateId);
bool (*keyword_lex_fn)(TSLexer *, TSStateId);
TSSymbol keyword_capture_token;
struct {
const bool *states;
const TSSymbol *symbol_map;
void *(*create)(void);
void (*destroy)(void *);
bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist);
unsigned (*serialize)(void *, char *);
void (*deserialize)(void *, const char *, unsigned);
} external_scanner;
const TSStateId *primary_state_ids;
};
static inline bool set_contains(TSCharacterRange *ranges, uint32_t len, int32_t lookahead) {
uint32_t index = 0;
uint32_t size = len - index;
while (size > 1) {
uint32_t half_size = size / 2;
uint32_t mid_index = index + half_size;
TSCharacterRange *range = &ranges[mid_index];
if (lookahead >= range->start && lookahead <= range->end) {
return true;
} else if (lookahead > range->end) {
index = mid_index;
}
size -= half_size;
}
TSCharacterRange *range = &ranges[index];
return (lookahead >= range->start && lookahead <= range->end);
}
/*
* Lexer Macros
*/
#ifdef _MSC_VER
#define UNUSED __pragma(warning(suppress : 4101))
#else
#define UNUSED __attribute__((unused))
#endif
#define START_LEXER() \
bool result = false; \
bool skip = false; \
UNUSED \
bool eof = false; \
int32_t lookahead; \
goto start; \
next_state: \
lexer->advance(lexer, skip); \
start: \
skip = false; \
lookahead = lexer->lookahead;
#define ADVANCE(state_value) \
{ \
state = state_value; \
goto next_state; \
}
#define ADVANCE_MAP(...) \
{ \
static const uint16_t map[] = { __VA_ARGS__ }; \
for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \
if (map[i] == lookahead) { \
state = map[i + 1]; \
goto next_state; \
} \
} \
}
#define SKIP(state_value) \
{ \
skip = true; \
state = state_value; \
goto next_state; \
}
#define ACCEPT_TOKEN(symbol_value) \
result = true; \
lexer->result_symbol = symbol_value; \
lexer->mark_end(lexer);
#define END_STATE() return result;
/*
* Parse Table Macros
*/
#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT)
#define STATE(id) id
#define ACTIONS(id) id
#define SHIFT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = (state_value) \
} \
}}
#define SHIFT_REPEAT(state_value) \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.state = (state_value), \
.repetition = true \
} \
}}
#define SHIFT_EXTRA() \
{{ \
.shift = { \
.type = TSParseActionTypeShift, \
.extra = true \
} \
}}
#define REDUCE(symbol_name, children, precedence, prod_id) \
{{ \
.reduce = { \
.type = TSParseActionTypeReduce, \
.symbol = symbol_name, \
.child_count = children, \
.dynamic_precedence = precedence, \
.production_id = prod_id \
}, \
}}
#define RECOVER() \
{{ \
.type = TSParseActionTypeRecover \
}}
#define ACCEPT_INPUT() \
{{ \
.type = TSParseActionTypeAccept \
}}
#ifdef __cplusplus
}
#endif
#endif // TREE_SITTER_PARSER_H_

View File

@@ -1,11 +1,20 @@
// Автогенерация тестов из папки с файлами. Удобно когда тестов много и // Автогенерация тестов из файлов/папок. Покрывает четыре типовых сценария:
// вручную выписывать каждый через test("...") { stdin = ... stdout = ... }
// будет слишком громоздко.
// //
// Два режима: // 1. Stdio-режим с парой globs — классика: stdin из .in, stdout = .ans
// 1) file-glob — пары .in/.ans файлов // 2. Shared expected — N входов, один общий ожидаемый файл
// 2) dir-mode — каждый тест лежит в своей подпапке с фиксированными // 3. File-mode по args — программа читает файл по аргументу
// именами input/output файлов // 4. Dir-mode с input+output файлами — программа читает И пишет файлы
//
// Плейсхолдеры в `args` pattern'а:
// {input_path} — путь к input-файлу текущего теста (для glob — разный,
// для литерала — один и тот же во всех тестах)
// {output_path} — аналогично для output
// {name} — wildcard-часть имени (glob) или basename директории (dir)
// {dir} — dir-mode: полный путь к директории теста
//
// Правило режима: наличие `{input_path}` в args → input кладётся как InFile,
// а не в stdin. Наличие `{output_path}` → expected сравнивается как OutFile,
// а не stdout.
toolchains { toolchains {
gcc { platforms = "linux" } gcc { platforms = "linux" }
@@ -19,11 +28,10 @@ build "release" {
profile = release profile = release
} }
// Режим 1: глобы на input и output файлы. // 1) Классика: каждая пара (*.in, *.ans) → один тест.
// Тестом становится каждая пара (tests/*.in, tests/*.ans) с совпадающим // Stdin ← .in, Stdout сравнивается с .ans.
// базовым именем. Имя теста — имя файла без расширения. group("stdio-pair") {
group("from-files") { weight = 0.25
weight = 0.5
pattern { pattern {
input = "tests/*.in" input = "tests/*.in"
@@ -31,22 +39,42 @@ group("from-files") {
} }
} }
// Режим 2: каждый тест — подкаталог с фиксированным layout'ом. // 2) Один общий expected для всех входов.
// Ожидается структура: // Удобно для задач где «для любого корректного входа ответ одинаковый»
// cases/ // (edge-case fuzzing) или наоборот «все некорректные входы → error»
// 01-basic/ // (смотрим на один и тот же файл с сообщением об ошибке).
// input.txt group("shared-output") {
// expected.txt weight = 0.25
// 02-edge/
// input.txt
// expected.txt
// Имя теста — имя подкаталога.
group("from-dirs") {
weight = 0.5
pattern { pattern {
dirs = "cases/*" input = "edge/*.in"
input = "input.txt" output = "edge/expected.ans" // литерал без *
output = "expected.txt" }
}
// 3) Программа читает файл по аргументу командной строки, а не из stdin.
// Expander создаёт InFiles[01.in]=..., запускает `./solution 01.in`,
// сравнивает stdout программы с содержимым соответствующего .ans.
group("file-input") {
weight = 0.25
pattern {
input = "file-tests/*.in"
output = "file-tests/*.ans"
args = "{input_path}"
}
}
// 4) Программа и читает, и пишет через файлы — никакого stdin/stdout.
// Expander кладёт input в InFiles, expected в OutFiles, запускает
// `./solution in.txt out.txt` и сравнивает созданный out.txt с expected.
group("file-io") {
weight = 0.25
pattern {
dirs = "cases/*" // каждая подпапка — отдельный тест
input = "in.txt"
output = "out.txt"
args = "{input_path}" "{output_path}"
} }
} }

View File

@@ -0,0 +1,41 @@
// Наследование общей конфигурации через `include`. Подключает соседний
// common.jdg (тулчейны + build_defaults + глобальные настройки), а затем
// задаёт только специфичные для этой задачи build-варианты и тесты.
//
// Пути в include относительны самому этому файлу (не CWD, не корню репо).
// Абсолютные пути тоже работают. Циклические включения детектятся парсером.
//
// Локальные директивы поверх include могут переопределять:
// - скаляры в build_defaults (через последующий build_defaults-блок)
// - timeout / memory_limit / binary / sources / normalize_crlf / trim_trailing_ws
// Но не могут переопределять:
// - toolchains с тем же именем (ошибка «duplicate toolchain»)
// - build с тем же именем
// - group с тем же именем
include "common.jdg"
build "release" {
profile = release
}
build "debug" {
profile = debug
warnings = pedantic
}
build "sanitized" {
profile = sanitized
sanitize = "address" "undefined"
platforms = "linux"
compilers = "gcc" "clang"
}
group("basic") {
weight = 1.0
test("smoke") {
stdin = "1\n42\n"
stdout = "42\n"
}
}

View File

@@ -0,0 +1,22 @@
// Общая инфраструктура для всех задач курса: тулчейны и базовые настройки
// билда. Подключается через `include "common.jdg"` из конкретных .jdg
// файлов задач. Локальные build-блоки наследуют эти дефолты через
// встроенный merge в build_defaults.
toolchains {
gcc { platforms = "linux" }
clang { platforms = "linux" "windows" }
msvc { platforms = "windows" }
}
build_defaults {
language = "c"
standard = "c11"
sources = "solution.c"
output = "solution"
warnings = strict
}
timeout 5s
normalize_crlf = true
trim_trailing_ws = true

View File

@@ -16,7 +16,28 @@ func expandPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) {
return expandGlobPattern(pattern) return expandGlobPattern(pattern)
} }
type patternCase struct {
name string
inputPath string
outputPath string
dir string
}
func expandGlobPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) { func expandGlobPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) {
inputIsGlob := strings.Contains(pattern.InputGlob, "*")
outputIsGlob := strings.Contains(pattern.OutputGlob, "*")
if pattern.InputGlob == "" && pattern.OutputGlob == "" {
return nil, fmt.Errorf("pattern needs at least one of input/output/dirs")
}
if !inputIsGlob && !outputIsGlob {
return nil, fmt.Errorf("pattern needs at least one glob field (input or output must contain *)")
}
var cases []patternCase
switch {
case inputIsGlob && outputIsGlob:
inputFiles, err := filepath.Glob(pattern.InputGlob) inputFiles, err := filepath.Glob(pattern.InputGlob)
if err != nil { if err != nil {
return nil, fmt.Errorf("invalid input glob %q: %w", pattern.InputGlob, err) return nil, fmt.Errorf("invalid input glob %q: %w", pattern.InputGlob, err)
@@ -24,39 +45,56 @@ func expandGlobPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) {
if len(inputFiles) == 0 { if len(inputFiles) == 0 {
return nil, fmt.Errorf("no files matched input glob %q", pattern.InputGlob) return nil, fmt.Errorf("no files matched input glob %q", pattern.InputGlob)
} }
inputPrefix, inputSuffix := splitGlob(pattern.InputGlob) inputPrefix, inputSuffix := splitGlob(pattern.InputGlob)
outputPrefix, outputSuffix := splitGlob(pattern.OutputGlob) outputPrefix, outputSuffix := splitGlob(pattern.OutputGlob)
var tests []*dsl.Test
for _, inputPath := range inputFiles { for _, inputPath := range inputFiles {
wildcard := extractWildcard(inputPath, inputPrefix, inputSuffix) wildcard := extractWildcard(inputPath, inputPrefix, inputSuffix)
outputPath := outputPrefix + wildcard + outputSuffix outputPath := outputPrefix + wildcard + outputSuffix
cases = append(cases, patternCase{
inputContent, err := os.ReadFile(inputPath) name: wildcard,
if err != nil { inputPath: inputPath,
return nil, fmt.Errorf("read input %q: %w", inputPath, err) outputPath: outputPath,
}
outputContent, err := os.ReadFile(outputPath)
if err != nil {
return nil, fmt.Errorf("read output %q: %w", outputPath, err)
}
name := fmt.Sprintf("pattern:%s", wildcard)
stdin := string(inputContent)
expected := string(outputContent)
tests = append(tests, &dsl.Test{
Name: name,
Stdin: &stdin,
Env: map[string]string{},
InFiles: map[string]string{},
OutFiles: map[string]string{},
Stdout: dsl.ExactMatcher{Value: expected},
Stderr: dsl.NoMatcher{},
}) })
} }
return tests, nil
case inputIsGlob && !outputIsGlob:
inputFiles, err := filepath.Glob(pattern.InputGlob)
if err != nil {
return nil, fmt.Errorf("invalid input glob %q: %w", pattern.InputGlob, err)
}
if len(inputFiles) == 0 {
return nil, fmt.Errorf("no files matched input glob %q", pattern.InputGlob)
}
inputPrefix, inputSuffix := splitGlob(pattern.InputGlob)
for _, inputPath := range inputFiles {
wildcard := extractWildcard(inputPath, inputPrefix, inputSuffix)
cases = append(cases, patternCase{
name: wildcard,
inputPath: inputPath,
outputPath: pattern.OutputGlob,
})
}
case !inputIsGlob && outputIsGlob:
outputFiles, err := filepath.Glob(pattern.OutputGlob)
if err != nil {
return nil, fmt.Errorf("invalid output glob %q: %w", pattern.OutputGlob, err)
}
if len(outputFiles) == 0 {
return nil, fmt.Errorf("no files matched output glob %q", pattern.OutputGlob)
}
outputPrefix, outputSuffix := splitGlob(pattern.OutputGlob)
for _, outputPath := range outputFiles {
wildcard := extractWildcard(outputPath, outputPrefix, outputSuffix)
cases = append(cases, patternCase{
name: wildcard,
inputPath: pattern.InputGlob,
outputPath: outputPath,
})
}
}
return buildTests(cases, pattern.Args)
} }
func expandDirPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) { func expandDirPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) {
@@ -68,42 +106,96 @@ func expandDirPattern(pattern *dsl.Pattern) ([]*dsl.Test, error) {
return nil, fmt.Errorf("no directories matched %q", pattern.DirsGlob) return nil, fmt.Errorf("no directories matched %q", pattern.DirsGlob)
} }
var tests []*dsl.Test var cases []patternCase
for _, dir := range dirs { for _, dir := range dirs {
info, err := os.Stat(dir) info, err := os.Stat(dir)
if err != nil || !info.IsDir() { if err != nil || !info.IsDir() {
continue continue
} }
cases = append(cases, patternCase{
inputPath := filepath.Join(dir, pattern.InputFile) name: filepath.Base(dir),
outputPath := filepath.Join(dir, pattern.OutputFile) inputPath: filepath.Join(dir, pattern.InputFile),
outputPath: filepath.Join(dir, pattern.OutputFile),
inputContent, err := os.ReadFile(inputPath) dir: dir,
if err != nil { })
return nil, fmt.Errorf("read %q: %w", inputPath, err)
} }
outputContent, err := os.ReadFile(outputPath) return buildTests(cases, pattern.Args)
}
func buildTests(cases []patternCase, argTemplate []string) ([]*dsl.Test, error) {
useInputAsFile := argsContain(argTemplate, "{input_path}")
useOutputAsFile := argsContain(argTemplate, "{output_path}")
var tests []*dsl.Test
for _, c := range cases {
inputContent, err := os.ReadFile(c.inputPath)
if err != nil { if err != nil {
return nil, fmt.Errorf("read %q: %w", outputPath, err) return nil, fmt.Errorf("read input %q: %w", c.inputPath, err)
}
outputContent, err := os.ReadFile(c.outputPath)
if err != nil {
return nil, fmt.Errorf("read output %q: %w", c.outputPath, err)
} }
name := fmt.Sprintf("pattern:%s", filepath.Base(dir)) t := &dsl.Test{
stdin := string(inputContent) Name: fmt.Sprintf("pattern:%s", c.name),
expected := string(outputContent)
tests = append(tests, &dsl.Test{
Name: name,
Stdin: &stdin,
Env: map[string]string{}, Env: map[string]string{},
InFiles: map[string]string{}, InFiles: map[string]string{},
OutFiles: map[string]string{}, OutFiles: map[string]string{},
Stdout: dsl.ExactMatcher{Value: expected},
Stderr: dsl.NoMatcher{}, Stderr: dsl.NoMatcher{},
}
inputName := filepath.Base(c.inputPath)
outputName := filepath.Base(c.outputPath)
if useInputAsFile {
t.InFiles[inputName] = string(inputContent)
} else {
s := string(inputContent)
t.Stdin = &s
}
if useOutputAsFile {
t.OutFiles[outputName] = string(outputContent)
t.Stdout = dsl.NoMatcher{}
} else {
t.Stdout = dsl.ExactMatcher{Value: string(outputContent)}
}
if len(argTemplate) > 0 {
t.Args = substituteArgs(argTemplate, map[string]string{
"{input_path}": inputName,
"{output_path}": outputName,
"{name}": c.name,
"{dir}": c.dir,
}) })
} }
tests = append(tests, t)
}
return tests, nil return tests, nil
} }
func argsContain(args []string, placeholder string) bool {
for _, a := range args {
if strings.Contains(a, placeholder) {
return true
}
}
return false
}
func substituteArgs(template []string, vars map[string]string) []string {
out := make([]string, len(template))
for i, a := range template {
for k, v := range vars {
a = strings.ReplaceAll(a, k, v)
}
out[i] = a
}
return out
}
func splitGlob(pattern string) (prefix, suffix string) { func splitGlob(pattern string) (prefix, suffix string) {
before, after, found := strings.Cut(pattern, "*") before, after, found := strings.Cut(pattern, "*")
if !found { if !found {

240
runner/expander_test.go Normal file
View File

@@ -0,0 +1,240 @@
package runner
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/Mond1c/judge/dsl"
)
func writeFile(t *testing.T, dir, name, content string) {
t.Helper()
path := filepath.Join(dir, name)
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
}
func TestExpandGlobPairedStdioMode(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "tests/01.in", "1 2 3\n")
writeFile(t, dir, "tests/01.ans", "6\n")
writeFile(t, dir, "tests/02.in", "10 20\n")
writeFile(t, dir, "tests/02.ans", "30\n")
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
tests, err := expandPattern(&dsl.Pattern{
InputGlob: "tests/*.in",
OutputGlob: "tests/*.ans",
})
if err != nil {
t.Fatal(err)
}
if len(tests) != 2 {
t.Fatalf("expected 2 tests, got %d", len(tests))
}
for _, tc := range tests {
if tc.Stdin == nil {
t.Errorf("%s: stdin should be set in stdio mode", tc.Name)
}
if len(tc.Args) != 0 {
t.Errorf("%s: args should be empty without template", tc.Name)
}
if _, ok := tc.Stdout.(dsl.ExactMatcher); !ok {
t.Errorf("%s: stdout should be ExactMatcher, got %T", tc.Name, tc.Stdout)
}
}
}
func TestExpandGlobWithSharedOutput(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "tests/01.in", "1\n")
writeFile(t, dir, "tests/02.in", "2\n")
writeFile(t, dir, "tests/03.in", "3\n")
writeFile(t, dir, "expected.ans", "ok\n")
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
tests, err := expandPattern(&dsl.Pattern{
InputGlob: "tests/*.in",
OutputGlob: "expected.ans",
})
if err != nil {
t.Fatalf("expand: %v", err)
}
if len(tests) != 3 {
t.Fatalf("expected 3 tests, got %d", len(tests))
}
for _, tc := range tests {
m, ok := tc.Stdout.(dsl.ExactMatcher)
if !ok {
t.Fatalf("%s: stdout should be ExactMatcher, got %T", tc.Name, tc.Stdout)
}
if m.Value != "ok\n" {
t.Errorf("%s: shared output = %q, want %q", tc.Name, m.Value, "ok\n")
}
}
}
func TestExpandGlobFileModeInputOnly(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "tests/01.in", "hello\n")
writeFile(t, dir, "tests/01.ans", "HELLO\n")
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
tests, err := expandPattern(&dsl.Pattern{
InputGlob: "tests/*.in",
OutputGlob: "tests/*.ans",
Args: []string{"{input_path}"},
})
if err != nil {
t.Fatal(err)
}
if len(tests) != 1 {
t.Fatalf("expected 1 test, got %d", len(tests))
}
tc := tests[0]
if tc.Stdin != nil {
t.Errorf("stdin should be nil in file mode for input")
}
if content, ok := tc.InFiles["01.in"]; !ok || content != "hello\n" {
t.Errorf("InFiles[01.in] = %q, want %q", content, "hello\n")
}
if _, ok := tc.Stdout.(dsl.ExactMatcher); !ok {
t.Errorf("stdout should still be ExactMatcher when output not in file mode, got %T", tc.Stdout)
}
if len(tc.Args) != 1 || tc.Args[0] != "01.in" {
t.Errorf("args = %v, want [01.in]", tc.Args)
}
}
func TestExpandGlobFileModeBoth(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "tests/01.in", "1 2 3\n")
writeFile(t, dir, "tests/01.ans", "6\n")
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
tests, err := expandPattern(&dsl.Pattern{
InputGlob: "tests/*.in",
OutputGlob: "tests/*.ans",
Args: []string{"{input_path}", "{output_path}"},
})
if err != nil {
t.Fatal(err)
}
tc := tests[0]
if tc.Stdin != nil {
t.Error("stdin should be nil")
}
if _, ok := tc.Stdout.(dsl.NoMatcher); !ok {
t.Errorf("stdout should be NoMatcher when output is file, got %T", tc.Stdout)
}
if content := tc.OutFiles["01.ans"]; content != "6\n" {
t.Errorf("OutFiles[01.ans] = %q, want %q", content, "6\n")
}
if len(tc.Args) != 2 || tc.Args[0] != "01.in" || tc.Args[1] != "01.ans" {
t.Errorf("args = %v, want [01.in 01.ans]", tc.Args)
}
}
func TestExpandGlobArgsWithStaticAndPlaceholders(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "tests/01.in", "x\n")
writeFile(t, dir, "tests/01.ans", "x\n")
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
tests, err := expandPattern(&dsl.Pattern{
InputGlob: "tests/*.in",
OutputGlob: "tests/*.ans",
Args: []string{"--mode", "strict", "{input_path}"},
})
if err != nil {
t.Fatal(err)
}
if len(tests[0].Args) != 3 || tests[0].Args[0] != "--mode" || tests[0].Args[2] != "01.in" {
t.Errorf("args = %v", tests[0].Args)
}
}
func TestExpandDirModeWithArgs(t *testing.T) {
dir := t.TempDir()
writeFile(t, dir, "cases/a/input.txt", "one\n")
writeFile(t, dir, "cases/a/expected.txt", "ONE\n")
writeFile(t, dir, "cases/b/input.txt", "two\n")
writeFile(t, dir, "cases/b/expected.txt", "TWO\n")
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
tests, err := expandPattern(&dsl.Pattern{
DirsGlob: "cases/*",
InputFile: "input.txt",
OutputFile: "expected.txt",
Args: []string{"{input_path}", "{output_path}"},
})
if err != nil {
t.Fatal(err)
}
if len(tests) != 2 {
t.Fatalf("expected 2 tests, got %d", len(tests))
}
for _, tc := range tests {
if _, ok := tc.InFiles["input.txt"]; !ok {
t.Errorf("%s: missing InFiles[input.txt]", tc.Name)
}
if _, ok := tc.OutFiles["expected.txt"]; !ok {
t.Errorf("%s: missing OutFiles[expected.txt]", tc.Name)
}
if len(tc.Args) != 2 {
t.Errorf("%s: args = %v", tc.Name, tc.Args)
}
}
}
func TestExpandPatternRejectsAllLiterals(t *testing.T) {
_, err := expandPattern(&dsl.Pattern{
InputGlob: "tests/a.in",
OutputGlob: "tests/a.ans",
})
if err == nil {
t.Fatal("expected error when no glob fields")
}
if !strings.Contains(err.Error(), "glob") {
t.Errorf("error %q does not mention glob", err.Error())
}
}
func TestExpandPatternNoMatches(t *testing.T) {
dir := t.TempDir()
cwd, _ := os.Getwd()
defer os.Chdir(cwd)
os.Chdir(dir)
_, err := expandPattern(&dsl.Pattern{
InputGlob: "missing/*.in",
OutputGlob: "missing/*.ans",
})
if err == nil {
t.Fatal("expected error on zero matches")
}
}