package runner import ( "context" _ "embed" "encoding/json" "log" "os/exec" "path/filepath" "regexp" "sort" "strconv" "strings" "sync" ) // tidyConfig is passed to clang-tidy with --config: the source is linted // in a temp directory outside the repo, so the repo's .clang-tidy (the // same file, for editors) is never found by clang-tidy's own search. // //go:embed clang-tidy.yaml var tidyConfig string // ruffRules are ruff's defaults (pycodestyle errors, pyflakes) plus // bugbear, which catches the mutable-default and loop-variable mistakes // that bite in contest code. No style rules: the editor is not a formatter. const ruffRules = "E4,E7,E9,F,B" // pySyntax reports the first syntax error as JSON. It runs isolated (-I), // so a submitted json.py cannot stand in for the real module, and calls // compile() rather than py_compile so it leaves no .pyc and gets the // error's span, not just a formatted traceback. const pySyntax = `import json try: compile(open("main.py", "rb").read(), "main.py", "exec") except SyntaxError as e: print(json.dumps({"line": e.lineno or 1, "col": e.offset or 0, "endLine": getattr(e, "end_lineno", 0) or 0, "endCol": getattr(e, "end_offset", 0) or 0, "msg": e.msg, "kind": type(e).__name__})) except ValueError as e: print(json.dumps({"line": 1, "col": 0, "msg": str(e), "kind": "ValueError"})) ` // tool is one linter: it runs in the workspace and returns diagnostics // already limited to the user's source. type tool struct { name string // as in Diagnostic.Source, and its binary on PATH bin string run func(ctx context.Context, ws *workspace) []Diagnostic } var lintTools = map[string][]tool{ Cpp: {{"g++", "g++", lintGCC}, {"clang-tidy", "clang-tidy", lintTidy}}, Python: {{"python", "python3", lintPython}, {"ruff", "ruff", lintRuff}}, } // lint runs every linter for the language that is installed, at the same // time, and merges what they say. A missing tool is skipped: the solve // page lints less, it does not fail. func lint(ctx context.Context, req LintRequest) (LintResponse, error) { lang := languages[req.Lang] ws, err := newWorkspace(lang.source, req.Source, req.Files) if err != nil { return LintResponse{}, err } defer ws.remove() tools := lintTools[req.Lang] found := make([][]Diagnostic, len(tools)) var wg sync.WaitGroup for i, t := range tools { if _, err := exec.LookPath(t.bin); err != nil { continue } wg.Go(func() { found[i] = t.run(ctx, ws) }) } wg.Wait() // python3 is the authority on syntax: ruff's own syntax errors say the // same thing at the same place, so they go when python3 has run. if req.Lang == Python && found[0] != nil { var kept []Diagnostic for _, d := range found[1] { if d.Rule != "" { kept = append(kept, d) } } found[1] = kept } resp := LintResponse{Diagnostics: []Diagnostic{}} seen := map[string]bool{} for _, ds := range found { for _, d := range ds { key := strconv.Itoa(d.Line) + "\x00" + d.Message if !seen[key] { seen[key] = true resp.Diagnostics = append(resp.Diagnostics, d) } } } sort.SliceStable(resp.Diagnostics, func(i, j int) bool { a, b := resp.Diagnostics[i], resp.Diagnostics[j] if a.Line != b.Line { return a.Line < b.Line } return a.Col < b.Col }) return resp, nil } // runTool runs a linter in the workspace and returns its stdout and // stderr together. Linters get only the wall limit: what they parse is the // user's code, but they never run it. func runTool(ctx context.Context, ws *workspace, name string, args []string, stdin string) string { out := ws.capture(name + ".txt") o := proc{dir: ws.work, args: args, stdin: stdin, stdout: out, stderr: out, wall: lintTimeout}.run(ctx) if o.err != nil || o.timedOut { log.Printf("[lint] %s: err=%v timedOut=%v", name, o.err, o.timedOut) } text, _ := readCapped(out, compareCap) return text } // C++ // lintGCC asks g++ for its warnings with the build's flags. Plain text, // not GCC's JSON: GCC 16 dropped -fdiagnostics-format=json for SARIF, // while the image's GCC 14 has both, and the one-line-per-diagnostic text // is the same on every version. Byte columns, so a tab counts as one // column as it does in the editor. -O2 as in the build: the precompiled // header only matches the same optimization level, and some warnings // (maybe-uninitialized) only come with it. func lintGCC(ctx context.Context, ws *workspace) []Diagnostic { out := runTool(ctx, ws, "g++", withGCCPCH([]string{ "g++", "-fsyntax-only", "-fdiagnostics-plain-output", "-fdiagnostics-column-unit=byte", "-O2", "-std=c++17", "-Wall", "-Wextra", "-DLOCAL", "-I.", "main.cpp", }), "") return parseGCC(out) } var ( // main.cpp:3:20: warning: unused variable 'x' [-Wunused-variable] diagLine = regexp.MustCompile(`^(.+?):(\d+):(\d+): (fatal error|error|warning|note): (.*)$`) // main.cpp:8:12: required from here requiredFrom = regexp.MustCompile(`^main\.cpp:(\d+):(\d+):\s+required from`) trailingRule = regexp.MustCompile(`^(.*) \[([^\[\]]+)\]$`) ) // parseGCC keeps main.cpp's diagnostics. An error inside a header that // main.cpp's code caused (std::sort on ints) is reported where GCC says // the instantiation came from in main.cpp, once per place, since a single // bad call can set off a page of header errors. func parseGCC(out string) []Diagnostic { var ds []Diagnostic var from []int // the last "main.cpp:L:C: required from" seen blamed := map[[2]int]bool{} for _, line := range strings.Split(out, "\n") { if m := requiredFrom.FindStringSubmatch(line); m != nil { from = []int{atoi(m[1]), atoi(m[2])} continue } m := diagLine.FindStringSubmatch(line) if m == nil || m[4] == "note" { continue } msg, rule := splitRule(m[5]) rule = strings.TrimSuffix(strings.TrimPrefix(rule, "-W"), "=") if rule == "enabled by default" { rule = "" } d := Diagnostic{Line: atoi(m[2]), Col: atoi(m[3]), Severity: severity(m[4]), Message: msg, Source: "g++", Rule: rule} if m[1] != "main.cpp" { if d.Severity != "error" || from == nil || blamed[[2]int{from[0], from[1]}] { continue } blamed[[2]int{from[0], from[1]}] = true d.Line, d.Col = from[0], from[1] d.Message += " (in " + filepath.Base(m[1]) + ")" } from = nil ds = append(ds, d) } return ds } // lintTidy runs clang-tidy with the embedded checks. clang-tidy only // reports on the main file unless told otherwise, so headers are quiet. func lintTidy(ctx context.Context, ws *workspace) []Diagnostic { out := runTool(ctx, ws, "clang-tidy", append([]string{ "clang-tidy", "main.cpp", "--quiet", "--config=" + tidyConfig, "--", "-std=c++17", "-DLOCAL", "-I.", }, tidyPCH()...), "") main := filepath.Join(ws.work, "main.cpp") paths := map[string]bool{"main.cpp": true, main: true} if real, err := filepath.EvalSymlinks(main); err == nil { paths[real] = true } return parseTidy(out, paths) } // parseTidy keeps clang-tidy's own checks in the given file. Its // clang-diagnostic-* entries are clang's compiler errors, which g++ has // already reported in its own words. func parseTidy(out string, mainPaths map[string]bool) []Diagnostic { var ds []Diagnostic for _, line := range strings.Split(out, "\n") { m := diagLine.FindStringSubmatch(line) if m == nil || m[4] == "note" || !mainPaths[m[1]] { continue } msg, rule := splitRule(m[5]) if rule == "" || strings.HasPrefix(rule, "clang-diagnostic-") { continue } ds = append(ds, Diagnostic{Line: atoi(m[2]), Col: atoi(m[3]), Severity: severity(m[4]), Message: msg, Source: "clang-tidy", Rule: rule}) } return ds } // Python func lintPython(ctx context.Context, ws *workspace) []Diagnostic { out := runTool(ctx, ws, "python", []string{"python3", "-I", "-c", pySyntax}, "") ds := parsePySyntax(out) if ds == nil { ds = []Diagnostic{} // ran and found nothing, which lint tells from not running } return ds } func parsePySyntax(out string) []Diagnostic { var e struct { Line, Col, EndLine, EndCol int Msg, Kind string } if json.Unmarshal([]byte(strings.TrimSpace(out)), &e) != nil || e.Msg == "" { return nil } d := Diagnostic{Line: e.Line, Col: e.Col, Severity: "error", Message: e.Msg, Source: "python", Rule: e.Kind} if e.EndLine >= e.Line && e.EndCol > 0 { d.EndLine, d.EndCol = e.EndLine, e.EndCol } return []Diagnostic{d} } // lintRuff passes the source on stdin, --isolated so no config file found // above the temp directory changes the rules. func lintRuff(ctx context.Context, ws *workspace) []Diagnostic { out := runTool(ctx, ws, "ruff", []string{ "ruff", "check", "--isolated", "--no-cache", "--output-format=json", "--select", ruffRules, "--stdin-filename", "main.py", "-", }, filepath.Join(ws.work, "main.py")) ds, err := parseRuff(out) if err != nil { log.Printf("[lint] ruff: %v", err) } return ds } func parseRuff(out string) ([]Diagnostic, error) { var items []struct { Code *string `json:"code"` Message string `json:"message"` Location struct { Row, Column int } `json:"location"` End struct { Row, Column int } `json:"end_location"` } // Anything ruff prints besides the array (a warning) comes first. if i := strings.Index(out, "["); i > 0 { out = out[i:] } if err := json.Unmarshal([]byte(out), &items); err != nil { return nil, err } var ds []Diagnostic for _, it := range items { d := Diagnostic{ Line: it.Location.Row, Col: it.Location.Column, EndLine: it.End.Row, EndCol: it.End.Column, Severity: "warning", Message: it.Message, Source: "ruff", } if it.Code != nil { d.Rule = *it.Code } // A syntax error, or a name that will raise NameError when run. if d.Rule == "" || strings.HasPrefix(d.Rule, "E9") || d.Rule == "F821" || d.Rule == "F822" || d.Rule == "F823" { d.Severity = "error" } ds = append(ds, d) } return ds, nil } func splitRule(msg string) (string, string) { if m := trailingRule.FindStringSubmatch(msg); m != nil { return m[1], m[2] } return msg, "" } func severity(kind string) string { if strings.Contains(kind, "error") { return "error" } return "warning" } func atoi(s string) int { n, _ := strconv.Atoi(s) return n }