CS100 · Fall 2026 · Programming Assignment

HW6: Expression Trees and Templates

C++17 · GitHub submission on Gradescope · 300 points

Release · 发布

Deadline · 截止

Download starter (ZIP)

Submission

Submit one GitHub repository to HW6_programming on Gradescope. Put p1.cc, p2.cc, and p3.cc at the top level. Each problem is worth 100 points.

These files contain the requested definitions. Gradescope compiles them with the course test drivers and their own main functions. The starter includes example drivers and the support files for Expression 2.0. Use g++ -std=c++17 for local compilation.

P1

Expression

100 pts

Background

In this problem, we deal with trees that represent arithmetic expressions. We first consider only the expressions consisting of numbers (constants), the unary + and - operators, and the binary +, -, * and / operators. Such expressions can be represented by a tree structure, which is named expression trees or abstract syntax trees (AST). For example, the tree representing (2 + 5) * 3 / (-6) is

---
title: (2 + 5) * 3 / (-6)
---
graph
  / --> *
  * --> +
  + --> 2
  + --> 5
  * --> 3
  / --> -
  - --> 6

Such a tree is quite useful, as it contains the structure of all subexpressions. We may perform some operations on the tree recursively, such as printing, evaluation, conversion to some special forms, etc. Now your task is to build a class hierarchy representing these different kinds of nodes. Parsing an expression into an AST is beyond the scope of CS100.

The basic structure

We start from the following basic structure.

---
title: Basic Structure
---
classDiagram
    class ExprNode {
        +evaluate()* double
        +toString()* std::string
    }
    class Constant {
        -double mValue
        +evaluate() double
    +toString() std::string
    }
  class UnaryOperator {
    -UnaryOpKind mOpKind
    -std::shared_ptr~ExprNode~ mOperand
    +evaluate() double
    +toString() std::string
  }
  class BinaryOperator {
    -BinaryOpKind mOpKind
    -std::shared_ptr~ExprNode~ mLeft
    -std::shared_ptr~ExprNode~ mRight
    +evaluate() double
    +toString() std::string
  }
  ExprNode <|-- Constant
  ExprNode <|-- UnaryOperator
  ExprNode <|-- BinaryOperator

Note: some functions should be declared virtual or pure virtual (your task).

class ExprNode {
public:
  // FIXME: Some of the functions below should be virtual or pure virtual.
  ExprNode() = default;
  double evaluate() const;
  std::string toString() const;
  ~ExprNode() = default;
};

class Constant : public ExprNode {
  double mValue;

public:
  explicit Constant(double value) : mValue{value} {}
  // TODO: evaluate() and toString() ...
};

enum class UnaryOpKind {
  UOK_Plus, UOK_Minus
};

class UnaryOperator : public ExprNode {
  UnaryOpKind mOpKind;
  std::shared_ptr<ExprNode> mOperand;

public:
  UnaryOperator(UnaryOpKind op, std::shared_ptr<ExprNode> operand)
      : mOpKind{op}, mOperand{std::move(operand)} {}
  // TODO: evaluate() and toString() ...
};

enum class BinaryOpKind {
  BOK_Plus, BOK_Minus, BOK_Mul, BOK_Div
};

class BinaryOperator : public ExprNode {
  BinaryOpKind mOpKind;
  std::shared_ptr<ExprNode> mLeft;
  std::shared_ptr<ExprNode> mRight;

public:
  BinaryOperator(BinaryOpKind op, std::shared_ptr<ExprNode> left, std::shared_ptr<ExprNode> right)
      : mOpKind{op}, mLeft{std::move(left)}, mRight{std::move(right)} {}
  // TODO: evaluate() and toString() ...
};

It seems to be a nice hierarchy, but how does the user create a node? The user has to write

// To create a BinaryOperator statically:
BinaryOperator bo1(BinaryOpKind::BOK_Plus,
                   std::make_shared<Constant>(3),
                   std::make_shared<Constant>(4));

// To create a BinaryOperator dynamically:
auto bo2 = std::make_shared<BinaryOperator>(
               BinaryOpKind::BOK_Plus,
               std::make_shared<Constant>(3),
               std::make_shared<Constant>(4));

which involves creating the shared_ptrs manually. This is too ugly and inconvenient.

A level of indirection

Here goes the so-called “Fundamental Theorem of Software Engineering”:

We can solve any problem by introducing an extra level of indirection.

Our problem is that the user still has to do memory management (even though smart pointers are used). Ideally, memory management should be part of our implementation details. The user should only care about the structure of the tree. For example, we expect the user to be able to create a node in the following way

Expr bo('+', Expr(3), Expr(4));

or even more conveniently like

auto bo = Expr(3) + Expr(4);

Clearly, the latter one can be supported with a simple overloaded operator as long as the former one is supported.

Let’s consider defining the Expr class, which works as the level of indirection between the user and the specific node classes. The class Expr should encapsulate a std::shared_ptr<ExprNode> and hide everything related to memory management from the user. Moreover, Expr should also provide the interfaces like evaluate() and toString().

class Expr {
  std::shared_ptr<ExprNode> mNode;

  Expr(std::shared_ptr<ExprNode> ptr) : mNode{std::move(ptr)} {}

public:
  // To enable the usage like `Expr(3)`.
  // This constructor is not marked `explicit`.
  Expr(double value) : mNode{std::make_shared<Constant>(value)} {}
  auto toString() const { return mNode->toString(); }
  auto evaluate() const { return mNode->evaluate(); }

