Files

163 lines
4.9 KiB
Go

// Package checker compares the output of a sandboxed program with the expected
// output of a test.
//
// A checker is selected by a Spec. Kinds that need parameters, such as a float
// tolerance, add fields to Spec; kinds that need to run code, such as a custom
// checker program, implement Checker with their own sandbox and use the
// context and the error result for cancellation and infrastructure failures.
package checker
import (
"bytes"
"context"
"errors"
"fmt"
"math"
"strconv"
)
// Kind names a comparison rule of the runner contract.
type Kind string
const (
// Exact accepts texts that are equal after line-ending and trailing
// whitespace normalization.
Exact Kind = "exact"
// Tokens accepts texts with the same sequence of whitespace-separated
// tokens.
Tokens Kind = "tokens"
// Numbers compares tokens like Tokens, but numeric tokens are equal
// within an absolute or a relative tolerance.
Numbers Kind = "numbers"
// Custom runs a checker program of the task family in the sandbox.
Custom Kind = "custom"
)
// ErrNeedsSandbox reports a kind that the judge builds with its sandbox.
var ErrNeedsSandbox = errors.New("checker.New - this checker kind runs in the sandbox")
// Spec selects and parameterizes a checker.
type Spec struct {
Kind Kind `json:"kind"`
// AbsTolerance and RelTolerance parameterize Numbers.
AbsTolerance float64 `json:"abs_tolerance,omitempty"`
RelTolerance float64 `json:"rel_tolerance,omitempty"`
// Program is the checker program of Custom.
Program *Program `json:"program,omitempty"`
}
// Program is the source of a custom checker. It reads the files input,
// expected, and actual, whose paths are its arguments, and exits with 0 to
// accept, 1 to reject, and any other status when it fails itself.
type Program struct {
Language string `json:"language"`
Source string `json:"source"`
}
// Input is everything a checker may look at for one test.
type Input struct {
TestInput []byte
Expected []byte
Actual []byte
}
// Checker decides whether the actual output of a test is accepted.
type Checker interface {
// Check reports whether the output is accepted. An error means that the
// checker itself failed, not that the output is wrong.
Check(ctx context.Context, input Input) (bool, error)
}
// New returns the checker for spec.
func New(spec Spec) (Checker, error) {
switch spec.Kind {
case Exact:
return exactChecker{}, nil
case Tokens:
return tokensChecker{}, nil
case Numbers:
if spec.AbsTolerance < 0 || spec.RelTolerance < 0 || spec.AbsTolerance == 0 && spec.RelTolerance == 0 {
return nil, errors.New("checker.New - numbers needs a positive tolerance")
}
return numbersChecker{absolute: spec.AbsTolerance, relative: spec.RelTolerance}, nil
case Custom:
return nil, ErrNeedsSandbox
default:
return nil, fmt.Errorf("checker.New - unknown kind %q", spec.Kind)
}
}
type exactChecker struct{}
func (exactChecker) Check(_ context.Context, input Input) (bool, error) {
return bytes.Equal(normalizeLines(input.Expected), normalizeLines(input.Actual)), nil
}
type tokensChecker struct{}
func (tokensChecker) Check(_ context.Context, input Input) (bool, error) {
expected := bytes.Fields(input.Expected)
actual := bytes.Fields(input.Actual)
if len(expected) != len(actual) {
return false, nil
}
for index := range expected {
if !bytes.Equal(expected[index], actual[index]) {
return false, nil
}
}
return true, nil
}
type numbersChecker struct {
absolute float64
relative float64
}
func (c numbersChecker) Check(_ context.Context, input Input) (bool, error) {
expected := bytes.Fields(input.Expected)
actual := bytes.Fields(input.Actual)
if len(expected) != len(actual) {
return false, nil
}
for index := range expected {
if !c.tokensMatch(expected[index], actual[index]) {
return false, nil
}
}
return true, nil
}
// tokensMatch compares two finite numbers within the tolerance and any
// other tokens exactly.
func (c numbersChecker) tokensMatch(expected, actual []byte) bool {
if bytes.Equal(expected, actual) {
return true
}
want, wantErr := strconv.ParseFloat(string(expected), 64)
got, gotErr := strconv.ParseFloat(string(actual), 64)
if wantErr != nil || gotErr != nil || !finite(want) || !finite(got) {
return false
}
difference := math.Abs(got - want)
return difference <= c.absolute || difference <= c.relative*math.Abs(want)
}
func finite(value float64) bool {
return !math.IsNaN(value) && !math.IsInf(value, 0)
}
// normalizeLines replaces CRLF with LF, removes spaces and tabs at the end of
// every line, and removes trailing empty lines.
func normalizeLines(text []byte) []byte {
lines := bytes.Split(bytes.ReplaceAll(text, []byte("\r\n"), []byte("\n")), []byte("\n"))
for index, line := range lines {
lines[index] = bytes.TrimRight(line, " \t")
}
last := len(lines)
for last > 0 && len(lines[last-1]) == 0 {
last--
}
return bytes.Join(lines[:last], []byte("\n"))
}