Files
adamfandClaude Opus 5.5 ccf4e4dd74
Test and publish the site / test (push) Successful in 1m19s
Test and publish the site / publish (push) Successful in 1m31s
Explain concepts on the site, and reuse their code from the CLI
/usaco/concepts is a library of techniques Claude explained: the admin
asks by topic ("help explain fenwick trees") or pastes code they could
not follow, and gets an intuitive explanation with SVG diagrams plus a
C++ snippet in contest style. Given code, the walkthrough traces that
code and the snippet is a general version of it. Anyone can read the
library; generating, rewriting and deleting are admin-only.

Each concept is committed as concepts/<slug>/: concept.md (tags in a
header comment, then a # title), snippet.cpp (first line
"// concept: <slug>") and request.md (the question, for rewrites). The
slug is Claude's to pick, so a new concept's job is keyed by an id and
returns {slug} as its result; a taken slug gets -2, -3... rather than
overwriting. Rewriting starts from the saved question and version plus
a note on what to change. The index reads concepts into Index.Concepts,
with their date from git.

internal/concept shares explain's math and diagram rules, now split out
as explain.MathRules and explain.DiagramRules; the explain prompt is
byte-for-byte unchanged. Code fences in explanations are highlighted
with the same highlight.js setup as CodeBlock (web/src/highlight.js).

`usaco snippet` lists concepts, prints one's snippet, or pastes it into
a solution above main (or class Solution), keeping a .bak and refusing
a concept the file already has. In interactive mode it pastes into the
selection.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 12:58:38 +01:00

271 lines
10 KiB
Bash

