Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions exercises/practice/pangram/.docs/hints.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Hints

## Passing the sentence: `const` reference

The reference solution's helper takes the sentence like this:

```cpp
bool found_letter(char a, const std::string &s)
```

`const std::string &s` is a reference to const: the function gets a read-only view of the caller's string instead of its own copy. A `char` is tiny, so it is passed by value. A whole sentence can be long, so it is passed by `const` reference.

This matters here because `is_pangram` asks `found_letter` about each of the 26 letters, so the sentence is passed 26 times.

The program below counts copies with a small wrapper type, so you can see them (it does not solve the exercise):

```cpp
#include <iostream>
#include <string>
#include <utility>

// A tiny wrapper that counts how many times it is copied.
struct Sentence {
std::string text;
static int copies;

explicit Sentence(std::string t) : text(std::move(t)) {}
Sentence(const Sentence &other) : text(other.text) { ++copies; }
};

int Sentence::copies = 0;

// Same shape as the reference helper: a char by value, the sentence by const reference.
bool found_letter(char a, const Sentence &s) {
for (char c : s.text) {
if (c == a) {
return true;
}
}
return false;
}

int main() {
Sentence sentence{"The quick brown fox jumps over the lazy dog"};
for (char letter = 'a'; letter <= 'z'; ++letter) {
found_letter(letter, sentence);
}
std::cout << "const reference: " << Sentence::copies << " copies\n";
}
```

Expected output:

```text
const reference: 0 copies
```

Now remove the `const` and the `&`, so the parameter becomes `Sentence s`, and change the output label to `by value: `. Every call now copies the whole sentence:

```text
by value: 26 copies
```

The answers from `found_letter` are identical, but there are 26 copies instead of none. As a rule of thumb, pass cheap types like `char` by value, and pass things you only read but that are expensive to copy, like strings, by `const` reference.

Further reading: [Reference declaration](https://en.cppreference.com/w/cpp/language/reference) on cppreference.
228 changes: 228 additions & 0 deletions work/R20-T057/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
#!/usr/bin/env python3
"""Task R20-T057 (pangram): check the reference build and the hint's micro-examples.

Run from anywhere: python3 work/R20-T057/check.py
Exits 0 only if every check passes. Any problem exits non-zero.
"""
import json
import re
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent # work/R20-T057
REPO = HERE.parents[1] # repository root
EXERCISE = REPO / "exercises" / "practice" / "pangram"
HINTS = EXERCISE / ".docs" / "hints.md"
CMAKE_FLAG = "-DEXERCISM_RUN_ALL_TESTS=ON"
PASS_LINE = re.compile(r"All tests passed \((\d+) assertions? in (\d+) test cases?\)")

# If a name is reported missing, open pangram_test.cpp and copy the TEST_CASE name exactly.
NAMED_CASES = ["sentence_empty", "pangram_with_only_lower_case", "missing_character_x"]

CONSTRUCT = "const std::string &s"
REFERENCE_LINK = "https://en.cppreference.com/w/cpp/language/reference"
MICRO_EXAMPLES = [
# (source file next to this script, exact expected output line)
("micro_const_ref.cpp", "const reference: 0 copies"),
("micro_by_value.cpp", "by value: 26 copies"),
]


class CheckError(Exception):
"""Raised when any check fails."""


def need(condition, message):
if not condition:
raise CheckError(message)


def run(cmd, cwd):
return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)


def squash(text):
"""Collapse all whitespace so formatting differences do not matter."""
return " ".join(text.split())


def count_enabled_cases(tests_toml):
"""Count the [uuid] sections in tests.toml that are not marked include = false."""
count, enabled = 0, None
for raw in tests_toml.read_text().splitlines():
line = raw.strip()
if re.fullmatch(r"\[[0-9a-fA-F-]{36}\]", line):
if enabled:
count += 1
enabled = True
elif re.fullmatch(r"include\s*=\s*false", line):
enabled = False
if enabled:
count += 1
return count


def save_tool_versions():
lines = []
for cmd in (["cmake", "--version"], ["g++", "--version"], [sys.executable, "--version"]):
result = run(cmd, REPO)
lines.append("$ " + " ".join(cmd))
lines.append((result.stdout + result.stderr).strip())
lines.append("")
(HERE / "tool_versions.txt").write_text("\n".join(lines))