  // TODO: Some friend declarations might be necessary ...
};

Since Expr is a wrapper of a std::shared_ptr<ExprNode>, it should have a constructor that initializes that shared_ptr member. We make this constructor private because we don’t want the user to call it directly.

Now let’s think about what Expr actually does. It contains a smart pointer to some node class, and behaves very much like a node class because it has the interfaces toString() and evaluate(). Such a class that represents an object of any node type perfectly and does memory management internally is called a surrogate (代理) or a handle (句柄).

With this handle class defined, wherever a std::shared_ptr<ExprNode> is needed, a Expr can always work. The other node classes can simply replace every std::shared_ptr<ExprNode> with Expr and completely forget about how memory is managed:

class UnaryOperator : public ExprNode {
  UnaryOpKind mOpKind;
  Expr mOperand;

public:
  UnaryOperator(UnaryOpKind op, Expr operand)
      : mOpKind{op}, mOperand{std::move(operand)} {}
  
  // TODO: evaluate and toString ...
};

The user may create a UnaryOperator node through the following overloaded operators:

Expr operator-(const Expr &arg) {
  return {std::make_shared<UnaryOperator>(UnaryOpKind::UOK_Minus, arg)};
}
Expr operator+(const Expr &arg) {
  return {std::make_shared<UnaryOperator>(UnaryOpKind::UOK_Plus, arg)};
}

(What is return {...}? See Appendix: Returning a braced-init-list.)

For example,

auto neg3 = -Expr(3);

More functionalities

With basic knowledge on our class hierarchy obtained, you are going to add support for more functionalities:

The operations that need to be supported are declared in this base class:

class ExprNode {
public:
  // FIXME: Make any of these functions virtual, or pure virtual, if necessary.
  ExprNode() = default;
  double evaluate(double x) const;   // Evaluate f(x)
  double derivative(double x) const; // Evaluate df(x)/dx
  std::string toString() const;      // Returns the parenthesized representation of the function.
  ~ExprNode() = default;
};

In the previous sections, we used only one class BinaryOperator to represent four different kinds of binary operators. Such design may not be convenient now, because the ways of evaluating the function and its derivative differ to a greater extent between different operators. Therefore, we separate them into four classes:

class BinaryOperator : public ExprNode {
protected:
  Expr mLeft;
  Expr mRight;

public:
  BinaryOperator(Expr left, Expr right)
      : mLeft{std::move(left)}, mRight{std::move(right)} {}
};

class PlusOperator : public BinaryOperator {
public:
  using BinaryOperator::BinaryOperator;
  // TODO: evaluate(), derivative() and toString() ...
};

class MinusOperator : public BinaryOperator {
public:
  using BinaryOperator::BinaryOperator;
  // TODO: evaluate(), derivative() and toString() ...
};

class MultiplyOperator : public BinaryOperator {
public:
  using BinaryOperator::BinaryOperator;
  // TODO: evaluate(), derivative() and toString() ...
};

class DivideOperator : public BinaryOperator {
public:
  using BinaryOperator::BinaryOperator;
  // TODO: evaluate(), derivative() and toString() ...
};

(What is using BinaryOperator::BinaryOperator;? See Appendix: Inheriting constructors.)

To support the variable x, we define a new class Variable:

class Variable : public ExprNode {
  // TODO: evaluate(), derivative() and toString() ...
};

Then we define a static data member of Expr as follows.

class Expr {
  std::shared_ptr<ExprNode> mNode;

  Expr(std::shared_ptr<ExprNode> ptr) : mNode{std::move(ptr)} {}

public:
  // This constructor should be defined after the class `Constant` is defined,
  // because creating an object of type `std::shared_ptr<T>` when `T` is incomplete
  // is not allowed.
  Expr(double value);

  static const Expr x;

  // Other members ...
};

// After the definition of the class `Variable`:
const Expr Expr::x{std::make_shared<Variable>()};

Note that Expr also has a non-explicit constructor that receives a double and creates a Constant node:

// After the definition of the class `Constant`:
Expr::Expr(double value) : mNode{std::make_shared<Constant>(value)} {}

Appendix: Unused parameters may be of help when defining Constant and Variable.

The final structure is as follows.

---
title: Final Structure
---
classDiagram
  class ExprNode {
    +evaluate(x)* double
    +derivative(x)* double
    +toString()* std::string
  }
  ExprNode <|-- Constant
  ExprNode <|-- BinaryOperator
  ExprNode <|-- Variable
  ExprNode <|-- UnaryOperator
  class Constant {
    -double mValue
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }
  class Variable {
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }
  class UnaryOperator {
    -UnaryOpKind mOpKind
    -Expr mOperand
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }
  class BinaryOperator {
    #Expr left
    #Expr right
  }
  BinaryOperator <|-- PlusOperator
  BinaryOperator <|-- MinusOperator
  BinaryOperator <|-- MultiplyOperator
  BinaryOperator <|-- DivideOperator
  class PlusOperator {
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }
  class MinusOperator {
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }
  class MultiplyOperator {
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }
  class DivideOperator {
    +evaluate(x) double
    +derivative(x) double
    +toString() std::string
  }

With all of these and the overloaded arithmetic operators defined (your task), we can create functions in a very convenient manner:

auto &x = Expr::x;
auto f = x * x + 2 * x + 1; // x^2 + 2x + 1
std::cout << f.toString() << std::endl;
std::cout << f.evaluate(3) << std::endl;
std::cout << f.derivative(3) << std::endl;
auto g = f / (-x * x + x - 1); // (x^2 + 2x + 1)/(-x^2 + x - 1)
std::cout << g.evaluate(3) << std::endl;
std::cout << g.derivative(3) << std::endl;

The output should be

(((x) * (x)) + ((2.000000) * (x))) + (1.000000)
16
8
-2.28571
0.489796

Requirements for toString()

Note: This is a very simple and naive way to convert an expression to a string, because we don’t want to set barriers on this part. You can search for some algorithms to make the expression as simplified as possible, but it may not pass the OJ tests.

Any operand of the unary operators (+, -) or the binary operators (+, -, *, /) should be surrounded by a pair of parentheses. Correct examples: - 2+32+3: (2.000000) + (3.000000) - 2x+32x+3: ((2.000000) * (x)) + (3.000000) - 2⋅(−x)+32\cdot(-x)+3: ((2.000000) * (-(x))) + (3.000000)

Note: If the floating-point value of a Constant node is negative, it is not treated as a unary minus sign applied to its absolute value. For example,

Expr e(-2);
std::cout << e.toString() << std::endl;

The output should be -2.000000 instead of -(2.000000).

There should be a space before and after each binary operator, e.g. (expr1) + (expr2) instead of (expr1)+(expr2).

To convert a floating-point number to std::string, just use std::to_string and you will be free of troubles caused by precisions and floating-point errors.

example.cpp contains these simple tests.

Requirements for Expr

From the user’s perspective, only Expr and its arithmetic operators are interfaces. Anything else in your code is implementation details, which user code will not rely on. In other words, you are free to implement these things in any way, as long as the interfaces of Expr meet our requirements.

Use compile_test.cpp to check whether your code compiles. See Appendix: Note on static assertion failure for how to understand the error messages.

Submission

Submit your implementation as p1.cc on Gradescope.

Thinking

Why do we use std::shared_ptr instead of std::unique_ptr?

Can you add support for more functionalities, e.g. the elementary functions sin(e)\sin(e), cos(e)\cos(e), exponential expressions e1e2e_1^{e_2}, …? More variables? Print expressions to $\LaTeX$?

Appendix

Returning a braced-init-list

In the following code

class Expr {
  Expr(std::shared_ptr<ExprNode>);

  friend Expr operator-(const Expr &);
};
Expr operator-(const Expr &arg) {
  return {std::make_shared<UnaryOperator>(UnaryOpKind::UOK_Minus, arg)};
}

The return statement is equivalent to

  return Expr{std::make_shared<UnaryOperator>(UnaryOpKind::UOK_Minus, arg)};

but we don’t want to repeat the return type in the return statement.

Here we use a braced initializer list {...} to initialize the returned object (of type Expr). Since Expr

whatever written inside the pair of braces are passed to that constructor.

Detailed rules about list-initialization can be found here.

Inheriting constructors

Given the following definition for BinaryOperator

class BinaryOperator : public ExprNode {
protected:
  Expr mLeft;
  Expr mRight;

public:
  BinaryOperator(Expr left, Expr right)
      : mLeft{std::move(left)}, mRight{std::move(right)} {}
};

which has a constructor that accepts two Exprs and initializes mLeft and mRight with them respectively, the derived class PlusOperator can easily obtain a constructor that does the same thing by inheriting the constructor using a using declaration.

class PlusOperator : public BinaryOperator {
  using BinaryOperator::BinaryOperator;
};

Now the user can create a PlusOperator object in the following way (suppose e1 and e2 are of type Expr):

PlusOperator po(e1, e2);

Note that the access level of the inheriting constructor is always the same as that of the inherited constructor in the base class, no matter where the using declaration is placed.

Same things apply to MinusOperator, MultiplyOperator and DivideOperator.

Note on static assertion failure

compile_test.cpp will test whether the requirements for Expr are satisfied, and will report errors using static_assert. Gradescope also checks these interface requirements.

If any requirement is not satisfied, an error will be reported like this:

compile_test.cpp:24:45: error: static assertion failed: Expect { e.evaluate(d) } -> double, with the setting (const Expr e, double d).
   24 |   static_assert(decltype(helper_##name(0))::value,                             \
      |                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~
compile_test.cpp:31:1: note: in expansion of macro ‘EXPECT’
   31 | EXPECT(evaluate,   e.evaluate(d),   double)
      | ^~~~~~

The key message in this error is what goes after static assertion failed:

Expect { e.evaluate(d) } -> double, with the setting (const Expr e, double d).

It says that given e of type const Expr and d of type double, the expression e.evaluate(d) is expected to return double. This error message indicates that either e.evaluate(d) is not supported, or its return type is not double.

Unused parameters

If a named parameter is not used in a function definition

void foo(int x) {}

the compiler will generate a warning, which becomes an error with -Werror.

a.cpp: In function ‘void foo(int)’:
a.cpp:1:14: warning: unused parameter ‘x’ [-Wunused-parameter]
    1 | void foo(int x) {}
      |          ~~~~^

If you do want to declare an unused parameter (particularly in a virtual function), the most common way is to simply omit the name of the parameter:

void foo(int /* unused */) {}

Note that we have seen this before: The overloaded postfix increment operator ++ has an unused parameter.

class Iterator {
public:
  Iterator &operator++();
  Iterator operator++(int); // the postfix version
};

Another noticeable way to suppress warning on unused parameters/variables is to use the [[maybe_unused]] attribute. However, we don’t recommend using this attribute for things that are definitely unused. A parameter should be marked [[maybe_unused]] only when it may be unused:

void skip([[maybe_unused]] const std::string &str, std::size_t &pos,
          [[maybe_unused]] char expect) {
  assert(str[pos] == expect);
  ++pos;
}

When the program is compiled with -DNDEBUG (i.e. with the macro NDEBUG defined), the assert will be removed, and str and expect will be unused.

P2

Expression 2.0

100 pts

在开始本题之前,请确保你已经完成了第一题Expression,否则你可能无法看懂本题的代码。

本题虽然题目描述很长,下发的代码很多,但是实际上要写的内容不多,也比较简单。

背景

在第一题中,我们为简单的算术表达式的表达式树的结点类建立了一套继承体系,以便于我们轻松地创建表达式并执行一些数学计算。此类设施可能被用于像 SymPy 这样的符号计算库中。

在本题中,我们仍然研究类似的树结构,但是这一次我们处理的不是数学表达式,而是计算机程序中的表达式。我们也将为“表达式树”起一个新的名字:抽象语法树 (Abstract Syntax Tree, AST) 。我们同样会为这棵树的各类结点创建一套类结构,这些设施可能会被用于一个编译器中, Clang AST 就是一个例子。

请注意数学表达式和计算机程序中的表达式的根本区别。在本题中,

下发的文件

attachments 中的文件结构如下。

.
└── attachments/
    ├── visitor_pattern/
    │   ├── cars.cpp
    │   └── shapes.cpp
    ├── dump.hpp
    ├── example.cpp
    ├── expr.hpp
    ├── parse.cpp
    ├── parse.hpp
    └── type_check.hpp

本题只评分你提交的 p2.cc(原 type_check.hpp)。如果你修改了其它文件中的代码,请不要让你的 type_check.hpp 依赖于那些改动。

Gradescope 会提供 expr.hpp ,为了测试,会和 attachments 中的版本有细微的区别。理论上这种区别不会产生影响,但如果你确信你的代码无法通过测试是由它所致,请联系 TA 。

expr.hpp

如果你已经完成了第一题,那么本题的 expr.hpp 中的大部分代码应该不难看懂。

首先, ExprType 是一个枚举类,其枚举项 Integer, Float 和 Boolean 分别表示整数、浮点数和布尔三种类型。 Unevaluated 表示该类型还未被计算, ErrorType 表示类型错误。初始状态下(即结点刚被创建时),变量和常量的类型是确定的,而其它结点的类型都是 Unevaluated 的。

结点类的继承体系如图所示:

classDiagram
  direction TB
  class ExprNode {
        -ExprType mType
    +setType()
    +getType() ExprType
    +accept(visitor)*
    }
    class Variable {
        -std::string mName
        +getName() const std::string &
    +accept(visitor)
    }
  class UnaryOperator {
    -OperatorKind mOpKind
    -Expr mOperand
    +getOpKind() OperatorKind
    +getOperand() const Expr &
  }
  class Constant~T, ET~ {
    -T mValue
    +getValue() T
    +accept(visitor)
  }
  class UnaryArithOp {
    +accept(visitor)
  }
  class LogicalNotOp {
    +accept(visitor)
  }
  class BinaryOperator {
    -OperatorKind mOpKind
    -mLeft Expr
    -mRight Expr
    +getLHS() const Expr &
    +getRHS() const Expr &
    +getOpKind() OperatorKind
  }
  class BinaryArithOp {
    +accept(visitor)
  }
  class EqualityOp {
    +accept(visitor)
  }
  class RelationalOp {
    +accept(visitor)
  }
  class BinaryLogicalOp {
    +accept(visitor)
  }
  class ConditionalOp {
    -Expr mCondition
    -Expr mExprTrue
    -Expr mExprFalse
    +accept(visitor)
    +getOpKind() OperatorKind
    +getCondition() const Expr &
    +getExprTrue() const Expr &
    +getExprFalse() const Expr &
  }
  ExprNode <|-- Variable
  ExprNode <|-- Constant
  ExprNode <|-- UnaryOperator
  UnaryOperator <|-- UnaryArithOp
  UnaryOperator <|-- LogicalNotOp
  ExprNode <|-- BinaryOperator
  BinaryOperator <|-- BinaryArithOp
  BinaryOperator <|-- EqualityOp
  BinaryOperator <|-- RelationalOp
  BinaryOperator <|-- BinaryLogicalOp
  ExprNode <|-- ConditionalOp

一些值得注意的点:

和第一题不同,我们不再提供一组重载运算符来创建结点, Expr 类也没有接受 double 的构造函数来创建常量结点。你可以调用结点类的构造函数来创建结点,但是想要创建 Expr 就必须要调用模板函数 Expr::create ,例如

auto three = Expr::create<IntegerConstant>(3);
auto pi = Expr::create<FloatConstant>(3.14);
auto sum = Expr::create<BinaryArithOp>(OperatorKind::BinaryPlus, three, pi);

对于一个结点类 T , Expr::create<T>(args...) 会将参数 args... 完美转发给 std::make_shared<T> 来创建一个 std::shared_ptr<T> ,然后用这个 std::shared_ptr<T> 经过 Expr 的那个私有构造函数去初始化一个 Expr ,也就是将它移入这个 Expr 对象的 mNode 。我们应该向 Expr::create<T> 传递什么参数?答案自然是看 T 的构造函数接受什么参数,因为 std::make_shared<T> 会把这些参数转发给 T 的构造函数。

需要说明的是,我们对于变量 Variable 的处理是比较粗糙的,这是因为我们没有提供变量声明、查找等机制。例如,下面的代码看似建模了表达式 x < x + 1 ,但实际上 < 两侧的变量 x 并不是同一个变量:

auto e1 = Expr::create<RelationalOp>(
    OperatorKind::Less,
    Expr::create<Variable>(ExprType::Float, "x"),
    Expr::create<BinaryArithOp>(OperatorKind::BinaryPlus,
                                Expr::create<Variable>(ExprType::Float, "x"),
                                Expr::create<IntegerConstant>(1)));

要想让两个 x 是同一个变量,得这样写:

auto x = Expr::create<Variable>(ExprType::Float, "x");
auto e2 = Expr::create<RelationalOp>(
    OperatorKind::Less,
    x,
    Expr::create<BinaryArithOp>(OperatorKind::BinaryPlus,
                                x,
                                Expr::create<IntegerConstant>(1)));

好在我们暂时并不关心这些变量是不是同一个变量,因为我们不需要对这些表达式求值,这些变量的名字其实也并不重要。

总是要写这么一大堆 Expr::create 是不是很烦人?你也可以调用 parse 函数,详见 parse 一节。

ExprNodeVisitor 的解释见下文。

访问者模式 (Visitor Pattern)

第一题中,我们在结点类上定义了三组虚函数 evaluate, derivative 和 toString 来实现三种操作,这三种操作都需要递归地遍历整棵树,并且在不同结点上的实现可能不同。这样做看起来不错,但是——每当我们想添加一种操作时,我们都需要修改这些结点类的代码,定义一组新的虚函数。当这个继承体系变得复杂起来,可支持的操作也更加丰富时,这种做法灵活性低的问题就凸显出来了。

我们采用访问者模式 (Visitor Pattern) 来解决这个问题。访问者模式是一种设计模式 (Design Patterns) 。如果你想获得关于设计模式的一些基本的认识,我们强烈推荐这个视频。

访问者模式的基本框架如下图。

classDiagram
  direction TB
  class Element {
    +accept(Visitor &visitor)*
  }
  class ConcreteElementA {
    +accept(Visitor &visitor)
  }
  class ConcreteElementB {
    +accept(Visitor &visitor)
  }
  class Visitor {
    +visit(ConcreteElementA &a)*
    +visit(ConcreteElementB &b)*
  }
  class ConcreteVisitor1 {
    +visit(ConcreteElementA &a)
    +visit(ConcreteElementB &b)
  }
  class ConcreteVisitor2 {
    +visit(ConcreteElementA &a)
    +visit(ConcreteElementB &b)
  }
  Element <|-- ConcreteElementA
  Element <|-- ConcreteElementB
  Visitor <|-- ConcreteVisitor1
  Visitor <|-- ConcreteVisitor2

其中, Element 、 ConcreteElementA 和 ConcreteElementB 是原有的类结构,它们被称为元素,在我们的例子中它们就是 ExprNode 及各种继承自它的结点类。 Visitor 是访问者基类,它为每一种具体的元素定义一个 visit 函数,来完成在“访问”每种具体的元素时要做的事。 ConcreteVisitor1 和 ConcreteVisitor2 是两种具体的访问者,代表两类具体的操作,它们分别实现各个 visit 函数来完成相应的操作。

你可以在 attachments/visitor_pattern 中看到一些例子,其中 cars.cpp 是 wikipedia 的 Visitor Pattern 词条中的一份 Java 代码示例的 C++ 版本。

当我们想要支持一个新的操作时,只需定义一个新的访问者类,实现它的各个 visit 函数即可,无需修改元素本身的定义,无需像原来那样为元素添加虚函数。

ExprNodeVisitor 和 dump.hpp

ExprNodeVisitor 定义在 expr.hpp 中,是我们的结点类的访问者基类,它为每一个具体的结点类(也就是说,不包含 UnaryOperator 和 BinaryOperator 这两个中间类)声明了一个 visit 纯虚函数。你将会需要定义一个继承自 ExprNodeVisitor 的类,实现这些虚函数来完成一些工作,具体要求见 type_check.hpp 。

注意,一种设计模式在实践时并不是一成不变的,需要根据实际问题的复杂性进行调整。本例中的以下三点设计是值得讨论的:

像 clang::RecursiveASTVisitor 这样复杂的“访问者”,不仅为所有结点类都提供了一组 VisitXXX 函数来实现“访问”,还有一组 TraverseXXX 函数来实现“遍历”,以及一组 WalkUpFromXXX 函数来处理父类。

dump.hpp 定义了 dump 函数来优美地打印一棵树的结构,例如 x < 2 && y + 3 == 5 对应的抽象语法树会被 dump 打印为

BinaryLogicalOp '&&' : Boolean
|-RelationalOp '<' : Boolean
| |-Variable 'x' : Float
| `-IntegerConstant 2
`-EqualityOp '==' : Boolean
  |-BinaryArithOp '+' : Float
  | |-Variable 'y' : Float
  | `-IntegerConstant 3
  `-IntegerConstant 5

当然,以上内容中的类型 Boolean 、 Float 等在未完成类型检查时都是 Unevaluated 。

dump 函数是借助一个名为 DumpVisitor 的访问者实现的,你可以阅读其中的代码来看看如何编写一个访问者。这份代码中涉及到一些花哨的技术,包括可变参数模板和成员指针。你不必看懂这里的每一个细节,只需大致知道每个 visit 函数要做什么即可。

type_check.hpp

这是你需要实现的部分:类型检查 (type checking) 。

和字面意思不同,类型检查并不只是“检查”,而是计算出这个表达式的各个部分的类型。 ExprNode 和 Expr 都有 getType 和 setType 接口,可以用来读取和设置一个结点的类型。

类型检查的规则如下。其中, e 、 f 和 g 都是表达式,其类型分别为 EE 、 FF 和 GG 。

表达式 要求 类型
!e E=𝙱𝚘𝚘𝚕𝚎𝚊𝚗E=\mathtt{Boolean} 𝙱𝚘𝚘𝚕𝚎𝚊𝚗\mathtt{Boolean}
+e, -e E∈{𝙸𝚗𝚝𝚎𝚐𝚎𝚛,𝙵𝚕𝚘𝚊𝚝}E\in\{\mathtt{Integer},\mathtt{Float}\} EE
e * f, e / f,
e + f, e - f
E,F∈{𝙸𝚗𝚝𝚎𝚐𝚎𝚛,𝙵𝚕𝚘𝚊𝚝}E,F\in\{\mathtt{Integer},\mathtt{Float}\} 若 E=F=𝙸𝚗𝚝𝚎𝚐𝚎𝚛E=F=\mathtt{Integer} ,则为 𝙸𝚗𝚝𝚎𝚐𝚎𝚛\mathtt{Integer}
否则为 𝙵𝚕𝚘𝚊𝚝\mathtt{Float}
e < f, e <= f,
e > f, e >= f
E,F∈{𝙸𝚗𝚝𝚎𝚐𝚎𝚛,𝙵𝚕𝚘𝚊𝚝}E,F\in\{\mathtt{Integer},\mathtt{Float}\} 𝙱𝚘𝚘𝚕𝚎𝚊𝚗\mathtt{Boolean}
e == f, e != f E=FE=F 𝙱𝚘𝚘𝚕𝚎𝚊𝚗\mathtt{Boolean}
e == f, e != f E,F∈{𝙸𝚗𝚝𝚎𝚐𝚎𝚛,𝙵𝚕𝚘𝚊𝚝}E,F\in\{\mathtt{Integer},\mathtt{Float}\} 𝙱𝚘𝚘𝚕𝚎𝚊𝚗\mathtt{Boolean}
e && f, e \|\| f E=F=𝙱𝚘𝚘𝚕𝚎𝚊𝚗E=F=\mathtt{Boolean} 𝙱𝚘𝚘𝚕𝚎𝚊𝚗\mathtt{Boolean}
e ? f : g E=𝙱𝚘𝚘𝚕𝚎𝚊𝚗,E=\mathtt{Boolean},
F=GF=G
FF
e ? f : g E=𝙱𝚘𝚘𝚕𝚎𝚊𝚗,E=\mathtt{Boolean},
F,G∈{𝙸𝚗𝚝𝚎𝚐𝚎𝚛,𝙵𝚕𝚘𝚊𝚝}F,G\in\{\mathtt{Integer},\mathtt{Float}\}
若 F=G=𝙸𝚗𝚝𝚎𝚐𝚎𝚛F=G=\mathtt{Integer} ,则为 𝙸𝚗𝚝𝚎𝚐𝚎𝚛\mathtt{Integer}
否则为 𝙵𝚕𝚘𝚊𝚝\mathtt{Float}

如果一个表达式不能匹配上表中的任何一条(即,相应的要求无法满足),则其类型为 𝙴𝚛𝚛𝚘𝚛𝚃𝚢𝚙𝚎\mathtt{ErrorType} 。如果一个表达式包含一个类型为 𝙴𝚛𝚛𝚘𝚛𝚃𝚢𝚙𝚎\mathtt{ErrorType} 的子表达式,则这个表达式的类型为 𝙴𝚛𝚛𝚘𝚛𝚃𝚢𝚙𝚎\mathtt{ErrorType} 。

注意,你需要为所有子表达式都进行类型检查。例如对于 e + f ,即便你已经发现 e 的类型是 𝙴𝚛𝚛𝚘𝚛𝚃𝚢𝚙𝚎\mathtt{ErrorType} ,你也不能跳过对 f 的类型检查。

以上规则的叙述中,我们没有定义类型之间的隐式转换关系,也没有指出某些类型是否可以被归为一类。但是,这些关系显然是存在的。你在实现的时候应该定义一些辅助函数来判断这样的关系,来避免重复的代码。

编译运行 example.cpp 来进行简单的测试。其中,第 39 到 48 行所处理的表达式是通过 parse 来创建的,但 parse 函数的编译比较特殊。如果你还不知道怎么编译它(见下文),你可以先把这几行注释掉。

parse

头文件 parse.hpp 中定义了 parse 函数以及一些辅助类。

Expr parse(std::string_view exprCode,
           const std::unordered_map<std::string_view, ExprType> &varTypes = {});

parse 接受一个以字符串形式给出的表达式,它会解析这个字符串并创建出与之对应的抽象语法树。例如,

auto g = parse("(x + 1 >= y * 2 - x ? true : x > 0) == false");
typeCheck(g);
dump(g);

将会打印出

EqualityOp '==' : Boolean
|-ConditionalOp '?:' : Boolean
| |-RelationalOp '>=' : Boolean
| | |-BinaryArithOp '+' : Float
| | | |-Variable 'x' : Float
| | | `-IntegerConstant 1
| | `-BinaryArithOp '-' : Float
| |   |-BinaryArithOp '*' : Float
| |   | |-Variable 'y' : Float
| |   | `-IntegerConstant 2
| |   `-Variable 'x' : Float
| |-BooleanConstant true
| `-RelationalOp '>' : Boolean
|   |-Variable 'x' : Float
|   `-IntegerConstant 0
`-BooleanConstant false

parse 的第二个参数是一个从变量名到类型的映射关系。例如,

auto h = parse("x < y && z", {{"x", ExprType::Integer},
                              {"z", ExprType::Boolean}});

这就意味着 x 的类型是 𝙸𝚗𝚝𝚎𝚐𝚎𝚛\mathtt{Integer} , z 的类型是 𝙱𝚘𝚘𝚕𝚎𝚊𝚗\mathtt{Boolean} 。未在这个参数里指出的变量的类型都是 𝙵𝚕𝚘𝚊𝚝\mathtt{Float} 。

关键问题是:怎么编译?你可能已经发现了, parse.hpp 中有相当多的函数只有声明、没有定义。 parse.cpp 包含这些函数的定义,但是和我们之前写过的 .cpp 文件不同——它不含 main 函数。一种简单的编译方式就是

g++ -I p2-examples p2-examples/example.cpp p2-examples/parse.cpp -o example -std=c++17 -Wall -Wpedantic -Wextra

即,同时向 g++ 传递两个文件 example.cpp 和 parse.cpp ,这样编译器就能看到那些函数的定义了。

事实上,我们是可以单独编译 parse.cpp ,单独编译 example.cpp ,然后再将它们链接起来的。当编译器看到诸如 fun(x) 的函数调用时,它只需要能看见 fun 的声明,便能知道这个调用是否合法,并为这个函数调用生成相应的代码。至于 fun 的定义,那是链接器需要的东西。在 Linux/Mac 上,我们可以

g++ -shared p2-examples/parse.cpp -fPIC -o libparse.so

这样单独编译 parse.cpp 并生成动态链接库文件 libparse.so ,然后

g++ -I p2-examples p2-examples/example.cpp -o example -Wl,-rpath . -L. -lparse

这样编译 example.cpp ,并将它与 libparse.so 动态链接。现在运行 example ,它就能够链接到 libparse.so 中的函数定义。有趣的是,如果我们现在对 parse.cpp 做一些改动,比如让 doParse() 直接抛出异常,然后再次编译生成 libparse.so ,那么直接重新运行 example ,你就会看到异常被抛出——无需重新编译 example.cpp 。类似的玩法在 Windows 上也是可以的,可以参考这篇文章。

这种分离式编译是很有用的。想象一下,在一个巨大的项目中,整个项目编译一次可能需要半个小时——这并不夸张,像 GCC 这样的项目就是。如果我只是改动了某个文件里的某两个函数的定义,却需要将整个项目重新编译一遍,这当然是不可接受的。

当然,一个复杂的项目可能包含成百上千个文件,要手动地编译各个文件是不现实的,这就需要借助一些自动化的工具了。在下一次作业中,我们会使用一个著名的工具—— CMake 来完成项目的构建。

提交

在 Gradescope 提交 p2.cc。起步包将原 type_check.hpp 命名为 p2.cc。

P3

Dynamic Array 3.0

100 pts

终于,是时候要把 Dynarray 变成一个可以存储各种可能的类型的元素的类模板 Dynarray<T> 了!

对元素类型 T 的要求

首先,不是什么类型的元素都能往 Dynarray 里存的。我们需要注意的情况主要有以下两点:

  1. T 不能是一个引用。引用是十分特别的类型,它并不是一个实际的对象,不能默认初始化,而且对于引用的初始化和赋值的含义也有根本上的区别。因此,我们应当拒绝实例化任何的 Dynarray<T &> 和 Dynarray<T &&> 。如果用户希望在 Dynarray 中存储“引用”,可以使用指针代替,或者存储 std::reference_wrapper<T> (它其实也是一个对指针的封装)。
  2. T 不能是 const 或 volatile (简称 cv-qualified ) 的。你可能不知道什么是 volatile ,没有关系,只需记住它是一种和 const 用法类似的特殊 qualification ,例如我们有“指向 volatile 的指针”和“volatile 指针”,有“绑定到 volatile 的引用”,有“volatile 成员函数”,有禁止去除底层 volatile 的规则等等。 T 之所以不能带有 cv-qualification ,是因为我们的 Dynarray 具有值语义( value semantics ):一个 const Dynarray<T> 就是一个存储 T 类型的元素但禁止修改的 Dynarray , Dynarray<T> 本身不是 const 就意味着它的元素可以修改。

标准库的许多容器(例如 std::vector ) 对于其存储的元素的类型也有以上要求。为了体现这两点要求,我们可以在 Dynarray 的开头使用 static_assert :

template <typename T>
class Dynarray {
  static_assert(/* condition */, /* message */);
  static_assert(/* condition */, /* message */);
  // ...
};

其中 /* condition */ 必须是一个编译时已知的 bool 表达式, /* message */ 必须是一个字符串字面值。 static_assert(condition, message) 会在编译时检测 condition 是否成立,如果不成立则报告一个编译错误,并且报错信息中会含有 message 的内容。请编写有意义的 message !

标准库文件 <type_traits> 中定义了 std::is_const_v<T>, std::is_volatile_v<T>, std::remove_cv_t<T>, std::is_same_v<T, U>, std::is_reference_v<T> 等等这些关于类型的“元函数”,其中,以 _v 结尾的都是编译期 bool 常量,以 _t 结尾的都是类型别名。你可能需要使用它们。在这里可以看到它们的文档和示例。

类型别名成员

在上一次作业中,我们已经为 Dynarray 定义了一些类型别名成员。这次需要进行的改动如下:

成员函数

在上一次作业中,我们建议你将所有涉及到元素类型的地方都使用前面声明的类型别名成员来代替,例如将 new int[n] 替换为 new value_type[n] ,将 const int & 替换为 const_reference 。如果你已经这么做了,那么除了以下三个改动之外,你什么都不用改。如果没有,那么你还需要仔细检查各个函数,将其中假定元素类型为 int 的部分改掉。

  1. 将接受一对指针的构造函数 Dynarray::Dynarray(const int *, const int *) 改为接受一对 ForwardIterator 。用户究竟会传进何种迭代器类型我们不得而知,所以我们直接以模板的方式接受参数:

    template <typename ForwardIter>
    Dynarray(ForwardIter begin, ForwardIter end);

    但是注意,并不是你给它命名为 ForwardIter 它就真的是 ForwardIterator 了。我们还需要限定它的迭代器型别:取出 typename std::iterator_traits<ForwardIter>::iterator_category 然后判断它是不是 std::forward_iterator_tag 或其子类,如果不是的话就不能允许实例化这个函数。这里我们借助 SFINAE (Substitution Failure Is Not An Error)手法实现:

    template <typename ForwardIter,
              typename = std::enable_if_t<std::is_base_of_v<
                  std::forward_iterator_tag,
                  typename std::iterator_traits<ForwardIter>::iterator_category>>>
    Dynarray(ForwardIter begin, ForwardIter end);

    ForwardIterator 不一定具有 operator- ,所以你不能使用 end - begin 来获取这两个迭代器的距离,而应该使用 std::distance 函数。

    有了这个构造函数,我们可以使用任意的一对迭代器来初始化一个 Dynarray<T> ,只要那个迭代器所指向的元素类型能用来给一个 T 类型的对象赋值即可。例如

    std::vector vec{2, 3, 5, 7};
    Dynarray<int> di1(vec.begin() + 2, vec.end()); // {5, 7}
    std::list lst{2.5, 3.7, 5.0, 7.2};
    Dynarray<int> di2(lst.begin(), lst.end()); // Truncated towards zero, {2, 3, 5, 7}
    Dynarray<int> di3(di2.crbegin(), di2.crend()); // {7, 5, 3, 2}
                                                   // 使用了 Dynarray 的反向迭代器,见下

    要写这么多 <int> 真是麻烦,这里的 di1 和 di3 的元素类型实际上都等于传入的迭代器所指向的元素类型。有没有办法让编译器自动根据 ForwardIter 指向的元素类型来推导出 T 呢?当然,只需在类外提供一个 deduction guide :

    template <typename ForwardIter>
    Dynarray(ForwardIter, ForwardIter)
        -> Dynarray<typename std::iterator_traits<ForwardIter>::value_type>;

    有了这个之后,上面的代码中的 di1 和 di3 前面的 <int> 都可以不用写了。

  2. 迭代器的获取: begin(), end(), cbegin(), cend(), rbegin(), rend(), crbegin(), crend() 。其中

    • c 表示 “const” , r 表示 “reverse” 。cbegin(), cend(), crbegin(), crend() 都只能在 const 对象上调用,前两个返回 const_iterator ,后两个返回 const_reverse_iterator 。

    • begin(), end(), rbegin(), rend() 都应该具有 const 和 non-const 的重载,其中 const 版本返回 const_iterator 和 const_reverse_iterator , non-const 版本返回 iterator 和 reverse_iterator 。

    • 你可以参考标准库 std::vector 的这 12 个函数的定义,特别是如何创建 reverse_iterator 和 const_reverse_iterator 。你只需要在 VSCode 中写一段这样的代码:

      std::vector<int> vec;
      auto rit = vec.rbegin();

      然后按住 ctrl ,鼠标左键点击 rbegin 就可以看到标准库 std::vector 的这一串成员函数的定义。其中一切有关 “nodiscard”, “constexpr” 和 noexcept 的东西都可以忽略。

  3. 正确编写适用于模板类的六个关系运算符 <, <=, >, >=, ==, != 以及输出运算符 << 。不同的人在此处需要做的改动可能不同,例如有的人需要给每个函数都加上 template <typename T> 并给 Dynarray 加上 <T> ,而那些将它们都作为 friend 并且在类内定义的人几乎什么都不用改。

特别说明:模板代码中的每一个函数都应当将对于未知的模板类型参数 T 的要求降到最低,例如

一份正常的、直接的实现应当很自然地满足这些要求。

Submission

Submit your implementation as p3.cc on Gradescope.