# common.sh - shared helpers for usaco commands (sourced, not executed)
# Expects ROOT to be set by the dispatcher.
# -DLOCAL turns on the template's debugging.h include and DBG macros (judges don't define it)
CXXFLAGS=(-O2 -std=c++17 -Wall -Wextra -DLOCAL -I"$ROOT")
# --debug (or USACO_DEBUG=1): catch out-of-bounds, overflow and UB at runtime
DEBUG_CXXFLAGS=(-g -O1 -fsanitize=address,undefined -fno-omit-frame-pointer -D_GLIBCXX_DEBUG)
RUSTCFLAGS=(-O --edition 2021)
# --debug for rust: debug info, plus the overflow and debug_assert! checks -O drops
DEBUG_RUSTCFLAGS=(-g --edition 2021 -C debug-assertions -C overflow-checks)
# ----- languages -----
# A problem's language is just whichever source file it has: main.cpp or main.rs.
LANGS="cpp rust"
default_lang() { # language 'usaco new' uses when no flag is given
local l="${USACO_LANG:-}"
[[ -z "$l" && -r "$ROOT/.lang" ]] && l="$(<"$ROOT/.lang")"
normalize_lang "${l:-cpp}" 2>/dev/null || echo cpp
}
normalize_lang() { # accepts cpp/c++/cc/rust/rs, echoes cpp|rust
case "${1,,}" in
cpp|c++|cc|cxx) echo cpp ;;
rust|rs) echo rust ;;
*) echo "Error: unknown language '$1' (use cpp or rust)" >&2; return 1 ;;
esac
}
src_name() { [[ "$1" == rust ]] && echo main.rs || echo main.cpp; }
lang_of() { # $1 = problem dir; echoes cpp|rust
if [[ -f "$1/main.rs" ]]; then echo rust
elif [[ -f "$1/main.cpp" ]]; then echo cpp
else echo "Error: no main.cpp or main.rs in $1" >&2; return 1; fi
}
main_file() { # $1 = problem dir; echoes the path of its source file
local l; l="$(lang_of "$1")" || return 1
echo "$1/$(src_name "$l")"
}
find_problem() { # echoes dir of problem in solving/, solved/, or skipped/; unique prefix ok
local name="$1" s d matches=()
for s in solving solved skipped; do
if [[ -d "$ROOT/$s/$name" ]]; then echo "$ROOT/$s/$name"; return 0; fi
done
for s in solving solved skipped; do
for d in "$ROOT/$s/$name"*/; do
[[ -d "$d" ]] && matches+=("${d%/}")
done
done
if [[ ${#matches[@]} -eq 1 ]]; then echo "${matches[0]}"; return 0; fi
if [[ ${#matches[@]} -gt 1 ]]; then
echo "Error: '$name' is ambiguous:" >&2
printf ' %s\n' "${matches[@]#$ROOT/}" >&2
return 1
fi
echo "Error: problem '$name' not found in solving/, solved/, or skipped/" >&2
return 1
}
find_concept() { # echoes dir of concepts/<slug>; unique prefix ok
local name="$1" d matches=()
if [[ -d "$ROOT/concepts/$name" ]]; then echo "$ROOT/concepts/$name"; return 0; fi
for d in "$ROOT/concepts/$name"*/; do
[[ -d "$d" ]] && matches+=("${d%/}")
done
if [[ ${#matches[@]} -eq 1 ]]; then echo "${matches[0]}"; return 0; fi
if [[ ${#matches[@]} -gt 1 ]]; then
echo "Error: '$name' is ambiguous:" >&2
printf ' %s\n' "${matches[@]#$ROOT/}" >&2
return 1
fi
echo "Error: concept '$name' not found in concepts/ (try 'usaco sync')" >&2
return 1
}
concept_title() { # $1 = concept dir: echoes the "# " title of its concept.md, if any
[[ -f "$1/concept.md" ]] || return 0
sed -n 's/^# //p' "$1/concept.md" | head -n 1
}
# ----- rust project model (for rust-analyzer / clippy) -----
# Problems are bare main.rs files with no manifest, and rust-analyzer only does
# real analysis -- type-aware diagnostics, clippy on save -- inside a cargo
# project. So we generate one package at the root that declares every rust
# solution (and template.rs) as its own [[bin]] target. Nothing builds through cargo: 'usaco
# build/run' still shells out to rustc. The manifest exists purely so the editor
# has something to chew on, which is why it's gitignored and regenerated from a
# directory scan (that also prunes problems that moved or went away).
#
# To change which lints fire, edit the [lints.clippy] table below.
sync_cargo_manifest() {
local s d name entry count=0 bins=""
for s in solving solved skipped; do
[[ -d "$ROOT/$s" ]] || continue
for d in "$ROOT/$s"/*/; do
[[ -f "${d}main.rs" ]] || continue
# Target names can't start with a digit, and problems like '101'
# do; the directory prefix keeps them legal and unique.
name="$s-$(basename "$d")"
printf -v entry '[[bin]]\nname = "%s"\npath = "%smain.rs"\n\n' "$name" "${d#"$ROOT"/}"
bins+="$entry"
count=$((count + 1))
done
done
# template.rs is a target too, so mistakes in it surface in the editor and
# in 'usaco lint template' instead of in every problem stamped out from it.
# Its name has no directory prefix, so it can't collide with a problem.
if [[ -f "$ROOT/template.rs" ]]; then
bins+=$'[[bin]]\nname = "template"\npath = "template.rs"\n\n'
fi
if [[ -z "$bins" ]]; then
rm -f "$ROOT/Cargo.toml"
return 0
fi
cat > "$ROOT/Cargo.toml" <<EOF
# GENERATED by 'usaco lint' -- edits here are lost. See sync_cargo_manifest()
# in lib/common.sh. This file only exists so rust-analyzer can analyse the
# solutions and run clippy on them; builds go through rustc, not cargo.
[package]
name = "usaco"
version = "0.0.0"
edition = "2021"
autobins = false
[lints.clippy]
pedantic = { level = "warn", priority = -1 }
# Casts between usize/i32/i64 are the bread and butter of competitive
# programming. Warning on each one buries the lints that find actual bugs.
cast_possible_truncation = "allow"
cast_possible_wrap = "allow"
cast_sign_loss = "allow"
cast_precision_loss = "allow"
# Library-API hygiene, meaningless for a single-file solution.
missing_panics_doc = "allow"
missing_errors_doc = "allow"
must_use_candidate = "allow"
doc_markdown = "allow"
# '|x| x.to_string()' reads better than the spelled-out method path.
redundant_closure_for_method_calls = "allow"
${bins%$'\n'}
EOF
printf '%s\n' "$count"
}
build_problem() { # $1 = problem dir; compiles to $1/main whatever the language
local dir="$1" lang
lang="$(lang_of "$dir")" || return 1
if [[ -n "${USACO_DEBUG:-}" ]]; then
echo "${DIM}(debug build: $([[ $lang == cpp ]] && echo sanitizers || echo overflow checks) on)${RST}" >&2
fi
case "$lang" in
cpp)
if [[ -n "${USACO_DEBUG:-}" ]]; then
g++ "${CXXFLAGS[@]}" "${DEBUG_CXXFLAGS[@]}" "$dir/main.cpp" -o "$dir/main"
else
g++ "${CXXFLAGS[@]}" "$dir/main.cpp" -o "$dir/main"
fi
;;
rust)
# Keep the editor's project model in step with what's on disk.
sync_cargo_manifest >/dev/null
if [[ -n "${USACO_DEBUG:-}" ]]; then
rustc "${DEBUG_RUSTCFLAGS[@]}" "$dir/main.rs" -o "$dir/main"
else
rustc "${RUSTCFLAGS[@]}" "$dir/main.rs" -o "$dir/main"
fi
;;
esac
}
detect_io() { # echoes the io basename (first *.in in $1), or nothing
local f
for f in "$1"/*.in; do [[ -e "$f" ]] && basename "$f" .in && return 0; done
return 1
}
last_touched() { # $1 = problem dir: epoch of its last change
# uncommitted work counts as "now"-ish (newest mtime); otherwise the last commit.
# File mtimes alone are useless here: every checkout/pull resets them.
local t
if [[ -n "$(git -C "$ROOT" status --porcelain -- "$1" 2>/dev/null)" ]]; then
find "$1" -type f -printf '%T@\n' | sort -n | tail -1 | cut -d. -f1
elif t="$(git -C "$ROOT" log -1 --format=%ct -- "$1" 2>/dev/null)" && [[ -n "$t" ]]; then
echo "$t"
else
find "$1" -type f -printf '%T@\n' | sort -n | tail -1 | cut -d. -f1
fi
}
solved_at() { # $1 = solved/<name> dir: epoch it (last) entered solved/
local t
t="$(git -C "$ROOT" log -1 --diff-filter=A --format=%ct -- "$1" 2>/dev/null)"
[[ -n "$t" ]] && echo "$t" || last_touched "$1"
}
fresh_main() { # $1 = problem dir, $2 = io name, [$3 = language]: source from template, io wired up
local dir="$1" io="$2" lang="${3:-}"
[[ -n "$lang" ]] || lang="$(lang_of "$dir")" || return 1
case "$lang" in
cpp) sed "s/^int main() {$/int main() {\n STDIO(\"$io\");/" "$ROOT/template.cpp" > "$dir/main.cpp" ;;
rust) sed "s/stdio(\"[^\"]*\")/stdio(\"$io\")/" "$ROOT/template.rs" > "$dir/main.rs" ;;
esac
}
wire_io() { # $1 = problem dir, $2 = io name: point the source's file-io call at <io>
local dir="$1" io="$2" lang src
lang="$(lang_of "$dir")" || return 1
src="$dir/$(src_name "$lang")"
if [[ "$lang" == rust ]]; then
if grep -q 'stdio("' "$src"; then
sed -i "s/stdio(\"[^\"]*\")/stdio(\"$io\")/" "$src"
echo "Updated stdio(\"$io\") in main.rs"
else
echo "Warning: couldn't find stdio(\"...\") in main.rs — wire it up manually" >&2
fi
else
if grep -q 'STDIO("' "$src"; then
sed -i "s/STDIO(\"[^\"]*\")/STDIO(\"$io\")/" "$src"
echo "Updated STDIO(\"$io\") in main.cpp"
elif grep -q '^int main() {$' "$src"; then
sed -i "s/^int main() {$/int main() {\n STDIO(\"$io\");/" "$src"
echo "Inserted STDIO(\"$io\") in main.cpp"
else
echo "Warning: couldn't find STDIO(...) or 'int main() {' in main.cpp — wire it up manually" >&2
fi
fi
}
show_io() { # $1 = problem dir: echo the io name the source is wired to, if any
local lang src; lang="$(lang_of "$1")" || return 1
src="$1/$(src_name "$lang")"
if [[ "$lang" == rust ]]; then
grep -o 'stdio("[^"]*")' "$src" | sed 's/stdio("\(.*\)")/\1/' | head -1
else
grep -o 'STDIO("[^"]*")' "$src" | sed 's/STDIO("\(.*\)")/\1/' | head -1
fi
}
run_solution() { # $1 = dir, $2 = io name: run ./main, leave its output in $1/$2.out
# Works for both styles: a solution that opens <io>.in/.out itself (STDIO / stdio)
# and one that just reads stdin and writes stdout (Codeforces-style).
local dir="$1" io="$2" tmp rc=0
rm -f "$dir/$io.out"
tmp="$(mktemp)"
[[ -e "$dir/$io.in" ]] || touch "$dir/$io.in"
(cd "$dir" && ./main) < "$dir/$io.in" > "$tmp" || rc=$?
[[ -e "$dir/$io.out" ]] || cp "$tmp" "$dir/$io.out"
rm -f "$tmp"
return $rc
}
# colors (disabled when not a tty or NO_COLOR is set)
if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then
GRN=$'\e[32m' RED=$'\e[31m' YEL=$'\e[33m' DIM=$'\e[2m' RST=$'\e[0m'
DIFF_COLOR=--color=always
else
GRN='' RED='' YEL='' DIM='' RST=''
DIFF_COLOR=--color=never
fi