From 1aee0050a0f02fe7416178798eaa7194122e7999 Mon Sep 17 00:00:00 2001 From: Adam French Date: Mon, 19 Oct 2026 21:17:50 +0100 Subject: [PATCH] Add Rust support: usaco lang, lint, and main.rs problems Brings in the stashed Rust work, merged onto the current CLI. A problem's language is whichever source it has (main.cpp or main.rs); 'usaco lang' sets the default for new problems (.lang, or $USACO_LANG), and 'new --rust/--cpp' picks per problem. template.rs is a paste-ready Rust template whose stdio() uses .in/.out when present and stdin/stdout otherwise. run/test now feed .in on stdin and capture stdout when the program doesn't write .out itself, so Codeforces-style solutions work too. 'reset rust|cpp' switches a problem's language (template is still an alias), and --debug builds Rust with overflow checks and debug assertions. 'usaco lint' runs clippy through a generated, gitignored Cargo.toml that also gives rust-analyzer a project; done/skip/undo keep it in step. LeetCode imports stay C++. Also: done stages solved/ and solving/ separately, so a problem that was never committed from solving/ still gets its "Solve" commit, and the site lists main.rs ahead of other files like it does main.cpp. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 7 ++ README.md | 93 +++++++++++++--- lib/cmd/build.sh | 2 +- lib/cmd/cat.sh | 2 +- lib/cmd/clean.sh | 3 +- lib/cmd/copy.sh | 11 +- lib/cmd/done.sh | 6 +- lib/cmd/edit.sh | 3 +- lib/cmd/interactive.sh | 17 ++- lib/cmd/io.sh | 16 +-- lib/cmd/lang.sh | 11 ++ lib/cmd/lint.sh | 35 ++++++ lib/cmd/new.sh | 18 +++- lib/cmd/reset.sh | 36 +++++-- lib/cmd/run.sh | 9 +- lib/cmd/skip.sh | 1 + lib/cmd/test.sh | 3 +- lib/cmd/undo.sh | 1 + lib/common.sh | 191 +++++++++++++++++++++++++++++++-- site/internal/index/index.go | 7 +- site/web/src/views/CliPage.vue | 23 ++-- template.rs | 133 +++++++++++++++++++++++ usaco | 34 +++--- usaco.zsh | 38 ++++--- 24 files changed, 588 insertions(+), 112 deletions(-) create mode 100644 lib/cmd/lang.sh create mode 100644 lib/cmd/lint.sh create mode 100644 template.rs diff --git a/.gitignore b/.gitignore index 5c76de9..3fa9545 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,11 @@ skipped/*/main .current .usaco_history .current_stack +.lang a.out + +# Generated cargo scaffolding: exists only so rust-analyzer/clippy can see +# the solutions. "usaco lint" (or any rust build) recreates it. +Cargo.toml +Cargo.lock +target/ diff --git a/README.md b/README.md index 03be5b8..80f37c9 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,8 @@ site in `site/` (see [site/README.md](site/README.md)). ## Layout ``` -template.cpp starting template for every problem +template.cpp starting template for C++ problems +template.rs starting template for Rust problems site/ the website (Go server + Vue SPA), deployed as its own container solving// problems in progress solved// finished problems @@ -16,17 +17,54 @@ skipped// problems set aside for later The website's CLI page (`site/web/src/views/CliPage.vue`) is a condensed copy of the Commands section below; keep it in step. -Each problem dir contains `main.cpp` plus `.in` / `.out` files (USACO file IO is wired up automatically via `STDIO("")`). Optional extras: `.url` (the problem link), `tests/N.in` + `N.out`, `notes.md` (shown on the website, usually written from there), `problem.md` (the statement, saved or fetched from the website's editor) and `explain.md` (an explanation the website had Claude write). +Each problem dir contains `main.cpp` *or* `main.rs` plus `.in` / `.out` files. File IO is wired up automatically — `STDIO("")` in C++, `stdio("")` in Rust. A problem's language is simply whichever source file it has, so every command (`run`, `test`, `cat`, `edit`, ...) figures it out on its own. Optional extras: `.url` (the problem link), `tests/N.in` + `N.out`, `notes.md` (shown on the website, usually written from there), `problem.md` (the statement, saved or fetched from the website's editor, or by a LeetCode import) and `explain.md` (an explanation the website had Claude write). + +## Languages + +``` +./usaco lang # show the default language for new problems +./usaco lang rust # set it (stored in .lang) +./usaco new foo --rust # or pick per problem (--cpp / --rust) +USACO_LANG=cpp ./usaco new foo # or per shell +``` + +Switch an existing problem's language with `./usaco reset rust` (or `template`) — the old source is kept as a `.bak`. LeetCode imports are always C++. + +**C++** compiles with `g++ -O2 -std=c++17 -Wall -Wextra -DLOCAL`, **Rust** with `rustc -O --edition 2021` (plain `rustc`, no Cargo, so the solution stays a single submittable file). Override the flags via `CXXFLAGS` / `RUSTCFLAGS` in `lib/common.sh`. + +### The Rust template + +`template.rs` is self-contained and paste-ready for any judge. It gives you: + +```rust +fn main() { + let (mut sc, mut out) = stdio("problem"); // <- usaco new wires the name in + let n: usize = sc.next(); // one token, any FromStr type + let v: Vec = sc.vec(n); // n tokens + let s: Vec = sc.bytes(); // a word as bytes + writeln!(out, "{}", join(&v, " ")).unwrap(); +} +``` + +`stdio(name)` picks its mode from the directory it runs in: + +- `name.in` exists → reads `name.in`, writes `name.out` (USACO, and what `usaco run` / `usaco test` use) +- `name.in` missing → reads stdin, writes stdout (paste straight into Codeforces) + +So the same file works locally and on a judge with no edits. Also included: a `Scanner` that slurps the whole input up front and hands out parsed tokens (`next`, `vec`, `pair`, `pairs`, `bytes`, `chars`), `yesno`, `join`, `remax`/`remin`, and the usual `std::collections` imports. `dbg!(x)` goes to stderr, so it never pollutes the `.out` file. ## Commands ### Start a problem ``` ./usaco new diamond-collector -./usaco new diamond-collector diamond # if the freopen name differs +./usaco new diamond-collector diamond # if the file-io name differs ./usaco new diamond-collector --url https://usaco.org/index.php?page=viewproblem2&cpid=639 ``` -Creates `solving//main.cpp` from the template and an empty `.in` file, then opens it in `$EDITOR`. `--url` saves the problem link for `open`. +``` +./usaco new diamond-collector --rust # Rust instead of the default +``` +Creates `solving//main.cpp` (or `main.rs`) from the template and an empty `.in` file, then opens it in `$EDITOR`. `--url` saves the problem link for `open`. ### Start a LeetCode problem ``` @@ -49,9 +87,9 @@ Limits: when the statement says "any order", a correct answer in a different ord ./usaco run diamond-collector # compile + run, then print the .out file ./usaco build diamond-collector # compile only ``` -Compiles with `g++ -O2 -std=c++17 -Wall -Wextra -DLOCAL` and runs inside the problem dir so file IO just works. Put your test input in the `.in` file first. +Compiles the problem's source (C++ or Rust) and runs it inside the problem dir, feeding it `.in` on stdin, so both file-IO and stdin/stdout solutions work. Put your test input in the `.in` file first. -Add `--debug` to `run`, `build` or `test` (or set `USACO_DEBUG=1`) for a sanitizer build (`-fsanitize=address,undefined`, `_GLIBCXX_DEBUG`): out-of-bounds indexing, overflow and other UB crash with a stack trace instead of silently giving wrong answers. +Add `--debug` to `run`, `build` or `test` (or set `USACO_DEBUG=1`) for a checked build. C++ gets sanitizers (`-fsanitize=address,undefined`, `_GLIBCXX_DEBUG`): out-of-bounds indexing, overflow and other UB crash with a stack trace instead of silently giving wrong answers. Rust gets `-C overflow-checks -C debug-assertions`, so integer overflow panics instead of wrapping. **Debug output:** `LOCAL` is only defined by `./usaco` builds, so the template's `#ifdef LOCAL #include "debugging.h"` (pretty-printers for vectors, maps, pairs…) and its `DBG(x)` macros vanish on the judge — submit `main.cpp` as-is. @@ -76,7 +114,7 @@ The website commits too: marking a problem solved/skipped, or editing its link o ### Edit ``` -./usaco vim diamond-collector # open main.cpp in $EDITOR (defaults to nvim) +./usaco vim diamond-collector # open the solution in $EDITOR (defaults to nvim) ./usaco e diamond-collector # same thing, shorter (also: edit) ``` Opens from inside the problem dir, so the `.in`/`.out` files are right there. @@ -90,9 +128,9 @@ Opens from inside the problem dir, so the `.in`/`.out` files are right there. ### Snippets ``` -./usaco cat diamond-collector # print main.cpp to stdout (pipeable) +./usaco cat diamond-collector # print the solution to stdout (pipeable) ./usaco cat diam | wl-copy # e.g. pipe it wherever you want -./usaco copy diamond-collector # copy main.cpp to the clipboard (alias: cp) +./usaco copy diamond-collector # copy the solution to the clipboard (alias: cp) ``` `copy` auto-detects the clipboard tool: `wl-copy` on Wayland, then `xclip`/`xsel` on X11, and falls back to an OSC52 terminal escape that works even over SSH. @@ -116,13 +154,37 @@ The selection persists across sessions in `.current` (cleared automatically if t ### Misc ``` -./usaco reset diamond-collector # fresh main.cpp from template (old one -> main.cpp.bak), delete binary + .out - # asks first (-y skips); keeps tests/ and .in (aliases: template, rm) -./usaco io diamond-collector # show the io name; 'io ' renames .in/.out and rewires STDIO -./usaco clean # delete compiled binaries (main, a.out) and .bak files everywhere -./usaco path diamond-collector # print the problem's directory +./usaco reset diamond-collector # fresh source from template (old one -> .bak), delete binary + .out + # asks first (-y skips); keeps tests/ and .in (aliases: template, rm) +./usaco reset diamond-collector rust # ...and switch the problem to Rust +./usaco io diamond-collector # show the io name; 'io ' renames .in/.out and rewires STDIO/stdio +./usaco clean # delete compiled binaries (main, a.out) and .bak files everywhere +./usaco lint # clippy over every Rust solution (see "Rust linting" below) +./usaco lint excel-sheet # ...or just one +./usaco lint template # ...or template.rs itself +./usaco path diamond-collector # print the problem's directory ``` +### Rust linting + +Problems are bare `main.rs` files, and rust-analyzer only does real analysis +(type-aware diagnostics, clippy on save) inside a cargo project. `usaco lint` +generates a root `Cargo.toml` that declares every Rust solution, plus +`template.rs`, as its own `[[bin]]`, which is enough to give the editor a +project to attach to. Any Rust build regenerates it too, so it stays in step as +problems are created or moved. + +Nothing compiles through cargo — `usaco build`/`run` still call `rustc` +directly. The manifest is purely for tooling, so it's gitignored along with +`Cargo.lock` and `target/`; run `usaco lint` once after a fresh clone to +recreate it. The lint selection (clippy pedantic, minus the cast and +missing-docs noise) lives in `sync_cargo_manifest()` in `lib/common.sh`. + +Editor side: rust-analyzer must actually be installed (`rustup component add +rust-analyzer` — the rustup shim is on `$PATH` even when the component isn't, +so it fails silently), and `check.command` has to be set to `clippy`, since the +default is plain `cargo check`. + ## Shell integration (recommended) Add to `~/.zshrc`: @@ -140,8 +202,9 @@ This gives you: ./usaco new the-lost-cow --url ./usaco open the-lost-cow # read the problem # paste sample input into solving/the-lost-cow/the-lost-cow.in -# edit solving/the-lost-cow/main.cpp +# edit solving/the-lost-cow/main.rs (or main.cpp) ./usaco run the-lost-cow # iterate until the output is right +./usaco test create the-lost-cow # lock the sample in as a test case ./usaco done the-lost-cow # 🎉 (auto-commits) ./usaco sync # publish it on the website ``` diff --git a/lib/cmd/build.sh b/lib/cmd/build.sh index 8825271..97fa504 100644 --- a/lib/cmd/build.sh +++ b/lib/cmd/build.sh @@ -2,4 +2,4 @@ [[ $# -ge 1 ]] || usage dir="$(find_problem "$1")" build_problem "$dir" -echo "Built $dir/main" +echo "Built $dir/main ${DIM}($(lang_of "$dir"))${RST}" diff --git a/lib/cmd/cat.sh b/lib/cmd/cat.sh index b709e60..8e8ed8e 100644 --- a/lib/cmd/cat.sh +++ b/lib/cmd/cat.sh @@ -1,4 +1,4 @@ # usaco cat [[ $# -ge 1 ]] || usage dir="$(find_problem "$1")" -cat "$dir/main.cpp" +cat "$(main_file "$dir")" diff --git a/lib/cmd/clean.sh b/lib/cmd/clean.sh index 10e274a..6d04603 100644 --- a/lib/cmd/clean.sh +++ b/lib/cmd/clean.sh @@ -2,5 +2,6 @@ for s in solving solved skipped; do [[ -d "$ROOT/$s" ]] || continue find "$ROOT/$s" -mindepth 2 -maxdepth 2 -type f \ - \( -name main -o -name a.out -o -name '*.bak' \) -print -delete | sed "s|^$ROOT/|removed |" + \( -name main -o -name a.out -o -name '*.bak' -o -name '*.pdb' \) -print -delete \ + | sed "s|^$ROOT/|removed |" done diff --git a/lib/cmd/copy.sh b/lib/cmd/copy.sh index 7de2e6f..935a7eb 100644 --- a/lib/cmd/copy.sh +++ b/lib/cmd/copy.sh @@ -1,16 +1,17 @@ # usaco copy (alias: cp) -# Copies the problem's main.cpp to the clipboard. +# Copies the problem's solution source to the clipboard. # Wayland: wl-copy; X11: xclip/xsel; last resort OSC52 escape (works over SSH). [[ $# -ge 1 ]] || usage dir="$(find_problem "$1")" +src="$(main_file "$dir")" if [[ -n ${WAYLAND_DISPLAY:-} ]] && command -v wl-copy >/dev/null 2>&1; then - wl-copy < "$dir/main.cpp" + wl-copy < "$src" elif command -v xclip >/dev/null 2>&1; then - xclip -selection clipboard < "$dir/main.cpp" + xclip -selection clipboard < "$src" elif command -v xsel >/dev/null 2>&1; then - xsel -b --input < "$dir/main.cpp" + xsel -b --input < "$src" else # OSC52: terminal-native clipboard, also works through SSH - base64 -w0 < "$dir/main.cpp" | printf '\e]52;c;%s\a' "$(cat)" + base64 -w0 < "$src" | printf '\e]52;c;%s\a' "$(cat)" fi diff --git a/lib/cmd/done.sh b/lib/cmd/done.sh index c16c325..1f2b9ce 100644 --- a/lib/cmd/done.sh +++ b/lib/cmd/done.sh @@ -4,8 +4,12 @@ dir="$(find_problem "$1")"; name="$(basename "$dir")" [[ "$dir" == "$ROOT/solving/$name" ]] || { echo "Error: $name is not in solving/ (it's in ${dir#$ROOT/})" >&2; exit 1; } [[ -d "$ROOT/solved/$name" ]] && { echo "Error: solved/$name already exists" >&2; exit 1; } mv "$ROOT/solving/$name" "$ROOT/solved/$name" +sync_cargo_manifest >/dev/null # the bin paths just moved echo "Moved to solved/$name 🎉" if git -C "$ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then - git -C "$ROOT" add -A "solved/$name" "solving/$name" 2>/dev/null || true + # separately: one pathspec that matches nothing (a problem never committed + # from solving/) would make git refuse to stage the other + git -C "$ROOT" add -A "solved/$name" 2>/dev/null || true + git -C "$ROOT" add -A "solving/$name" 2>/dev/null || true git -C "$ROOT" commit -m "Solve $name" >/dev/null && echo "Committed: Solve $name ${DIM}(usaco sync to publish it)${RST}" fi diff --git a/lib/cmd/edit.sh b/lib/cmd/edit.sh index dc328dd..b51701d 100644 --- a/lib/cmd/edit.sh +++ b/lib/cmd/edit.sh @@ -1,5 +1,6 @@ # usaco vim/edit/e [[ $# -ge 1 ]] || usage dir="$(find_problem "$1")" +src="$(basename "$(main_file "$dir")")" # run from inside the dir so :!./main etc. work and .in files are at hand -(cd "$dir" && exec ${EDITOR:-nvim} main.cpp) +(cd "$dir" && exec ${EDITOR:-nvim} "$src") diff --git a/lib/cmd/interactive.sh b/lib/cmd/interactive.sh index 1d6d149..b64123d 100644 --- a/lib/cmd/interactive.sh +++ b/lib/cmd/interactive.sh @@ -10,7 +10,7 @@ HISTFILE="$ROOT/.usaco_history" # commands that take a problem name (the selection is injected when you omit it) WITH_PROBLEM="run build test done undo skip io cat copy edit open path reset" # commands that take no problem -NO_PROBLEM="list stats clean sync" +NO_PROBLEM="list stats clean sync lang" # REPL-only words (used for completion and for 'help') REPL_WORDS="s use none push pop stack help quit exit" @@ -70,7 +70,8 @@ ${DIM}selection${RST} ${DIM}problem commands${RST} ${DIM}(name optional — omit it to use the selection; giving one switches to it)${RST} $WITH_PROBLEM ${DIM}other${RST} - $NO_PROBLEM, new , new + $NO_PROBLEM, new [io] [--rust|--cpp], new + lint [] clippy the selection, or every rust solution help [] this, or the dispatcher's usage line for !cmd run a shell command in the problem dir q quit @@ -83,7 +84,7 @@ _usaco_comp() { # completes REPL commands and problem names for d in "$ROOT"/solving/*/ "$ROOT"/solved/*/ "$ROOT"/skipped/*/; do names+=("$(basename "$d")"); done shopt -u nullglob if [[ $COMP_CWORD -eq 0 ]]; then - COMPREPLY=($(compgen -W "$WITH_PROBLEM $NO_PROBLEM $REPL_WORDS new ${names[*]}" -- "$w")) + COMPREPLY=($(compgen -W "$WITH_PROBLEM $NO_PROBLEM $REPL_WORDS new lint ${names[*]}" -- "$w")) else COMPREPLY=($(compgen -W "${names[*]}" -- "$w")) fi @@ -141,6 +142,12 @@ while :; do if USACO_CREATED="$created" "$ROOT/usaco" new "${args[@]}"; then set_current "$(<"$created")"; fi rm -f "$created" continue ;; + lint) + # the one command whose problem name is optional: it lints the + # selection if there is one, otherwise every rust solution + [[ ${#args[@]} -eq 0 && -n "$cur" ]] && args=("$cur") + "$ROOT/usaco" lint "${args[@]+"${args[@]}"}" || true + continue ;; esac # expand short aliases to full names so the tables below match @@ -158,7 +165,9 @@ while :; do if [[ " $WITH_PROBLEM " == *" $c "* ]]; then # 'test create' keeps its subword first; the name goes after it pre=(); if [[ "$c" == test && "${args[0]:-}" =~ ^(create|add|new)$ ]]; then pre=("${args[0]}"); args=("${args[@]:1}"); fi - if [[ ${#args[@]} -ge 1 && "${args[0]}" != -* ]]; then # explicit name: use it and switch to it + # 'reset rust' switches the selection's language: a language word isn't a name + lang_arg=""; [[ "$c" == reset ]] && normalize_lang "${args[0]:-}" >/dev/null 2>&1 && lang_arg=1 + if [[ ${#args[@]} -ge 1 && "${args[0]}" != -* && -z "$lang_arg" ]]; then # explicit name: use it and switch to it n="$(real_name "${args[0]}")" || { find_problem "${args[0]}" >/dev/null || true; continue; } set_current "$n"; args=("${args[@]:1}") elif [[ -z "$cur" ]]; then diff --git a/lib/cmd/io.sh b/lib/cmd/io.sh index b07e313..7f64e08 100644 --- a/lib/cmd/io.sh +++ b/lib/cmd/io.sh @@ -3,9 +3,10 @@ dir="$(find_problem "$1")" old="$(detect_io "$dir" || true)" if [[ $# -lt 2 ]]; then - stdio="$(grep -o 'STDIO("[^"]*")' "$dir/main.cpp" 2>/dev/null | sed 's/STDIO("\(.*\)")/\1/' | head -1 || true)" + wired="$(show_io "$dir" || true)" + echo "lang: $(lang_of "$dir")" echo "files: ${old:-none}" - echo "STDIO: ${stdio:-none}" + echo "source: ${wired:-none}" exit 0 fi io="$2" @@ -16,14 +17,5 @@ if [[ -n "$old" && "$old" != "$io" ]]; then done fi [[ -e "$dir/$io.in" ]] || { touch "$dir/$io.in"; echo "Created $io.in"; } -# rewire STDIO in main.cpp -if grep -q 'STDIO("' "$dir/main.cpp" 2>/dev/null; then - sed -i "s/STDIO(\"[^\"]*\")/STDIO(\"$io\")/" "$dir/main.cpp" - echo "Updated STDIO(\"$io\") in main.cpp" -elif grep -q '^int main() {$' "$dir/main.cpp" 2>/dev/null; then - sed -i "s/^int main() {$/int main() {\n STDIO(\"$io\");/" "$dir/main.cpp" - 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 +wire_io "$dir" "$io" echo "io name for $(basename "$dir") is now '$io'" diff --git a/lib/cmd/lang.sh b/lib/cmd/lang.sh new file mode 100644 index 0000000..dc829af --- /dev/null +++ b/lib/cmd/lang.sh @@ -0,0 +1,11 @@ +# usaco lang [cpp|rust] +if [[ $# -eq 0 ]]; then + echo "default for 'usaco new': $(default_lang)" + [[ -n "${USACO_LANG:-}" ]] && echo "${DIM}(from \$USACO_LANG)${RST}" + exit 0 +fi +lang="$(normalize_lang "$1")" || exit 1 +printf '%s\n' "$lang" > "$ROOT/.lang" +echo "Default language for new problems: $lang" +[[ -n "${USACO_LANG:-}" ]] && echo "${YEL}note:${RST} \$USACO_LANG=$USACO_LANG overrides this in your shell" >&2 +exit 0 diff --git a/lib/cmd/lint.sh b/lib/cmd/lint.sh new file mode 100644 index 0000000..f360ae1 --- /dev/null +++ b/lib/cmd/lint.sh @@ -0,0 +1,35 @@ +# usaco lint [name...] +# Regenerates the cargo manifest rust-analyzer reads, then runs clippy over the +# rust solutions. With no arguments it lints every one, plus template.rs; names +# select individual problems (unique prefixes work, as everywhere else), and +# the literal name "template" selects template.rs. +command -v cargo >/dev/null || { echo "Error: cargo not found" >&2; exit 1; } + +count="$(sync_cargo_manifest)" +if [[ -z "$count" ]]; then + echo "No rust solutions or template.rs yet — nothing to lint." + exit 0 +fi + +targets=() +for name in "$@"; do + if [[ "$name" == template ]]; then + [[ -f "$ROOT/template.rs" ]] || { echo "Error: template.rs not found" >&2; exit 1; } + targets+=(--bin template) + continue + fi + dir="$(find_problem "$name")" || exit 1 + [[ -f "$dir/main.rs" ]] || { echo "Error: $(basename "$dir") is not a rust problem" >&2; exit 1; } + rel="${dir#"$ROOT"/}" + targets+=(--bin "${rel%/*}-${rel##*/}") +done + +if [[ ${#targets[@]} -eq 0 ]]; then + what="$count rust solution(s)" + [[ -f "$ROOT/template.rs" ]] && what+=" and template.rs" + echo "${DIM}Linting $what...${RST}" + targets=(--bins) +fi + +# Builds live under target/, away from the ./main binaries usaco produces. +(cd "$ROOT" && cargo clippy --quiet "${targets[@]}") diff --git a/lib/cmd/new.sh b/lib/cmd/new.sh index c9d283c..3f412a5 100644 --- a/lib/cmd/new.sh +++ b/lib/cmd/new.sh @@ -1,9 +1,12 @@ -# usaco new [io-name] [--url ] | usaco new +# usaco new [io-name] [--url ] [--rust|--cpp] | usaco new [[ $# -ge 1 ]] || usage -name=""; io=""; url="" +name=""; io=""; url=""; lang="" while [[ $# -gt 0 ]]; do case "$1" in --url) url="${2:-}"; shift 2 ;; + --lang|-l) lang="$(normalize_lang "${2:-}")" || exit 1; shift 2 ;; + --rust|--rs) lang=rust; shift ;; + --cpp|--c++) lang=cpp; shift ;; *) if [[ -z "$name" ]]; then name="$1"; elif [[ -z "$io" ]]; then io="$1"; fi; shift ;; esac done @@ -11,7 +14,9 @@ done # A LeetCode link (or "daily": today's daily question) imports the problem: # statement, starter code, a generated driver, and the examples as tests. +# Always C++, whatever 'usaco lang' says: the driver is C++. if [[ "$name" == daily || "$name" =~ ^(https?://)?(www\.)?leetcode\.com/problems/ ]]; then + [[ "${lang:-cpp}" == cpp ]] || { echo "Error: LeetCode imports are C++ only" >&2; exit 1; } name="$(python3 -I "$ROOT/lib/leetcode.py" "$ROOT" "$name")" || exit 1 [[ -n "${USACO_CREATED:-}" ]] && printf '%s\n' "$name" > "$USACO_CREATED" echo "Created solving/$name (statement in problem.md; 'usaco t $name' runs the examples)" @@ -20,14 +25,17 @@ if [[ "$name" == daily || "$name" =~ ^(https?://)?(www\.)?leetcode\.com/problems fi io="${io:-$name}" +lang="${lang:-$(default_lang)}" dir="$ROOT/solving/$name" if [[ -d "$dir" || -d "$ROOT/solved/$name" || -d "$ROOT/skipped/$name" ]]; then echo "Error: '$name' already exists" >&2; exit 1 fi mkdir -p "$dir" -fresh_main "$dir" "$io" +fresh_main "$dir" "$io" "$lang" touch "$dir/$io.in" [[ -n "$url" ]] && echo "$url" > "$dir/.url" [[ -n "${USACO_CREATED:-}" ]] && printf '%s\n' "$name" > "$USACO_CREATED" -echo "Created solving/$name (io: $io.in / $io.out)" -(cd "$dir" && exec ${EDITOR:-nvim} main.cpp) +src="$(src_name "$lang")" +echo "Created solving/$name/$src (io: $io.in / $io.out)" +[[ "$lang" == rust ]] && sync_cargo_manifest >/dev/null +(cd "$dir" && exec ${EDITOR:-nvim} "$src") diff --git a/lib/cmd/reset.sh b/lib/cmd/reset.sh index d681e04..d007844 100644 --- a/lib/cmd/reset.sh +++ b/lib/cmd/reset.sh @@ -1,25 +1,39 @@ -# usaco reset/rm/delete/template/tpl [-y] +# usaco reset/rm/delete/template/tpl [cpp|rust] [-y] [[ $# -ge 1 ]] || usage -dir="$(find_problem "$1")" +dir="$(find_problem "$1")"; shift name="$(basename "$dir")" +yes=""; lang="" +for a in "$@"; do + if [[ "$a" == -y ]]; then yes=1; else lang="$(normalize_lang "$a")" || exit 1; fi +done +lang="${lang:-$(lang_of "$dir" 2>/dev/null || default_lang)}" +leet=""; [[ -f "$dir/driver.h" ]] && leet=1 +if [[ -n "$leet" && "$lang" != cpp ]]; then + echo "Error: $name is a LeetCode import, and those are C++ only" >&2; exit 1 +fi io="$(detect_io "$dir" || true)" io="${io:-$name}" -if [[ "${2:-}" != -y ]]; then - echo "This resets ${dir#$ROOT/} to a fresh template:" - if [[ -f "$dir/driver.h" ]]; then - echo " main.cpp -> LeetCode's starter code again (old one saved as main.cpp.bak)" +old="$(main_file "$dir" 2>/dev/null || true)" +src="$(src_name "$lang")" +if [[ -z "$yes" ]]; then + echo "This resets ${dir#$ROOT/} to a fresh $lang template:" + if [[ -n "$leet" ]]; then + echo " $src -> LeetCode's starter code again (old one saved as $src.bak)" else - echo " main.cpp -> re-created from template (old one saved as main.cpp.bak)" + echo " $src -> re-created from template (old one saved as $(basename "${old:-$src}").bak)" fi echo " removes compiled binary and $io.out (tests/ and $io.in are kept)" read -r -p "Reset '$name'? [y/N] " ans [[ "$ans" == y || "$ans" == Y ]] || { echo "Aborted."; exit 1; } fi -[[ -f "$dir/main.cpp" ]] && cp "$dir/main.cpp" "$dir/main.cpp.bak" -if [[ -f "$dir/driver.h" ]]; then # a LeetCode import: re-fetch its starter code +[[ -n "$old" && -f "$old" ]] && cp "$old" "$old.bak" +# switching language: drop the old source so lang_of stays unambiguous +[[ -n "$old" && "$(basename "$old")" != "$src" ]] && rm -f "$old" +if [[ -n "$leet" ]]; then # a LeetCode import: re-fetch its starter code python3 -I "$ROOT/lib/leetcode.py" "$ROOT" "$dir" --main-only >/dev/null || exit 1 else - fresh_main "$dir" "$io" + fresh_main "$dir" "$io" "$lang" fi +[[ "$lang" == rust || "$old" == *.rs ]] && sync_cargo_manifest >/dev/null rm -f "$dir/main" "$dir/a.out" "$dir/$io.out" -echo "Reset $name (old solution in main.cpp.bak)" +echo "Reset $name (old solution in $(basename "${old:-$src}").bak)" diff --git a/lib/cmd/run.sh b/lib/cmd/run.sh index 2e7690d..5673c8b 100644 --- a/lib/cmd/run.sh +++ b/lib/cmd/run.sh @@ -2,11 +2,12 @@ [[ $# -ge 1 ]] || usage dir="$(find_problem "$1")" build_problem "$dir" -# run from inside the dir so freopen finds the .in file -(cd "$dir" && ./main) -# show the .out file if the program wrote one io="$(detect_io "$dir" || true)" -if [[ -n "$io" && -f "$dir/$io.out" ]]; then +io="${io:-$(basename "$dir")}" +rc=0; run_solution "$dir" "$io" || rc=$? +if [[ -e "$dir/$io.out" ]]; then echo "── $io.out ──" cat "$dir/$io.out" fi +[[ $rc -eq 0 ]] || echo "${RED}exited $rc${RST}" >&2 +exit $rc diff --git a/lib/cmd/skip.sh b/lib/cmd/skip.sh index 92093ff..0dcaee3 100644 --- a/lib/cmd/skip.sh +++ b/lib/cmd/skip.sh @@ -5,4 +5,5 @@ dir="$(find_problem "$1")"; name="$(basename "$dir")" [[ -d "$ROOT/skipped/$name" ]] && { echo "Error: skipped/$name already exists" >&2; exit 1; } mkdir -p "$ROOT/skipped" mv "$ROOT/solving/$name" "$ROOT/skipped/$name" +sync_cargo_manifest >/dev/null # the bin paths just moved echo "Moved to skipped/$name (usaco undo $name to bring it back)" diff --git a/lib/cmd/test.sh b/lib/cmd/test.sh index 4ecd781..bc7236a 100644 --- a/lib/cmd/test.sh +++ b/lib/cmd/test.sh @@ -28,9 +28,8 @@ run_case() { # $1 = dir, $2 = io, $3 = tests/N.in path; returns 0 pass, 1 fail, local dir="$1" io="$2" tin="$3" n ms start exp n="$(basename "$tin" .in)" cp "$tin" "$dir/$io.in" - rm -f "$dir/$io.out" start=$(date +%s%N) - if ! (cd "$dir" && ./main); then + if ! run_solution "$dir" "$io"; then echo "${RED}✗ case $n CRASHED (nonzero exit)${RST}" return 1 fi diff --git a/lib/cmd/undo.sh b/lib/cmd/undo.sh index 2a4071f..198c59a 100644 --- a/lib/cmd/undo.sh +++ b/lib/cmd/undo.sh @@ -5,4 +5,5 @@ from="$(basename "$(dirname "$dir")")" [[ "$from" != solving ]] || { echo "Error: $name is already in solving/" >&2; exit 1; } [[ -d "$ROOT/solving/$name" ]] && { echo "Error: solving/$name already exists" >&2; exit 1; } mv "$ROOT/$from/$name" "$ROOT/solving/$name" +sync_cargo_manifest >/dev/null # the bin paths just moved echo "Moved back to solving/$name (was $from)" diff --git a/lib/common.sh b/lib/common.sh index 016a7a7..9cbc7f2 100644 --- a/lib/common.sh +++ b/lib/common.sh @@ -5,6 +5,40 @@ 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=() @@ -26,13 +60,102 @@ find_problem() { # echoes dir of problem in solving/, solved/, or skipped/; uni return 1 } -build_problem() { # $1 = problem dir - if [[ -n "${USACO_DEBUG:-}" ]]; then - echo "${DIM}(debug build: sanitizers on)${RST}" >&2 - g++ "${CXXFLAGS[@]}" "${DEBUG_CXXFLAGS[@]}" "$1/main.cpp" -o "$1/main" - else - g++ "${CXXFLAGS[@]}" "$1/main.cpp" -o "$1/main" +# ----- 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" <&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 @@ -60,8 +183,60 @@ solved_at() { # $1 = solved/ dir: epoch it (last) entered solved/ [[ -n "$t" ]] && echo "$t" || last_touched "$1" } -fresh_main() { # $1 = problem dir, $2 = io name: main.cpp from template with STDIO wired up - sed "s/^int main() {$/int main() {\n STDIO(\"$2\");/" "$ROOT/template.cpp" > "$1/main.cpp" +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 + 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 .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) diff --git a/site/internal/index/index.go b/site/internal/index/index.go index 6786f83..72bc4a5 100644 --- a/site/internal/index/index.go +++ b/site/internal/index/index.go @@ -192,10 +192,11 @@ func readProblem(pdir, status string) (*Problem, error) { } } } - // main.cpp first: it is the CLI's solution, anything else is a side - // experiment (sol.py) or a helper. + // main.cpp / main.rs first: it is the CLI's solution, anything else is + // a side experiment (sol.py) or a helper. + isMain := func(name string) bool { return strings.HasPrefix(name, "main.") } sort.SliceStable(p.Files, func(i, j int) bool { - return p.Files[i].Name == "main.cpp" && p.Files[j].Name != "main.cpp" + return isMain(p.Files[i].Name) && !isMain(p.Files[j].Name) }) if p.Sample != nil && strings.TrimSpace(p.Sample.Content) == "" { p.Sample = nil diff --git a/site/web/src/views/CliPage.vue b/site/web/src/views/CliPage.vue index 25e1ce7..078a4ac 100644 --- a/site/web/src/views/CliPage.vue +++ b/site/web/src/views/CliPage.vue @@ -16,7 +16,9 @@ const sections = [ { title: "Start a problem", rows: [ - ["usaco new ", "Create solving// with main.cpp from the template and an empty .in file, then open it in $EDITOR."], + ["usaco new ", "Create solving// with main.cpp (or main.rs) from the template and an empty .in file, then open it in $EDITOR."], + ["usaco new --rust", "Pick the language for this problem (--cpp / --rust); otherwise the default from usaco lang."], + ["usaco lang [cpp|rust]", "Show or set the default language for new problems (stored in .lang; $USACO_LANG overrides it per shell)."], ["usaco new ", "Same, when the USACO file name differs from the problem name."], ["usaco new --url ", "Also save the problem link, for usaco open."], ["usaco new ", "Import a LeetCode problem (also usaco from): the statement as problem.md, LeetCode's C++ starter code in main.cpp, a generated driver.h that runs it on LeetCode-format input, and the examples as tests with their expected outputs."], @@ -26,11 +28,11 @@ const sections = [ { title: "Build, run and test", rows: [ - ["usaco run ", "Compile and run inside the problem dir (so file IO just works), then print the .out file."], - ["usaco build ", "Compile only: g++ -O2 -std=c++17 -Wall -Wextra -DLOCAL."], + ["usaco run ", "Compile and run inside the problem dir, feeding it the .in on stdin (so file-IO and stdin/stdout solutions both work), then print the .out file."], + ["usaco build ", "Compile only: g++ -O2 -std=c++17 -Wall -Wextra -DLOCAL, or rustc -O --edition 2021 for main.rs."], ["usaco test create ", "Save a test case: tests/N.in (the current .in, or pasted) and the expected N.out."], ["usaco test [N…]", "Build, run every saved case (or just the ones given), diff, and show pass/fail with timings."], - ["--debug", "On run, build or test (or USACO_DEBUG=1): an ASan/UBSan + _GLIBCXX_DEBUG build, so out-of-bounds and UB crash with a stack trace."], + ["--debug", "On run, build or test (or USACO_DEBUG=1): an ASan/UBSan + _GLIBCXX_DEBUG build, so out-of-bounds and UB crash with a stack trace. Rust gets overflow checks and debug assertions."], ], }, { @@ -45,20 +47,21 @@ const sections = [ { title: "Edit and look around", rows: [ - ["usaco e ", "Open main.cpp in $EDITOR from inside the problem dir (also vim, edit)."], + ["usaco e ", "Open the solution in $EDITOR from inside the problem dir (also vim, edit)."], ["usaco list", "All problems by status, oldest-touched first."], ["usaco stats", "Counts, plus problems solved in the last 7 and 30 days."], ["usaco open ", "Open the saved problem link in a browser."], - ["usaco cat ", "Print main.cpp to stdout."], - ["usaco copy ", "Copy main.cpp to the clipboard (wl-copy, xclip/xsel, or OSC52 over SSH)."], + ["usaco cat ", "Print the solution to stdout."], + ["usaco copy ", "Copy the solution to the clipboard (wl-copy, xclip/xsel, or OSC52 over SSH)."], ], }, { title: "Misc", rows: [ - ["usaco reset ", "Fresh main.cpp from the template (the old one goes to main.cpp.bak). Asks first; -y skips. Keeps tests/ and the .in."], - ["usaco io [new]", "Show the IO name, or rename the .in/.out and rewire STDIO."], + ["usaco reset [cpp|rust]", "Fresh source from the template (the old one goes to a .bak); giving a language switches the problem to it. Asks first; -y skips. Keeps tests/ and the .in."], + ["usaco io [new]", "Show the IO name, or rename the .in/.out and rewire STDIO / stdio."], ["usaco clean", "Delete compiled binaries and .bak files everywhere."], + ["usaco lint [name…]", "Run clippy over the Rust solutions (or the named ones; template lints template.rs), refreshing the Cargo.toml rust-analyzer reads."], ["usaco path ", "Print the problem's directory."], ], }, @@ -89,7 +92,7 @@ usaco [watermelon:solved]> q`; Every problem here is written in a workspace managed by ./usaco, a small bash script at the root of the repo on Gitea (the commands themselves are in lib/cmd/). Each problem lives in solving/, solved/ or - skipped/ as a directory with main.cpp and its .in/.out + skipped/ as a directory with main.cpp or main.rs and its .in/.out files. Wherever a command takes a problem name, a unique prefix works too: usaco e diam finds diamond-collector.

diff --git a/template.rs b/template.rs new file mode 100644 index 0000000..ac398a9 --- /dev/null +++ b/template.rs @@ -0,0 +1,133 @@ +#![allow(dead_code, unused_imports, unused_macros, unused_mut, unused_variables)] +use std::cmp::{max, min, Ordering, Reverse}; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque}; +use std::fs::File; +use std::io::{self, BufWriter, Read, Write}; + +// ----- TYPES ----- +type Ll = i64; +type Pii = (i32, i32); + +// ----- FILE IO ----- +// stdio("name") picks the mode from the directory it runs in: +// name.in exists -> read name.in, write name.out (USACO + `usaco run/test`) +// name.in missing -> read stdin, write stdout (Codeforces submission) +// So the same file works locally and when pasted into a judge. +fn stdio(name: &str) -> (Scanner, Box) { + let infile = format!("{name}.in"); + if std::path::Path::new(&infile).exists() { + let src = std::fs::read_to_string(&infile).expect("could not read .in file"); + let out = File::create(format!("{name}.out")).expect("could not create .out file"); + (Scanner::new(&src), Box::new(BufWriter::new(out))) + } else { + let mut src = String::new(); + io::stdin() + .read_to_string(&mut src) + .expect("could not read stdin"); + (Scanner::new(&src), Box::new(BufWriter::new(io::stdout()))) + } +} + +// ----- INPUT ----- +// Slurps the whole input, then hands out whitespace-separated tokens. +// let n: usize = sc.next(); one token +// let (a, b) = (sc.next::(), sc.next::()); +// let v: Vec = sc.vec(n); n tokens +// let s: Vec = sc.bytes(); a word as bytes (s[i] - b'a') +struct Scanner { + toks: std::str::SplitAsciiWhitespace<'static>, +} + +impl Scanner { + fn new(src: &str) -> Scanner { + let leaked: &'static str = Box::leak(src.to_owned().into_boxed_str()); + Scanner { + toks: leaked.split_ascii_whitespace(), + } + } + fn next(&mut self) -> T { + let tok = self.toks.next().expect("ran out of input"); + tok.parse().ok().expect("could not parse token") + } + fn vec(&mut self, n: usize) -> Vec { + (0..n).map(|_| self.next()).collect() + } + fn pair(&mut self) -> (T, U) { + (self.next(), self.next()) + } + fn pairs(&mut self, n: usize) -> Vec<(T, U)> { + (0..n).map(|_| self.pair()).collect() + } + fn bytes(&mut self) -> Vec { + self.next::().into_bytes() + } + fn chars(&mut self) -> Vec { + self.next::().chars().collect() + } + fn leet_vec(&mut self) -> Vec { + let s: String = self.next(); + s.trim_matches(|c| c == '[' || c == ']') + .split(',') + .filter(|s| !s.is_empty()) + .map(|s| s.parse().ok().expect("leet vec parse err")) + .collect() + } + fn leet_grid(&mut self) -> Vec> { + let s: String = self.next(); + let s = s.trim_start_matches('[').trim_end_matches(']'); + let mut res = Vec::new(); + for row in s.split("],[") { + let cur = row + .split(',') + .filter(|c| !c.is_empty()) + .map(|c| c.parse().ok().expect("leet grid error")) + .collect(); + res.push(cur); + } + res + } +} + +// ----- OUTPUT ----- +// Write with writeln!(out, "{}", x). These help with the common shapes: +fn yesno(b: bool) -> &'static str { + if b { + "YES" + } else { + "NO" + } +} +// join(&v, " ") -> "1 2 3" +fn join(v: &[T], sep: &str) -> String { + v.iter() + .map(|x| x.to_string()) + .collect::>() + .join(sep) +} + +// ----- DEBUG ----- +// dbg!(x) is built in and goes to stderr, so it never pollutes the .out file. + +// ----- MAX MIN ----- +fn remax(a: &mut T, b: T) -> bool { + if b > *a { + *a = b; + true + } else { + false + } +} +fn remin(a: &mut T, b: T) -> bool { + if b < *a { + *a = b; + true + } else { + false + } +} + +fn main() { + let (mut sc, mut out) = stdio("problem"); + let t: usize = sc.next(); + for _ in 0..t {} +} diff --git a/usaco b/usaco index e3c83e7..b20c965 100755 --- a/usaco +++ b/usaco @@ -9,32 +9,40 @@ # r / t / e act on the current problem # !cmd run a shell command in the problem dir # q quit -# usaco new [io-name] [--url ] -# Create solving/ from template.cpp -# (io-name sets freopen filenames, defaults to ) +# usaco new [io-name] [--url ] [--rust|--cpp] +# Create solving/ from template.cpp or template.rs +# (io-name sets the file-io name, defaults to ; +# language defaults to 'usaco lang', see below) # usaco new Import a LeetCode problem (alias: from): statement in # problem.md, C++ starter + generated driver.h, the examples # as tests/ with expected outputs # usaco daily Same, for today's LeetCode daily question -# usaco run Build main.cpp and run it (in the problem dir) -# usaco build Build main.cpp only +# usaco lang [cpp|rust] Show or set the default language for 'usaco new' +# ($USACO_LANG wins for a single shell) +# usaco run Build the solution and run it (in the problem dir) +# usaco build Build only # usaco done Move solving/ -> solved/ and git commit # usaco undo Move solved/ or skipped/ -> solving/ # usaco skip Move solving/ -> skipped/ # usaco io [io-name] Show the problem's io name, or set it: renames .in/.out -# and rewires STDIO("...") in main.cpp (adds it if missing) -# usaco cat Print the problem's main.cpp to stdout (pipeable) -# usaco copy Copy the problem's main.cpp to the clipboard (alias: cp) -# usaco vim Open the problem's main.cpp in $EDITOR (aliases: edit, e) +# and rewires STDIO("...") / stdio("...") in the source +# usaco cat Print the problem's solution to stdout (pipeable) +# usaco copy Copy the problem's solution to the clipboard (alias: cp) +# usaco vim Open the problem's solution in $EDITOR (aliases: edit, e) # usaco open Open the problem's saved URL in a browser # usaco list List problems by status # usaco stats Show solve counts and recent activity # usaco path Print the problem's directory (used by the ucd shell helper) # usaco clean Delete compiled binaries and backups from all problem dirs # usaco sync git pull --rebase (picks up edits made on the website), then push -# usaco reset [-y] Reset the solution: fresh main.cpp from template (STDIO wired up, -# old one saved as main.cpp.bak), delete binary + .out; keeps tests/ -# and .in. Asks first unless -y (aliases: rm, delete, template, tpl) +# usaco lint [name...] Run clippy over the rust solutions (all of them, or just the +# named ones; "template" lints template.rs) and refresh the +# Cargo.toml rust-analyzer reads +# usaco reset [lang] [-y] +# Reset the solution: fresh source from template (io wired up, +# old one saved as .bak), delete binary + .out; keeps tests/ and +# .in. cpp/rust switches the problem's language. Asks first +# unless -y (aliases: rm, delete, template, tpl) # usaco test create Save a test case: uses the current .in (or lets you paste one), # then asks for the expected output. Stored in tests/N.in + N.out # usaco test [nums...] Build and run every saved test case (or just the given ones), @@ -74,6 +82,8 @@ case "$cmd" in path|p) cmd=path ;; clean) cmd=clean ;; sync|sy) cmd=sync ;; + lang) cmd=lang ;; + lint) cmd=lint ;; reset|rm|delete|template|tpl) cmd=reset ;; *) usage ;; esac diff --git a/usaco.zsh b/usaco.zsh index 01c001c..8b40e67 100644 --- a/usaco.zsh +++ b/usaco.zsh @@ -34,13 +34,13 @@ _usaco() { 'n:create a problem from template' 'from:import a LeetCode problem from its link' "daily:import today's LeetCode daily question" - 'run:build and run main.cpp' - 'r:build and run main.cpp' - 'build:build main.cpp' - 'b:build main.cpp' - 'vim:open main.cpp in $EDITOR' - 'edit:open main.cpp in $EDITOR' - 'e:open main.cpp in $EDITOR' + 'run:build and run the solution' + 'r:build and run the solution' + 'build:build the solution' + 'b:build the solution' + 'vim:open the solution in $EDITOR' + 'edit:open the solution in $EDITOR' + 'e:open the solution in $EDITOR' 'test:run saved test cases (test create to add one)' 't:run saved test cases' 'done:mark solved (auto-commits)' @@ -49,10 +49,10 @@ _usaco() { 'u:move back to solving' 'skip:set aside for later' 'sk:set aside for later' - 'io:show or set the freopen io name' - 'cat:print main.cpp to stdout' - 'copy:copy main.cpp to the clipboard' - 'cp:copy main.cpp to the clipboard' + 'io:show or set the file-io name' + 'cat:print the solution to stdout' + 'copy:copy the solution to the clipboard' + 'cp:copy the solution to the clipboard' 'open:open the saved problem URL' 'o:open the saved problem URL' 'list:list problems by status' @@ -65,17 +65,20 @@ _usaco() { 'clean:delete binaries and backups' 'sync:pull website edits, push local commits' 'sy:pull website edits, push local commits' + 'lint:run clippy over the rust solutions and template.rs' 'template:same as reset' 'tpl:same as reset' - 'reset:fresh main.cpp from template, delete binary/.out' - 'rm:fresh main.cpp from template, delete binary/.out' - 'delete:fresh main.cpp from template, delete binary/.out' + 'reset:fresh solution from template (cpp/rust switches language), delete binary/.out' + 'rm:fresh solution from template (cpp/rust switches language), delete binary/.out' + 'delete:fresh solution from template (cpp/rust switches language), delete binary/.out' + 'lang:show or set the default language for new problems' ) if (( CURRENT == 2 )); then _describe 'command' cmds elif (( CURRENT == 3 )); then case "$words[2]" in i|interactive|repl|new|n|from|daily|list|l|ls|stats|st|clean|sync|sy) ;; # no problem-name argument + lang) _values 'language' cpp rust ;; test|t) local -a subs subs=('create:save a new test case' 'add:save a new test case' 'new:save a new test case') @@ -83,8 +86,11 @@ _usaco() { _usaco_problems ;; *) _usaco_problems ;; esac - elif (( CURRENT == 4 )) && [[ "$words[2]" == (test|t) && "$words[3]" == (create|add|new) ]]; then - _usaco_problems + elif (( CURRENT == 4 )); then + case "$words[2]" in + test|t) [[ "$words[3]" == (create|add|new) ]] && _usaco_problems ;; + template|tpl|reset|rm|delete) _values 'language' cpp rust ;; + esac fi } if (( $+functions[compdef] )); then