The editor's completion popup was on but empty for C++, since @codemirror/lang-cpp has no completion source. web/src/completions.js adds one: keywords, the STL, every name in the file (the template's macros show their expansion, typedefs what they alias), members after . and ->, and snippets for the loops and lambdas typed over and over. Python gains the contest standard library and members after ., on top of lang-python's builtins and local names. Nothing knows types, so members are the common ones plus those already used in the file. Evaluate (POST/GET /problems/<name>/evaluate) has Claude judge the editor's code as a strong competitive programmer would before submitting. It runs the saved tests on the runner first, as Submit does, and gives Claude the verdicts and up to three failing cases. The reply is a verdict, correctness, complexity against the constraints, line-anchored issues and a traced counterexample (internal/evaluate). The page shows it in an Evaluation tab of the results panel, marks the issues in the editor beside the lint's for as long as their lines are unchanged, and can load the counterexample as the custom input. It is a background job the page polls, like explanations, but it commits nothing: the code is a draft. explain.Jobs.StartWith keeps a finished job's answer in memory until the next one or a restart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
259 lines
12 KiB
JavaScript
259 lines
12 KiB
JavaScript
/**
|
|
* The solve page's autocomplete. CodeMirror's basicSetup already shows
|
|
* completions as you type, but @codemirror/lang-cpp offers none, and
|
|
* lang-python only keywords, builtins and the names defined in the file.
|
|
*
|
|
* Both languages get the library a contest solution reaches for, and
|
|
* member names after "." (and "->"), which neither language package does.
|
|
* Members are the common STL (or list/dict/str) ones plus every member
|
|
* already used in the file: without a type checker, that is as close as a
|
|
* completion can get to what the object actually has. C++ also gets every
|
|
* name in the file, so the template's macros and typedefs (F, takeI, ll)
|
|
* come up with what they expand to, and snippets for the loops and lambdas
|
|
* that are typed over and over.
|
|
*
|
|
* A real language server (clangd) would know types, but would have to run
|
|
* beside the code runner and hold a session open per editor; this is local
|
|
* and instant.
|
|
*/
|
|
import { completeFromList, ifNotIn, snippetCompletion as snip } from "@codemirror/autocomplete";
|
|
import { syntaxTree } from "@codemirror/language";
|
|
import { cppLanguage } from "@codemirror/lang-cpp";
|
|
import { pythonLanguage } from "@codemirror/lang-python";
|
|
|
|
// "a b c" as completions of one type, with a detail (the header).
|
|
const words = (list, type, detail) => list.trim().split(/\s+/).map((label) => ({ label, type, detail }));
|
|
|
|
// ---- C++ ----
|
|
|
|
const CPP_KEYWORDS = words(
|
|
`auto bool break case catch char class const constexpr continue default delete do double else enum explicit
|
|
extern false float for friend goto if inline int long mutable namespace new noexcept nullptr operator private
|
|
protected public return short signed sizeof static static_assert static_cast struct switch template this throw
|
|
true try typedef typename union unsigned using virtual void volatile while`,
|
|
"keyword",
|
|
);
|
|
|
|
const CPP_LIBRARY = [
|
|
...words(
|
|
"vector string array deque list map multimap set multiset unordered_map unordered_set unordered_multimap stack queue priority_queue bitset pair tuple optional function",
|
|
"type",
|
|
"std",
|
|
),
|
|
...words("int64_t uint64_t int32_t uint32_t size_t __int128", "type"),
|
|
...words("greater less hash", "class", "<functional>"),
|
|
...words("cin cout cerr endl", "variable", "<iostream>"),
|
|
...words("getline to_string stoi stoll stod freopen printf scanf puts", "function", "<string>/<cstdio>"),
|
|
...words(
|
|
`sort stable_sort reverse min max swap minmax lower_bound upper_bound equal_range binary_search unique fill
|
|
find find_if count count_if max_element min_element next_permutation prev_permutation nth_element
|
|
partial_sort rotate all_of any_of none_of transform copy remove remove_if shuffle`,
|
|
"function",
|
|
"<algorithm>",
|
|
),
|
|
...words("accumulate iota partial_sum adjacent_difference gcd lcm", "function", "<numeric>"),
|
|
...words("abs sqrt sqrtl cbrt pow exp log log2 log10 floor ceil round hypot", "function", "<cmath>"),
|
|
...words("make_pair make_tuple tie get move distance next prev advance begin end", "function", "std"),
|
|
...words("memset memcpy strlen", "function", "<cstring>"),
|
|
...words(
|
|
"__builtin_popcount __builtin_popcountll __builtin_clz __builtin_clzll __builtin_ctz __builtin_ctzll __lg",
|
|
"function",
|
|
"builtin",
|
|
),
|
|
...words("INT_MAX INT_MIN LLONG_MAX LLONG_MIN UINT_MAX", "constant", "<climits>"),
|
|
{ label: "numeric_limits", type: "class", detail: "<limits>" },
|
|
{ label: "mt19937", type: "class", detail: "<random>" },
|
|
{ label: "chrono", type: "namespace" },
|
|
{ label: "std", type: "namespace" },
|
|
];
|
|
|
|
// Nothing knows the object's type, so the members used most come first.
|
|
const COMMON_MEMBERS = new Set(["push_back", "size", "begin", "end", "first", "second", "back", "pop_back", "insert", "count"]);
|
|
const CPP_MEMBERS = words(
|
|
`push_back emplace_back pop_back push_front emplace_front pop_front back front size empty clear begin end
|
|
rbegin rend insert emplace erase find count lower_bound upper_bound resize reserve assign at data swap
|
|
push pop top first second substr length append c_str compare set reset flip test any none all to_string
|
|
to_ullong value has_value`,
|
|
"method",
|
|
).map((c) => (COMMON_MEMBERS.has(c.label) ? { ...c, boost: 1 } : c));
|
|
|
|
// The template's habits, as snippets. Same-named fields are edited
|
|
// together, so typing the loop variable once fills in all three.
|
|
const CPP_SNIPPETS = [
|
|
snip("for (int ${i} = 0; ${i} < ${n}; ${i}++) {\n\t${}\n}", { label: "for", detail: "loop", type: "keyword" }),
|
|
snip("for (int ${i} = ${n} - 1; ${i} >= 0; ${i}--) {\n\t${}\n}", { label: "forr", detail: "loop down", type: "keyword" }),
|
|
snip("for (auto &${x} : ${v}) {\n\t${}\n}", { label: "foreach", detail: "range loop", type: "keyword" }),
|
|
snip("while (${}) {\n\t${}\n}", { label: "while", detail: "loop", type: "keyword" }),
|
|
snip("if (${}) {\n\t${}\n}", { label: "if", detail: "block", type: "keyword" }),
|
|
snip("if (${}) {\n\t${}\n} else {\n\t${}\n}", { label: "ifelse", detail: "block", type: "keyword" }),
|
|
snip("struct ${Name} {\n\t${}\n};", { label: "struct", detail: "definition", type: "keyword" }),
|
|
snip("auto ${f} = [&](${}) {\n\t${}\n};", { label: "lambda", detail: "[&] lambda", type: "keyword" }),
|
|
snip("function<void(int)> ${dfs} = [&](int ${u}) {\n\t${}\n};", {
|
|
label: "dfs",
|
|
detail: "recursive lambda",
|
|
type: "keyword",
|
|
}),
|
|
snip("sort(${a}.begin(), ${a}.end(), [&](const auto &${x}, const auto &${y}) {\n\treturn ${};\n});", {
|
|
label: "sortby",
|
|
detail: "sort with a comparator",
|
|
type: "keyword",
|
|
}),
|
|
];
|
|
|
|
// A keyword with a snippet of the same name would hide it behind a plain
|
|
// word, so the snippet stands in for it.
|
|
const SNIPPED = new Set(CPP_SNIPPETS.map((c) => c.label));
|
|
const CPP_FIXED = [...CPP_KEYWORDS.filter((c) => !SNIPPED.has(c.label)), ...CPP_LIBRARY, ...CPP_SNIPPETS];
|
|
const CPP_FIXED_LABELS = new Set(CPP_FIXED.map((c) => c.label));
|
|
|
|
// Comments, strings and #include <...> get no completions.
|
|
const CPP_SKIP = new Set(["LineComment", "BlockComment", "String", "RawString", "CharLiteral", "SystemLibString"]);
|
|
const CPP_NAMES = new Set(["Identifier", "TypeIdentifier", "NamespaceIdentifier"]);
|
|
|
|
// "#define F(i, L, R) for (...)": a macro, shown with its parameters and
|
|
// what it expands to.
|
|
const DEFINE = /^[ \t]*#[ \t]*define[ \t]+([A-Za-z_]\w*)(\([^)]*\))?/dgm;
|
|
// "typedef long long ll;" and "using vi = vector<int>;"
|
|
const ALIAS = /\btypedef\s+([^;]+?)\s+([A-Za-z_]\w*)\s*;|\busing\s+([A-Za-z_]\w*)\s*=\s*([^;]+);/g;
|
|
|
|
function brief(s) {
|
|
s = s.replace(/\s+/g, " ").trim();
|
|
return s.length > 48 ? s.slice(0, 47) + "…" : s;
|
|
}
|
|
|
|
// A macro's body: the rest of its line, and the next while a line ends in
|
|
// a backslash.
|
|
function macroBody(text, at) {
|
|
let body = "";
|
|
for (;;) {
|
|
const end = text.indexOf("\n", at);
|
|
const line = text.slice(at, end < 0 ? text.length : end);
|
|
if (!line.endsWith("\\") || end < 0) return body + line;
|
|
body += line.slice(0, -1) + " ";
|
|
at = end + 1;
|
|
}
|
|
}
|
|
|
|
// The file's own names, leaving out the word being typed (at skipFrom):
|
|
// otherwise every half-typed name would complete to itself.
|
|
function cppFileNames(state, skipFrom) {
|
|
const text = state.doc.toString();
|
|
const out = new Map();
|
|
for (const m of text.matchAll(DEFINE)) {
|
|
if (m.indices[1][0] === skipFrom) continue;
|
|
const body = brief(macroBody(text, m.index + m[0].length));
|
|
// The template defines DBG twice, the #else one empty: keep the one
|
|
// that says something.
|
|
if (!body && out.has(m[1])) continue;
|
|
out.set(m[1], {
|
|
label: m[1],
|
|
type: m[2] ? "function" : "constant",
|
|
detail: m[2] ? m[2].replace(/\s+/g, "") : undefined,
|
|
info: body || undefined,
|
|
boost: 2,
|
|
});
|
|
}
|
|
for (const m of text.matchAll(ALIAS)) {
|
|
const [name, to] = m[2] ? [m[2], m[1]] : [m[3], m[4]];
|
|
if (!out.has(name)) out.set(name, { label: name, type: "type", detail: brief(to), boost: 2 });
|
|
}
|
|
syntaxTree(state).iterate({
|
|
enter(n) {
|
|
if (CPP_SKIP.has(n.name)) return false;
|
|
if (!CPP_NAMES.has(n.name) || n.from === skipFrom) return;
|
|
const name = text.slice(n.from, n.to);
|
|
if (name.length < 2 || out.has(name) || CPP_FIXED_LABELS.has(name)) return;
|
|
out.set(name, { label: name, type: n.name === "TypeIdentifier" ? "type" : "variable", boost: 1 });
|
|
},
|
|
});
|
|
return [...out.values()];
|
|
}
|
|
|
|
// Members already used in the file (x.first, it->second, seg.query).
|
|
function fileMembers(state, nodeName, skipFrom, known) {
|
|
const out = [];
|
|
const seen = new Set(known);
|
|
syntaxTree(state).iterate({
|
|
enter(n) {
|
|
if (n.name !== nodeName || n.from === skipFrom) return;
|
|
const name = state.sliceDoc(n.from, n.to);
|
|
if (seen.has(name)) return;
|
|
seen.add(name);
|
|
out.push({ label: name, type: "property" });
|
|
},
|
|
});
|
|
return out;
|
|
}
|
|
|
|
const CPP_MEMBER_LABELS = CPP_MEMBERS.map((c) => c.label);
|
|
|
|
// Whether the word at from follows a member access: "." but not the one in
|
|
// "1." (a number), and in C++ "->" too.
|
|
function afterMember(state, from, arrow) {
|
|
const text = state.sliceDoc(Math.max(0, from - 32), from);
|
|
if (arrow && text.endsWith("->")) return true;
|
|
return text.endsWith(".") && !/(^|[^\w])\d+\.$/.test(text);
|
|
}
|
|
|
|
function cppSource(context) {
|
|
const node = syntaxTree(context.state).resolveInner(context.pos, -1);
|
|
for (let n = node; n; n = n.parent) if (CPP_SKIP.has(n.name)) return null;
|
|
const word = context.matchBefore(/[A-Za-z_]\w*/);
|
|
const from = word ? word.from : context.pos;
|
|
if (afterMember(context.state, from, true)) {
|
|
return {
|
|
from,
|
|
options: [...CPP_MEMBERS, ...fileMembers(context.state, "FieldIdentifier", from, CPP_MEMBER_LABELS)],
|
|
validFor: /^\w*$/,
|
|
};
|
|
}
|
|
if (!word && !context.explicit) return null;
|
|
return { from, options: [...cppFileNames(context.state, from), ...CPP_FIXED], validFor: /^\w*$/ };
|
|
}
|
|
|
|
export const cppCompletions = () => cppLanguage.data.of({ autocomplete: cppSource });
|
|
|
|
// ---- Python ----
|
|
|
|
// The standard library a contest solution imports from. lang-python
|
|
// already completes builtins and the file's own names, and has its own
|
|
// def/for/class snippets.
|
|
const PY_LIBRARY = [
|
|
...words("defaultdict Counter deque OrderedDict", "class", "collections"),
|
|
...words("heappush heappop heapify heappushpop nlargest nsmallest", "function", "heapq"),
|
|
...words("bisect_left bisect_right insort", "function", "bisect"),
|
|
...words("lru_cache cache cmp_to_key reduce", "function", "functools"),
|
|
...words("accumulate permutations combinations combinations_with_replacement product groupby pairwise", "function", "itertools"),
|
|
...words("gcd lcm isqrt comb perm inf sqrt log2 ceil floor", "function", "math"),
|
|
...words("setrecursionlimit stdin stdout", "function", "sys"),
|
|
snip("sys.setrecursionlimit(${10 ** 6})", { label: "recursionlimit", detail: "sys", type: "keyword" }),
|
|
];
|
|
|
|
const PY_MEMBERS = words(
|
|
`append extend insert pop remove clear sort reverse index count copy keys values items get setdefault update
|
|
add discard union intersection difference split join strip lstrip rstrip startswith endswith replace find
|
|
lower upper isdigit appendleft popleft most_common read readline buffer`,
|
|
"method",
|
|
);
|
|
const PY_MEMBER_LABELS = PY_MEMBERS.map((c) => c.label);
|
|
|
|
const pyLibrary = completeFromList(PY_LIBRARY);
|
|
|
|
function pySource(context) {
|
|
const word = context.matchBefore(/[A-Za-z_]\w*/);
|
|
const from = word ? word.from : context.pos;
|
|
if (afterMember(context.state, from, false)) {
|
|
return {
|
|
from,
|
|
options: [...PY_MEMBERS, ...fileMembers(context.state, "PropertyName", from, PY_MEMBER_LABELS)],
|
|
validFor: /^\w*$/,
|
|
};
|
|
}
|
|
// lang-python leaves property names alone; everywhere else the library
|
|
// joins its builtins.
|
|
return pyLibrary(context);
|
|
}
|
|
|
|
export const pythonCompletions = () =>
|
|
pythonLanguage.data.of({ autocomplete: ifNotIn(["String", "FormatString", "Comment"], pySource) });
|