"""
=============================================================================
Lecture 4 · 脚本：用编译器本身来验证语言规则（讲义 §3、§6、§7）
=============================================================================

【这个脚本要回答的问题】
    "这样写编译不过"这句话，光看讲义是学不会的。这里把每条规则写成一小段代码，
    真的交给 clang++ 编译，把结果列成一张表。编译器说了算。

    其中有一条要特别注意：原课 slides 把 `int const *c` 说成"不能改指针的 const 指针"。
    实测 `int const *` 和 `const int *` 是**同一个类型**（都是指向常量的指针）；
    真正的 const 指针要写成 `int *const`。这也是为什么规则要让编译器来验证。

【运行】python3 compile_checks.py        （约 5 秒）

【边界】需要 c++ 命令。这里只做语法和类型检查（-fsyntax-only），不生成程序；
    链接相关的两条用真正的编译和链接。
"""

import os
import shutil
import subprocess
import tempfile

import course_path
course_path.use("lecture01")
import console

CXX = shutil.which("c++") or shutil.which("clang++") or "c++"

PTR = "int a = 1, b = 2;\n"

CHECKS = [
    ("const 和指针", [
        ("int* p：改指向", PTR + "int* p = &a; p = &b;", True),
        ("int* p：改内容", PTR + "int* p = &a; *p = 5;", True),
        ("const int* p：改指向", PTR + "const int* p = &a; p = &b;", True),
        ("const int* p：改内容", PTR + "const int* p = &a; *p = 5;", False),
        ("int const* p：改指向", PTR + "int const* p = &a; p = &b;", True),
        ("int const* p：改内容", PTR + "int const* p = &a; *p = 5;", False),
        ("int* const p：改指向", PTR + "int* const p = &a; p = &b;", False),
        ("int* const p：改内容", PTR + "int* const p = &a; *p = 5;", True),
        ("const int* const p：改指向", PTR + "const int* const p = &a; p = &b;", False),
        ("const int* const p：改内容", PTR + "const int* const p = &a; *p = 5;", False),
    ]),
    ("const 成员函数", [
        ("const 函数里读成员", "struct V { int x; int get() const { return x; } };", True),
        ("const 函数里写成员", "struct V { int x; void set() const { x = 1; } };", False),
        ("const 对象调用 const 函数", "struct V { int x; int get() const { return x; } }; const V v{1}; int r = v.get();", True),
        ("const 对象调用非 const 函数", "struct V { int x; int get() { return x; } }; const V v{1}; int r = v.get();", False),
        ("mutable 成员可以在 const 函数里写", "struct V { mutable int hits = 0; void f() const { hits++; } };", True),
    ]),
    ("访问权限", [
        ("类外读 public", "class A { public: int x = 1; }; int f() { A a; return a.x; }", True),
        ("类外读 private", "class A { int x = 1; }; int f() { A a; return a.x; }", False),
        ("类外读 protected", "class A { protected: int x = 1; }; int f() { A a; return a.x; }", False),
        ("派生类读 protected", "class A { protected: int x = 1; }; class B : public A { int f() { return x; } };", True),
        ("派生类读 private", "class A { int x = 1; }; class B : public A { int f() { return x; } };", False),
        ("friend 读 private", "class A { int x = 1; friend class C; }; class C { int f(A& a) { return a.x; } };", True),
        ("friend 不能继承", "class A { int x = 1; friend class C; }; class C {}; class D : public C { int f(A& a) { return a.x; } };", False),
        ("struct 默认 public", "struct A { int x = 1; }; int f() { A a; return a.x; }", True),
        ("private 构造函数：类外不能创建", "class A { A() {} }; A a;", False),
    ]),
    ("引用", [
        ("引用必须初始化", "int& r;", False),
        ("引用绑定到变量", "int a = 1; int& r = a;", True),
        ("非 const 引用不能绑定临时值", "int& r = 1 + 2;", False),
        ("const 引用可以绑定临时值", "const int& r = 1 + 2;", True),
    ]),
    ("模板", [
        ("没被调用的模板成员函数可以有错", "#include <vector>\ntemplate <class T> struct C { T x; int f() { return x.size(); } }; C<float> c;", True),
        ("一旦调用就报错", "#include <vector>\ntemplate <class T> struct C { T x; int f() { return x.size(); } }; C<float> c; int r = c.f();", False),
        ("类型要满足隐含要求", "template <class T> T lerp(T a, T b) { return a * 0.5f + b * 0.5f; } struct S {}; S r = lerp(S{}, S{});", False),
    ]),
    ("虚函数", [
        ("抽象类不能实例化", "struct S { virtual float hit() const = 0; }; S s;", False),
        ("实现了纯虚函数的派生类可以", "struct S { virtual float hit() const = 0; }; struct P : S { float hit() const override { return 0; } }; P p;", True),
        ("override 拼错了签名会报错", "struct S { virtual float hit() const { return 0; } }; struct P : S { float hit() override { return 1; } };", False),
        ("不写 override 则悄悄变成新函数", "struct S { virtual float hit() const { return 0; } }; struct P : S { float hit() { return 1; } };", True),
    ]),
]


