File size: 10,156 Bytes
fb2916f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""Deterministic offline verdict model.

The server never executes guest source code, in any language, under any
identity. A submission is graded by a fixed, ordered set of rules applied to
the submitted text, while the *expected* output of each test case is produced
by this repository's own reference implementations
(:mod:`leetcode_app.content`).

Rule order, applied to the comment-stripped source:

1. blank source                      -> Compile Error
2. required entry point missing      -> Compile Error
3. source still equals the starter   -> Wrong Answer, no output produced
4. no result-producing statement     -> Wrong Answer, no output produced
5. no token of the question's method -> Wrong Answer at the first case
6. otherwise                         -> Accepted

Everything derived from the source (verdict, runtime, memory, the failing
case) is a pure function of ``(question, language, source, cases)``: the same
submission always produces the same result.
"""

from __future__ import annotations

import hashlib
import json
import re
from dataclasses import dataclass, field
from typing import Any

from . import content
from .content import Question


ACCEPTED = "Accepted"
WRONG_ANSWER = "Wrong Answer"
COMPILE_ERROR = "Compile Error"
RUNTIME_ERROR = "Runtime Error"

# A statement that produces the answer, per language.
RESULT_TOKENS: dict[str, tuple[str, ...]] = {
    "python3": ("return",),
    "pandas": ("return",),
    "cpp": ("return",),
    "java": ("return",),
    "javascript": ("return",),
    "mysql": ("select",),
    "bash": ("sed", "awk", "head", "tail", "cat", "nl", "echo", "sort", "printf"),
}

# The declaration a compiler needs to find, per language.
ENTRY_MARKERS: dict[str, tuple[str, ...]] = {
    "python3": ("class solution", "def "),
    "pandas": ("def ",),
    "cpp": ("class solution",),
    "java": ("class solution",),
    "javascript": ("var ", "function", "const ", "let "),
    "mysql": ("select",),
    "bash": (),
}

ENTRY_MESSAGES: dict[str, str] = {
    "python3": "NameError: name 'Solution' is not defined",
    "pandas": "NameError: the required function is not defined",
    "cpp": "error: 'Solution' was not declared in this scope",
    "java": "error: cannot find symbol: class Solution",
    "javascript": "ReferenceError: the required function is not defined",
    "mysql": "You have an error in your SQL syntax",
    "bash": "command not found",
}

_LINE_COMMENTS: dict[str, tuple[str, ...]] = {
    "python3": ("#",),
    "pandas": ("#",),
    "bash": ("#",),
    "mysql": ("--", "#"),
    "cpp": ("//",),
    "java": ("//",),
    "javascript": ("//",),
}

_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
_SQL_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.DOTALL)
_WHITESPACE = re.compile(r"\s+")


class CaseInputError(ValueError):
    """A test case could not be read as input for this question."""


@dataclass
class CaseResult:
    index: int
    input: str
    output: str | None
    expected: str
    passed: bool
    executed: bool = True

    def as_dict(self) -> dict[str, Any]:
        return {
            "index": self.index,
            "input": self.input,
            "output": self.output,
            "expected": self.expected,
            "passed": self.passed,
            "executed": self.executed,
        }


@dataclass
class Verdict:
    status: str
    message: str = ""
    cases: list[CaseResult] = field(default_factory=list)
    runtime_ms: int | None = None
    memory_mb: float | None = None
    runtime_percentile: float | None = None
    memory_percentile: float | None = None

    @property
    def passed(self) -> int:
        return sum(1 for case in self.cases if case.passed)

    @property
    def total(self) -> int:
        return len(self.cases)

    @property
    def failing(self) -> CaseResult | None:
        for case in self.cases:
            if not case.passed:
                return case
        return None

    def as_dict(self) -> dict[str, Any]:
        failing = self.failing
        return {
            "status": self.status,
            "message": self.message,
            "passed": self.passed,
            "total": self.total,
            "runtime_ms": self.runtime_ms,
            "memory_mb": self.memory_mb,
            "runtime_percentile": self.runtime_percentile,
            "memory_percentile": self.memory_percentile,
            "cases": [case.as_dict() for case in self.cases],
            "failing": failing.as_dict() if failing is not None else None,
        }


def strip_comments(source: str, language: str) -> str:
    text = source
    if language in {"cpp", "java", "javascript"}:
        text = _BLOCK_COMMENT.sub(" ", text)
    if language == "mysql":
        text = _SQL_BLOCK_COMMENT.sub(" ", text)
    markers = _LINE_COMMENTS.get(language, ("#",))
    lines: list[str] = []
    for line in text.splitlines():
        cut = len(line)
        for marker in markers:
            position = line.find(marker)
            if position != -1:
                cut = min(cut, position)
        lines.append(line[:cut])
    return "\n".join(lines)


def normalize(source: str) -> str:
    return _WHITESPACE.sub(" ", source).strip()


def _digest(question: Question, language: str, source: str) -> bytes:
    payload = f"{question.slug}\0{language}\0{normalize(source)}".encode("utf-8")
    return hashlib.sha256(payload).digest()


def _performance(question: Question, language: str, source: str) -> dict[str, Any]:
    """Deterministic runtime/memory figures derived from the submission."""

    digest = _digest(question, language, source)
    runtime_ms = digest[0] % 90
    memory_mb = 15.0 + (digest[1] % 60) / 10
    runtime_percentile = round(20.0 + (digest[2] % 790) / 10, 2)
    memory_percentile = round(20.0 + (digest[3] % 790) / 10, 2)
    return {
        "runtime_ms": runtime_ms,
        "memory_mb": round(memory_mb, 2),
        "runtime_percentile": runtime_percentile,
        "memory_percentile": memory_percentile,
    }


def expected_output(question: Question, raw_case: str) -> str:
    """Expected output for one case, from this repository's own reference."""

    fixed = question.fixed_expected.get(raw_case.strip())
    if fixed is not None:
        return fixed
    reference = content.REFERENCES.get(question.slug)
    if reference is None:
        raise CaseInputError(
            "This question runs against its own fixed data set."
        )
    try:
        arguments = content.parse_case(raw_case)
    except (json.JSONDecodeError, ValueError) as error:
        raise CaseInputError(f"The test case could not be read: {error}") from error
    if not arguments:
        raise CaseInputError("The test case is empty.")
    try:
        return content.format_expected(reference(*arguments))
    except TypeError as error:
        raise CaseInputError(
            "The test case does not match this question's input format."
        ) from error
    except (IndexError, KeyError, ValueError, ZeroDivisionError) as error:
        raise CaseInputError(f"The test case could not be evaluated: {error}") from error