def build_and_test_reference(reference, expected_cases):
"""Build the exercise in a temporary copy with the reference swapped in, then run its tests."""
with tempfile.TemporaryDirectory() as tmp:
# Keep the folder name: CMake names the test program after it.
copy = Path(tmp) / EXERCISE.name
shutil.copytree(EXERCISE, copy) # copies dotfiles such as .meta and .docs too
for name, source in reference.items():
shutil.copyfile(source, copy / name)

step = run(["cmake", "-S", ".", "-B", "build", CMAKE_FLAG], copy)
need(step.returncode == 0, f"cmake configure failed:\n{step.stdout}{step.stderr}")

step = run(["cmake", "--build", "build"], copy)
need(step.returncode == 0, f"build failed:\n{step.stdout}{step.stderr}")

exe = copy / "build" / EXERCISE.name
need(exe.exists(), f"test program not found at {exe}")

result = run([str(exe)], copy)
output = result.stdout + result.stderr
(HERE / "reference_test_output.txt").write_text(output)
need(result.returncode == 0, f"tests failed (exit code {result.returncode}):\n{output}")

match = PASS_LINE.search(output)
need(match, f"could not find the 'All tests passed' summary:\n{output}")
cases = int(match.group(2))
need(cases > 0, "zero test cases ran")
need(cases == expected_cases, f"expected {expected_cases} test cases but {cases} ran")

# The named cases must exist and pass on their own.
listing = run([str(exe), "--list-test-names-only"], copy)
names = [line.strip() for line in listing.stdout.splitlines() if line.strip()]
named = {}
for case in NAMED_CASES:
need(case in names, f"named case '{case}' not found. Test names are: {names}")
single = run([str(exe), case], copy)
single_out = single.stdout + single.stderr
found = PASS_LINE.search(single_out)
need(
single.returncode == 0 and found and int(found.group(2)) == 1,
f"named case '{case}' did not pass on its own:\n{single_out}",
)
named[case] = "passed"

return {
"exit_code": result.returncode,
"expected_cases": expected_cases,
"actual_cases": cases,
"assertions": int(match.group(1)),
"named_cases": named,
}


def run_micro_examples():
"""Compile and run each micro-example, and assert its exact output."""
compiler = shutil.which("g++") or shutil.which("c++")
need(compiler, "no C++ compiler found (g++ or c++)")
outputs = {}
with tempfile.TemporaryDirectory() as tmp:
for filename, expected in MICRO_EXAMPLES:
source = HERE / filename
need(source.exists(), f"missing {source}")
exe = Path(tmp) / source.stem
step = run([compiler, "-std=c++17", "-O0", str(source), "-o", str(exe)], tmp)
need(step.returncode == 0, f"{filename} failed to compile:\n{step.stdout}{step.stderr}")
result = run([str(exe)], tmp)
need(result.returncode == 0, f"{filename} exited with {result.returncode}")
actual = result.stdout.strip()
(HERE / f"{source.stem}_output.txt").write_text(result.stdout)
need(actual == expected, f"{filename}: expected {expected!r} but got {actual!r}")
outputs[filename] = {"expected": expected, "actual": actual}
return outputs


def check_hint(reference_cpp):
"""The published hint must agree with the micro-examples and the reference."""
need(HINTS.exists(), f"missing {HINTS}")
hint = HINTS.read_text()

need(CONSTRUCT in reference_cpp.read_text(), f"'{CONSTRUCT}' is not in the reference")
need(CONSTRUCT in hint, f"hints.md must name the construct '{CONSTRUCT}'")
need(REFERENCE_LINK in hint, f"hints.md must link {REFERENCE_LINK}")

for filename, expected in MICRO_EXAMPLES:
need(expected in hint, f"hints.md must show the output line: {expected}")

example = squash((HERE / "micro_const_ref.cpp").read_text())
need(example in squash(hint), "the code in hints.md must match micro_const_ref.cpp")

need("tolower(c) == a" not in hint, "hints.md must not contain the reference's solution code")


def main():
config = json.loads((EXERCISE / ".meta" / "config.json").read_text())
solution = config["files"]["solution"]
example = config["files"]["example"]
need(len(solution) == len(example), "config.json: solution and example lists differ in length")

