1. New build system
All checks were successful
build-dsl-smoke / Build judge (push) Successful in 12s
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 8s
build-dsl-smoke / release / gcc / linux (push) Successful in 6s
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 13s
build-dsl-smoke / debug-valgrind / gcc / linux (push) Successful in 14s
build-dsl-smoke / release / clang / windows (push) Successful in 16s
build-dsl-smoke / debug / msvc / windows (push) Successful in 18s
build-dsl-smoke / release / msvc / windows (push) Successful in 17s
build-dsl-smoke / SUMMARY (push) Successful in 4s
Release / Build & publish (push) Successful in 48s
All checks were successful
build-dsl-smoke / Build judge (push) Successful in 12s
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 8s
build-dsl-smoke / release / gcc / linux (push) Successful in 6s
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 13s
build-dsl-smoke / debug-valgrind / gcc / linux (push) Successful in 14s
build-dsl-smoke / release / clang / windows (push) Successful in 16s
build-dsl-smoke / debug / msvc / windows (push) Successful in 18s
build-dsl-smoke / release / msvc / windows (push) Successful in 17s
build-dsl-smoke / SUMMARY (push) Successful in 4s
Release / Build & publish (push) Successful in 48s
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
152
.gitea/workflows/build-dsl-smoke.yml
Normal file
152
.gitea/workflows/build-dsl-smoke.yml
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
name: build-dsl-smoke
|
||||||
|
run-name: "Structured build DSL smoke test"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- 'dsl/**'
|
||||||
|
- 'runner/**'
|
||||||
|
- 'reporter/**'
|
||||||
|
- 'cmd/cli/**'
|
||||||
|
- 'example/c-sum-v2/**'
|
||||||
|
- '.gitea/workflows/build-dsl-smoke.yml'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
SUITE_FILE: sum.jdg
|
||||||
|
EXAMPLE_DIR: example/c-sum-v2
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_judge:
|
||||||
|
name: Build judge
|
||||||
|
runs-on: Linux-Runner
|
||||||
|
timeout-minutes: 10
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.22'
|
||||||
|
|
||||||
|
- name: Cross-compile judge
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mkdir -p dist
|
||||||
|
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o dist/judge-linux-amd64 ./cmd/cli
|
||||||
|
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o dist/judge-windows-amd64.exe ./cmd/cli
|
||||||
|
ls -la dist/
|
||||||
|
|
||||||
|
- name: Upload judge binaries
|
||||||
|
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: judge-bin-csum2
|
||||||
|
path: dist/
|
||||||
|
retention-days: 1
|
||||||
|
|
||||||
|
test:
|
||||||
|
needs: build_judge
|
||||||
|
name: "${{ matrix.build }} / ${{ matrix.toolchain }} / ${{ matrix.platform }}"
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- { build: release, toolchain: gcc, platform: linux }
|
||||||
|
- { build: release, toolchain: clang, platform: linux }
|
||||||
|
- { build: release, toolchain: clang, platform: windows }
|
||||||
|
- { build: release, toolchain: msvc, platform: windows }
|
||||||
|
- { build: debug, toolchain: gcc, platform: linux }
|
||||||
|
- { build: debug, toolchain: clang, platform: linux }
|
||||||
|
- { build: debug, toolchain: clang, platform: windows }
|
||||||
|
- { build: debug, toolchain: msvc, platform: windows }
|
||||||
|
- { build: sanitized, toolchain: gcc, platform: linux }
|
||||||
|
- { build: sanitized, toolchain: clang, platform: linux }
|
||||||
|
- { build: debug-valgrind, toolchain: gcc, platform: linux }
|
||||||
|
|
||||||
|
runs-on: ${{ matrix.platform == 'windows' && 'Windows-Runner' || 'Linux-Runner' }}
|
||||||
|
timeout-minutes: 10
|
||||||
|
|
||||||
|
env:
|
||||||
|
REPORT_NAME: "report_${{ matrix.build }}_${{ matrix.toolchain }}_${{ matrix.platform }}"
|
||||||
|
JUDGE_TOOLCHAIN: ${{ matrix.toolchain }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up MSVC environment
|
||||||
|
if: matrix.toolchain == 'msvc'
|
||||||
|
uses: ilammy/msvc-dev-cmd@v1
|
||||||
|
|
||||||
|
- name: Download judge binary
|
||||||
|
uses: https://github.com/christopherHX/gitea-download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: judge-bin-csum2
|
||||||
|
path: judge-bin
|
||||||
|
|
||||||
|
- name: Install judge on PATH
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mkdir -p bin
|
||||||
|
if [ "${{ matrix.platform }}" = "windows" ]; then
|
||||||
|
cp judge-bin/judge-windows-amd64.exe bin/judge.exe
|
||||||
|
else
|
||||||
|
cp judge-bin/judge-linux-amd64 bin/judge
|
||||||
|
chmod +x bin/judge
|
||||||
|
fi
|
||||||
|
echo "$PWD/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
|
- name: Run judge
|
||||||
|
shell: bash
|
||||||
|
working-directory: ${{ env.EXAMPLE_DIR }}
|
||||||
|
run: |
|
||||||
|
judge "$SUITE_FILE" . --build=${{ matrix.build }} --json > "$GITHUB_WORKSPACE/${REPORT_NAME}.json" || true
|
||||||
|
cat "$GITHUB_WORKSPACE/${REPORT_NAME}.json"
|
||||||
|
judge "$SUITE_FILE" . --build=${{ matrix.build }}
|
||||||
|
|
||||||
|
- name: Upload report
|
||||||
|
if: ${{ always() }}
|
||||||
|
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ env.REPORT_NAME }}
|
||||||
|
path: ${{ env.REPORT_NAME }}.json
|
||||||
|
retention-days: 7
|
||||||
|
compression-level: 9
|
||||||
|
|
||||||
|
summary:
|
||||||
|
needs: [build_judge, test]
|
||||||
|
if: ${{ always() }}
|
||||||
|
name: SUMMARY
|
||||||
|
runs-on: Linux-Runner
|
||||||
|
timeout-minutes: 5
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Download judge binary
|
||||||
|
uses: https://github.com/christopherHX/gitea-download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: judge-bin-csum2
|
||||||
|
path: judge-bin
|
||||||
|
|
||||||
|
- name: Install judge on PATH
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
mkdir -p bin
|
||||||
|
cp judge-bin/judge-linux-amd64 bin/judge
|
||||||
|
chmod +x bin/judge
|
||||||
|
echo "$PWD/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
|
- name: Download all reports
|
||||||
|
uses: https://github.com/christopherHX/gitea-download-artifact@v4
|
||||||
|
with:
|
||||||
|
path: reports
|
||||||
|
pattern: report_*
|
||||||
|
|
||||||
|
- name: Aggregate
|
||||||
|
shell: bash
|
||||||
|
run: judge aggregate reports | tee SUMMARY.md
|
||||||
|
|
||||||
|
- name: Upload summary
|
||||||
|
uses: https://github.com/christopherHX/gitea-upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: SUMMARY
|
||||||
|
path: SUMMARY.md
|
||||||
|
retention-days: 7
|
||||||
@@ -2,9 +2,6 @@ name: memory-limit
|
|||||||
run-name: "memory_limit enforcement check"
|
run-name: "memory_limit enforcement check"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
|
||||||
branches: [main]
|
|
||||||
pull_request:
|
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
|
|||||||
132
cmd/cli/main.go
132
cmd/cli/main.go
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -20,11 +21,16 @@ Flags:
|
|||||||
--json output as JSON instead of text
|
--json output as JSON instead of text
|
||||||
--wrapper <cmd> exec wrapper (e.g. "valgrind --error-exitcode=99")
|
--wrapper <cmd> exec wrapper (e.g. "valgrind --error-exitcode=99")
|
||||||
--binary <name> name of executable produced by build (overrides .jdg)
|
--binary <name> name of executable produced by build (overrides .jdg)
|
||||||
|
--build <name> run only the named structured build (use with matrix CI)
|
||||||
|
--list-builds print the names of structured builds in the suite as JSON
|
||||||
|
--list-matrix print the full (build, toolchain, platform) matrix as JSON
|
||||||
--help show help
|
--help show help
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
judge lab1.jdg ./student-solution
|
judge lab1.jdg ./student-solution
|
||||||
judge lab1.jdg ./student-solution --json
|
judge lab1.jdg ./student-solution --json
|
||||||
|
judge lab1.jdg ./student-solution --build=sanitized
|
||||||
|
judge --list-builds lab1.jdg
|
||||||
judge aggregate reports/
|
judge aggregate reports/
|
||||||
`
|
`
|
||||||
|
|
||||||
@@ -41,9 +47,20 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if hasFlag(args, "--list-builds") {
|
||||||
|
runListBuilds(args)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasFlag(args, "--list-matrix") {
|
||||||
|
runListMatrix(args)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
jsonOutput := hasFlag(args, "--json")
|
jsonOutput := hasFlag(args, "--json")
|
||||||
wrapper := flagValue(args, "--wrapper")
|
wrapper := flagValue(args, "--wrapper")
|
||||||
binary := flagValue(args, "--binary")
|
binary := flagValue(args, "--binary")
|
||||||
|
targetBuild := flagValue(args, "--build")
|
||||||
positional := positionalArgs(args)
|
positional := positionalArgs(args)
|
||||||
|
|
||||||
if len(positional) < 2 {
|
if len(positional) < 2 {
|
||||||
@@ -54,18 +71,7 @@ func main() {
|
|||||||
testFile := positional[0]
|
testFile := positional[0]
|
||||||
solutionDir := positional[1]
|
solutionDir := positional[1]
|
||||||
|
|
||||||
src, err := os.ReadFile(testFile)
|
f := parseSuite(testFile)
|
||||||
if err != nil {
|
|
||||||
fatalf("cannot read %q: %v", testFile, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
f, warns, err := dsl.Parse(string(src))
|
|
||||||
if err != nil {
|
|
||||||
fatalf("parse error in %q:\n %v", testFile, err)
|
|
||||||
}
|
|
||||||
for _, w := range warns {
|
|
||||||
fmt.Fprintf(os.Stderr, "warning: %s\n", w)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := os.Stat(solutionDir); err != nil {
|
if _, err := os.Stat(solutionDir); err != nil {
|
||||||
fatalf("solution dir %q not found: %v", solutionDir, err)
|
fatalf("solution dir %q not found: %v", solutionDir, err)
|
||||||
@@ -75,6 +81,7 @@ func main() {
|
|||||||
WorkDir: solutionDir,
|
WorkDir: solutionDir,
|
||||||
BinaryName: binary,
|
BinaryName: binary,
|
||||||
Wrapper: wrapper,
|
Wrapper: wrapper,
|
||||||
|
TargetBuild: targetBuild,
|
||||||
})
|
})
|
||||||
result := r.Run()
|
result := r.Run()
|
||||||
|
|
||||||
@@ -91,6 +98,91 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseSuite(path string) *dsl.File {
|
||||||
|
f, warns, err := dsl.ParseFile(path)
|
||||||
|
if err != nil {
|
||||||
|
fatalf("parse error in %q:\n %v", path, err)
|
||||||
|
}
|
||||||
|
for _, w := range warns {
|
||||||
|
fmt.Fprintf(os.Stderr, "warning: %s\n", w)
|
||||||
|
}
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func runListBuilds(args []string) {
|
||||||
|
positional := positionalArgs(args)
|
||||||
|
if len(positional) < 1 {
|
||||||
|
fatalf("--list-builds requires the path to a .jdg file")
|
||||||
|
}
|
||||||
|
f := parseSuite(positional[0])
|
||||||
|
|
||||||
|
var names []string
|
||||||
|
if len(f.Builds) == 0 {
|
||||||
|
names = []string{"default"}
|
||||||
|
} else {
|
||||||
|
for _, b := range f.Builds {
|
||||||
|
names = append(names, b.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
enc := json.NewEncoder(os.Stdout)
|
||||||
|
if err := enc.Encode(names); err != nil {
|
||||||
|
fatalf("encode list-builds: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type matrixEntry struct {
|
||||||
|
Build string `json:"build"`
|
||||||
|
Toolchain string `json:"toolchain"`
|
||||||
|
Platform string `json:"platform"`
|
||||||
|
Wrapper string `json:"wrapper,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runListMatrix(args []string) {
|
||||||
|
positional := positionalArgs(args)
|
||||||
|
if len(positional) < 1 {
|
||||||
|
fatalf("--list-matrix requires the path to a .jdg file")
|
||||||
|
}
|
||||||
|
f := parseSuite(positional[0])
|
||||||
|
|
||||||
|
var entries []matrixEntry
|
||||||
|
|
||||||
|
if len(f.Builds) == 0 {
|
||||||
|
if len(f.Toolchains) == 0 {
|
||||||
|
entries = append(entries, matrixEntry{Build: "default", Toolchain: "default", Platform: "linux"})
|
||||||
|
} else {
|
||||||
|
for _, tc := range f.Toolchains {
|
||||||
|
for _, platform := range tc.Platforms {
|
||||||
|
entries = append(entries, matrixEntry{Build: "default", Toolchain: tc.Name, Platform: platform})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if len(f.Toolchains) == 0 {
|
||||||
|
fatalf("suite has structured builds but no `toolchains { ... }` block; add one to use --list-matrix")
|
||||||
|
} else {
|
||||||
|
for _, b := range f.Builds {
|
||||||
|
for _, tc := range f.Toolchains {
|
||||||
|
for _, platform := range tc.Platforms {
|
||||||
|
eff := b.Resolve(f.BuildDefaults, platform)
|
||||||
|
if !eff.AppliesTo(platform, tc.Name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
entries = append(entries, matrixEntry{
|
||||||
|
Build: b.Name,
|
||||||
|
Toolchain: tc.Name,
|
||||||
|
Platform: platform,
|
||||||
|
Wrapper: eff.Wrapper,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enc := json.NewEncoder(os.Stdout)
|
||||||
|
if err := enc.Encode(entries); err != nil {
|
||||||
|
fatalf("encode list-matrix: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func runAggregate(args []string) {
|
func runAggregate(args []string) {
|
||||||
if len(args) < 1 {
|
if len(args) < 1 {
|
||||||
fatalf("usage: judge aggregate <reports-dir>")
|
fatalf("usage: judge aggregate <reports-dir>")
|
||||||
@@ -128,8 +220,18 @@ func flagValue(args []string, name string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func positionalArgs(args []string) []string {
|
func positionalArgs(args []string) []string {
|
||||||
known := map[string]bool{"--json": true, "--help": true, "-h": true}
|
known := map[string]bool{
|
||||||
withValue := map[string]bool{"--wrapper": true, "--binary": true}
|
"--json": true,
|
||||||
|
"--help": true,
|
||||||
|
"-h": true,
|
||||||
|
"--list-builds": true,
|
||||||
|
"--list-matrix": true,
|
||||||
|
}
|
||||||
|
withValue := map[string]bool{
|
||||||
|
"--wrapper": true,
|
||||||
|
"--binary": true,
|
||||||
|
"--build": true,
|
||||||
|
}
|
||||||
|
|
||||||
var out []string
|
var out []string
|
||||||
skip := false
|
skip := false
|
||||||
@@ -145,7 +247,7 @@ func positionalArgs(args []string) []string {
|
|||||||
skip = true
|
skip = true
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(a, "--wrapper=") || strings.HasPrefix(a, "--binary=") {
|
if strings.HasPrefix(a, "--wrapper=") || strings.HasPrefix(a, "--binary=") || strings.HasPrefix(a, "--build=") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out = append(out, a)
|
out = append(out, a)
|
||||||
|
|||||||
25
dsl/ast.go
25
dsl/ast.go
@@ -7,13 +7,18 @@ type File struct {
|
|||||||
BuildLinux string
|
BuildLinux string
|
||||||
BuildWindows string
|
BuildWindows string
|
||||||
BuildDarwin string
|
BuildDarwin string
|
||||||
Timeout time.Duration
|
|
||||||
MemoryLimit int64 // bytes; 0 means no limit
|
|
||||||
Binary string // executable name produced by build (default: solution)
|
|
||||||
Sources string // glob pattern for source files, expanded as $SOURCES in build
|
|
||||||
|
|
||||||
NormalizeCRLF bool // strip \r before matching stdout/stderr/outFiles
|
BuildDefaults *BuildConfig
|
||||||
TrimTrailingWS bool // trim trailing whitespace on each line before matching
|
Builds []*BuildConfig
|
||||||
|
Toolchains []*ToolchainSpec
|
||||||
|
|
||||||
|
Timeout time.Duration
|
||||||
|
MemoryLimit int64
|
||||||
|
Binary string
|
||||||
|
Sources string
|
||||||
|
|
||||||
|
NormalizeCRLF bool
|
||||||
|
TrimTrailingWS bool
|
||||||
|
|
||||||
Groups []*Group
|
Groups []*Group
|
||||||
}
|
}
|
||||||
@@ -25,7 +30,7 @@ type Group struct {
|
|||||||
MemoryLimit int64
|
MemoryLimit int64
|
||||||
Env map[string]string
|
Env map[string]string
|
||||||
Scoring ScoringMode
|
Scoring ScoringMode
|
||||||
Wrapper string // exec wrapper command (e.g., "valgrind --error-exitcode=1")
|
Wrapper string
|
||||||
|
|
||||||
Tests []*Test
|
Tests []*Test
|
||||||
Pattern *Pattern
|
Pattern *Pattern
|
||||||
@@ -34,8 +39,8 @@ type Group struct {
|
|||||||
type ScoringMode int
|
type ScoringMode int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
ScoringPartial ScoringMode = iota // weight * passed/total (default)
|
ScoringPartial ScoringMode = iota
|
||||||
ScoringAllOrNone // weight or 0
|
ScoringAllOrNone
|
||||||
)
|
)
|
||||||
|
|
||||||
type Pattern struct {
|
type Pattern struct {
|
||||||
@@ -45,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 {
|
||||||
|
|||||||
158
dsl/build.go
Normal file
158
dsl/build.go
Normal file
@@ -0,0 +1,158 @@
|
|||||||
|
package dsl
|
||||||
|
|
||||||
|
type BuildProfile int
|
||||||
|
|
||||||
|
const (
|
||||||
|
ProfileUnset BuildProfile = iota
|
||||||
|
ProfileRelease
|
||||||
|
ProfileDebug
|
||||||
|
ProfileSanitized
|
||||||
|
)
|
||||||
|
|
||||||
|
func (p BuildProfile) String() string {
|
||||||
|
switch p {
|
||||||
|
case ProfileRelease:
|
||||||
|
return "release"
|
||||||
|
case ProfileDebug:
|
||||||
|
return "debug"
|
||||||
|
case ProfileSanitized:
|
||||||
|
return "sanitized"
|
||||||
|
default:
|
||||||
|
return "unset"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type WarningLevel int
|
||||||
|
|
||||||
|
const (
|
||||||
|
WarningsUnset WarningLevel = iota
|
||||||
|
WarningsDefault
|
||||||
|
WarningsStrict
|
||||||
|
WarningsPedantic
|
||||||
|
)
|
||||||
|
|
||||||
|
func (w WarningLevel) String() string {
|
||||||
|
switch w {
|
||||||
|
case WarningsDefault:
|
||||||
|
return "default"
|
||||||
|
case WarningsStrict:
|
||||||
|
return "strict"
|
||||||
|
case WarningsPedantic:
|
||||||
|
return "pedantic"
|
||||||
|
default:
|
||||||
|
return "unset"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type BuildConfig struct {
|
||||||
|
Name string
|
||||||
|
|
||||||
|
Language string
|
||||||
|
Standard string
|
||||||
|
Sources []string
|
||||||
|
Includes []string
|
||||||
|
Output string
|
||||||
|
|
||||||
|
Profile BuildProfile
|
||||||
|
Warnings WarningLevel
|
||||||
|
Sanitize []string
|
||||||
|
Wrapper string
|
||||||
|
|
||||||
|
Defines map[string]string
|
||||||
|
Link []string
|
||||||
|
Extra []string
|
||||||
|
|
||||||
|
Platforms []string
|
||||||
|
Compilers []string
|
||||||
|
|
||||||
|
Linux *BuildConfig
|
||||||
|
Windows *BuildConfig
|
||||||
|
Darwin *BuildConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (dst *BuildConfig) MergeFrom(src *BuildConfig) {
|
||||||
|
if src == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if src.Language != "" {
|
||||||
|
dst.Language = src.Language
|
||||||
|
}
|
||||||
|
if src.Standard != "" {
|
||||||
|
dst.Standard = src.Standard
|
||||||
|
}
|
||||||
|
if src.Output != "" {
|
||||||
|
dst.Output = src.Output
|
||||||
|
}
|
||||||
|
if src.Profile != ProfileUnset {
|
||||||
|
dst.Profile = src.Profile
|
||||||
|
}
|
||||||
|
if src.Warnings != WarningsUnset {
|
||||||
|
dst.Warnings = src.Warnings
|
||||||
|
}
|
||||||
|
if src.Wrapper != "" {
|
||||||
|
dst.Wrapper = src.Wrapper
|
||||||
|
}
|
||||||
|
|
||||||
|
dst.Sources = append(dst.Sources, src.Sources...)
|
||||||
|
dst.Includes = append(dst.Includes, src.Includes...)
|
||||||
|
dst.Sanitize = append(dst.Sanitize, src.Sanitize...)
|
||||||
|
dst.Link = append(dst.Link, src.Link...)
|
||||||
|
dst.Extra = append(dst.Extra, src.Extra...)
|
||||||
|
dst.Platforms = append(dst.Platforms, src.Platforms...)
|
||||||
|
dst.Compilers = append(dst.Compilers, src.Compilers...)
|
||||||
|
|
||||||
|
if len(src.Defines) > 0 {
|
||||||
|
if dst.Defines == nil {
|
||||||
|
dst.Defines = map[string]string{}
|
||||||
|
}
|
||||||
|
for k, v := range src.Defines {
|
||||||
|
dst.Defines[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BuildConfig) Resolve(defaults *BuildConfig, os string) BuildConfig {
|
||||||
|
var out BuildConfig
|
||||||
|
out.MergeFrom(defaults)
|
||||||
|
out.MergeFrom(b)
|
||||||
|
out.Name = b.Name
|
||||||
|
|
||||||
|
var osOverride *BuildConfig
|
||||||
|
switch os {
|
||||||
|
case "linux":
|
||||||
|
osOverride = b.Linux
|
||||||
|
case "windows":
|
||||||
|
osOverride = b.Windows
|
||||||
|
case "darwin":
|
||||||
|
osOverride = b.Darwin
|
||||||
|
}
|
||||||
|
out.MergeFrom(osOverride)
|
||||||
|
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BuildConfig) AppliesTo(os, compiler string) bool {
|
||||||
|
if len(b.Platforms) > 0 && !contains(b.Platforms, os) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if len(b.Compilers) > 0 && !contains(b.Compilers, compiler) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func contains(xs []string, x string) bool {
|
||||||
|
for _, v := range xs {
|
||||||
|
if v == x {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
type ToolchainSpec struct {
|
||||||
|
Name string
|
||||||
|
Platforms []string
|
||||||
|
Binary string
|
||||||
|
Class string
|
||||||
|
}
|
||||||
355
dsl/build_parser.go
Normal file
355
dsl/build_parser.go
Normal file
@@ -0,0 +1,355 @@
|
|||||||
|
package dsl
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func (p *Parser) parseBuildBlock(name string) (*BuildConfig, error) {
|
||||||
|
return p.parseBuildBlockInner(name, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Parser) parseBuildBlockInner(name string, inOSOverride bool) (*BuildConfig, error) {
|
||||||
|
if _, err := p.expect(TOKEN_LBRACE); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
bc := &BuildConfig{Name: name}
|
||||||
|
|
||||||
|
for !p.isRBrace() {
|
||||||
|
t := p.peek()
|
||||||
|
if t.Type != TOKEN_IDENT {
|
||||||
|
return nil, fmt.Errorf("%d:%d: unexpected token %q in build block", t.Line, t.Col, t.Value)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch t.Value {
|
||||||
|
case "language":
|
||||||
|
p.advance()
|
||||||
|
s, err := p.parseAssignString()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Language = s
|
||||||
|
|
||||||
|
case "standard":
|
||||||
|
p.advance()
|
||||||
|
s, err := p.parseAssignString()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Standard = s
|
||||||
|
|
||||||
|
case "output":
|
||||||
|
p.advance()
|
||||||
|
s, err := p.parseAssignString()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Output = s
|
||||||
|
|
||||||
|
case "wrapper":
|
||||||
|
p.advance()
|
||||||
|
s, err := p.parseAssignString()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Wrapper = s
|
||||||
|
|
||||||
|
case "sources":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Sources = xs
|
||||||
|
|
||||||
|
case "includes":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Includes = xs
|
||||||
|
|
||||||
|
case "sanitize":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Sanitize = xs
|
||||||
|
|
||||||
|
case "link":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Link = xs
|
||||||
|
|
||||||
|
case "extra":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Extra = xs
|
||||||
|
|
||||||
|
case "platforms":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePlatformList(xs, t.Line, t.Col); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Platforms = xs
|
||||||
|
|
||||||
|
case "compilers":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Compilers = xs
|
||||||
|
|
||||||
|
case "profile":
|
||||||
|
p.advance()
|
||||||
|
if _, err := p.expect(TOKEN_ASSIGN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := p.expect(TOKEN_IDENT)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
prof, err := parseProfileIdent(id.Value, id.Line, id.Col)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Profile = prof
|
||||||
|
|
||||||
|
case "warnings":
|
||||||
|
p.advance()
|
||||||
|
if _, err := p.expect(TOKEN_ASSIGN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := p.expect(TOKEN_IDENT)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
w, err := parseWarningsIdent(id.Value, id.Line, id.Col)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
bc.Warnings = w
|
||||||
|
|
||||||
|
case "define":
|
||||||
|
p.advance()
|
||||||
|
if _, err := p.expect(TOKEN_LPAREN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
key, err := p.expect(TOKEN_STRING)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err := p.expect(TOKEN_RPAREN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err := p.expect(TOKEN_ASSIGN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
val, err := p.expect(TOKEN_STRING)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if bc.Defines == nil {
|
||||||
|
bc.Defines = map[string]string{}
|
||||||
|
}
|
||||||
|
bc.Defines[key.Value] = val.Value
|
||||||
|
|
||||||
|
case "linux", "windows", "darwin":
|
||||||
|
if inOSOverride {
|
||||||
|
return nil, fmt.Errorf("%d:%d: OS override %q cannot be nested inside another OS override", t.Line, t.Col, t.Value)
|
||||||
|
}
|
||||||
|
osName := t.Value
|
||||||
|
p.advance()
|
||||||
|
sub, err := p.parseBuildBlockInner("", true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
switch osName {
|
||||||
|
case "linux":
|
||||||
|
if bc.Linux != nil {
|
||||||
|
return nil, fmt.Errorf("%d:%d: duplicate linux override", t.Line, t.Col)
|
||||||
|
}
|
||||||
|
bc.Linux = sub
|
||||||
|
case "windows":
|
||||||
|
if bc.Windows != nil {
|
||||||
|
return nil, fmt.Errorf("%d:%d: duplicate windows override", t.Line, t.Col)
|
||||||
|
}
|
||||||
|
bc.Windows = sub
|
||||||
|
case "darwin":
|
||||||
|
if bc.Darwin != nil {
|
||||||
|
return nil, fmt.Errorf("%d:%d: duplicate darwin override", t.Line, t.Col)
|
||||||
|
}
|
||||||
|
bc.Darwin = sub
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%d:%d: unknown field %q in build block", t.Line, t.Col, t.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := p.expect(TOKEN_RBRACE); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return bc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Parser) parseAssignString() (string, error) {
|
||||||
|
if _, err := p.expect(TOKEN_ASSIGN); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
s, err := p.expect(TOKEN_STRING)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return s.Value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Parser) parseAssignStringList() ([]string, error) {
|
||||||
|
if _, err := p.expect(TOKEN_ASSIGN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return p.parseStringList()
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseProfileIdent(v string, line, col int) (BuildProfile, error) {
|
||||||
|
switch v {
|
||||||
|
case "release":
|
||||||
|
return ProfileRelease, nil
|
||||||
|
case "debug":
|
||||||
|
return ProfileDebug, nil
|
||||||
|
case "sanitized":
|
||||||
|
return ProfileSanitized, nil
|
||||||
|
default:
|
||||||
|
return ProfileUnset, fmt.Errorf("%d:%d: unknown profile %q (expected release/debug/sanitized)", line, col, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseWarningsIdent(v string, line, col int) (WarningLevel, error) {
|
||||||
|
switch v {
|
||||||
|
case "default":
|
||||||
|
return WarningsDefault, nil
|
||||||
|
case "strict":
|
||||||
|
return WarningsStrict, nil
|
||||||
|
case "pedantic":
|
||||||
|
return WarningsPedantic, nil
|
||||||
|
default:
|
||||||
|
return WarningsUnset, fmt.Errorf("%d:%d: unknown warnings level %q (expected default/strict/pedantic)", line, col, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func validatePlatformList(xs []string, line, col int) error {
|
||||||
|
for _, x := range xs {
|
||||||
|
switch x {
|
||||||
|
case "linux", "windows", "darwin":
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%d:%d: unknown platform %q (expected linux/windows/darwin)", line, col, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Parser) parseToolchainsBlock() ([]*ToolchainSpec, error) {
|
||||||
|
if _, err := p.expect(TOKEN_LBRACE); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var specs []*ToolchainSpec
|
||||||
|
seen := map[string]bool{}
|
||||||
|
|
||||||
|
for !p.isRBrace() {
|
||||||
|
nameTok := p.peek()
|
||||||
|
if nameTok.Type != TOKEN_IDENT && nameTok.Type != TOKEN_STRING {
|
||||||
|
return nil, fmt.Errorf("%d:%d: expected toolchain name, got %q", nameTok.Line, nameTok.Col, nameTok.Value)
|
||||||
|
}
|
||||||
|
p.advance()
|
||||||
|
name := nameTok.Value
|
||||||
|
if seen[name] {
|
||||||
|
return nil, fmt.Errorf("%d:%d: duplicate toolchain %q", nameTok.Line, nameTok.Col, name)
|
||||||
|
}
|
||||||
|
seen[name] = true
|
||||||
|
|
||||||
|
spec, err := p.parseToolchainEntry(name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
specs = append(specs, spec)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := p.expect(TOKEN_RBRACE); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return specs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Parser) parseToolchainEntry(name string) (*ToolchainSpec, error) {
|
||||||
|
if _, err := p.expect(TOKEN_LBRACE); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
spec := &ToolchainSpec{Name: name}
|
||||||
|
for !p.isRBrace() {
|
||||||
|
t := p.peek()
|
||||||
|
if t.Type != TOKEN_IDENT {
|
||||||
|
return nil, fmt.Errorf("%d:%d: unexpected token %q in toolchain block", t.Line, t.Col, t.Value)
|
||||||
|
}
|
||||||
|
switch t.Value {
|
||||||
|
case "platforms":
|
||||||
|
p.advance()
|
||||||
|
xs, err := p.parseAssignStringList()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := validatePlatformList(xs, t.Line, t.Col); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
spec.Platforms = xs
|
||||||
|
|
||||||
|
case "binary":
|
||||||
|
p.advance()
|
||||||
|
s, err := p.parseAssignString()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
spec.Binary = s
|
||||||
|
|
||||||
|
case "class":
|
||||||
|
p.advance()
|
||||||
|
if _, err := p.expect(TOKEN_ASSIGN); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
id, err := p.expect(TOKEN_IDENT)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
switch id.Value {
|
||||||
|
case "gnu", "msvc":
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%d:%d: unknown compiler class %q (expected gnu/msvc)", id.Line, id.Col, id.Value)
|
||||||
|
}
|
||||||
|
spec.Class = id.Value
|
||||||
|
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%d:%d: unknown field %q in toolchain block", t.Line, t.Col, t.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := p.expect(TOKEN_RBRACE); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(spec.Platforms) == 0 {
|
||||||
|
return nil, fmt.Errorf("toolchain %q: platforms is required", name)
|
||||||
|
}
|
||||||
|
return spec, nil
|
||||||
|
}
|
||||||
455
dsl/build_test.go
Normal file
455
dsl/build_test.go
Normal file
@@ -0,0 +1,455 @@
|
|||||||
|
package dsl
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseBuildBlockMinimal(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build_defaults {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "*.c"
|
||||||
|
output = "solution"
|
||||||
|
warnings = strict
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
build "debug" {
|
||||||
|
profile = debug
|
||||||
|
}
|
||||||
|
|
||||||
|
group("g1") {
|
||||||
|
weight = 1.0
|
||||||
|
test("t1") {
|
||||||
|
stdout = "ok\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`
|
||||||
|
f, _, err := Parse(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if f.BuildDefaults == nil {
|
||||||
|
t.Fatal("BuildDefaults not populated")
|
||||||
|
}
|
||||||
|
if f.BuildDefaults.Language != "c" {
|
||||||
|
t.Errorf("language = %q", f.BuildDefaults.Language)
|
||||||
|
}
|
||||||
|
if f.BuildDefaults.Standard != "c11" {
|
||||||
|
t.Errorf("standard = %q", f.BuildDefaults.Standard)
|
||||||
|
}
|
||||||
|
if len(f.BuildDefaults.Sources) != 1 || f.BuildDefaults.Sources[0] != "*.c" {
|
||||||
|
t.Errorf("sources = %v", f.BuildDefaults.Sources)
|
||||||
|
}
|
||||||
|
if f.BuildDefaults.Output != "solution" {
|
||||||
|
t.Errorf("output = %q", f.BuildDefaults.Output)
|
||||||
|
}
|
||||||
|
if f.BuildDefaults.Warnings != WarningsStrict {
|
||||||
|
t.Errorf("warnings = %v", f.BuildDefaults.Warnings)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(f.Builds) != 2 {
|
||||||
|
t.Fatalf("expected 2 builds, got %d", len(f.Builds))
|
||||||
|
}
|
||||||
|
if f.Builds[0].Name != "release" || f.Builds[0].Profile != ProfileRelease {
|
||||||
|
t.Errorf("builds[0] = %+v", f.Builds[0])
|
||||||
|
}
|
||||||
|
if f.Builds[1].Name != "debug" || f.Builds[1].Profile != ProfileDebug {
|
||||||
|
t.Errorf("builds[1] = %+v", f.Builds[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildLegacyStillWorks(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build "cc -O2 solution.c -o solution"
|
||||||
|
timeout 5s
|
||||||
|
|
||||||
|
group("g1") {
|
||||||
|
weight = 1.0
|
||||||
|
test("t1") { stdout = "ok\n" }
|
||||||
|
}
|
||||||
|
`
|
||||||
|
f, _, err := Parse(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
if f.Build != "cc -O2 solution.c -o solution" {
|
||||||
|
t.Errorf("legacy build = %q", f.Build)
|
||||||
|
}
|
||||||
|
if f.BuildDefaults != nil || len(f.Builds) != 0 {
|
||||||
|
t.Errorf("structured fields should be empty for legacy form")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildOSOverride(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build_defaults {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "*.c"
|
||||||
|
output = "solution"
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
profile = release
|
||||||
|
linux { extra = "-fPIC" }
|
||||||
|
windows { extra = "/bigobj" }
|
||||||
|
}
|
||||||
|
|
||||||
|
group("g1") {
|
||||||
|
weight = 1.0
|
||||||
|
test("t1") { stdout = "ok\n" }
|
||||||
|
}
|
||||||
|
`
|
||||||
|
f, _, err := Parse(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
b := f.Builds[0]
|
||||||
|
if b.Linux == nil || len(b.Linux.Extra) != 1 || b.Linux.Extra[0] != "-fPIC" {
|
||||||
|
t.Errorf("linux override = %+v", b.Linux)
|
||||||
|
}
|
||||||
|
if b.Windows == nil || len(b.Windows.Extra) != 1 || b.Windows.Extra[0] != "/bigobj" {
|
||||||
|
t.Errorf("windows override = %+v", b.Windows)
|
||||||
|
}
|
||||||
|
if b.Darwin != nil {
|
||||||
|
t.Errorf("darwin override should be nil")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildPlatformsFilter(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build "sanitized" {
|
||||||
|
profile = sanitized
|
||||||
|
sanitize = "address" "undefined"
|
||||||
|
platforms = "linux"
|
||||||
|
compilers = "gcc" "clang"
|
||||||
|
}
|
||||||
|
|
||||||
|
group("g1") {
|
||||||
|
weight = 1.0
|
||||||
|
test("t1") { stdout = "ok\n" }
|
||||||
|
}
|
||||||
|
`
|
||||||
|
f, _, err := Parse(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
b := f.Builds[0]
|
||||||
|
if b.Profile != ProfileSanitized {
|
||||||
|
t.Errorf("profile = %v", b.Profile)
|
||||||
|
}
|
||||||
|
if len(b.Sanitize) != 2 || b.Sanitize[0] != "address" || b.Sanitize[1] != "undefined" {
|
||||||
|
t.Errorf("sanitize = %v", b.Sanitize)
|
||||||
|
}
|
||||||
|
if len(b.Platforms) != 1 || b.Platforms[0] != "linux" {
|
||||||
|
t.Errorf("platforms = %v", b.Platforms)
|
||||||
|
}
|
||||||
|
if len(b.Compilers) != 2 {
|
||||||
|
t.Errorf("compilers = %v", b.Compilers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildDefineField(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build "rel" {
|
||||||
|
profile = release
|
||||||
|
define("NDEBUG") = "1"
|
||||||
|
define("VERSION") = "42"
|
||||||
|
}
|
||||||
|
|
||||||
|
group("g1") {
|
||||||
|
weight = 1.0
|
||||||
|
test("t1") { stdout = "ok\n" }
|
||||||
|
}
|
||||||
|
`
|
||||||
|
f, _, err := Parse(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
d := f.Builds[0].Defines
|
||||||
|
if d["NDEBUG"] != "1" || d["VERSION"] != "42" {
|
||||||
|
t.Errorf("defines = %v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildErrors(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
src string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "unknown profile",
|
||||||
|
src: `
|
||||||
|
build "x" { profile = ultra }
|
||||||
|
group("g") { weight=1.0 test("t"){ stdout="ok\n" } }
|
||||||
|
`,
|
||||||
|
want: "unknown profile",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown warnings",
|
||||||
|
src: `
|
||||||
|
build "x" { warnings = insane }
|
||||||
|
group("g") { weight=1.0 test("t"){ stdout="ok\n" } }
|
||||||
|
`,
|
||||||
|
want: "unknown warnings",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown platform",
|
||||||
|
src: `
|
||||||
|
build "x" { platforms = "bsd" }
|
||||||
|
group("g") { weight=1.0 test("t"){ stdout="ok\n" } }
|
||||||
|
`,
|
||||||
|
want: "unknown platform",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "nested OS override",
|
||||||
|
src: `
|
||||||
|
build "x" {
|
||||||
|
linux {
|
||||||
|
windows { extra = "nope" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
group("g") { weight=1.0 test("t"){ stdout="ok\n" } }
|
||||||
|
`,
|
||||||
|
want: "cannot be nested",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "duplicate OS override",
|
||||||
|
src: `
|
||||||
|
build "x" {
|
||||||
|
linux { extra = "-a" }
|
||||||
|
linux { extra = "-b" }
|
||||||
|
}
|
||||||
|
group("g") { weight=1.0 test("t"){ stdout="ok\n" } }
|
||||||
|
`,
|
||||||
|
want: "duplicate linux override",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unknown field",
|
||||||
|
src: `
|
||||||
|
build "x" { magic = "yes" }
|
||||||
|
group("g") { weight=1.0 test("t"){ stdout="ok\n" } }
|
||||||
|
`,
|
||||||
|
want: "unknown field",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
_, _, err := Parse(c.src)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error, got nil")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), c.want) {
|
||||||
|
t.Errorf("error %q does not contain %q", err.Error(), c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildMixedLegacyAndStructuredRejected(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build "cc -O2 solution.c -o solution"
|
||||||
|
build "release" { profile = release }
|
||||||
|
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
|
||||||
|
`
|
||||||
|
_, _, err := Parse(src)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error mixing legacy and structured builds")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "cannot mix") {
|
||||||
|
t.Errorf("error %q does not mention mixing", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseBuildDuplicateNameRejected(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
build "release" { profile = release }
|
||||||
|
build "release" { profile = debug }
|
||||||
|
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
|
||||||
|
`
|
||||||
|
_, _, err := Parse(src)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error on duplicate build name")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "duplicate") {
|
||||||
|
t.Errorf("error %q does not mention duplicate", err.Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildConfigResolveMerge(t *testing.T) {
|
||||||
|
defaults := &BuildConfig{
|
||||||
|
Language: "c",
|
||||||
|
Standard: "c11",
|
||||||
|
Sources: []string{"*.c"},
|
||||||
|
Output: "solution",
|
||||||
|
Warnings: WarningsStrict,
|
||||||
|
}
|
||||||
|
b := &BuildConfig{
|
||||||
|
Name: "release",
|
||||||
|
Profile: ProfileRelease,
|
||||||
|
Extra: []string{"-DFOO"},
|
||||||
|
Linux: &BuildConfig{
|
||||||
|
Extra: []string{"-fPIC"},
|
||||||
|
},
|
||||||
|
Windows: &BuildConfig{
|
||||||
|
Extra: []string{"/bigobj"},
|
||||||
|
Output: "solution",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
linux := b.Resolve(defaults, "linux")
|
||||||
|
if linux.Language != "c" || linux.Standard != "c11" {
|
||||||
|
t.Errorf("linux defaults not merged: %+v", linux)
|
||||||
|
}
|
||||||
|
if linux.Profile != ProfileRelease {
|
||||||
|
t.Errorf("linux profile = %v", linux.Profile)
|
||||||
|
}
|
||||||
|
if linux.Warnings != WarningsStrict {
|
||||||
|
t.Errorf("linux warnings = %v", linux.Warnings)
|
||||||
|
}
|
||||||
|
if len(linux.Sources) != 1 || linux.Sources[0] != "*.c" {
|
||||||
|
t.Errorf("linux sources = %v", linux.Sources)
|
||||||
|
}
|
||||||
|
if len(linux.Extra) != 2 || linux.Extra[0] != "-DFOO" || linux.Extra[1] != "-fPIC" {
|
||||||
|
t.Errorf("linux extra = %v", linux.Extra)
|
||||||
|
}
|
||||||
|
|
||||||
|
windows := b.Resolve(defaults, "windows")
|
||||||
|
if len(windows.Extra) != 2 || windows.Extra[0] != "-DFOO" || windows.Extra[1] != "/bigobj" {
|
||||||
|
t.Errorf("windows extra = %v", windows.Extra)
|
||||||
|
}
|
||||||
|
|
||||||
|
darwin := b.Resolve(defaults, "darwin")
|
||||||
|
if len(darwin.Extra) != 1 || darwin.Extra[0] != "-DFOO" {
|
||||||
|
t.Errorf("darwin extra (no override) = %v", darwin.Extra)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(b.Extra) != 1 {
|
||||||
|
t.Errorf("receiver mutated: %v", b.Extra)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseToolchainsBlock(t *testing.T) {
|
||||||
|
src := `
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
clang {
|
||||||
|
platforms = "linux" "windows"
|
||||||
|
binary = "clang-17"
|
||||||
|
class = gnu
|
||||||
|
}
|
||||||
|
msvc { platforms = "windows" }
|
||||||
|
nvcc {
|
||||||
|
platforms = "linux"
|
||||||
|
class = gnu
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" { profile = release }
|
||||||
|
|
||||||
|
group("g") { weight = 1.0 test("t") { stdout = "ok\n" } }
|
||||||
|
`
|
||||||
|
f, _, err := Parse(src)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse: %v", err)
|
||||||
|
}
|
||||||
|
if len(f.Toolchains) != 4 {
|
||||||
|
t.Fatalf("expected 4 toolchains, got %d", len(f.Toolchains))
|
||||||
|
}
|
||||||
|
gcc := f.Toolchains[0]
|
||||||
|
if gcc.Name != "gcc" || len(gcc.Platforms) != 1 || gcc.Platforms[0] != "linux" {
|
||||||
|
t.Errorf("gcc = %+v", gcc)
|
||||||
|
}
|
||||||
|
clang := f.Toolchains[1]
|
||||||
|
if clang.Name != "clang" || len(clang.Platforms) != 2 || clang.Binary != "clang-17" || clang.Class != "gnu" {
|
||||||
|
t.Errorf("clang = %+v", clang)
|
||||||
|
}
|
||||||
|
if clang.Platforms[0] != "linux" || clang.Platforms[1] != "windows" {
|
||||||
|
t.Errorf("clang platforms = %v", clang.Platforms)
|
||||||
|
}
|
||||||
|
nvcc := f.Toolchains[3]
|
||||||
|
if nvcc.Name != "nvcc" || len(nvcc.Platforms) != 1 || nvcc.Platforms[0] != "linux" || nvcc.Class != "gnu" {
|
||||||
|
t.Errorf("nvcc = %+v", nvcc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseToolchainsErrors(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
src string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"missing platforms",
|
||||||
|
`toolchains { gcc { } }
|
||||||
|
group("g") { weight=1.0 test("t") { stdout="ok\n" } }`,
|
||||||
|
"platforms is required",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"unknown platform",
|
||||||
|
`toolchains { gcc { platforms = "bsd" } }
|
||||||
|
group("g") { weight=1.0 test("t") { stdout="ok\n" } }`,
|
||||||
|
"unknown platform",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"unknown class",
|
||||||
|
`toolchains { gcc { platforms = "linux" class = llvm } }
|
||||||
|
group("g") { weight=1.0 test("t") { stdout="ok\n" } }`,
|
||||||
|
"unknown compiler class",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"duplicate toolchain",
|
||||||
|
`toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
}
|
||||||
|
group("g") { weight=1.0 test("t") { stdout="ok\n" } }`,
|
||||||
|
"duplicate toolchain",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
_, _, err := Parse(c.src)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected error, got nil")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), c.want) {
|
||||||
|
t.Errorf("error %q does not contain %q", err.Error(), c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildConfigAppliesTo(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
b BuildConfig
|
||||||
|
os, cc string
|
||||||
|
expected bool
|
||||||
|
}{
|
||||||
|
{"no filters", BuildConfig{}, "linux", "gcc", true},
|
||||||
|
{"os match", BuildConfig{Platforms: []string{"linux"}}, "linux", "gcc", true},
|
||||||
|
{"os mismatch", BuildConfig{Platforms: []string{"linux"}}, "windows", "msvc", false},
|
||||||
|
{"cc match", BuildConfig{Compilers: []string{"gcc", "clang"}}, "linux", "clang", true},
|
||||||
|
{"cc mismatch", BuildConfig{Compilers: []string{"gcc"}}, "linux", "msvc", false},
|
||||||
|
{"both match", BuildConfig{Platforms: []string{"linux"}, Compilers: []string{"gcc"}}, "linux", "gcc", true},
|
||||||
|
{"os ok cc bad", BuildConfig{Platforms: []string{"linux"}, Compilers: []string{"gcc"}}, "linux", "clang", false},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
got := c.b.AppliesTo(c.os, c.cc)
|
||||||
|
if got != c.expected {
|
||||||
|
t.Errorf("AppliesTo(%q, %q) = %v, want %v", c.os, c.cc, got, c.expected)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
210
dsl/include_test.go
Normal file
210
dsl/include_test.go
Normal 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
81
dsl/merge.go
Normal 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
|
||||||
|
}
|
||||||
171
dsl/parser.go
171
dsl/parser.go
@@ -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{}
|
||||||
|
|
||||||
@@ -91,7 +153,72 @@ func (p *Parser) parseFile() (*File, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if p.peek().Type == TOKEN_LBRACE {
|
||||||
|
bc, err := p.parseBuildBlock(s.Value)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f.Builds = append(f.Builds, bc)
|
||||||
|
} else {
|
||||||
f.Build = s.Value
|
f.Build = s.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
case "build_defaults":
|
||||||
|
p.advance()
|
||||||
|
bc, err := p.parseBuildBlock("")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if f.BuildDefaults == nil {
|
||||||
|
f.BuildDefaults = &BuildConfig{}
|
||||||
|
}
|
||||||
|
f.BuildDefaults.MergeFrom(bc)
|
||||||
|
|
||||||
|
case "toolchains":
|
||||||
|
p.advance()
|
||||||
|
specs, err := p.parseToolchainsBlock()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
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()
|
||||||
@@ -192,11 +319,28 @@ func (p *Parser) parseFile() (*File, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := p.validateWeights(f); err != nil {
|
return f, nil
|
||||||
return nil, err
|
}
|
||||||
|
|
||||||
|
func validateBuilds(f *File) error {
|
||||||
|
hasLegacy := f.Build != "" || f.BuildLinux != "" || f.BuildWindows != "" || f.BuildDarwin != ""
|
||||||
|
hasStructured := f.BuildDefaults != nil || len(f.Builds) > 0
|
||||||
|
|
||||||
|
if hasLegacy && hasStructured {
|
||||||
|
return fmt.Errorf("cannot mix legacy `build \"shell\"` with structured `build \"name\" { ... }` in the same suite")
|
||||||
}
|
}
|
||||||
|
|
||||||
return f, nil
|
seen := map[string]bool{}
|
||||||
|
for _, b := range f.Builds {
|
||||||
|
if b.Name == "" {
|
||||||
|
return fmt.Errorf("structured build must have a name")
|
||||||
|
}
|
||||||
|
if seen[b.Name] {
|
||||||
|
return fmt.Errorf("duplicate build name %q", b.Name)
|
||||||
|
}
|
||||||
|
seen[b.Name] = true
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Parser) validateWeights(f *File) error {
|
func (p *Parser) validateWeights(f *File) error {
|
||||||
@@ -635,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)
|
||||||
}
|
}
|
||||||
@@ -715,8 +874,6 @@ func (p *Parser) parseInt() (int, error) {
|
|||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// parseSize accepts either a TOKEN_SIZE (e.g. "256MB", "1GiB", "512K") or a bare
|
|
||||||
// TOKEN_INT interpreted as bytes. MiB/MB are both 1024² — we use IEC semantics.
|
|
||||||
func (p *Parser) parseSize() (int64, error) {
|
func (p *Parser) parseSize() (int64, error) {
|
||||||
t := p.peek()
|
t := p.peek()
|
||||||
switch t.Type {
|
switch t.Type {
|
||||||
|
|||||||
17
editor/zed/.gitignore
vendored
Normal file
17
editor/zed/.gitignore
vendored
Normal 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
23
editor/zed/extension.toml
Normal 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]
|
||||||
2
editor/zed/languages/jdg/brackets.scm
Normal file
2
editor/zed/languages/jdg/brackets.scm
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
("{" @open "}" @close)
|
||||||
|
("(" @open ")" @close)
|
||||||
12
editor/zed/languages/jdg/config.toml
Normal file
12
editor/zed/languages/jdg/config.toml
Normal 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
|
||||||
100
editor/zed/languages/jdg/highlights.scm
Normal file
100
editor/zed/languages/jdg/highlights.scm
Normal 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)
|
||||||
11
editor/zed/languages/jdg/indents.scm
Normal file
11
editor/zed/languages/jdg/indents.scm
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
[
|
||||||
|
(build_block)
|
||||||
|
(toolchains)
|
||||||
|
(toolchain_entry)
|
||||||
|
(group)
|
||||||
|
(test)
|
||||||
|
(pattern)
|
||||||
|
(any_order_matcher)
|
||||||
|
] @indent
|
||||||
|
|
||||||
|
"}" @end
|
||||||
7
editor/zed/languages/jdg/injections.scm
Normal file
7
editor/zed/languages/jdg/injections.scm
Normal 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))
|
||||||
23
editor/zed/languages/jdg/outline.scm
Normal file
23
editor/zed/languages/jdg/outline.scm
Normal 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
|
||||||
39
editor/zed/tree-sitter-jdg/.editorconfig
Normal file
39
editor/zed/tree-sitter-jdg/.editorconfig
Normal 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
|
||||||
11
editor/zed/tree-sitter-jdg/.gitattributes
vendored
Normal file
11
editor/zed/tree-sitter-jdg/.gitattributes
vendored
Normal 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
38
editor/zed/tree-sitter-jdg/.gitignore
vendored
Normal 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
|
||||||
342
editor/zed/tree-sitter-jdg/grammar.js
Normal file
342
editor/zed/tree-sitter-jdg/grammar.js
Normal 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)/),
|
||||||
|
}
|
||||||
|
});
|
||||||
54
editor/zed/tree-sitter-jdg/package.json
Normal file
54
editor/zed/tree-sitter-jdg/package.json
Normal 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
1732
editor/zed/tree-sitter-jdg/src/grammar.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
1570
editor/zed/tree-sitter-jdg/src/node-types.json
generated
Normal file
1570
editor/zed/tree-sitter-jdg/src/node-types.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
5922
editor/zed/tree-sitter-jdg/src/parser.c
generated
Normal file
5922
editor/zed/tree-sitter-jdg/src/parser.c
generated
Normal file
File diff suppressed because it is too large
Load Diff
54
editor/zed/tree-sitter-jdg/src/tree_sitter/alloc.h
generated
Normal file
54
editor/zed/tree-sitter-jdg/src/tree_sitter/alloc.h
generated
Normal 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_
|
||||||
290
editor/zed/tree-sitter-jdg/src/tree_sitter/array.h
generated
Normal file
290
editor/zed/tree-sitter-jdg/src/tree_sitter/array.h
generated
Normal 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_
|
||||||
265
editor/zed/tree-sitter-jdg/src/tree_sitter/parser.h
generated
Normal file
265
editor/zed/tree-sitter-jdg/src/tree_sitter/parser.h
generated
Normal 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_
|
||||||
19
example/c-sum-v2/solution.c
Normal file
19
example/c-sum-v2/solution.c
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
|
||||||
|
int main(void) {
|
||||||
|
long n;
|
||||||
|
if (scanf("%ld", &n) != 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
long long sum = 0;
|
||||||
|
for (long i = 0; i < n; i++) {
|
||||||
|
long long x;
|
||||||
|
if (scanf("%lld", &x) != 1) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
sum += x;
|
||||||
|
}
|
||||||
|
printf("%lld\n", sum);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
82
example/c-sum-v2/sum.jdg
Normal file
82
example/c-sum-v2/sum.jdg
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
// Smoke test for the structured build DSL. Same task as example/c-sum
|
||||||
|
// (sum of N integers) but described declaratively — no shell strings,
|
||||||
|
// no per-platform `if /I "%CC%"=="msvc"` branching. The compiler is
|
||||||
|
// selected via the JUDGE_CC env variable set by the CI matrix.
|
||||||
|
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
clang { platforms = "linux" "windows" }
|
||||||
|
msvc { platforms = "windows" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build_defaults {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "solution.c"
|
||||||
|
output = "solution"
|
||||||
|
warnings = strict
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
build "debug" {
|
||||||
|
profile = debug
|
||||||
|
}
|
||||||
|
|
||||||
|
build "sanitized" {
|
||||||
|
profile = sanitized
|
||||||
|
sanitize = "address" "undefined"
|
||||||
|
platforms = "linux"
|
||||||
|
compilers = "gcc" "clang"
|
||||||
|
}
|
||||||
|
|
||||||
|
build "debug-valgrind" {
|
||||||
|
profile = debug
|
||||||
|
wrapper = "valgrind --error-exitcode=99 --leak-check=full -q"
|
||||||
|
platforms = "linux"
|
||||||
|
compilers = "gcc"
|
||||||
|
}
|
||||||
|
|
||||||
|
timeout 5s
|
||||||
|
normalize_crlf = true
|
||||||
|
trim_trailing_ws = true
|
||||||
|
|
||||||
|
group("basic") {
|
||||||
|
weight = 0.5
|
||||||
|
|
||||||
|
test("one number") {
|
||||||
|
stdin = "1\n42\n"
|
||||||
|
stdout = "42\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("three numbers") {
|
||||||
|
stdin = "3\n1 2 3\n"
|
||||||
|
stdout = "6\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("negatives") {
|
||||||
|
stdin = "4\n-1 -2 3 5\n"
|
||||||
|
stdout = "5\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("zero count") {
|
||||||
|
stdin = "0\n"
|
||||||
|
stdout = "0\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group("edge") {
|
||||||
|
weight = 0.5
|
||||||
|
|
||||||
|
test("large sum fits in int64") {
|
||||||
|
stdin = "3\n2000000000 2000000000 2000000000\n"
|
||||||
|
stdout = "6000000000\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("multiline input") {
|
||||||
|
stdin = "5\n10\n20\n30\n40\n50\n"
|
||||||
|
stdout = "150\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
23
example/showcase/01-minimal.jdg
Normal file
23
example/showcase/01-minimal.jdg
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
// Минимальный рабочий suite на structured DSL.
|
||||||
|
// Декларируем один toolchain, один build, одну группу с одним тестом.
|
||||||
|
// С этого можно копипастить для новых задач.
|
||||||
|
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "solution.c"
|
||||||
|
output = "solution"
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
group("basic") {
|
||||||
|
weight = 1.0
|
||||||
|
|
||||||
|
test("hello") {
|
||||||
|
stdout = "Hello, World!\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
72
example/showcase/02-structured-build.jdg
Normal file
72
example/showcase/02-structured-build.jdg
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
// Полный showcase возможностей build-блока.
|
||||||
|
// Показывает: toolchains c платформами / переопределением binary / явным class,
|
||||||
|
// build_defaults как общая основа, три профиля (release/debug/sanitized),
|
||||||
|
// фильтры platforms и compilers, OS-оверрайды, wrapper, sanitize, define,
|
||||||
|
// includes, link, extra, а также build-level `wrapper` для valgrind.
|
||||||
|
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
clang {
|
||||||
|
platforms = "linux" "windows"
|
||||||
|
binary = "clang-17" // конкретная версия в PATH
|
||||||
|
class = gnu // явный class если имя нестандартное
|
||||||
|
}
|
||||||
|
msvc { platforms = "windows" }
|
||||||
|
nvcc {
|
||||||
|
platforms = "linux"
|
||||||
|
class = gnu // nvcc принимает gnu-like флаги
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
build_defaults {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "src/*.c" // glob, раскрывается относительно work dir
|
||||||
|
output = "solution" // на Windows автоматически станет solution.exe
|
||||||
|
includes = "include" "vendor/include"
|
||||||
|
link = "m" "pthread"
|
||||||
|
warnings = strict // → -Wall -Wextra / /W4
|
||||||
|
define("BUILD_ID") = "42"
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
profile = release // → -O2 / /O2
|
||||||
|
|
||||||
|
// OS-специфичные правки поверх defaults. Скаляры переопределяются,
|
||||||
|
// списки (extra, sanitize, sources, includes) аккумулируются.
|
||||||
|
linux { extra = "-fPIC" }
|
||||||
|
windows { extra = "/bigobj" }
|
||||||
|
darwin { extra = "-mmacosx-version-min=11" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build "debug" {
|
||||||
|
profile = debug // → -O0 -g / /Od /Zi
|
||||||
|
warnings = pedantic // → добавляет -Wpedantic / /permissive-
|
||||||
|
define("DEBUG") = "1"
|
||||||
|
}
|
||||||
|
|
||||||
|
build "sanitized" {
|
||||||
|
profile = sanitized
|
||||||
|
sanitize = "address" "undefined" "leak"
|
||||||
|
platforms = "linux" // UBSan не работает на MSVC
|
||||||
|
compilers = "gcc" "clang" // и только gnu-like
|
||||||
|
extra = "-fno-sanitize-recover=all"
|
||||||
|
}
|
||||||
|
|
||||||
|
build "debug-valgrind" {
|
||||||
|
profile = debug
|
||||||
|
wrapper = "valgrind --error-exitcode=99 --leak-check=full -q"
|
||||||
|
platforms = "linux"
|
||||||
|
compilers = "gcc"
|
||||||
|
}
|
||||||
|
|
||||||
|
timeout 10s
|
||||||
|
memory_limit = 256M
|
||||||
|
|
||||||
|
group("basic") {
|
||||||
|
weight = 1.0
|
||||||
|
|
||||||
|
test("smoke") {
|
||||||
|
stdout = "ok\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
69
example/showcase/03-matchers.jdg
Normal file
69
example/showcase/03-matchers.jdg
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
// Все способы сматчить stdout/stderr: exact, contains, regex, anyOrder,
|
||||||
|
// numeric-eps. Плюс случай, когда сравнение вывода вообще не нужно
|
||||||
|
// (достаточно exitCode).
|
||||||
|
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "solution.c"
|
||||||
|
output = "solution"
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
group("matchers") {
|
||||||
|
weight = 1.0
|
||||||
|
|
||||||
|
// Точное совпадение (по умолчанию). Пробелы, переводы строк и
|
||||||
|
// регистр важны. Нормализация CRLF / trim_ws настраивается на
|
||||||
|
// уровне файла.
|
||||||
|
test("exact") {
|
||||||
|
stdin = "42\n"
|
||||||
|
stdout = "42\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Подстрока в любом месте вывода.
|
||||||
|
test("contains") {
|
||||||
|
stdin = "log me\n"
|
||||||
|
stdout contains "log me"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Регулярное выражение (Go regexp syntax).
|
||||||
|
test("regex") {
|
||||||
|
stdin = "7\n"
|
||||||
|
stdout matches "^result:\\s+[0-9]+\\s*$"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Лайны могут прийти в любом порядке — полезно для stress-тестов
|
||||||
|
// с параллельным выводом.
|
||||||
|
test("any-order") {
|
||||||
|
stdin = "start\n"
|
||||||
|
stdout anyOrder {
|
||||||
|
"alpha"
|
||||||
|
"beta"
|
||||||
|
"gamma"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Числовое сравнение с epsilon — для задач с плавающей точкой.
|
||||||
|
// Синтаксис: ~ <float> of "<ожидаемое значение как строка>"
|
||||||
|
test("numeric") {
|
||||||
|
stdin = "3.14159\n"
|
||||||
|
stdout ~ 0.0001 of "3.14159\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Проверяем только stderr; stdout не трогаем вообще (NoMatcher).
|
||||||
|
test("stderr-only") {
|
||||||
|
args = "--version"
|
||||||
|
stderr contains "version 1."
|
||||||
|
}
|
||||||
|
|
||||||
|
// Никакого матчинга вывода — нас интересует только exit code.
|
||||||
|
test("exit-code-only") {
|
||||||
|
args = "--help"
|
||||||
|
exitCode = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
77
example/showcase/04-limits-scoring-env.jdg
Normal file
77
example/showcase/04-limits-scoring-env.jdg
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
// Тонкая настройка: timeout и memory_limit на разных уровнях (file → group
|
||||||
|
// → test), режимы скоринга (partial / all_or_none), переменные окружения,
|
||||||
|
// проверка exit code, передача аргументов.
|
||||||
|
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "solution.c"
|
||||||
|
output = "solution"
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
// Глобальные дефолты. Применяются к каждому тесту, если тот не
|
||||||
|
// переопределит у себя или на уровне группы.
|
||||||
|
timeout 5s
|
||||||
|
memory_limit = 256M
|
||||||
|
normalize_crlf = true // стрип \r перед сравнением — полезно на Windows
|
||||||
|
trim_trailing_ws = true // trim trailing space/tab на каждой строке
|
||||||
|
|
||||||
|
group("strict-subset") {
|
||||||
|
weight = 0.4
|
||||||
|
scoring = all_or_none // группа даёт weight или 0 — без частичного
|
||||||
|
|
||||||
|
// Эти дефолты применятся к каждому тесту группы.
|
||||||
|
timeout = 2s
|
||||||
|
memory_limit = 64M
|
||||||
|
env("LC_ALL") = "C"
|
||||||
|
env("LANG") = "C"
|
||||||
|
|
||||||
|
test("fast") {
|
||||||
|
args = "--mode" "fast"
|
||||||
|
stdout = "ok\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("strict-timeout") {
|
||||||
|
timeout = 500ms // переопределяет group timeout
|
||||||
|
stdout = "ok\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("high-memory") {
|
||||||
|
memory_limit = 128M // переопределяет group memory_limit
|
||||||
|
stdout = "ok\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
test("own-env") {
|
||||||
|
env("FOO") = "bar" // добавляется к group env
|
||||||
|
stdout = "ok\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
group("partial-credit") {
|
||||||
|
weight = 0.6
|
||||||
|
scoring = partial // default: weight * passed/total
|
||||||
|
|
||||||
|
test("case-1") {
|
||||||
|
stdin = "1\n"
|
||||||
|
stdout = "1\n"
|
||||||
|
exitCode = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
test("case-2") {
|
||||||
|
stdin = "2\n"
|
||||||
|
stdout = "4\n"
|
||||||
|
exitCode = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
test("case-error") {
|
||||||
|
// Программа ДОЛЖНА выйти с кодом 1 на плохом вводе.
|
||||||
|
stdin = "abc\n"
|
||||||
|
exitCode = 1
|
||||||
|
stderr contains "invalid input"
|
||||||
|
}
|
||||||
|
}
|
||||||
80
example/showcase/05-pattern-expansion.jdg
Normal file
80
example/showcase/05-pattern-expansion.jdg
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
// Автогенерация тестов из файлов/папок. Покрывает четыре типовых сценария:
|
||||||
|
//
|
||||||
|
// 1. Stdio-режим с парой globs — классика: stdin из .in, stdout = .ans
|
||||||
|
// 2. Shared expected — N входов, один общий ожидаемый файл
|
||||||
|
// 3. File-mode по args — программа читает файл по аргументу
|
||||||
|
// 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 {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "solution.c"
|
||||||
|
output = "solution"
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1) Классика: каждая пара (*.in, *.ans) → один тест.
|
||||||
|
// Stdin ← .in, Stdout сравнивается с .ans.
|
||||||
|
group("stdio-pair") {
|
||||||
|
weight = 0.25
|
||||||
|
|
||||||
|
pattern {
|
||||||
|
input = "tests/*.in"
|
||||||
|
output = "tests/*.ans"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Один общий expected для всех входов.
|
||||||
|
// Удобно для задач где «для любого корректного входа ответ одинаковый»
|
||||||
|
// (edge-case fuzzing) или наоборот «все некорректные входы → error»
|
||||||
|
// (смотрим на один и тот же файл с сообщением об ошибке).
|
||||||
|
group("shared-output") {
|
||||||
|
weight = 0.25
|
||||||
|
|
||||||
|
pattern {
|
||||||
|
input = "edge/*.in"
|
||||||
|
output = "edge/expected.ans" // литерал без *
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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}"
|
||||||
|
}
|
||||||
|
}
|
||||||
59
example/showcase/06-files.jdg
Normal file
59
example/showcase/06-files.jdg
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
// Тесты, которые общаются через файлы, а не через stdin/stdout.
|
||||||
|
// file("name") = "content" — файл кладётся в рабочую директорию теста
|
||||||
|
// перед запуском программы.
|
||||||
|
// outFile("name") = "content" — после запуска содержимое файла сравнивается
|
||||||
|
// с ожидаемым (точное совпадение с учётом
|
||||||
|
// normalize_crlf / trim_trailing_ws).
|
||||||
|
|
||||||
|
toolchains {
|
||||||
|
gcc { platforms = "linux" }
|
||||||
|
}
|
||||||
|
|
||||||
|
build "release" {
|
||||||
|
language = "c"
|
||||||
|
standard = "c11"
|
||||||
|
sources = "solution.c"
|
||||||
|
output = "solution"
|
||||||
|
profile = release
|
||||||
|
}
|
||||||
|
|
||||||
|
normalize_crlf = true
|
||||||
|
trim_trailing_ws = true
|
||||||
|
|
||||||
|
group("io") {
|
||||||
|
weight = 1.0
|
||||||
|
|
||||||
|
// Программа читает input.txt, пишет output.txt.
|
||||||
|
test("copy") {
|
||||||
|
args = "input.txt" "output.txt"
|
||||||
|
file("input.txt") = "hello world\n"
|
||||||
|
outFile("output.txt") = "hello world\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Несколько входных и выходных файлов сразу — удобно для задач
|
||||||
|
// вроде «посчитать сумму по каждой строке и записать в отдельный
|
||||||
|
// файл».
|
||||||
|
test("multi-file") {
|
||||||
|
args = "a.txt" "b.txt" "result.txt"
|
||||||
|
file("a.txt") = "1 2 3\n"
|
||||||
|
file("b.txt") = "10 20 30\n"
|
||||||
|
outFile("result.txt") = "11 22 33\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Вложенные пути тоже работают — создаются автоматически.
|
||||||
|
test("nested") {
|
||||||
|
args = "data/in.txt" "data/out.txt"
|
||||||
|
file("data/in.txt") = "payload\n"
|
||||||
|
outFile("data/out.txt") = "PAYLOAD\n"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Можно комбинировать с stdin/stdout и переменными окружения.
|
||||||
|
test("combined") {
|
||||||
|
stdin = "42\n"
|
||||||
|
args = "config.ini"
|
||||||
|
env("MODE") = "strict"
|
||||||
|
file("config.ini") = "threshold=10\n"
|
||||||
|
stdout = "ok\n"
|
||||||
|
outFile("log.txt") = "processed 42\n"
|
||||||
|
}
|
||||||
|
}
|
||||||
41
example/showcase/07-include.jdg
Normal file
41
example/showcase/07-include.jdg
Normal 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
22
example/showcase/common.jdg
Normal file
22
example/showcase/common.jdg
Normal 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
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"math"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"sort"
|
"sort"
|
||||||
@@ -13,11 +14,47 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func Text(w io.Writer, result *runner.SuiteResult) {
|
func Text(w io.Writer, result *runner.SuiteResult) {
|
||||||
if result.BuildLog != "" {
|
if len(result.Builds) == 0 {
|
||||||
fmt.Fprintf(w, "=== BUILD LOG ===\n%s\n", result.BuildLog)
|
fmt.Fprintln(w, "(no builds executed)")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, gr := range result.Groups {
|
multi := len(result.Builds) > 1
|
||||||
|
if multi {
|
||||||
|
fmt.Fprintf(w, "=== %d builds ===\n", len(result.Builds))
|
||||||
|
for _, b := range result.Builds {
|
||||||
|
marker := ""
|
||||||
|
if b.Skipped {
|
||||||
|
marker = " (skipped)"
|
||||||
|
}
|
||||||
|
fmt.Fprintf(w, " • %s%s score=%.4f\n", b.Name, marker, b.TotalScore)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, b := range result.Builds {
|
||||||
|
if multi {
|
||||||
|
fmt.Fprintf(w, "======== build %q ========\n", b.Name)
|
||||||
|
}
|
||||||
|
writeBuildText(w, b, multi)
|
||||||
|
}
|
||||||
|
|
||||||
|
if multi {
|
||||||
|
fmt.Fprintf(w, "\n══ AGGREGATE SCORE (min across builds): %.4f / 1.0000 ══\n", result.TotalScore)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeBuildText(w io.Writer, b *runner.BuildRun, multi bool) {
|
||||||
|
if b.Skipped {
|
||||||
|
fmt.Fprintf(w, "skipped: %s\n", b.SkipReason)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.BuildLog != "" {
|
||||||
|
fmt.Fprintf(w, "=== BUILD LOG ===\n%s\n", b.BuildLog)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, gr := range b.Groups {
|
||||||
passed := gr.Passed
|
passed := gr.Passed
|
||||||
total := gr.Total
|
total := gr.Total
|
||||||
pct := 0.0
|
pct := 0.0
|
||||||
@@ -53,13 +90,19 @@ func Text(w io.Writer, result *runner.SuiteResult) {
|
|||||||
fmt.Fprintf(w, "└─\n")
|
fmt.Fprintf(w, "└─\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Fprintf(w, "\n══ TOTAL SCORE: %.4f / 1.0000 ══\n", result.TotalScore)
|
if !multi {
|
||||||
|
fmt.Fprintf(w, "\n══ TOTAL SCORE: %.4f / 1.0000 ══\n", b.TotalScore)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func JSON(w io.Writer, result *runner.SuiteResult) error {
|
func JSON(w io.Writer, result *runner.SuiteResult) error {
|
||||||
enc := json.NewEncoder(w)
|
enc := json.NewEncoder(w)
|
||||||
enc.SetIndent("", " ")
|
enc.SetIndent("", " ")
|
||||||
return enc.Encode(jsonResult(result))
|
|
||||||
|
if len(result.Builds) <= 1 {
|
||||||
|
return enc.Encode(flatResult(result))
|
||||||
|
}
|
||||||
|
return enc.Encode(nestedResult(result))
|
||||||
}
|
}
|
||||||
|
|
||||||
type jsonSuiteResult struct {
|
type jsonSuiteResult struct {
|
||||||
@@ -68,6 +111,21 @@ type jsonSuiteResult struct {
|
|||||||
Groups []jsonGroupResult `json:"groups"`
|
Groups []jsonGroupResult `json:"groups"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type jsonMultiSuiteResult struct {
|
||||||
|
TotalScore float64 `json:"total_score"`
|
||||||
|
Builds map[string]jsonSuiteBuild `json:"builds"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type jsonSuiteBuild struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Toolchain string `json:"toolchain,omitempty"`
|
||||||
|
Skipped bool `json:"skipped,omitempty"`
|
||||||
|
SkipReason string `json:"skip_reason,omitempty"`
|
||||||
|
TotalScore float64 `json:"total_score"`
|
||||||
|
BuildLog string `json:"build_log,omitempty"`
|
||||||
|
Groups []jsonGroupResult `json:"groups"`
|
||||||
|
}
|
||||||
|
|
||||||
type jsonGroupResult struct {
|
type jsonGroupResult struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Weight float64 `json:"weight"`
|
Weight float64 `json:"weight"`
|
||||||
@@ -86,6 +144,62 @@ type jsonTestResult struct {
|
|||||||
Failures []string `json:"failures,omitempty"`
|
Failures []string `json:"failures,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func flatResult(r *runner.SuiteResult) jsonSuiteResult {
|
||||||
|
res := jsonSuiteResult{TotalScore: r.TotalScore}
|
||||||
|
if len(r.Builds) == 0 {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
b := r.Builds[0]
|
||||||
|
res.BuildLog = b.BuildLog
|
||||||
|
for _, gr := range b.Groups {
|
||||||
|
res.Groups = append(res.Groups, groupJSON(gr))
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func nestedResult(r *runner.SuiteResult) jsonMultiSuiteResult {
|
||||||
|
res := jsonMultiSuiteResult{
|
||||||
|
TotalScore: r.TotalScore,
|
||||||
|
Builds: map[string]jsonSuiteBuild{},
|
||||||
|
}
|
||||||
|
for _, b := range r.Builds {
|
||||||
|
entry := jsonSuiteBuild{
|
||||||
|
Name: b.Name,
|
||||||
|
Toolchain: b.Toolchain,
|
||||||
|
Skipped: b.Skipped,
|
||||||
|
SkipReason: b.SkipReason,
|
||||||
|
TotalScore: b.TotalScore,
|
||||||
|
BuildLog: b.BuildLog,
|
||||||
|
}
|
||||||
|
for _, gr := range b.Groups {
|
||||||
|
entry.Groups = append(entry.Groups, groupJSON(gr))
|
||||||
|
}
|
||||||
|
res.Builds[b.Name] = entry
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
func groupJSON(gr *runner.GroupResult) jsonGroupResult {
|
||||||
|
jgr := jsonGroupResult{
|
||||||
|
Name: gr.Name,
|
||||||
|
Weight: gr.Weight,
|
||||||
|
Score: gr.Score,
|
||||||
|
Passed: gr.Passed,
|
||||||
|
Total: gr.Total,
|
||||||
|
}
|
||||||
|
for _, tr := range gr.Tests {
|
||||||
|
jgr.Tests = append(jgr.Tests, jsonTestResult{
|
||||||
|
Name: tr.Name,
|
||||||
|
Status: tr.Status.String(),
|
||||||
|
ElapsedMs: tr.Elapsed.Milliseconds(),
|
||||||
|
PeakMemoryKB: tr.PeakMemory / 1024,
|
||||||
|
MemoryLimitKB: tr.MemoryLimit / 1024,
|
||||||
|
Failures: tr.Failures,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return jgr
|
||||||
|
}
|
||||||
|
|
||||||
func Aggregate(w io.Writer, dir string) error {
|
func Aggregate(w io.Writer, dir string) error {
|
||||||
files, err := filepath.Glob(filepath.Join(dir, "*", "*.json"))
|
files, err := filepath.Glob(filepath.Join(dir, "*", "*.json"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -105,24 +219,24 @@ func Aggregate(w io.Writer, dir string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var entries []entry
|
var entries []entry
|
||||||
allPassed := true
|
minScore := math.Inf(1)
|
||||||
|
|
||||||
for _, f := range files {
|
for _, f := range files {
|
||||||
data, err := os.ReadFile(f)
|
data, err := os.ReadFile(f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("read %s: %w", f, err)
|
return fmt.Errorf("read %s: %w", f, err)
|
||||||
}
|
}
|
||||||
var report jsonSuiteResult
|
score, err := extractTotalScore(data)
|
||||||
if err := json.Unmarshal(data, &report); err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("parse %s: %w", f, err)
|
return fmt.Errorf("parse %s: %w", f, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
cfg := filepath.Base(filepath.Dir(f))
|
cfg := filepath.Base(filepath.Dir(f))
|
||||||
cfg = strings.TrimPrefix(cfg, "report_")
|
cfg = strings.TrimPrefix(cfg, "report_")
|
||||||
|
|
||||||
entries = append(entries, entry{Config: cfg, Score: report.TotalScore})
|
entries = append(entries, entry{Config: cfg, Score: score})
|
||||||
if report.TotalScore < 0.9999 {
|
if score < minScore {
|
||||||
allPassed = false
|
minScore = score
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,13 +247,24 @@ func Aggregate(w io.Writer, dir string) error {
|
|||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(w, "| %s | %.4f |\n", e.Config, e.Score)
|
fmt.Fprintf(w, "| %s | %.4f |\n", e.Config, e.Score)
|
||||||
}
|
}
|
||||||
|
fmt.Fprintf(w, "| **Overall (min)** | **%.4f** |\n", minScore)
|
||||||
|
|
||||||
if !allPassed {
|
if minScore < 0.9999 {
|
||||||
return fmt.Errorf("one or more configurations scored below 1.0")
|
return fmt.Errorf("minimum score across configurations is %.4f (below 1.0)", minScore)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func extractTotalScore(data []byte) (float64, error) {
|
||||||
|
var header struct {
|
||||||
|
TotalScore float64 `json:"total_score"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(data, &header); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return header.TotalScore, nil
|
||||||
|
}
|
||||||
|
|
||||||
func humanBytes(n int64) string {
|
func humanBytes(n int64) string {
|
||||||
const (
|
const (
|
||||||
KiB = 1024
|
KiB = 1024
|
||||||
@@ -157,31 +282,3 @@ func humanBytes(n int64) string {
|
|||||||
return fmt.Sprintf("%dB", n)
|
return fmt.Sprintf("%dB", n)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func jsonResult(r *runner.SuiteResult) jsonSuiteResult {
|
|
||||||
res := jsonSuiteResult{
|
|
||||||
TotalScore: r.TotalScore,
|
|
||||||
BuildLog: r.BuildLog,
|
|
||||||
}
|
|
||||||
for _, gr := range r.Groups {
|
|
||||||
jgr := jsonGroupResult{
|
|
||||||
Name: gr.Name,
|
|
||||||
Weight: gr.Weight,
|
|
||||||
Score: gr.Score,
|
|
||||||
Passed: gr.Passed,
|
|
||||||
Total: gr.Total,
|
|
||||||
}
|
|
||||||
for _, tr := range gr.Tests {
|
|
||||||
jgr.Tests = append(jgr.Tests, jsonTestResult{
|
|
||||||
Name: tr.Name,
|
|
||||||
Status: tr.Status.String(),
|
|
||||||
ElapsedMs: tr.Elapsed.Milliseconds(),
|
|
||||||
PeakMemoryKB: tr.PeakMemory / 1024,
|
|
||||||
MemoryLimitKB: tr.MemoryLimit / 1024,
|
|
||||||
Failures: tr.Failures,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
res.Groups = append(res.Groups, jgr)
|
|
||||||
}
|
|
||||||
return res
|
|
||||||
}
|
|
||||||
|
|||||||
198
runner/compiler.go
Normal file
198
runner/compiler.go
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
package runner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Mond1c/judge/dsl"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CompilerClass int
|
||||||
|
|
||||||
|
const (
|
||||||
|
CompilerUnknown CompilerClass = iota
|
||||||
|
CompilerGNU
|
||||||
|
CompilerMSVC
|
||||||
|
)
|
||||||
|
|
||||||
|
type Toolchain struct {
|
||||||
|
Class CompilerClass
|
||||||
|
Binary string
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveToolchain(ccEnv string) Toolchain {
|
||||||
|
if ccEnv == "" {
|
||||||
|
ccEnv = defaultCC()
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(ccEnv)
|
||||||
|
switch lower {
|
||||||
|
case "gcc", "g++":
|
||||||
|
return Toolchain{Class: CompilerGNU, Binary: ccEnv, Name: "gcc"}
|
||||||
|
case "clang", "clang++":
|
||||||
|
return Toolchain{Class: CompilerGNU, Binary: ccEnv, Name: "clang"}
|
||||||
|
case "cl", "cl.exe", "msvc":
|
||||||
|
return Toolchain{Class: CompilerMSVC, Binary: "cl", Name: "msvc"}
|
||||||
|
case "clang-cl", "clang-cl.exe":
|
||||||
|
return Toolchain{Class: CompilerMSVC, Binary: "clang-cl", Name: "clang-cl"}
|
||||||
|
case "cc":
|
||||||
|
return Toolchain{Class: CompilerGNU, Binary: "cc", Name: "cc"}
|
||||||
|
default:
|
||||||
|
return Toolchain{Class: CompilerGNU, Binary: ccEnv, Name: lower}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ResolveToolchainSpec(spec *dsl.ToolchainSpec) Toolchain {
|
||||||
|
inferred := ResolveToolchain(spec.Name)
|
||||||
|
binary := spec.Binary
|
||||||
|
if binary == "" {
|
||||||
|
binary = inferred.Binary
|
||||||
|
}
|
||||||
|
var class CompilerClass
|
||||||
|
switch spec.Class {
|
||||||
|
case "gnu":
|
||||||
|
class = CompilerGNU
|
||||||
|
case "msvc":
|
||||||
|
class = CompilerMSVC
|
||||||
|
default:
|
||||||
|
class = inferred.Class
|
||||||
|
}
|
||||||
|
return Toolchain{Class: class, Binary: binary, Name: spec.Name}
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultCC() string {
|
||||||
|
if runtime.GOOS == "windows" {
|
||||||
|
return "cl"
|
||||||
|
}
|
||||||
|
return "cc"
|
||||||
|
}
|
||||||
|
|
||||||
|
func Compile(cfg dsl.BuildConfig, tc Toolchain, outputPath string) ([]string, error) {
|
||||||
|
switch tc.Class {
|
||||||
|
case CompilerGNU:
|
||||||
|
return compileGNU(cfg, tc, outputPath), nil
|
||||||
|
case CompilerMSVC:
|
||||||
|
return compileMSVC(cfg, tc, outputPath), nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown compiler class for toolchain %q", tc.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func compileGNU(cfg dsl.BuildConfig, tc Toolchain, outputPath string) []string {
|
||||||
|
argv := []string{tc.Binary}
|
||||||
|
|
||||||
|
if cfg.Standard != "" {
|
||||||
|
argv = append(argv, "-std="+cfg.Standard)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch cfg.Profile {
|
||||||
|
case dsl.ProfileRelease:
|
||||||
|
argv = append(argv, "-O2")
|
||||||
|
case dsl.ProfileDebug:
|
||||||
|
argv = append(argv, "-O0", "-g")
|
||||||
|
case dsl.ProfileSanitized:
|
||||||
|
argv = append(argv, "-O1", "-g", "-fno-omit-frame-pointer")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch cfg.Warnings {
|
||||||
|
case dsl.WarningsStrict:
|
||||||
|
argv = append(argv, "-Wall", "-Wextra")
|
||||||
|
case dsl.WarningsPedantic:
|
||||||
|
argv = append(argv, "-Wall", "-Wextra", "-Wpedantic")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(cfg.Sanitize) > 0 {
|
||||||
|
argv = append(argv, "-fsanitize="+strings.Join(cfg.Sanitize, ","))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, inc := range cfg.Includes {
|
||||||
|
argv = append(argv, "-I"+inc)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, k := range sortedKeys(cfg.Defines) {
|
||||||
|
v := cfg.Defines[k]
|
||||||
|
if v == "" {
|
||||||
|
argv = append(argv, "-D"+k)
|
||||||
|
} else {
|
||||||
|
argv = append(argv, fmt.Sprintf("-D%s=%s", k, v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
argv = append(argv, cfg.Extra...)
|
||||||
|
argv = append(argv, cfg.Sources...)
|
||||||
|
argv = append(argv, "-o", outputPath)
|
||||||
|
|
||||||
|
for _, lib := range cfg.Link {
|
||||||
|
argv = append(argv, "-l"+lib)
|
||||||
|
}
|
||||||
|
return argv
|
||||||
|
}
|
||||||
|
|
||||||
|
func compileMSVC(cfg dsl.BuildConfig, tc Toolchain, outputPath string) []string {
|
||||||
|
argv := []string{tc.Binary, "/nologo"}
|
||||||
|
|
||||||
|
if cfg.Standard != "" {
|
||||||
|
argv = append(argv, "/std:"+cfg.Standard)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch cfg.Profile {
|
||||||
|
case dsl.ProfileRelease:
|
||||||
|
argv = append(argv, "/O2")
|
||||||
|
case dsl.ProfileDebug:
|
||||||
|
argv = append(argv, "/Od", "/Zi")
|
||||||
|
case dsl.ProfileSanitized:
|
||||||
|
argv = append(argv, "/Od", "/Zi", "/fsanitize=address")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch cfg.Warnings {
|
||||||
|
case dsl.WarningsStrict:
|
||||||
|
argv = append(argv, "/W4")
|
||||||
|
case dsl.WarningsPedantic:
|
||||||
|
argv = append(argv, "/W4", "/permissive-")
|
||||||
|
}
|
||||||
|
|
||||||
|
if containsString(cfg.Sanitize, "address") && cfg.Profile != dsl.ProfileSanitized {
|
||||||
|
argv = append(argv, "/fsanitize=address")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, inc := range cfg.Includes {
|
||||||
|
argv = append(argv, "/I"+inc)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, k := range sortedKeys(cfg.Defines) {
|
||||||
|
v := cfg.Defines[k]
|
||||||
|
if v == "" {
|
||||||
|
argv = append(argv, "/D"+k)
|
||||||
|
} else {
|
||||||
|
argv = append(argv, fmt.Sprintf("/D%s=%s", k, v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
argv = append(argv, cfg.Extra...)
|
||||||
|
argv = append(argv, cfg.Sources...)
|
||||||
|
argv = append(argv, "/Fe:"+outputPath)
|
||||||
|
return argv
|
||||||
|
}
|
||||||
|
|
||||||
|
func sortedKeys(m map[string]string) []string {
|
||||||
|
if len(m) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
return keys
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsString(xs []string, x string) bool {
|
||||||
|
for _, v := range xs {
|
||||||
|
if v == x {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
293
runner/compiler_test.go
Normal file
293
runner/compiler_test.go
Normal file
@@ -0,0 +1,293 @@
|
|||||||
|
package runner
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Mond1c/judge/dsl"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestResolveToolchainKnown(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
in string
|
||||||
|
wantClass CompilerClass
|
||||||
|
wantName string
|
||||||
|
}{
|
||||||
|
{"gcc", CompilerGNU, "gcc"},
|
||||||
|
{"g++", CompilerGNU, "gcc"},
|
||||||
|
{"clang", CompilerGNU, "clang"},
|
||||||
|
{"clang++", CompilerGNU, "clang"},
|
||||||
|
{"cl", CompilerMSVC, "msvc"},
|
||||||
|
{"cl.exe", CompilerMSVC, "msvc"},
|
||||||
|
{"msvc", CompilerMSVC, "msvc"},
|
||||||
|
{"clang-cl", CompilerMSVC, "clang-cl"},
|
||||||
|
{"cc", CompilerGNU, "cc"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.in, func(t *testing.T) {
|
||||||
|
tc := ResolveToolchain(c.in)
|
||||||
|
if tc.Class != c.wantClass {
|
||||||
|
t.Errorf("class: got %v, want %v", tc.Class, c.wantClass)
|
||||||
|
}
|
||||||
|
if tc.Name != c.wantName {
|
||||||
|
t.Errorf("name: got %q, want %q", tc.Name, c.wantName)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveToolchainSpec(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
spec dsl.ToolchainSpec
|
||||||
|
wantClass CompilerClass
|
||||||
|
wantBin string
|
||||||
|
wantName string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"gcc inferred",
|
||||||
|
dsl.ToolchainSpec{Name: "gcc", Platforms: []string{"linux"}},
|
||||||
|
CompilerGNU, "gcc", "gcc",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"msvc inferred",
|
||||||
|
dsl.ToolchainSpec{Name: "msvc", Platforms: []string{"windows"}},
|
||||||
|
CompilerMSVC, "cl", "msvc",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nvcc with explicit class",
|
||||||
|
dsl.ToolchainSpec{Name: "nvcc", Platforms: []string{"linux"}, Class: "gnu"},
|
||||||
|
CompilerGNU, "nvcc", "nvcc",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"custom binary override",
|
||||||
|
dsl.ToolchainSpec{Name: "clang", Platforms: []string{"linux", "windows"}, Binary: "clang-17"},
|
||||||
|
CompilerGNU, "clang-17", "clang",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"unknown name, explicit class",
|
||||||
|
dsl.ToolchainSpec{Name: "hipcc", Platforms: []string{"linux"}, Class: "gnu"},
|
||||||
|
CompilerGNU, "hipcc", "hipcc",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
got := ResolveToolchainSpec(&c.spec)
|
||||||
|
if got.Class != c.wantClass {
|
||||||
|
t.Errorf("class: got %v, want %v", got.Class, c.wantClass)
|
||||||
|
}
|
||||||
|
if got.Binary != c.wantBin {
|
||||||
|
t.Errorf("binary: got %q, want %q", got.Binary, c.wantBin)
|
||||||
|
}
|
||||||
|
if got.Name != c.wantName {
|
||||||
|
t.Errorf("name: got %q, want %q", got.Name, c.wantName)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveToolchainUnknownFallsBackToGNU(t *testing.T) {
|
||||||
|
tc := ResolveToolchain("gcc-13")
|
||||||
|
if tc.Class != CompilerGNU {
|
||||||
|
t.Errorf("unknown compiler should fall back to GNU, got %v", tc.Class)
|
||||||
|
}
|
||||||
|
if tc.Binary != "gcc-13" {
|
||||||
|
t.Errorf("binary should preserve the original string, got %q", tc.Binary)
|
||||||
|
}
|
||||||
|
if tc.Name != "gcc-13" {
|
||||||
|
t.Errorf("name should be the lowercased original, got %q", tc.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileGNURelease(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Language: "c",
|
||||||
|
Standard: "c11",
|
||||||
|
Sources: []string{"solution.c"},
|
||||||
|
Profile: dsl.ProfileRelease,
|
||||||
|
Warnings: dsl.WarningsStrict,
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerGNU, Binary: "gcc", Name: "gcc"}
|
||||||
|
argv, err := Compile(cfg, tc, "solution")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []string{"gcc", "-std=c11", "-O2", "-Wall", "-Wextra", "solution.c", "-o", "solution"}
|
||||||
|
if !reflect.DeepEqual(argv, want) {
|
||||||
|
t.Errorf("argv =\n %v\nwant\n %v", argv, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileGNUDebug(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Standard: "c11",
|
||||||
|
Sources: []string{"a.c", "b.c"},
|
||||||
|
Profile: dsl.ProfileDebug,
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerGNU, Binary: "gcc"}
|
||||||
|
argv, _ := Compile(cfg, tc, "out")
|
||||||
|
if !containsSubsequence(argv, []string{"-O0", "-g"}) {
|
||||||
|
t.Errorf("debug flags missing: %v", argv)
|
||||||
|
}
|
||||||
|
if !containsSubsequence(argv, []string{"a.c", "b.c", "-o", "out"}) {
|
||||||
|
t.Errorf("sources and output order wrong: %v", argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileGNUSanitized(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Standard: "c11",
|
||||||
|
Sources: []string{"s.c"},
|
||||||
|
Profile: dsl.ProfileSanitized,
|
||||||
|
Sanitize: []string{"address", "undefined"},
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerGNU, Binary: "clang"}
|
||||||
|
argv, _ := Compile(cfg, tc, "s")
|
||||||
|
joined := strings.Join(argv, " ")
|
||||||
|
if !strings.Contains(joined, "-fsanitize=address,undefined") {
|
||||||
|
t.Errorf("sanitize flag missing: %v", argv)
|
||||||
|
}
|
||||||
|
if !strings.Contains(joined, "-O1") {
|
||||||
|
t.Errorf("-O1 missing for sanitized profile: %v", argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileGNUIncludesAndDefinesAndLink(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Sources: []string{"m.c"},
|
||||||
|
Includes: []string{"include", "vendor/inc"},
|
||||||
|
Defines: map[string]string{"FOO": "1", "BAR": ""},
|
||||||
|
Link: []string{"m", "pthread"},
|
||||||
|
Extra: []string{"-fno-strict-aliasing"},
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerGNU, Binary: "gcc"}
|
||||||
|
argv, _ := Compile(cfg, tc, "out")
|
||||||
|
|
||||||
|
joined := strings.Join(argv, " ")
|
||||||
|
for _, want := range []string{"-Iinclude", "-Ivendor/inc", "-DFOO=1", "-DBAR", "-lm", "-lpthread", "-fno-strict-aliasing"} {
|
||||||
|
if !strings.Contains(joined, want) {
|
||||||
|
t.Errorf("missing %q in %v", want, argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
oIdx := indexOf(argv, "-o")
|
||||||
|
lmIdx := indexOf(argv, "-lm")
|
||||||
|
if oIdx == -1 || lmIdx == -1 || lmIdx < oIdx {
|
||||||
|
t.Errorf("-lm must come after -o: %v", argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileGNUDefinesOrderDeterministic(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Sources: []string{"s.c"},
|
||||||
|
Defines: map[string]string{"Z": "1", "A": "2", "M": "3"},
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerGNU, Binary: "gcc"}
|
||||||
|
argv1, _ := Compile(cfg, tc, "s")
|
||||||
|
for i := 0; i < 20; i++ {
|
||||||
|
argv2, _ := Compile(cfg, tc, "s")
|
||||||
|
if !reflect.DeepEqual(argv1, argv2) {
|
||||||
|
t.Fatalf("defines order not deterministic:\n %v\n %v", argv1, argv2)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileMSVCRelease(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Standard: "c11",
|
||||||
|
Sources: []string{"solution.c"},
|
||||||
|
Profile: dsl.ProfileRelease,
|
||||||
|
Warnings: dsl.WarningsStrict,
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerMSVC, Binary: "cl", Name: "msvc"}
|
||||||
|
argv, _ := Compile(cfg, tc, "solution.exe")
|
||||||
|
want := []string{"cl", "/nologo", "/std:c11", "/O2", "/W4", "solution.c", "/Fe:solution.exe"}
|
||||||
|
if !reflect.DeepEqual(argv, want) {
|
||||||
|
t.Errorf("argv =\n %v\nwant\n %v", argv, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileMSVCDebug(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Sources: []string{"s.c"},
|
||||||
|
Profile: dsl.ProfileDebug,
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerMSVC, Binary: "cl"}
|
||||||
|
argv, _ := Compile(cfg, tc, "s.exe")
|
||||||
|
joined := strings.Join(argv, " ")
|
||||||
|
for _, want := range []string{"/Od", "/Zi"} {
|
||||||
|
if !strings.Contains(joined, want) {
|
||||||
|
t.Errorf("missing %q in %v", want, argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileMSVCSanitizedAddressOnly(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Sources: []string{"s.c"},
|
||||||
|
Profile: dsl.ProfileSanitized,
|
||||||
|
Sanitize: []string{"address", "undefined", "thread"},
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerMSVC, Binary: "cl"}
|
||||||
|
argv, _ := Compile(cfg, tc, "s.exe")
|
||||||
|
joined := strings.Join(argv, " ")
|
||||||
|
if !strings.Contains(joined, "/fsanitize=address") {
|
||||||
|
t.Errorf("msvc should emit /fsanitize=address for sanitized profile: %v", argv)
|
||||||
|
}
|
||||||
|
if strings.Contains(joined, "undefined") || strings.Contains(joined, "thread") {
|
||||||
|
t.Errorf("msvc should drop unsupported sanitizers, got: %v", argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileMSVCIncludesAndDefines(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{
|
||||||
|
Sources: []string{"m.c"},
|
||||||
|
Includes: []string{"include"},
|
||||||
|
Defines: map[string]string{"FOO": "1", "BAR": ""},
|
||||||
|
}
|
||||||
|
tc := Toolchain{Class: CompilerMSVC, Binary: "cl"}
|
||||||
|
argv, _ := Compile(cfg, tc, "m.exe")
|
||||||
|
joined := strings.Join(argv, " ")
|
||||||
|
for _, want := range []string{"/Iinclude", "/DFOO=1", "/DBAR"} {
|
||||||
|
if !strings.Contains(joined, want) {
|
||||||
|
t.Errorf("missing %q in %v", want, argv)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCompileUnknownClassErrors(t *testing.T) {
|
||||||
|
cfg := dsl.BuildConfig{Sources: []string{"s.c"}}
|
||||||
|
tc := Toolchain{Class: CompilerUnknown, Binary: "weird"}
|
||||||
|
if _, err := Compile(cfg, tc, "s"); err == nil {
|
||||||
|
t.Error("expected error for unknown compiler class")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func containsSubsequence(haystack, needle []string) bool {
|
||||||
|
if len(needle) == 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for i := 0; i+len(needle) <= len(haystack); i++ {
|
||||||
|
match := true
|
||||||
|
for j := range needle {
|
||||||
|
if haystack[i+j] != needle[j] {
|
||||||
|
match = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if match {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func indexOf(xs []string, x string) int {
|
||||||
|
for i, v := range xs {
|
||||||
|
if v == x {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
@@ -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
240
runner/expander_test.go
Normal 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")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package runner
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -40,8 +41,8 @@ type TestResult struct {
|
|||||||
Status Status
|
Status Status
|
||||||
Elapsed time.Duration
|
Elapsed time.Duration
|
||||||
|
|
||||||
PeakMemory int64 // bytes; 0 if not measured
|
PeakMemory int64
|
||||||
MemoryLimit int64 // bytes; 0 if unlimited
|
MemoryLimit int64
|
||||||
|
|
||||||
Failures []string
|
Failures []string
|
||||||
|
|
||||||
@@ -64,8 +65,40 @@ type GroupResult struct {
|
|||||||
Total int
|
Total int
|
||||||
}
|
}
|
||||||
|
|
||||||
type SuiteResult struct {
|
type BuildRun struct {
|
||||||
|
Name string
|
||||||
|
Toolchain string
|
||||||
|
Skipped bool
|
||||||
|
SkipReason string
|
||||||
|
|
||||||
|
BuildLog string
|
||||||
Groups []*GroupResult
|
Groups []*GroupResult
|
||||||
TotalScore float64
|
TotalScore float64
|
||||||
BuildLog string
|
}
|
||||||
|
|
||||||
|
type SuiteResult struct {
|
||||||
|
Builds []*BuildRun
|
||||||
|
|
||||||
|
TotalScore float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *SuiteResult) AggregateScore() float64 {
|
||||||
|
if len(r.Builds) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
min := math.Inf(1)
|
||||||
|
anyRan := false
|
||||||
|
for _, b := range r.Builds {
|
||||||
|
if b.Skipped {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
anyRan = true
|
||||||
|
if b.TotalScore < min {
|
||||||
|
min = b.TotalScore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !anyRan {
|
||||||
|
return 1.0
|
||||||
|
}
|
||||||
|
return min
|
||||||
}
|
}
|
||||||
|
|||||||
57
runner/result_test.go
Normal file
57
runner/result_test.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package runner
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestAggregateScoreEmpty(t *testing.T) {
|
||||||
|
r := &SuiteResult{}
|
||||||
|
if got := r.AggregateScore(); got != 0 {
|
||||||
|
t.Errorf("empty aggregate = %v, want 0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAggregateScoreSingleBuild(t *testing.T) {
|
||||||
|
r := &SuiteResult{
|
||||||
|
Builds: []*BuildRun{{Name: "release", TotalScore: 0.75}},
|
||||||
|
}
|
||||||
|
if got := r.AggregateScore(); got != 0.75 {
|
||||||
|
t.Errorf("single build aggregate = %v, want 0.75", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAggregateScoreTakesMinimum(t *testing.T) {
|
||||||
|
r := &SuiteResult{
|
||||||
|
Builds: []*BuildRun{
|
||||||
|
{Name: "release", TotalScore: 1.0},
|
||||||
|
{Name: "debug", TotalScore: 0.9},
|
||||||
|
{Name: "sanitized", TotalScore: 0.95},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if got := r.AggregateScore(); got != 0.9 {
|
||||||
|
t.Errorf("aggregate = %v, want 0.9 (minimum)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAggregateScoreIgnoresSkipped(t *testing.T) {
|
||||||
|
r := &SuiteResult{
|
||||||
|
Builds: []*BuildRun{
|
||||||
|
{Name: "release", TotalScore: 1.0},
|
||||||
|
{Name: "sanitized", Skipped: true, SkipReason: "platforms=linux"},
|
||||||
|
{Name: "debug", TotalScore: 0.8},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if got := r.AggregateScore(); got != 0.8 {
|
||||||
|
t.Errorf("aggregate with skipped = %v, want 0.8", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAggregateScoreAllSkipped(t *testing.T) {
|
||||||
|
r := &SuiteResult{
|
||||||
|
Builds: []*BuildRun{
|
||||||
|
{Name: "a", Skipped: true},
|
||||||
|
{Name: "b", Skipped: true},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if got := r.AggregateScore(); got != 1.0 {
|
||||||
|
t.Errorf("all-skipped aggregate = %v, want 1.0", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
291
runner/runner.go
291
runner/runner.go
@@ -21,6 +21,8 @@ type Config struct {
|
|||||||
WorkDir string
|
WorkDir string
|
||||||
BinaryName string
|
BinaryName string
|
||||||
Wrapper string
|
Wrapper string
|
||||||
|
|
||||||
|
TargetBuild string
|
||||||
}
|
}
|
||||||
|
|
||||||
type Runner struct {
|
type Runner struct {
|
||||||
@@ -63,16 +65,116 @@ func (r *Runner) Run() *SuiteResult {
|
|||||||
|
|
||||||
result := &SuiteResult{}
|
result := &SuiteResult{}
|
||||||
|
|
||||||
buildLog, err := r.build()
|
if len(r.file.Builds) == 0 {
|
||||||
result.BuildLog = buildLog
|
run := r.runLegacyBuild()
|
||||||
|
result.Builds = append(result.Builds, run)
|
||||||
|
} else {
|
||||||
|
result.Builds = r.runStructuredBuilds()
|
||||||
|
}
|
||||||
|
|
||||||
|
result.TotalScore = result.AggregateScore()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) runLegacyBuild() *BuildRun {
|
||||||
|
run := &BuildRun{Name: "default"}
|
||||||
|
|
||||||
|
if r.cfg.TargetBuild != "" && r.cfg.TargetBuild != "default" {
|
||||||
|
run.Skipped = true
|
||||||
|
run.SkipReason = fmt.Sprintf("--build=%q selected, but this suite has no structured builds", r.cfg.TargetBuild)
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
|
||||||
|
buildLog, err := r.legacyBuild()
|
||||||
|
run.BuildLog = buildLog
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
r.fillBuildError(run)
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
|
||||||
|
r.binary = resolveBinary(r.cfg.WorkDir, filepath.Base(r.binary))
|
||||||
|
r.runGroups(run)
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) resolveRuntimeToolchain() (Toolchain, string) {
|
||||||
|
goos := runtime.GOOS
|
||||||
|
wanted := os.Getenv("JUDGE_TOOLCHAIN")
|
||||||
|
if wanted == "" {
|
||||||
|
wanted = os.Getenv("JUDGE_CC")
|
||||||
|
}
|
||||||
|
for _, spec := range r.file.Toolchains {
|
||||||
|
if spec.Name == wanted {
|
||||||
|
return ResolveToolchainSpec(spec), goos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ResolveToolchain(wanted), goos
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) runStructuredBuilds() []*BuildRun {
|
||||||
|
tc, goos := r.resolveRuntimeToolchain()
|
||||||
|
var runs []*BuildRun
|
||||||
|
|
||||||
|
for _, b := range r.file.Builds {
|
||||||
|
run := &BuildRun{Name: b.Name, Toolchain: tc.Name}
|
||||||
|
|
||||||
|
if r.cfg.TargetBuild != "" && r.cfg.TargetBuild != b.Name {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
effective := b.Resolve(r.file.BuildDefaults, goos)
|
||||||
|
if !effective.AppliesTo(goos, tc.Name) {
|
||||||
|
run.Skipped = true
|
||||||
|
run.SkipReason = fmt.Sprintf("not applicable to %s/%s (platforms=%v, compilers=%v)", goos, tc.Name, effective.Platforms, effective.Compilers)
|
||||||
|
runs = append(runs, run)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
log, binaryPath, err := r.compileStructured(b.Name, effective, tc)
|
||||||
|
run.BuildLog = log
|
||||||
|
if err != nil {
|
||||||
|
run.Groups = r.synthesizeBuildError()
|
||||||
|
run.TotalScore = 0
|
||||||
|
runs = append(runs, run)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
prevBinary := r.binary
|
||||||
|
prevWrapper := r.cfg.Wrapper
|
||||||
|
r.binary = binaryPath
|
||||||
|
if r.cfg.Wrapper == "" && effective.Wrapper != "" {
|
||||||
|
r.cfg.Wrapper = effective.Wrapper
|
||||||
|
}
|
||||||
|
r.runGroups(run)
|
||||||
|
r.binary = prevBinary
|
||||||
|
r.cfg.Wrapper = prevWrapper
|
||||||
|
|
||||||
|
runs = append(runs, run)
|
||||||
|
}
|
||||||
|
|
||||||
|
return runs
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) runGroups(run *BuildRun) {
|
||||||
|
for _, g := range r.file.Groups {
|
||||||
|
gr := r.runGroup(g)
|
||||||
|
run.Groups = append(run.Groups, gr)
|
||||||
|
run.TotalScore += gr.Score
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) fillBuildError(run *BuildRun) {
|
||||||
|
run.Groups = r.synthesizeBuildError()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) synthesizeBuildError() []*GroupResult {
|
||||||
|
var out []*GroupResult
|
||||||
for _, g := range r.file.Groups {
|
for _, g := range r.file.Groups {
|
||||||
gr := &GroupResult{
|
gr := &GroupResult{
|
||||||
Name: g.Name,
|
Name: g.Name,
|
||||||
Weight: g.Weight,
|
Weight: g.Weight,
|
||||||
Score: 0,
|
Score: 0,
|
||||||
}
|
}
|
||||||
|
|
||||||
total := len(g.Tests)
|
total := len(g.Tests)
|
||||||
if g.Pattern != nil {
|
if g.Pattern != nil {
|
||||||
total = -1
|
total = -1
|
||||||
@@ -84,20 +186,125 @@ func (r *Runner) Run() *SuiteResult {
|
|||||||
Status: StatusBuildError,
|
Status: StatusBuildError,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
result.Groups = append(result.Groups, gr)
|
out = append(out, gr)
|
||||||
}
|
}
|
||||||
return result
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) legacyBuild() (string, error) {
|
||||||
|
buildCmd := r.buildCommand()
|
||||||
|
|
||||||
|
sources, err := r.findSources()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if sources != "" {
|
||||||
|
buildCmd = strings.ReplaceAll(buildCmd, "$SOURCES", sources)
|
||||||
}
|
}
|
||||||
|
|
||||||
r.binary = resolveBinary(r.cfg.WorkDir, filepath.Base(r.binary))
|
ctx := context.Background()
|
||||||
|
if r.file.Timeout > 0 {
|
||||||
for _, g := range r.file.Groups {
|
var cancel context.CancelFunc
|
||||||
gr := r.runGroup(g)
|
ctx, cancel = context.WithTimeout(ctx, r.file.Timeout)
|
||||||
result.Groups = append(result.Groups, gr)
|
defer cancel()
|
||||||
result.TotalScore += gr.Score
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
cmd := shellCommand(ctx, buildCmd)
|
||||||
|
cmd.Dir = r.cfg.WorkDir
|
||||||
|
setProcessGroup(cmd)
|
||||||
|
cmd.Env = os.Environ()
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
cmd.Stdout = &out
|
||||||
|
cmd.Stderr = &out
|
||||||
|
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
killProcessGroup(cmd)
|
||||||
|
return out.String(), fmt.Errorf("build failed: %w\n%s", err, out.String())
|
||||||
|
}
|
||||||
|
return out.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runner) compileStructured(name string, cfg dsl.BuildConfig, tc Toolchain) (string, string, error) {
|
||||||
|
sources, err := expandSources(r.cfg.WorkDir, cfg.Sources)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
if len(sources) == 0 {
|
||||||
|
return "", "", fmt.Errorf("build %q: no sources", name)
|
||||||
|
}
|
||||||
|
cfg.Sources = sources
|
||||||
|
|
||||||
|
outputName := cfg.Output
|
||||||
|
if outputName == "" {
|
||||||
|
outputName = "solution"
|
||||||
|
}
|
||||||
|
if runtime.GOOS == "windows" && !strings.HasSuffix(strings.ToLower(outputName), ".exe") {
|
||||||
|
outputName += ".exe"
|
||||||
|
}
|
||||||
|
buildDir := filepath.Join(r.cfg.WorkDir, "build", name)
|
||||||
|
if err := os.MkdirAll(buildDir, 0755); err != nil {
|
||||||
|
return "", "", fmt.Errorf("mkdir %s: %w", buildDir, err)
|
||||||
|
}
|
||||||
|
outputPath := filepath.Join(buildDir, outputName)
|
||||||
|
|
||||||
|
argv, err := Compile(cfg, tc, outputPath)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
if r.file.Timeout > 0 {
|
||||||
|
var cancel context.CancelFunc
|
||||||
|
ctx, cancel = context.WithTimeout(ctx, r.file.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
|
||||||
|
cmd.Dir = r.cfg.WorkDir
|
||||||
|
setProcessGroup(cmd)
|
||||||
|
cmd.Env = os.Environ()
|
||||||
|
|
||||||
|
var out bytes.Buffer
|
||||||
|
cmd.Stdout = &out
|
||||||
|
cmd.Stderr = &out
|
||||||
|
|
||||||
|
logPrefix := fmt.Sprintf("$ %s\n", strings.Join(argv, " "))
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
killProcessGroup(cmd)
|
||||||
|
return logPrefix + out.String(), "", fmt.Errorf("build %q failed: %w\n%s", name, err, out.String())
|
||||||
|
}
|
||||||
|
return logPrefix + out.String(), outputPath, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func expandSources(workDir string, patterns []string) ([]string, error) {
|
||||||
|
var out []string
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, pat := range patterns {
|
||||||
|
matches, err := filepath.Glob(filepath.Join(workDir, pat))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("glob %q: %w", pat, err)
|
||||||
|
}
|
||||||
|
if len(matches) == 0 {
|
||||||
|
if _, statErr := os.Stat(filepath.Join(workDir, pat)); statErr == nil {
|
||||||
|
matches = []string{filepath.Join(workDir, pat)}
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("source glob %q matched no files", pat)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, m := range matches {
|
||||||
|
rel, err := filepath.Rel(workDir, m)
|
||||||
|
if err != nil {
|
||||||
|
rel = m
|
||||||
|
}
|
||||||
|
rel = filepath.ToSlash(rel)
|
||||||
|
if !seen[rel] {
|
||||||
|
seen[rel] = true
|
||||||
|
out = append(out, rel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Runner) buildCommand() string {
|
func (r *Runner) buildCommand() string {
|
||||||
@@ -152,40 +359,6 @@ func (r *Runner) findSources() (string, error) {
|
|||||||
return strings.Join(files, " "), nil
|
return strings.Join(files, " "), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Runner) build() (string, error) {
|
|
||||||
buildCmd := r.buildCommand()
|
|
||||||
|
|
||||||
sources, err := r.findSources()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if sources != "" {
|
|
||||||
buildCmd = strings.ReplaceAll(buildCmd, "$SOURCES", sources)
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
if r.file.Timeout > 0 {
|
|
||||||
var cancel context.CancelFunc
|
|
||||||
ctx, cancel = context.WithTimeout(ctx, r.file.Timeout)
|
|
||||||
defer cancel()
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd := shellCommand(ctx, buildCmd)
|
|
||||||
cmd.Dir = r.cfg.WorkDir
|
|
||||||
setProcessGroup(cmd)
|
|
||||||
cmd.Env = os.Environ()
|
|
||||||
|
|
||||||
var out bytes.Buffer
|
|
||||||
cmd.Stdout = &out
|
|
||||||
cmd.Stderr = &out
|
|
||||||
|
|
||||||
if err := cmd.Run(); err != nil {
|
|
||||||
killProcessGroup(cmd)
|
|
||||||
return out.String(), fmt.Errorf("build failed: %w\n%s", err, out.String())
|
|
||||||
}
|
|
||||||
return out.String(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func shellCommand(ctx context.Context, cmdline string) *exec.Cmd {
|
func shellCommand(ctx context.Context, cmdline string) *exec.Cmd {
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
return exec.CommandContext(ctx, "cmd", "/C", cmdline)
|
return exec.CommandContext(ctx, "cmd", "/C", cmdline)
|
||||||
@@ -392,21 +565,23 @@ func (r *Runner) runTest(t *dsl.Test) *TestResult {
|
|||||||
tr.addFailure("%s", f)
|
tr.addFailure("%s", f)
|
||||||
}
|
}
|
||||||
|
|
||||||
for name, expected := range t.OutFiles {
|
if len(tr.Failures) > 0 {
|
||||||
path := filepath.Join(tmpDir, name)
|
tr.Status = StatusFail
|
||||||
content, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
tr.addFailure("output file %q not found: %v", name, err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
actual := normalizeOutput(string(content), r.file)
|
|
||||||
for _, f := range applyMatcher(fmt.Sprintf("file(%s)", name), dsl.ExactMatcher{Value: expected}, actual) {
|
|
||||||
tr.addFailure("%s", f)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if tr.Status == StatusPass && len(tr.Failures) > 0 {
|
for name, expected := range t.OutFiles {
|
||||||
|
actualPath := filepath.Join(tmpDir, name)
|
||||||
|
data, err := os.ReadFile(actualPath)
|
||||||
|
if err != nil {
|
||||||
tr.Status = StatusFail
|
tr.Status = StatusFail
|
||||||
|
tr.addFailure("output file %q missing: %v", name, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
actual := normalizeOutput(string(data), r.file)
|
||||||
|
if actual != expected {
|
||||||
|
tr.Status = StatusFail
|
||||||
|
tr.addFailure("output file %q mismatch\n expected: %q\n actual: %q", name, expected, actual)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return tr
|
return tr
|
||||||
|
|||||||
Reference in New Issue
Block a user