def _entry_markers(question: Question, language: str) -> tuple[str, ...]:
    override = question.entry_markers.get(language)
    if override is not None:
        return override
    return ENTRY_MARKERS.get(language, ())


def classify(question: Question, language: str, source: str) -> tuple[str, str]:
    """Return ``(status, message)`` for the submission's source alone."""

    stripped = strip_comments(source, language)
    if not stripped.strip():
        return COMPILE_ERROR, "error: the submission is empty"
    lowered = stripped.casefold()
    for marker in _entry_markers(question, language):
        if marker not in lowered:
            return COMPILE_ERROR, ENTRY_MESSAGES.get(language, "error: compile failed")
    starter = question.starter.get(language, "")
    if normalize(strip_comments(starter, language)) == normalize(stripped):
        return WRONG_ANSWER, "The starter code does not produce an answer yet."
    result_tokens = RESULT_TOKENS.get(language, ("return",))
    if not any(token in lowered for token in result_tokens):
        return WRONG_ANSWER, "The submission never produces a result."
    if not any(token in lowered for token in question.technique_tokens):
        return WRONG_ANSWER, ""
    return ACCEPTED, ""


def evaluate(
    question: Question,
    language: str,
    source: str,
    cases: list[str],
) -> Verdict:
    """Grade ``source`` against ``cases`` and return the verdict."""

    status, message = classify(question, language, source)
    results: list[CaseResult] = []
    produce_output = status == ACCEPTED
    failing_index = 0 if status == WRONG_ANSWER else -1
    for index, raw_case in enumerate(cases):
        try:
            expected = expected_output(question, raw_case)
        except CaseInputError as error:
            return Verdict(status=RUNTIME_ERROR, message=str(error), cases=[])
        output: str | None
        if produce_output:
            output, passed, executed = expected, True, True
        elif status == COMPILE_ERROR:
            output, passed, executed = None, False, False
        elif index == failing_index:
            output = None if message else question.wrong_output
            passed, executed = False, True
        else:
            # Execution stops at the first case that does not match.
            output, passed, executed = None, False, False
        results.append(
            CaseResult(
                index=index,
                input=raw_case,
                output=output,
                expected=expected,
                passed=passed,
                executed=executed,
            )
        )
    verdict = Verdict(status=status, message=message, cases=results)
    if status == ACCEPTED:
        for key, value in _performance(question, language, source).items():
            setattr(verdict, key, value)
    elif status == WRONG_ANSWER:
        performance = _performance(question, language, source)
        verdict.runtime_ms = performance["runtime_ms"]
        verdict.memory_mb = performance["memory_mb"]
    return verdict