# The learner stub and test files must stay exactly as they are in git.
# (hints.md is allowed to change: that is the contribution.)
protected = [str(EXERCISE / name) for name in solution + config["files"]["test"]]
status = run(["git", "status", "--porcelain", "--", *protected], REPO)
need(status.returncode == 0, f"git status failed: {status.stderr}")
need(status.stdout.strip() == "", f"learner files were modified:\n{status.stdout}")

toml_cases = count_enabled_cases(EXERCISE / ".meta" / "tests.toml")
test_source = (EXERCISE / config["files"]["test"][0]).read_text()
expected = len(re.findall(r"^\s*TEST_CASE\(", test_source, re.M))
need(expected > 0, "found no TEST_CASE in the test file")
if toml_cases != expected:
print(f"NOTE: tests.toml lists {toml_cases} enabled cases but the test file has {expected}")

reference = {sol: EXERCISE / ex for sol, ex in zip(solution, example)}
reference_cpp = next(path for name, path in reference.items() if name.endswith(".cpp"))

save_tool_versions()
build = build_and_test_reference(reference, expected)
micro = run_micro_examples()
check_hint(reference_cpp)

evidence = {
"inputs": {
"reference_files": {k: str(v.relative_to(REPO)) for k, v in reference.items()},
"micro_examples": [name for name, _ in MICRO_EXAMPLES],
"hint": str(HINTS.relative_to(REPO)),
"cmake_flag": CMAKE_FLAG,
},
"tests_toml_enabled": toml_cases,
"reference_build": build,
"micro_examples": micro,
}
(HERE / "evidence.json").write_text(json.dumps(evidence, indent=2))

print(f"reference: {build['actual_cases']} test cases ran "
f"({build['assertions']} assertions), expected {build['expected_cases']}, "
f"exit code {build['exit_code']}")
print("named cases: " + ", ".join(f"{k} {v}" for k, v in build["named_cases"].items()))
for name, result in micro.items():
print(f"{name}: {result['actual']}")
print("PASS: reference tests, micro-examples and hint all agree")


if __name__ == "__main__":
try:
main()
except CheckError as err:
print(f"FAIL: {err}")
sys.exit(1)
except OSError as err:
print(f"FAIL: could not run a required tool or read a file: {err}")
sys.exit(1)
36 changes: 36 additions & 0 deletions work/R20-T057/evidence.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"inputs": {
"reference_files": {
"pangram.cpp": "exercises/practice/pangram/.meta/example.cpp",
"pangram.h": "exercises/practice/pangram/.meta/example.h"
},
"micro_examples": [
"micro_const_ref.cpp",
"micro_by_value.cpp"
],
"hint": "exercises/practice/pangram/.docs/hints.md",
"cmake_flag": "-DEXERCISM_RUN_ALL_TESTS=ON"
},
"tests_toml_enabled": 10,
"reference_build": {
"exit_code": 0,
"expected_cases": 9,
"actual_cases": 9,
"assertions": 9,
"named_cases": {
"sentence_empty": "passed",
"pangram_with_only_lower_case": "passed",
"missing_character_x": "passed"
}
},
"micro_examples": {
"micro_const_ref.cpp": {
"expected": "const reference: 0 copies",
"actual": "const reference: 0 copies"
},
"micro_by_value.cpp": {
"expected": "by value: 26 copies",
"actual": "by value: 26 copies"
}
}
}
32 changes: 32 additions & 0 deletions work/R20-T057/micro_by_value.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include <iostream>
#include <string>
#include <utility>

// A tiny wrapper that counts how many times it is copied.
struct Sentence {
std::string text;
static int copies;

explicit Sentence(std::string t) : text(std::move(t)) {}
Sentence(const Sentence &other) : text(other.text) { ++copies; }
};

int Sentence::copies = 0;

// The contrast: the sentence is taken by value, so every call copies it.
bool found_letter(char a, Sentence s) {
for (char c : s.text) {
if (c == a) {
return true;
}
}
return false;
}

int main() {
Sentence sentence{"The quick brown fox jumps over the lazy dog"};
for (char letter = 'a'; letter <= 'z'; ++letter) {
found_letter(letter, sentence);
}
std::cout << "by value: " << Sentence::copies << " copies\n";
}
1 change: 1 addition & 0 deletions work/R20-T057/micro_by_value_output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
by value: 26 copies
Loading