CS100 · Fall 2026 · Programming Assignment
HW6: Expression Trees and Templates
C++17 · GitHub submission on Gradescope · 300 points
Release · 发布
Deadline · 截止
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.
Expression
100 ptsBackground
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:
- A new kind of node called
Variable, which represents the varaiblex. With this supported, our AST can be used to represent unary functions, instead of only arithmetic expressions with constants. - Evaluation of the function at a certain point .
- Evaluation of the derivative of the function at a certain point .
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.000000) + (3.000000) -
:
((2.000000) * (x)) + (3.000000) -
:
((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.
Expris copy-constructible, copy-assignable, move-constructible, move-assignable and destructible. These operations should just perform the corresponding operations on the membermNode, and let the corresponding function ofstd::shared_ptrhandle everything. The move operations should benoexcept.Expris constructible from adoublevalue, and this constructor is non-explicit.- Let
ebe of typeconst Exprandx0be of typedouble, then the subtree rooted aterepresents a function.e.evaluate(x0)returns the value of this function at .e.derivative(x0)returns the value of the derivative of this function at .e.toString()returns astd::stringrepresenting this function.
- Let
e1ande2be two objects of typeconst Expr. The following expressions return an object of typeExpr, which creates a new node corresponding to the operators.-e1+e1e1 + e2e1 - e2e1 * e2e1 / e2
Expr::xis an object of typeconst Expr, which represents the variablex.
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 , , exponential expressions , …? 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
- is a non-aggregate class type, and
- does not have a constructor accepting
std::initializer_list, and - has a non-explicit constructor accepting
std::shared_ptr<ExprNode>,
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.
Expression 2.0
100 pts在开始本题之前,请确保你已经完成了第一题Expression,否则你可能无法看懂本题的代码。
本题虽然题目描述很长,下发的代码很多,但是实际上要写的内容不多,也比较简单。
背景
在第一题中,我们为简单的算术表达式的表达式树的结点类建立了一套继承体系,以便于我们轻松地创建表达式并执行一些数学计算。此类设施可能被用于像 SymPy 这样的符号计算库中。
在本题中,我们仍然研究类似的树结构,但是这一次我们处理的不是数学表达式,而是计算机程序中的表达式。我们也将为“表达式树”起一个新的名字:抽象语法树 (Abstract Syntax Tree, AST) 。我们同样会为这棵树的各类结点创建一套类结构,这些设施可能会被用于一个编译器中, Clang AST 就是一个例子。
请注意数学表达式和计算机程序中的表达式的根本区别。在本题中,
- 表达式的运算符更加多样。我们将会支持逻辑运算符
!,&&,||、比较运算符<,<=,>,>=,==,!=和条件运算符?:,所支持的运算符的优先级和结合性和 C++ 中相同; - 每一个表达式都具有一个类型。我们的类型系统包含三种类型:整数、浮点数、布尔。变量和常量的类型是在创建时就确定的,而其它子表达式的类型则需要根据相应的规则及其子表达式的类型计算得出。这也是你在本题中需要实现的部分,详见
type_check.hpp; - 我们不再关注表达式的值,不会对表达式进行求导;
- 我们不再提供像第一题中的那些重载运算符和
Expr::Expr(double)构造函数来创建结点。创建结点的方式是调用模板函数Expr::create,或者直接调用parse解析以字符串形式给出的表达式(详见parse); - 我们不再研究如何打印“表达式”,而是研究如何打印“树”的结构,详见
ExprNodeVisitor和dump.hpp。
下发的文件
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
一些值得注意的点:
Variable表示一个变量,mName是这个变量的名字。Variable的类型是在创建之时就指定了的,因为Variable的构造函数要求传入一个ExprType参数。- 常量有三种,分别是整数常量
IntegerConstant、浮点数常量FloatConstant和布尔常量BooleanConstant,这三个类型实际上是统一由一个模板类Constant<T, ET>定义的,它们分别是Constant<int, ExprType::Integer>、Constant<double, ExprType::Float>和Constant<bool, ExprType::Boolean>的别名。 - 各类运算符结点类所表示的运算符都可以从代码中看出。例如,
UnaryArithOp的构造函数中有一个断言assert(op == OperatorKind::UnaryPlus || op == OperatorKind::UnaryMinus);,这表明UnaryArithOp所表示的运算符是一元正号或者一元负号。 - 每一个结点类都有相应的 getters 来返回它所保存的各种信息,例如
Variable有getName(),BinaryOperator有getLHS()和getRHS(),各类运算符都有getOpKind()。但是这些 getters 返回的都是不可修改的东西,也就是说我们不希望用户在创建好一棵树之后去改变其中的结构。 - 每一个具体类,即处在继承树的叶子位置的类,都
override 了
accept函数。这一组accept函数是访问者模式 (Visitor Pattern) 的一部分,详见访问者模式 (Visitor Pattern) 。
和第一题不同,我们不再提供一组重载运算符来创建结点,
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 。
注意,一种设计模式在实践时并不是一成不变的,需要根据实际问题的复杂性进行调整。本例中的以下三点设计是值得讨论的:
- 基类
ExprNodeVisitor的各个visit函数都是纯虚的,也就是说,没有默认行为。 - 结点类的
accept(visitor)函数只会调用visitor.visit(*this),不会对它的孩子调用accept。也就是说,对于子结点的递归的遍历需要在 visitor 的visit函数中完成,例如在visit(UnaryArithOp &u)中,你可能需要调用u.getOperand().accept(*this)。 - 我们没有为
UnaryOperator和BinaryOperator这样的中间类提供visit函数。
像 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 都是表达式,其类型分别为
、
和
。
| 表达式 | 要求 | 类型 |
|---|---|---|
!e |
||
+e, -e |
||
e * f, e / f,e + f,
e - f |
若
,则为
否则为 |
|
e < f, e <= f,e > f, e >= f |
||
e == f, e != f |
||
e == f, e != f |
||
e && f, e \|\| f |
||
e ? f : g |
||
e ? f : g |
若
,则为
否则为 |
如果一个表达式不能匹配上表中的任何一条(即,相应的要求无法满足),则其类型为 。如果一个表达式包含一个类型为 的子表达式,则这个表达式的类型为 。
注意,你需要为所有子表达式都进行类型检查。例如对于
e + f ,即便你已经发现 e 的类型是
,你也不能跳过对 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 的类型是
, z 的类型是
。未在这个参数里指出的变量的类型都是
。
关键问题是:怎么编译?你可能已经发现了, 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。
Dynamic Array 3.0
100 pts终于,是时候要把 Dynarray
变成一个可以存储各种可能的类型的元素的类模板
Dynarray<T> 了!
对元素类型 T 的要求
首先,不是什么类型的元素都能往 Dynarray
里存的。我们需要注意的情况主要有以下两点:
T不能是一个引用。引用是十分特别的类型,它并不是一个实际的对象,不能默认初始化,而且对于引用的初始化和赋值的含义也有根本上的区别。因此,我们应当拒绝实例化任何的Dynarray<T &>和Dynarray<T &&>。如果用户希望在Dynarray中存储“引用”,可以使用指针代替,或者存储std::reference_wrapper<T>(它其实也是一个对指针的封装)。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
定义了一些类型别名成员。这次需要进行的改动如下:
value_type,pointer,reference,const_pointer,const_reference都应当是关于T的,而非关于int的。Dynarray<T>::iterator和Dynarray<T>::const_iterator应该是Dynarray<T>的两个正向迭代器类型。由于Dynarray<T>的存储方式十分简单,迭代器完全可以使用指针代替。Dynarray<T>::difference_type是两个Dynarray<T>::iterator相减的结果类型。Dynarray<T>::reverse_iterator和Dynarray<T>::const_reverse_iterator是Dynarray<T>的两个反向迭代器类型。对于一个普通的(正向)迭代器Iter,其对应的反向迭代器就是std::reverse_iterator<Iter>。
成员函数
在上一次作业中,我们建议你将所有涉及到元素类型的地方都使用前面声明的类型别名成员来代替,例如将
new int[n] 替换为 new value_type[n] ,将
const int & 替换为 const_reference
。如果你已经这么做了,那么除了以下三个改动之外,你什么都不用改。如果没有,那么你还需要仔细检查各个函数,将其中假定元素类型为
int 的部分改掉。
将接受一对指针的构造函数
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>都可以不用写了。迭代器的获取:
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的东西都可以忽略。
正确编写适用于模板类的六个关系运算符
<,<=,>,>=,==,!=以及输出运算符<<。不同的人在此处需要做的改动可能不同,例如有的人需要给每个函数都加上template <typename T>并给Dynarray加上<T>,而那些将它们都作为friend并且在类内定义的人几乎什么都不用改。
特别说明:模板代码中的每一个函数都应当将对于未知的模板类型参数
T 的要求降到最低,例如
- 接受一个长度参数
n的构造函数应将n个元素进行值初始化,而不是将它们初始化为零。这个函数只能假定T是 default-initializable 的(即可以进行默认初始化和值初始化),不能依赖于T的任何拷贝或移动操作。 - 接受一个长度参数
n和一个值x的构造函数需以const value_type &的方式传递x,并且只能假定T是 default-initializable 且可以进行拷贝赋值的。 - 拷贝操作可以假定
T可以拷贝构造、可以拷贝赋值。 - 移动操作不能对
T所支持的操作作任何假定。T甚至不需要是可以移动的。 ==和!=只能依赖T的相等运算符==;四个比较运算符<,<=,>,>=只能依赖T的小于运算符<。<<可以使用os << x输出一个T类型的对象x,其中os是一个输出流对象。
一份正常的、直接的实现应当很自然地满足这些要求。
Submission
Submit your implementation as p3.cc on Gradescope.