def compiles(code):
    """
    让编译器检查一小段代码。

    【参数】code：完整的 C++ 代码
    【返回】(是否通过, 第一条错误信息)
    """
    with tempfile.TemporaryDirectory() as d:
        path = os.path.join(d, "t.cpp")
        with open(path, "w", encoding="utf-8") as f:
            f.write(code)
        r = subprocess.run([CXX, "-std=c++20", "-fsyntax-only", "-w", path], capture_output=True, text=True)
    first = next((line.split("error:", 1)[1].strip() for line in r.stderr.splitlines() if "error:" in line), "")
    return r.returncode == 0, first


def wrap(code):
    """
    把语句放进一个函数，把声明放在全局。

    【思路】struct、class 开头或 #include 开头的片段本身就是完整的声明；其余的是函数内的语句。
    """
    stripped = code.lstrip()
    if stripped.startswith(("struct", "class", "template", "#include")):
        return code
    return "void test() {\n" + code + "\n}\n"


def link_check():
    """
    演示 static 全局变量的用处：两个 .cpp 文件各定义一个同名全局变量。

    【思路】不写 static：链接器发现两个定义，报错。写了 static：每个文件有自己的一份，互不影响。
    """
    console.print_header("链接：两个文件都定义全局变量 numCores")
    with tempfile.TemporaryDirectory() as d:
        main_cpp = os.path.join(d, "main.cpp")
        lib_cpp = os.path.join(d, "lib.cpp")
        binary = os.path.join(d, "a.out")
        rows = []
        for label, prefix in [("都不写 static", ""), ("lib.cpp 写 static", "static ")]:
            with open(main_cpp, "w", encoding="utf-8") as f:
                f.write('#include <cstdio>\nint numCores = 8;\nint lib_cores();\nint main() { std::printf("%d %d", numCores, lib_cores()); }\n')
            with open(lib_cpp, "w", encoding="utf-8") as f:
                f.write(f"{prefix}int numCores = 1;\nint lib_cores() {{ return numCores; }}\n")
            r = subprocess.run([CXX, "-std=c++20", main_cpp, lib_cpp, "-o", binary], capture_output=True, text=True)
            if r.returncode == 0:
                out = subprocess.run([binary], capture_output=True, text=True).stdout
                rows.append([label, "成功", f"main 看到 {out.split()[0]}，lib 看到 {out.split()[1]}"])
            else:
                line = next((x for x in r.stderr.splitlines() if "duplicate" in x or "multiple" in x), "链接失败")
                rows.append([label, "失败", line.strip()[:50]])
        console.print_table(["写法", "链接结果", "说明"], rows, align=["<", "<", "<"])
    print("\n  观察：static 全局变量只在本文件可见，所以两个文件可以各有一份。这是 static 的第三种含义，和类里的 static 毫无关系。")


def main():
    total = wrong = 0
    for group, cases in CHECKS:
        console.print_header(group)
        rows = []
        for name, code, expected in cases:
            ok, message = compiles(wrap(code))
            total += 1
            wrong += ok != expected
            mark = "" if ok == expected else "  ← 和预期不符！"
            rows.append([name, "通过" if ok else "报错", (message[:62] if not ok else "") + mark])
        console.print_table(["写法", "编译结果", "错误信息"], rows, align=["<", "<", "<"])
    link_check()
    print(f"\n  共 {total} 条规则，和预期不符的 {wrong} 条。")
    print("  结论：const 写在 * 左边限制内容，写在 * 右边限制指针。`int const *` 和 `const int *` 是同一个类型（都不能改内容）；")
    print("        原课 slides 把 `int const *c` 写成不能改指针，这一处不对，真正的 const 指针是 `int *const c`。")
    print("        从右往左读最不容易错：`int *const p` 读作 p 是一个 const 指针，指向 int。")


if __name__ == "__main__":
    main()
