Mass rename SourceLoc and Tag (#860)

This does a mass rename of:

-   `SourceLoc()` -> `source_loc()` for property naming
    - `loc` -> `source_loc_` for underscore+consistency
    - Generally changing function args to `source_loc` for consistency
-   `Tag()` -> `kind()` for property naming and `Kind` parity
    - `tag` -> `kind_` for underscore

Also renames `Pos` and `Results` on `Action`. These are a bit of an exception in that most base classes only have `Tag` and maybe `SourceLoc`, whereas `Action` has a little more. I felt okay having `source_loc()` and `kind()` on the base class where children do `Exp()` and the like, but it felt weird to me to mix it on the same class.

The reason for doing this cross-class in one PR is so that I can do it efficiently with a global replace in the codebase, rather than e.g. changing `Expression` but having to read through compiler errors to determine where it's calling `Expression`'s `Tag` versus a different `Tag`. The end result should be equivalent.
This commit is contained in:
Jon Meow
2021-09-29 16:52:12 -07:00
committed by GitHub
parent c4e40aaa86
commit 70797e8bf8
27 changed files with 779 additions and 734 deletions
+2 -1
View File
@@ -41,6 +41,7 @@ class Declaration {
Declaration& operator=(const Member&) = delete;
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
@@ -50,7 +51,7 @@ class Declaration {
protected:
// Constructs a Declaration representing syntax at the given line number.
// `tag` must be the enumerator corresponding to the most-derived type being
// `kind` must be the enumerator corresponding to the most-derived type being
// constructed.
Declaration(Kind kind, SourceLocation source_loc)
: kind_(kind), source_loc_(source_loc) {}
+6 -6
View File
@@ -17,21 +17,21 @@ namespace Carbon {
using llvm::cast;
auto ExpressionFromParenContents(
Nonnull<Arena*> arena, SourceLocation loc,
Nonnull<Arena*> arena, SourceLocation source_loc,
const ParenContents<Expression>& paren_contents) -> Nonnull<Expression*> {
std::optional<Nonnull<Expression*>> single_term = paren_contents.SingleTerm();
if (single_term.has_value()) {
return *single_term;
} else {
return TupleExpressionFromParenContents(arena, loc, paren_contents);
return TupleExpressionFromParenContents(arena, source_loc, paren_contents);
}
}
auto TupleExpressionFromParenContents(
Nonnull<Arena*> arena, SourceLocation loc,
Nonnull<Arena*> arena, SourceLocation source_loc,
const ParenContents<Expression>& paren_contents) -> Nonnull<Expression*> {
return arena->New<TupleLiteral>(
loc, paren_contents.TupleElements<FieldInitializer>(loc));
source_loc, paren_contents.TupleElements<FieldInitializer>(source_loc));
}
static void PrintOp(llvm::raw_ostream& out, Operator op) {
@@ -73,7 +73,7 @@ static void PrintFields(llvm::raw_ostream& out,
}
void Expression::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Expression::Kind::IndexExpression: {
const auto& index = cast<IndexExpression>(*this);
out << *index.Aggregate() << "[" << *index.Offset() << "]";
@@ -127,7 +127,7 @@ void Expression::Print(llvm::raw_ostream& out) const {
case Expression::Kind::CallExpression: {
const auto& call = cast<CallExpression>(*this);
out << *call.Function();
if (call.Argument()->Tag() == Expression::Kind::TupleLiteral) {
if (call.Argument()->kind() == Expression::Kind::TupleLiteral) {
out << *call.Argument();
} else {
out << "(" << *call.Argument() << ")";
+66 -61
View File
@@ -42,37 +42,38 @@ class Expression {
IntrinsicExpression,
};
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
auto SourceLoc() const -> SourceLocation { return loc; }
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
auto source_loc() const -> SourceLocation { return source_loc_; }
protected:
// Constructs an Expression representing syntax at the given line number.
// `tag` must be the enumerator corresponding to the most-derived type being
// `kind` must be the enumerator corresponding to the most-derived type being
// constructed.
Expression(Kind kind, SourceLocation loc) : kind(kind), loc(loc) {}
Expression(Kind kind, SourceLocation source_loc)
: kind_(kind), source_loc_(source_loc) {}
private:
const Kind kind;
SourceLocation loc;
const Kind kind_;
SourceLocation source_loc_;
};
// Converts paren_contents to an Expression, interpreting the parentheses as
// grouping if their contents permit that interpretation, or as forming a
// tuple otherwise.
auto ExpressionFromParenContents(
Nonnull<Arena*> arena, SourceLocation loc,
Nonnull<Arena*> arena, SourceLocation source_loc,
const ParenContents<Expression>& paren_contents) -> Nonnull<Expression*>;
// Converts paren_contents to an Expression, interpreting the parentheses as
// forming a tuple.
auto TupleExpressionFromParenContents(
Nonnull<Arena*> arena, SourceLocation loc,
Nonnull<Arena*> arena, SourceLocation source_loc,
const ParenContents<Expression>& paren_contents) -> Nonnull<Expression*>;
// A FieldInitializer represents the initialization of a single tuple field.
@@ -102,11 +103,12 @@ enum class Operator {
class IdentifierExpression : public Expression {
public:
explicit IdentifierExpression(SourceLocation loc, std::string name)
: Expression(Kind::IdentifierExpression, loc), name(std::move(name)) {}
explicit IdentifierExpression(SourceLocation source_loc, std::string name)
: Expression(Kind::IdentifierExpression, source_loc),
name(std::move(name)) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::IdentifierExpression;
return exp->kind() == Kind::IdentifierExpression;
}
auto Name() const -> const std::string& { return name; }
@@ -117,15 +119,15 @@ class IdentifierExpression : public Expression {
class FieldAccessExpression : public Expression {
public:
explicit FieldAccessExpression(SourceLocation loc,
explicit FieldAccessExpression(SourceLocation source_loc,
Nonnull<Expression*> aggregate,
std::string field)
: Expression(Kind::FieldAccessExpression, loc),
: Expression(Kind::FieldAccessExpression, source_loc),
aggregate(aggregate),
field(std::move(field)) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::FieldAccessExpression;
return exp->kind() == Kind::FieldAccessExpression;
}
auto Aggregate() const -> Nonnull<const Expression*> { return aggregate; }
@@ -139,14 +141,15 @@ class FieldAccessExpression : public Expression {
class IndexExpression : public Expression {
public:
explicit IndexExpression(SourceLocation loc, Nonnull<Expression*> aggregate,
explicit IndexExpression(SourceLocation source_loc,
Nonnull<Expression*> aggregate,
Nonnull<Expression*> offset)
: Expression(Kind::IndexExpression, loc),
: Expression(Kind::IndexExpression, source_loc),
aggregate(aggregate),
offset(offset) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::IndexExpression;
return exp->kind() == Kind::IndexExpression;
}
auto Aggregate() const -> Nonnull<const Expression*> { return aggregate; }
@@ -161,11 +164,11 @@ class IndexExpression : public Expression {
class IntLiteral : public Expression {
public:
explicit IntLiteral(SourceLocation loc, int val)
: Expression(Kind::IntLiteral, loc), val(val) {}
explicit IntLiteral(SourceLocation source_loc, int val)
: Expression(Kind::IntLiteral, source_loc), val(val) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::IntLiteral;
return exp->kind() == Kind::IntLiteral;
}
auto Val() const -> int { return val; }
@@ -176,11 +179,11 @@ class IntLiteral : public Expression {
class BoolLiteral : public Expression {
public:
explicit BoolLiteral(SourceLocation loc, bool val)
: Expression(Kind::BoolLiteral, loc), val(val) {}
explicit BoolLiteral(SourceLocation source_loc, bool val)
: Expression(Kind::BoolLiteral, source_loc), val(val) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::BoolLiteral;
return exp->kind() == Kind::BoolLiteral;
}
auto Val() const -> bool { return val; }
@@ -191,11 +194,11 @@ class BoolLiteral : public Expression {
class StringLiteral : public Expression {
public:
explicit StringLiteral(SourceLocation loc, std::string val)
: Expression(Kind::StringLiteral, loc), val(std::move(val)) {}
explicit StringLiteral(SourceLocation source_loc, std::string val)
: Expression(Kind::StringLiteral, source_loc), val(std::move(val)) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::StringLiteral;
return exp->kind() == Kind::StringLiteral;
}
auto Val() const -> const std::string& { return val; }
@@ -206,24 +209,25 @@ class StringLiteral : public Expression {
class StringTypeLiteral : public Expression {
public:
explicit StringTypeLiteral(SourceLocation loc)
: Expression(Kind::StringTypeLiteral, loc) {}
explicit StringTypeLiteral(SourceLocation source_loc)
: Expression(Kind::StringTypeLiteral, source_loc) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::StringTypeLiteral;
return exp->kind() == Kind::StringTypeLiteral;
}
};
class TupleLiteral : public Expression {
public:
explicit TupleLiteral(SourceLocation loc) : TupleLiteral(loc, {}) {}
explicit TupleLiteral(SourceLocation source_loc)
: TupleLiteral(source_loc, {}) {}
explicit TupleLiteral(SourceLocation loc,
explicit TupleLiteral(SourceLocation source_loc,
std::vector<FieldInitializer> fields)
: Expression(Kind::TupleLiteral, loc), fields(std::move(fields)) {}
: Expression(Kind::TupleLiteral, source_loc), fields(std::move(fields)) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::TupleLiteral;
return exp->kind() == Kind::TupleLiteral;
}
auto Fields() const -> const std::vector<FieldInitializer>& { return fields; }
@@ -248,7 +252,7 @@ class StructLiteral : public Expression {
}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::StructLiteral;
return exp->kind() == Kind::StructLiteral;
}
auto fields() const -> const std::vector<FieldInitializer>& {
@@ -272,7 +276,7 @@ class StructTypeLiteral : public Expression {
: Expression(Kind::StructTypeLiteral, loc), fields_(std::move(fields)) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::StructTypeLiteral;
return exp->kind() == Kind::StructTypeLiteral;
}
auto fields() const -> const std::vector<FieldInitializer>& {
@@ -286,14 +290,14 @@ class StructTypeLiteral : public Expression {
class PrimitiveOperatorExpression : public Expression {
public:
explicit PrimitiveOperatorExpression(
SourceLocation loc, Operator op,
SourceLocation source_loc, Operator op,
std::vector<Nonnull<Expression*>> arguments)
: Expression(Kind::PrimitiveOperatorExpression, loc),
: Expression(Kind::PrimitiveOperatorExpression, source_loc),
op(op),
arguments(std::move(arguments)) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::PrimitiveOperatorExpression;
return exp->kind() == Kind::PrimitiveOperatorExpression;
}
auto Op() const -> Operator { return op; }
@@ -311,14 +315,15 @@ class PrimitiveOperatorExpression : public Expression {
class CallExpression : public Expression {
public:
explicit CallExpression(SourceLocation loc, Nonnull<Expression*> function,
explicit CallExpression(SourceLocation source_loc,
Nonnull<Expression*> function,
Nonnull<Expression*> argument)
: Expression(Kind::CallExpression, loc),
: Expression(Kind::CallExpression, source_loc),
function(function),
argument(argument) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::CallExpression;
return exp->kind() == Kind::CallExpression;
}
auto Function() const -> Nonnull<const Expression*> { return function; }
@@ -333,17 +338,17 @@ class CallExpression : public Expression {
class FunctionTypeLiteral : public Expression {
public:
explicit FunctionTypeLiteral(SourceLocation loc,
explicit FunctionTypeLiteral(SourceLocation source_loc,
Nonnull<Expression*> parameter,
Nonnull<Expression*> return_type,
bool is_omitted_return_type)
: Expression(Kind::FunctionTypeLiteral, loc),
: Expression(Kind::FunctionTypeLiteral, source_loc),
parameter(parameter),
return_type(return_type),
is_omitted_return_type(is_omitted_return_type) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::FunctionTypeLiteral;
return exp->kind() == Kind::FunctionTypeLiteral;
}
auto Parameter() const -> Nonnull<const Expression*> { return parameter; }
@@ -360,41 +365,41 @@ class FunctionTypeLiteral : public Expression {
class BoolTypeLiteral : public Expression {
public:
explicit BoolTypeLiteral(SourceLocation loc)
: Expression(Kind::BoolTypeLiteral, loc) {}
explicit BoolTypeLiteral(SourceLocation source_loc)
: Expression(Kind::BoolTypeLiteral, source_loc) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::BoolTypeLiteral;
return exp->kind() == Kind::BoolTypeLiteral;
}
};
class IntTypeLiteral : public Expression {
public:
explicit IntTypeLiteral(SourceLocation loc)
: Expression(Kind::IntTypeLiteral, loc) {}
explicit IntTypeLiteral(SourceLocation source_loc)
: Expression(Kind::IntTypeLiteral, source_loc) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::IntTypeLiteral;
return exp->kind() == Kind::IntTypeLiteral;
}
};
class ContinuationTypeLiteral : public Expression {
public:
explicit ContinuationTypeLiteral(SourceLocation loc)
: Expression(Kind::ContinuationTypeLiteral, loc) {}
explicit ContinuationTypeLiteral(SourceLocation source_loc)
: Expression(Kind::ContinuationTypeLiteral, source_loc) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::ContinuationTypeLiteral;
return exp->kind() == Kind::ContinuationTypeLiteral;
}
};
class TypeTypeLiteral : public Expression {
public:
explicit TypeTypeLiteral(SourceLocation loc)
: Expression(Kind::TypeTypeLiteral, loc) {}
explicit TypeTypeLiteral(SourceLocation source_loc)
: Expression(Kind::TypeTypeLiteral, source_loc) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::TypeTypeLiteral;
return exp->kind() == Kind::TypeTypeLiteral;
}
};
@@ -409,7 +414,7 @@ class IntrinsicExpression : public Expression {
intrinsic(intrinsic) {}
static auto classof(const Expression* exp) -> bool {
return exp->Tag() == Kind::IntrinsicExpression;
return exp->kind() == Kind::IntrinsicExpression;
}
auto Intrinsic() const -> IntrinsicKind { return intrinsic; }
+17 -17
View File
@@ -23,7 +23,7 @@ using testing::IsEmpty;
// `IntLiteral`
MATCHER_P(IntFieldNamed, name, "") {
return arg.name == std::string(name) &&
arg.expression->Tag() == Expression::Kind::IntLiteral;
arg.expression->kind() == Expression::Kind::IntLiteral;
}
static auto FakeSourceLoc(int line_num) -> SourceLocation {
@@ -40,8 +40,8 @@ TEST_F(ExpressionTest, EmptyAsExpression) {
.has_trailing_comma = false};
Nonnull<const Expression*> expression =
ExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(expression->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(expression->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(expression->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(expression->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*expression).Fields(), IsEmpty());
}
@@ -50,8 +50,8 @@ TEST_F(ExpressionTest, EmptyAsTuple) {
.has_trailing_comma = false};
Nonnull<const Expression*> tuple =
TupleExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*tuple).Fields(), IsEmpty());
}
@@ -69,8 +69,8 @@ TEST_F(ExpressionTest, UnaryNoCommaAsExpression) {
Nonnull<const Expression*> expression =
ExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(expression->SourceLoc(), FakeSourceLoc(2));
ASSERT_EQ(expression->Tag(), Expression::Kind::IntLiteral);
EXPECT_EQ(expression->source_loc(), FakeSourceLoc(2));
ASSERT_EQ(expression->kind(), Expression::Kind::IntLiteral);
}
TEST_F(ExpressionTest, UnaryNoCommaAsTuple) {
@@ -81,8 +81,8 @@ TEST_F(ExpressionTest, UnaryNoCommaAsTuple) {
Nonnull<const Expression*> tuple =
TupleExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*tuple).Fields(),
ElementsAre(IntFieldNamed("0")));
}
@@ -95,8 +95,8 @@ TEST_F(ExpressionTest, UnaryWithCommaAsExpression) {
Nonnull<const Expression*> expression =
ExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(expression->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(expression->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(expression->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(expression->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*expression).Fields(),
ElementsAre(IntFieldNamed("0")));
}
@@ -109,8 +109,8 @@ TEST_F(ExpressionTest, UnaryWithCommaAsTuple) {
Nonnull<const Expression*> tuple =
TupleExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*tuple).Fields(),
ElementsAre(IntFieldNamed("0")));
}
@@ -125,8 +125,8 @@ TEST_F(ExpressionTest, BinaryAsExpression) {
Nonnull<const Expression*> expression =
ExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(expression->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(expression->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(expression->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(expression->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*expression).Fields(),
ElementsAre(IntFieldNamed("0"), IntFieldNamed("1")));
}
@@ -141,8 +141,8 @@ TEST_F(ExpressionTest, BinaryAsTuple) {
Nonnull<const Expression*> tuple =
TupleExpressionFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->Tag(), Expression::Kind::TupleLiteral);
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
ASSERT_EQ(tuple->kind(), Expression::Kind::TupleLiteral);
EXPECT_THAT(cast<TupleLiteral>(*tuple).Fields(),
ElementsAre(IntFieldNamed("0"), IntFieldNamed("1")));
}
+1 -1
View File
@@ -12,7 +12,7 @@ namespace Carbon {
using llvm::cast;
void Member::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Kind::FieldMember:
const auto& field = cast<FieldMember>(*this);
out << "var " << *field.Binding() << ";\n";
+13 -11
View File
@@ -30,32 +30,34 @@ class Member {
Member(const Member&) = delete;
Member& operator=(const Member&) = delete;
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
auto kind() const -> Kind { return kind_; }
auto SourceLoc() const -> SourceLocation { return loc; }
void Print(llvm::raw_ostream& out) const;
auto source_loc() const -> SourceLocation { return source_loc_; }
protected:
// Constructs a Member representing syntax at the given line number.
// `tag` must be the enumerator corresponding to the most-derived type being
// `kind` must be the enumerator corresponding to the most-derived type being
// constructed.
Member(Kind kind, SourceLocation loc) : kind(kind), loc(loc) {}
Member(Kind kind, SourceLocation source_loc)
: kind_(kind), source_loc_(source_loc) {}
private:
const Kind kind;
SourceLocation loc;
const Kind kind_;
SourceLocation source_loc_;
};
class FieldMember : public Member {
public:
FieldMember(SourceLocation loc, Nonnull<const BindingPattern*> binding)
: Member(Kind::FieldMember, loc), binding(binding) {}
FieldMember(SourceLocation source_loc, Nonnull<const BindingPattern*> binding)
: Member(Kind::FieldMember, source_loc), binding(binding) {}
static auto classof(const Member* member) -> bool {
return member->Tag() == Kind::FieldMember;
return member->kind() == Kind::FieldMember;
}
auto Binding() const -> Nonnull<const BindingPattern*> { return binding; }
+4 -3
View File
@@ -41,7 +41,8 @@ struct ParenContents {
//
// TODO: Find a way to deduce TupleElement from Term.
template <typename TupleElement>
auto TupleElements(SourceLocation loc) const -> std::vector<TupleElement>;
auto TupleElements(SourceLocation source_loc) const
-> std::vector<TupleElement>;
std::vector<Element> elements;
bool has_trailing_comma;
@@ -61,7 +62,7 @@ auto ParenContents<Term>::SingleTerm() const -> std::optional<Nonnull<Term*>> {
template <typename Term>
template <typename TupleElement>
auto ParenContents<Term>::TupleElements(SourceLocation loc) const
auto ParenContents<Term>::TupleElements(SourceLocation source_loc) const
-> std::vector<TupleElement> {
std::vector<TupleElement> result;
int i = 0;
@@ -72,7 +73,7 @@ auto ParenContents<Term>::TupleElements(SourceLocation loc) const
result.push_back(TupleElement(*element.name, element.term));
} else {
if (seen_named_member) {
FATAL_PROGRAM_ERROR(loc)
FATAL_PROGRAM_ERROR(source_loc)
<< "positional members must come before named members";
}
result.push_back(TupleElement(std::to_string(i), element.term));
+11 -9
View File
@@ -18,7 +18,7 @@ namespace Carbon {
using llvm::cast;
void Pattern::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Kind::AutoPattern:
out << "auto";
break;
@@ -54,22 +54,24 @@ void Pattern::Print(llvm::raw_ostream& out) const {
}
}
auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation loc,
auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation source_loc,
const ParenContents<Pattern>& paren_contents)
-> Nonnull<Pattern*> {
std::optional<Nonnull<Pattern*>> single_term = paren_contents.SingleTerm();
if (single_term.has_value()) {
return *single_term;
} else {
return TuplePatternFromParenContents(arena, loc, paren_contents);
return TuplePatternFromParenContents(arena, source_loc, paren_contents);
}
}
auto TuplePatternFromParenContents(Nonnull<Arena*> arena, SourceLocation loc,
auto TuplePatternFromParenContents(Nonnull<Arena*> arena,
SourceLocation source_loc,
const ParenContents<Pattern>& paren_contents)
-> Nonnull<TuplePattern*> {
return arena->New<TuplePattern>(
loc, paren_contents.TupleElements<TuplePattern::Field>(loc));
source_loc,
paren_contents.TupleElements<TuplePattern::Field>(source_loc));
}
// Used by AlternativePattern for constructor initialization. Produces a helpful
@@ -77,17 +79,17 @@ auto TuplePatternFromParenContents(Nonnull<Arena*> arena, SourceLocation loc,
// apply.
static auto RequireFieldAccess(Nonnull<Expression*> alternative)
-> FieldAccessExpression& {
if (alternative->Tag() != Expression::Kind::FieldAccessExpression) {
FATAL_PROGRAM_ERROR(alternative->SourceLoc())
if (alternative->kind() != Expression::Kind::FieldAccessExpression) {
FATAL_PROGRAM_ERROR(alternative->source_loc())
<< "Alternative pattern must have the form of a field access.";
}
return cast<FieldAccessExpression>(*alternative);
}
AlternativePattern::AlternativePattern(SourceLocation loc,
AlternativePattern::AlternativePattern(SourceLocation source_loc,
Nonnull<Expression*> alternative,
Nonnull<TuplePattern*> arguments)
: Pattern(Kind::AlternativePattern, loc),
: Pattern(Kind::AlternativePattern, source_loc),
choice_type(RequireFieldAccess(alternative).Aggregate()),
alternative_name(RequireFieldAccess(alternative).Field()),
arguments(arguments) {}
+33 -26
View File
@@ -37,33 +37,35 @@ class Pattern {
Pattern(const Pattern&) = delete;
Pattern& operator=(const Pattern&) = delete;
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
auto SourceLoc() const -> SourceLocation { return loc; }
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
auto source_loc() const -> SourceLocation { return source_loc_; }
protected:
// Constructs a Pattern representing syntax at the given line number.
// `tag` must be the enumerator corresponding to the most-derived type being
// `kind` must be the enumerator corresponding to the most-derived type being
// constructed.
Pattern(Kind kind, SourceLocation loc) : kind(kind), loc(loc) {}
Pattern(Kind kind, SourceLocation source_loc)
: kind_(kind), source_loc_(source_loc) {}
private:
const Kind kind;
SourceLocation loc;
const Kind kind_;
SourceLocation source_loc_;
};
// A pattern consisting of the `auto` keyword.
class AutoPattern : public Pattern {
public:
explicit AutoPattern(SourceLocation loc) : Pattern(Kind::AutoPattern, loc) {}
explicit AutoPattern(SourceLocation source_loc)
: Pattern(Kind::AutoPattern, source_loc) {}
static auto classof(const Pattern* pattern) -> bool {
return pattern->Tag() == Kind::AutoPattern;
return pattern->kind() == Kind::AutoPattern;
}
};
@@ -71,12 +73,14 @@ class AutoPattern : public Pattern {
// a name to it.
class BindingPattern : public Pattern {
public:
BindingPattern(SourceLocation loc, std::optional<std::string> name,
BindingPattern(SourceLocation source_loc, std::optional<std::string> name,
Nonnull<Pattern*> type)
: Pattern(Kind::BindingPattern, loc), name(std::move(name)), type(type) {}
: Pattern(Kind::BindingPattern, source_loc),
name(std::move(name)),
type(type) {}
static auto classof(const Pattern* pattern) -> bool {
return pattern->Tag() == Kind::BindingPattern;
return pattern->kind() == Kind::BindingPattern;
}
// The name this pattern binds, if any.
@@ -106,11 +110,11 @@ class TuplePattern : public Pattern {
Nonnull<Pattern*> pattern;
};
TuplePattern(SourceLocation loc, std::vector<Field> fields)
: Pattern(Kind::TuplePattern, loc), fields(std::move(fields)) {}
TuplePattern(SourceLocation source_loc, std::vector<Field> fields)
: Pattern(Kind::TuplePattern, source_loc), fields(std::move(fields)) {}
static auto classof(const Pattern* pattern) -> bool {
return pattern->Tag() == Kind::TuplePattern;
return pattern->kind() == Kind::TuplePattern;
}
auto Fields() const -> llvm::ArrayRef<Field> { return fields; }
@@ -123,13 +127,14 @@ class TuplePattern : public Pattern {
// Converts paren_contents to a Pattern, interpreting the parentheses as
// grouping if their contents permit that interpretation, or as forming a
// tuple otherwise.
auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation loc,
auto PatternFromParenContents(Nonnull<Arena*> arena, SourceLocation source_loc,
const ParenContents<Pattern>& paren_contents)
-> Nonnull<Pattern*>;
// Converts paren_contents to a TuplePattern, interpreting the parentheses as
// forming a tuple.
auto TuplePatternFromParenContents(Nonnull<Arena*> arena, SourceLocation loc,
auto TuplePatternFromParenContents(Nonnull<Arena*> arena,
SourceLocation source_loc,
const ParenContents<Pattern>& paren_contents)
-> Nonnull<TuplePattern*>;
@@ -145,21 +150,23 @@ class AlternativePattern : public Pattern {
// Constructs an AlternativePattern that matches a value of the type
// specified by choice_type if it represents an alternative named
// alternative_name, and its arguments match `arguments`.
AlternativePattern(SourceLocation loc, Nonnull<Expression*> choice_type,
AlternativePattern(SourceLocation source_loc,
Nonnull<Expression*> choice_type,
std::string alternative_name,
Nonnull<TuplePattern*> arguments)
: Pattern(Kind::AlternativePattern, loc),
: Pattern(Kind::AlternativePattern, source_loc),
choice_type(choice_type),
alternative_name(std::move(alternative_name)),
arguments(arguments) {}
// Constructs an AlternativePattern that matches the alternative specified
// by `alternative`, if its arguments match `arguments`.
AlternativePattern(SourceLocation loc, Nonnull<Expression*> alternative,
AlternativePattern(SourceLocation source_loc,
Nonnull<Expression*> alternative,
Nonnull<TuplePattern*> arguments);
static auto classof(const Pattern* pattern) -> bool {
return pattern->Tag() == Kind::AlternativePattern;
return pattern->kind() == Kind::AlternativePattern;
}
auto ChoiceType() const -> Nonnull<const Expression*> { return choice_type; }
@@ -181,11 +188,11 @@ class AlternativePattern : public Pattern {
class ExpressionPattern : public Pattern {
public:
ExpressionPattern(Nonnull<Expression*> expression)
: Pattern(Kind::ExpressionPattern, expression->SourceLoc()),
: Pattern(Kind::ExpressionPattern, expression->source_loc()),
expression(expression) {}
static auto classof(const Pattern* pattern) -> bool {
return pattern->Tag() == Kind::ExpressionPattern;
return pattern->kind() == Kind::ExpressionPattern;
}
auto Expression() const -> Nonnull<const Expression*> { return expression; }
+8 -8
View File
@@ -39,7 +39,7 @@ TEST_F(PatternTest, EmptyAsPattern) {
.has_trailing_comma = false};
Nonnull<const Pattern*> pattern =
PatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(pattern->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(pattern->source_loc(), FakeSourceLoc(1));
ASSERT_TRUE(isa<TuplePattern>(*pattern));
EXPECT_THAT(cast<TuplePattern>(*pattern).Fields(), IsEmpty());
}
@@ -49,7 +49,7 @@ TEST_F(PatternTest, EmptyAsTuplePattern) {
.has_trailing_comma = false};
Nonnull<const TuplePattern*> tuple =
TuplePatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
EXPECT_THAT(tuple->Fields(), IsEmpty());
}
@@ -67,7 +67,7 @@ TEST_F(PatternTest, UnaryNoCommaAsPattern) {
Nonnull<const Pattern*> pattern =
PatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(pattern->SourceLoc(), FakeSourceLoc(2));
EXPECT_EQ(pattern->source_loc(), FakeSourceLoc(2));
ASSERT_TRUE(isa<AutoPattern>(*pattern));
}
@@ -79,7 +79,7 @@ TEST_F(PatternTest, UnaryNoCommaAsTuplePattern) {
Nonnull<const TuplePattern*> tuple =
TuplePatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
EXPECT_THAT(tuple->Fields(), ElementsAre(AutoFieldNamed("0")));
}
@@ -91,7 +91,7 @@ TEST_F(PatternTest, UnaryWithCommaAsPattern) {
Nonnull<const Pattern*> pattern =
PatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(pattern->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(pattern->source_loc(), FakeSourceLoc(1));
ASSERT_TRUE(isa<TuplePattern>(*pattern));
EXPECT_THAT(cast<TuplePattern>(*pattern).Fields(),
ElementsAre(AutoFieldNamed("0")));
@@ -105,7 +105,7 @@ TEST_F(PatternTest, UnaryWithCommaAsTuplePattern) {
Nonnull<const TuplePattern*> tuple =
TuplePatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
EXPECT_THAT(tuple->Fields(), ElementsAre(AutoFieldNamed("0")));
}
@@ -119,7 +119,7 @@ TEST_F(PatternTest, BinaryAsPattern) {
Nonnull<const Pattern*> pattern =
PatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(pattern->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(pattern->source_loc(), FakeSourceLoc(1));
ASSERT_TRUE(isa<TuplePattern>(*pattern));
EXPECT_THAT(cast<TuplePattern>(*pattern).Fields(),
ElementsAre(AutoFieldNamed("0"), AutoFieldNamed("1")));
@@ -135,7 +135,7 @@ TEST_F(PatternTest, BinaryAsTuplePattern) {
Nonnull<const TuplePattern*> tuple =
TuplePatternFromParenContents(&arena, FakeSourceLoc(1), contents);
EXPECT_EQ(tuple->SourceLoc(), FakeSourceLoc(1));
EXPECT_EQ(tuple->source_loc(), FakeSourceLoc(1));
EXPECT_THAT(tuple->Fields(),
ElementsAre(AutoFieldNamed("0"), AutoFieldNamed("1")));
}
+1 -1
View File
@@ -17,7 +17,7 @@ void Statement::PrintDepth(int depth, llvm::raw_ostream& out) const {
out << " ... ";
return;
}
switch (Tag()) {
switch (kind()) {
case Kind::Match: {
const auto& match = cast<Match>(*this);
out << "match (" << match.expression() << ") {";
+58 -51
View File
@@ -36,34 +36,35 @@ class Statement {
Await, // Pause execution of the continuation.
};
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
auto SourceLoc() const -> SourceLocation { return loc; }
void Print(llvm::raw_ostream& out) const { PrintDepth(-1, out); }
void PrintDepth(int depth, llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
auto source_loc() const -> SourceLocation { return source_loc_; }
protected:
// Constructs an Statement representing syntax at the given line number.
// `tag` must be the enumerator corresponding to the most-derived type being
// `kind` must be the enumerator corresponding to the most-derived type being
// constructed.
Statement(Kind kind, SourceLocation loc) : kind(kind), loc(loc) {}
Statement(Kind kind, SourceLocation source_loc)
: kind_(kind), source_loc_(source_loc) {}
private:
const Kind kind;
SourceLocation loc;
const Kind kind_;
SourceLocation source_loc_;
};
class ExpressionStatement : public Statement {
public:
ExpressionStatement(SourceLocation loc, Nonnull<Expression*> exp)
: Statement(Kind::ExpressionStatement, loc), exp(exp) {}
ExpressionStatement(SourceLocation source_loc, Nonnull<Expression*> exp)
: Statement(Kind::ExpressionStatement, source_loc), exp(exp) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::ExpressionStatement;
return stmt->kind() == Kind::ExpressionStatement;
}
auto Exp() const -> Nonnull<const Expression*> { return exp; }
@@ -75,11 +76,12 @@ class ExpressionStatement : public Statement {
class Assign : public Statement {
public:
Assign(SourceLocation loc, Nonnull<Expression*> lhs, Nonnull<Expression*> rhs)
: Statement(Kind::Assign, loc), lhs(lhs), rhs(rhs) {}
Assign(SourceLocation source_loc, Nonnull<Expression*> lhs,
Nonnull<Expression*> rhs)
: Statement(Kind::Assign, source_loc), lhs(lhs), rhs(rhs) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Assign;
return stmt->kind() == Kind::Assign;
}
auto Lhs() const -> Nonnull<const Expression*> { return lhs; }
@@ -94,12 +96,12 @@ class Assign : public Statement {
class VariableDefinition : public Statement {
public:
VariableDefinition(SourceLocation loc, Nonnull<Pattern*> pat,
VariableDefinition(SourceLocation source_loc, Nonnull<Pattern*> pat,
Nonnull<Expression*> init)
: Statement(Kind::VariableDefinition, loc), pat(pat), init(init) {}
: Statement(Kind::VariableDefinition, source_loc), pat(pat), init(init) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::VariableDefinition;
return stmt->kind() == Kind::VariableDefinition;
}
auto Pat() const -> Nonnull<const Pattern*> { return pat; }
@@ -114,16 +116,16 @@ class VariableDefinition : public Statement {
class If : public Statement {
public:
If(SourceLocation loc, Nonnull<Expression*> cond,
If(SourceLocation source_loc, Nonnull<Expression*> cond,
Nonnull<Statement*> then_stmt,
std::optional<Nonnull<Statement*>> else_stmt)
: Statement(Kind::If, loc),
: Statement(Kind::If, source_loc),
cond(cond),
then_stmt(then_stmt),
else_stmt(else_stmt) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::If;
return stmt->kind() == Kind::If;
}
auto Cond() const -> Nonnull<const Expression*> { return cond; }
@@ -143,15 +145,16 @@ class If : public Statement {
class Return : public Statement {
public:
Return(Nonnull<Arena*> arena, SourceLocation loc)
: Return(loc, arena->New<TupleLiteral>(loc), true) {}
Return(SourceLocation loc, Nonnull<Expression*> exp, bool is_omitted_exp)
: Statement(Kind::Return, loc),
Return(Nonnull<Arena*> arena, SourceLocation source_loc)
: Return(source_loc, arena->New<TupleLiteral>(source_loc), true) {}
Return(SourceLocation source_loc, Nonnull<Expression*> exp,
bool is_omitted_exp)
: Statement(Kind::Return, source_loc),
exp(exp),
is_omitted_exp(is_omitted_exp) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Return;
return stmt->kind() == Kind::Return;
}
auto Exp() const -> Nonnull<const Expression*> { return exp; }
@@ -165,12 +168,12 @@ class Return : public Statement {
class Sequence : public Statement {
public:
Sequence(SourceLocation loc, Nonnull<Statement*> stmt,
Sequence(SourceLocation source_loc, Nonnull<Statement*> stmt,
std::optional<Nonnull<Statement*>> next)
: Statement(Kind::Sequence, loc), stmt(stmt), next(next) {}
: Statement(Kind::Sequence, source_loc), stmt(stmt), next(next) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Sequence;
return stmt->kind() == Kind::Sequence;
}
auto Stmt() const -> Nonnull<const Statement*> { return stmt; }
@@ -185,11 +188,11 @@ class Sequence : public Statement {
class Block : public Statement {
public:
Block(SourceLocation loc, std::optional<Nonnull<Statement*>> stmt)
: Statement(Kind::Block, loc), stmt(stmt) {}
Block(SourceLocation source_loc, std::optional<Nonnull<Statement*>> stmt)
: Statement(Kind::Block, source_loc), stmt(stmt) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Block;
return stmt->kind() == Kind::Block;
}
auto Stmt() const -> std::optional<Nonnull<const Statement*>> { return stmt; }
@@ -201,11 +204,12 @@ class Block : public Statement {
class While : public Statement {
public:
While(SourceLocation loc, Nonnull<Expression*> cond, Nonnull<Statement*> body)
: Statement(Kind::While, loc), cond(cond), body(body) {}
While(SourceLocation source_loc, Nonnull<Expression*> cond,
Nonnull<Statement*> body)
: Statement(Kind::While, source_loc), cond(cond), body(body) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::While;
return stmt->kind() == Kind::While;
}
auto Cond() const -> Nonnull<const Expression*> { return cond; }
@@ -220,19 +224,21 @@ class While : public Statement {
class Break : public Statement {
public:
explicit Break(SourceLocation loc) : Statement(Kind::Break, loc) {}
explicit Break(SourceLocation source_loc)
: Statement(Kind::Break, source_loc) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Break;
return stmt->kind() == Kind::Break;
}
};
class Continue : public Statement {
public:
explicit Continue(SourceLocation loc) : Statement(Kind::Continue, loc) {}
explicit Continue(SourceLocation source_loc)
: Statement(Kind::Continue, source_loc) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Continue;
return stmt->kind() == Kind::Continue;
}
};
@@ -253,14 +259,14 @@ class Match : public Statement {
Nonnull<Statement*> statement_;
};
Match(SourceLocation loc, Nonnull<Expression*> expression,
Match(SourceLocation source_loc, Nonnull<Expression*> expression,
std::vector<Clause> clauses)
: Statement(Kind::Match, loc),
: Statement(Kind::Match, source_loc),
expression_(expression),
clauses_(std::move(clauses)) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Match;
return stmt->kind() == Kind::Match;
}
auto expression() const -> const Expression& { return *expression_; }
@@ -280,14 +286,14 @@ class Match : public Statement {
// }
class Continuation : public Statement {
public:
Continuation(SourceLocation loc, std::string continuation_variable,
Continuation(SourceLocation source_loc, std::string continuation_variable,
Nonnull<Statement*> body)
: Statement(Kind::Continuation, loc),
: Statement(Kind::Continuation, source_loc),
continuation_variable(std::move(continuation_variable)),
body(body) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Continuation;
return stmt->kind() == Kind::Continuation;
}
auto ContinuationVariable() const -> const std::string& {
@@ -306,11 +312,11 @@ class Continuation : public Statement {
// __run <argument>;
class Run : public Statement {
public:
Run(SourceLocation loc, Nonnull<Expression*> argument)
: Statement(Kind::Run, loc), argument(argument) {}
Run(SourceLocation source_loc, Nonnull<Expression*> argument)
: Statement(Kind::Run, source_loc), argument(argument) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Run;
return stmt->kind() == Kind::Run;
}
auto Argument() const -> Nonnull<const Expression*> { return argument; }
@@ -325,10 +331,11 @@ class Run : public Statement {
// __await;
class Await : public Statement {
public:
explicit Await(SourceLocation loc) : Statement(Kind::Await, loc) {}
explicit Await(SourceLocation source_loc)
: Statement(Kind::Await, source_loc) {}
static auto classof(const Statement* stmt) -> bool {
return stmt->Tag() == Kind::Await;
return stmt->kind() == Kind::Await;
}
};
+4 -4
View File
@@ -22,7 +22,7 @@ namespace Carbon {
using llvm::cast;
void Action::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Action::Kind::LValAction:
out << *cast<LValAction>(*this).Exp();
break;
@@ -36,11 +36,11 @@ void Action::Print(llvm::raw_ostream& out) const {
cast<StatementAction>(*this).Stmt()->PrintDepth(1, out);
break;
}
out << "<" << pos << ">";
if (results.size() > 0) {
out << "<" << pos_ << ">";
if (results_.size() > 0) {
out << "(";
llvm::ListSeparator sep;
for (auto& result : results) {
for (auto& result : results_) {
out << sep << *result;
}
out << ")";
+31 -31
View File
@@ -29,48 +29,48 @@ class Action {
Action(const Value&) = delete;
Action& operator=(const Value&) = delete;
// The position or state of the action. Starts at 0 and goes up to the number
// of subexpressions.
//
// pos indicates how many of the entries in the following `results` vector
// will be filled in the next time this action is active.
// For each i < pos, results[i] contains a pointer to a Value.
auto Pos() const -> int { return pos; }
// Results from a subexpression.
auto Results() const -> const std::vector<Nonnull<const Value*>>& {
return results;
}
void SetPos(int pos) { this->pos = pos; }
void AddResult(Nonnull<const Value*> result) { results.push_back(result); }
void AddResult(Nonnull<const Value*> result) { results_.push_back(result); }
void Clear() {
pos = 0;
results.clear();
pos_ = 0;
results_.clear();
}
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
static void PrintList(const Stack<Nonnull<Action*>>& ls,
llvm::raw_ostream& out);
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
// The position or state of the action. Starts at 0 and goes up to the number
// of subexpressions.
//
// pos indicates how many of the entries in the following `results` vector
// will be filled in the next time this action is active.
// For each i < pos, results[i] contains a pointer to a Value.
auto pos() const -> int { return pos_; }
void set_pos(int pos) { this->pos_ = pos; }
// Results from a subexpression.
auto results() const -> const std::vector<Nonnull<const Value*>>& {
return results_;
}
protected:
// Constructs an Action. `tag` must be the enumerator corresponding to the
// Constructs an Action. `kind` must be the enumerator corresponding to the
// most-derived type being constructed.
explicit Action(Kind kind) : kind(kind) {}
explicit Action(Kind kind) : kind_(kind) {}
private:
int pos = 0;
std::vector<Nonnull<const Value*>> results;
int pos_ = 0;
std::vector<Nonnull<const Value*>> results_;
const Kind kind;
const Kind kind_;
};
class LValAction : public Action {
@@ -79,7 +79,7 @@ class LValAction : public Action {
: Action(Kind::LValAction), exp(exp) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::LValAction;
return action->kind() == Kind::LValAction;
}
auto Exp() const -> Nonnull<const Expression*> { return exp; }
@@ -94,7 +94,7 @@ class ExpressionAction : public Action {
: Action(Kind::ExpressionAction), exp(exp) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::ExpressionAction;
return action->kind() == Kind::ExpressionAction;
}
auto Exp() const -> Nonnull<const Expression*> { return exp; }
@@ -109,7 +109,7 @@ class PatternAction : public Action {
: Action(Kind::PatternAction), pat(pat) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::PatternAction;
return action->kind() == Kind::PatternAction;
}
auto Pat() const -> Nonnull<const Pattern*> { return pat; }
@@ -124,7 +124,7 @@ class StatementAction : public Action {
: Action(Kind::StatementAction), stmt(stmt) {}
static auto classof(const Action* action) -> bool {
return action->Tag() == Kind::StatementAction;
return action->kind() == Kind::StatementAction;
}
auto Stmt() const -> Nonnull<const Statement*> { return stmt; }
@@ -17,21 +17,21 @@ namespace Carbon {
// standardized, but is made available for printing state in tests.
static void AddIntrinsics(Nonnull<Arena*> arena,
std::vector<Nonnull<Declaration*>>* declarations) {
SourceLocation loc("<intrinsic>", 0);
SourceLocation source_loc("<intrinsic>", 0);
std::vector<TuplePattern::Field> print_fields = {TuplePattern::Field(
"0",
arena->New<BindingPattern>(
loc, "format_str",
arena->New<ExpressionPattern>(arena->New<StringTypeLiteral>(loc))))};
"0", arena->New<BindingPattern>(
source_loc, "format_str",
arena->New<ExpressionPattern>(
arena->New<StringTypeLiteral>(source_loc))))};
auto print_return =
arena->New<Return>(loc,
arena->New<Return>(source_loc,
arena->New<IntrinsicExpression>(
IntrinsicExpression::IntrinsicKind::Print),
false);
auto print = arena->New<FunctionDeclaration>(arena->New<FunctionDefinition>(
loc, "Print", std::vector<GenericBinding>(),
arena->New<TuplePattern>(loc, print_fields),
arena->New<ExpressionPattern>(arena->New<TupleLiteral>(loc)),
source_loc, "Print", std::vector<GenericBinding>(),
arena->New<TuplePattern>(source_loc, print_fields),
arena->New<ExpressionPattern>(arena->New<TupleLiteral>(source_loc)),
/*is_omitted_return_type=*/false, print_return));
declarations->insert(declarations->begin(), print);
}
@@ -62,10 +62,10 @@ void ExecProgram(Nonnull<Arena*> arena, AST ast) {
llvm::outs() << "********** starting execution **********\n";
}
SourceLocation loc("<main()>", 0);
SourceLocation source_loc("<main()>", 0);
Nonnull<Expression*> call_main = arena->New<CallExpression>(
loc, arena->New<IdentifierExpression>(loc, "main"),
arena->New<TupleLiteral>(loc));
source_loc, arena->New<IdentifierExpression>(source_loc, "main"),
arena->New<TupleLiteral>(source_loc));
int result = Interpreter(arena).InterpProgram(new_decls, call_main);
llvm::outs() << "result: " << result << "\n";
}
+12 -9
View File
@@ -20,21 +20,24 @@ auto Heap::AllocateValue(Nonnull<const Value*> v) -> Address {
return a;
}
auto Heap::Read(const Address& a, SourceLocation loc) -> Nonnull<const Value*> {
this->CheckAlive(a, loc);
return values[a.index]->GetField(arena, a.field_path, loc);
auto Heap::Read(const Address& a, SourceLocation source_loc)
-> Nonnull<const Value*> {
this->CheckAlive(a, source_loc);
return values[a.index]->GetField(arena, a.field_path, source_loc);
}
void Heap::Write(const Address& a, Nonnull<const Value*> v,
SourceLocation loc) {
this->CheckAlive(a, loc);
values[a.index] = values[a.index]->SetField(arena, a.field_path, v, loc);
SourceLocation source_loc) {
this->CheckAlive(a, source_loc);
values[a.index] =
values[a.index]->SetField(arena, a.field_path, v, source_loc);
}
void Heap::CheckAlive(const Address& address, SourceLocation loc) {
void Heap::CheckAlive(const Address& address, SourceLocation source_loc) {
if (!alive[address.index]) {
FATAL_RUNTIME_ERROR(loc) << "undefined behavior: access to dead value "
<< *values[address.index];
FATAL_RUNTIME_ERROR(source_loc)
<< "undefined behavior: access to dead value "
<< *values[address.index];
}
}
+5 -3
View File
@@ -25,11 +25,13 @@ class Heap {
// Returns the value at the given address in the heap after
// checking that it is alive.
auto Read(const Address& a, SourceLocation loc) -> Nonnull<const Value*>;
auto Read(const Address& a, SourceLocation source_loc)
-> Nonnull<const Value*>;
// Writes the given value at the address in the heap after
// checking that the address is alive.
void Write(const Address& a, Nonnull<const Value*> v, SourceLocation loc);
void Write(const Address& a, Nonnull<const Value*> v,
SourceLocation source_loc);
// Put the given value on the heap and mark it as alive.
auto AllocateValue(Nonnull<const Value*> v) -> Address;
@@ -47,7 +49,7 @@ class Heap {
private:
// Signal an error if the address is no longer alive.
void CheckAlive(const Address& address, SourceLocation loc);
void CheckAlive(const Address& address, SourceLocation source_loc);
Nonnull<Arena*> arena;
std::vector<Nonnull<const Value*>> values;
+171 -167
View File
@@ -51,11 +51,11 @@ auto Interpreter::CurrentEnv() -> Env {
}
// Returns the given name from the environment, printing an error if not found.
auto Interpreter::GetFromEnv(SourceLocation loc, const std::string& name)
auto Interpreter::GetFromEnv(SourceLocation source_loc, const std::string& name)
-> Address {
std::optional<Address> pointer = CurrentEnv().Get(name);
if (!pointer) {
FATAL_RUNTIME_ERROR(loc) << "could not find `" << name << "`";
FATAL_RUNTIME_ERROR(source_loc) << "could not find `" << name << "`";
}
return *pointer;
}
@@ -76,7 +76,7 @@ void Interpreter::PrintState(llvm::raw_ostream& out) {
auto Interpreter::EvalPrim(Operator op,
const std::vector<Nonnull<const Value*>>& args,
SourceLocation loc) -> Nonnull<const Value*> {
SourceLocation source_loc) -> Nonnull<const Value*> {
switch (op) {
case Operator::Neg:
return arena->New<IntValue>(-cast<IntValue>(*args[0]).Val());
@@ -98,7 +98,7 @@ auto Interpreter::EvalPrim(Operator op,
return arena->New<BoolValue>(cast<BoolValue>(*args[0]).Val() ||
cast<BoolValue>(*args[1]).Val());
case Operator::Eq:
return arena->New<BoolValue>(ValueEqual(args[0], args[1], loc));
return arena->New<BoolValue>(ValueEqual(args[0], args[1], source_loc));
case Operator::Ptr:
return arena->New<PointerType>(args[0]);
case Operator::Deref:
@@ -129,7 +129,7 @@ void Interpreter::InitEnv(const Declaration& d, Env* env) {
VarValues fields;
VarValues methods;
for (Nonnull<const Member*> m : class_def.members()) {
switch (m->Tag()) {
switch (m->kind()) {
case Member::Kind::FieldMember: {
Nonnull<const BindingPattern*> binding =
cast<FieldMember>(*m).Binding();
@@ -201,11 +201,11 @@ auto Interpreter::CreateTuple(Nonnull<Action*> act,
// { { (v1,...,vn) :: C, E, F} :: S, H}
// -> { { `(v1,...,vn) :: C, E, F} :: S, H}
const auto& tup_lit = cast<TupleLiteral>(*exp);
CHECK(act->Results().size() == tup_lit.Fields().size());
CHECK(act->results().size() == tup_lit.Fields().size());
std::vector<TupleElement> elements;
for (size_t i = 0; i < act->Results().size(); ++i) {
for (size_t i = 0; i < act->results().size(); ++i) {
elements.push_back(
{.name = tup_lit.Fields()[i].name, .value = act->Results()[i]});
{.name = tup_lit.Fields()[i].name, .value = act->results()[i]});
}
return arena->New<TupleValue>(std::move(elements));
@@ -224,37 +224,39 @@ auto Interpreter::CreateStruct(const std::vector<FieldInitializer>& fields,
}
auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
SourceLocation loc) -> std::optional<Env> {
switch (p->Tag()) {
SourceLocation source_loc)
-> std::optional<Env> {
switch (p->kind()) {
case Value::Kind::BindingPlaceholderValue: {
const auto& placeholder = cast<BindingPlaceholderValue>(*p);
Env values(arena);
if (placeholder.Name().has_value()) {
Address a = heap.AllocateValue(CopyVal(arena, v, loc));
Address a = heap.AllocateValue(CopyVal(arena, v, source_loc));
values.Set(*placeholder.Name(), a);
}
return values;
}
case Value::Kind::TupleValue:
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::TupleValue: {
const auto& p_tup = cast<TupleValue>(*p);
const auto& v_tup = cast<TupleValue>(*v);
if (p_tup.Elements().size() != v_tup.Elements().size()) {
FATAL_PROGRAM_ERROR(loc)
FATAL_PROGRAM_ERROR(source_loc)
<< "arity mismatch in tuple pattern match:\n pattern: "
<< p_tup << "\n value: " << v_tup;
}
Env values(arena);
for (size_t i = 0; i < p_tup.Elements().size(); ++i) {
if (p_tup.Elements()[i].name != v_tup.Elements()[i].name) {
FATAL_PROGRAM_ERROR(loc)
FATAL_PROGRAM_ERROR(source_loc)
<< "Tuple field name '" << v_tup.Elements()[i].name
<< "' does not match pattern field name '"
<< p_tup.Elements()[i].name << "'";
}
std::optional<Env> matches = PatternMatch(
p_tup.Elements()[i].value, v_tup.Elements()[i].value, loc);
std::optional<Env> matches =
PatternMatch(p_tup.Elements()[i].value,
v_tup.Elements()[i].value, source_loc);
if (!matches) {
return std::nullopt;
}
@@ -274,8 +276,9 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
Env values(arena);
for (size_t i = 0; i < p_struct.elements().size(); ++i) {
CHECK(p_struct.elements()[i].name == v_struct.elements()[i].name);
std::optional<Env> matches = PatternMatch(
p_struct.elements()[i].value, v_struct.elements()[i].value, loc);
std::optional<Env> matches =
PatternMatch(p_struct.elements()[i].value,
v_struct.elements()[i].value, source_loc);
if (!matches) {
return std::nullopt;
}
@@ -286,7 +289,7 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
return values;
}
case Value::Kind::AlternativeValue:
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::AlternativeValue: {
const auto& p_alt = cast<AlternativeValue>(*p);
const auto& v_alt = cast<AlternativeValue>(*v);
@@ -294,23 +297,23 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
p_alt.AltName() != v_alt.AltName()) {
return std::nullopt;
}
return PatternMatch(p_alt.Argument(), v_alt.Argument(), loc);
return PatternMatch(p_alt.Argument(), v_alt.Argument(), source_loc);
}
default:
FATAL() << "expected a choice alternative in pattern, not " << *v;
}
case Value::Kind::FunctionType:
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::FunctionType: {
const auto& p_fn = cast<FunctionType>(*p);
const auto& v_fn = cast<FunctionType>(*v);
std::optional<Env> param_matches =
PatternMatch(p_fn.Param(), v_fn.Param(), loc);
PatternMatch(p_fn.Param(), v_fn.Param(), source_loc);
if (!param_matches) {
return std::nullopt;
}
std::optional<Env> ret_matches =
PatternMatch(p_fn.Ret(), v_fn.Ret(), loc);
PatternMatch(p_fn.Ret(), v_fn.Ret(), source_loc);
if (!ret_matches) {
return std::nullopt;
}
@@ -328,7 +331,7 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
// on the typechecker to ensure that `v` is a type.
return Env(arena);
default:
if (ValueEqual(p, v, loc)) {
if (ValueEqual(p, v, source_loc)) {
return Env(arena);
} else {
return std::nullopt;
@@ -338,18 +341,19 @@ auto Interpreter::PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
Nonnull<const Value*> val,
SourceLocation loc) {
switch (pat->Tag()) {
SourceLocation source_loc) {
switch (pat->kind()) {
case Value::Kind::PointerValue:
heap.Write(cast<PointerValue>(*pat).Val(), CopyVal(arena, val, loc), loc);
heap.Write(cast<PointerValue>(*pat).Val(),
CopyVal(arena, val, source_loc), source_loc);
break;
case Value::Kind::TupleValue: {
switch (val->Tag()) {
switch (val->kind()) {
case Value::Kind::TupleValue: {
const auto& pat_tup = cast<TupleValue>(*pat);
const auto& val_tup = cast<TupleValue>(*val);
if (pat_tup.Elements().size() != val_tup.Elements().size()) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "arity mismatch in tuple pattern assignment:\n pattern: "
<< pat_tup << "\n value: " << val_tup;
}
@@ -357,10 +361,10 @@ void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
std::optional<Nonnull<const Value*>> value_field =
val_tup.FindField(pattern_element.name);
if (!value_field) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "field " << pattern_element.name << "not in " << *val;
}
PatternAssignment(pattern_element.value, *value_field, loc);
PatternAssignment(pattern_element.value, *value_field, source_loc);
}
break;
}
@@ -370,14 +374,14 @@ void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
break;
}
case Value::Kind::AlternativeValue: {
switch (val->Tag()) {
switch (val->kind()) {
case Value::Kind::AlternativeValue: {
const auto& pat_alt = cast<AlternativeValue>(*pat);
const auto& val_alt = cast<AlternativeValue>(*val);
CHECK(val_alt.ChoiceName() == pat_alt.ChoiceName() &&
val_alt.AltName() == pat_alt.AltName())
<< "internal error in pattern assignment";
PatternAssignment(pat_alt.Argument(), val_alt.Argument(), loc);
PatternAssignment(pat_alt.Argument(), val_alt.Argument(), source_loc);
break;
}
default:
@@ -386,7 +390,7 @@ void Interpreter::PatternAssignment(Nonnull<const Value*> pat,
break;
}
default:
CHECK(ValueEqual(pat, val, loc))
CHECK(ValueEqual(pat, val, source_loc))
<< "internal error in pattern assignment";
}
}
@@ -395,20 +399,20 @@ auto Interpreter::StepLvalue() -> Transition {
Nonnull<Action*> act = stack.Top()->todo.Top();
Nonnull<const Expression*> exp = cast<LValAction>(*act).Exp();
if (tracing_output) {
llvm::outs() << "--- step lvalue " << *exp << " (" << exp->SourceLoc()
llvm::outs() << "--- step lvalue " << *exp << " (" << exp->source_loc()
<< ") --->\n";
}
switch (exp->Tag()) {
switch (exp->kind()) {
case Expression::Kind::IdentifierExpression: {
// { {x :: C, E, F} :: S, H}
// -> { {E(x) :: C, E, F} :: S, H}
Address pointer =
GetFromEnv(exp->SourceLoc(), cast<IdentifierExpression>(*exp).Name());
Address pointer = GetFromEnv(exp->source_loc(),
cast<IdentifierExpression>(*exp).Name());
Nonnull<const Value*> v = arena->New<PointerValue>(pointer);
return Done{v};
}
case Expression::Kind::FieldAccessExpression: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e.f :: C, E, F} :: S, H}
// -> { e :: [].f :: C, E, F} :: S, H}
return Spawn{arena->New<LValAction>(
@@ -416,41 +420,41 @@ auto Interpreter::StepLvalue() -> Transition {
} else {
// { v :: [].f :: C, E, F} :: S, H}
// -> { { &v.f :: C, E, F} :: S, H }
Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
Address aggregate = cast<PointerValue>(*act->results()[0]).Val();
Address field = aggregate.SubobjectAddress(
cast<FieldAccessExpression>(*exp).Field());
return Done{arena->New<PointerValue>(field)};
}
}
case Expression::Kind::IndexExpression: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e[i] :: C, E, F} :: S, H}
// -> { e :: [][i] :: C, E, F} :: S, H}
return Spawn{
arena->New<LValAction>(cast<IndexExpression>(*exp).Aggregate())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{
arena->New<ExpressionAction>(cast<IndexExpression>(*exp).Offset())};
} else {
// { v :: [][i] :: C, E, F} :: S, H}
// -> { { &v[i] :: C, E, F} :: S, H }
Address aggregate = cast<PointerValue>(*act->Results()[0]).Val();
Address aggregate = cast<PointerValue>(*act->results()[0]).Val();
std::string f =
std::to_string(cast<IntValue>(*act->Results()[1]).Val());
std::to_string(cast<IntValue>(*act->results()[1]).Val());
Address field = aggregate.SubobjectAddress(f);
return Done{arena->New<PointerValue>(field)};
}
}
case Expression::Kind::TupleLiteral: {
if (act->Pos() <
if (act->pos() <
static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
// { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
// H}
// -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
// H}
Nonnull<const Expression*> elt =
cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
cast<TupleLiteral>(*exp).Fields()[act->pos()].expression;
return Spawn{arena->New<LValAction>(elt)};
} else {
return Done{CreateTuple(act, exp)};
@@ -479,29 +483,29 @@ auto Interpreter::StepExp() -> Transition {
Nonnull<Action*> act = stack.Top()->todo.Top();
Nonnull<const Expression*> exp = cast<ExpressionAction>(*act).Exp();
if (tracing_output) {
llvm::outs() << "--- step exp " << *exp << " (" << exp->SourceLoc()
llvm::outs() << "--- step exp " << *exp << " (" << exp->source_loc()
<< ") --->\n";
}
switch (exp->Tag()) {
switch (exp->kind()) {
case Expression::Kind::IndexExpression: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { { e[i] :: C, E, F} :: S, H}
// -> { { e :: [][i] :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<IndexExpression>(*exp).Aggregate())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{
arena->New<ExpressionAction>(cast<IndexExpression>(*exp).Offset())};
} else {
// { { v :: [][i] :: C, E, F} :: S, H}
// -> { { v_i :: C, E, F} : S, H}
auto* tuple = dyn_cast<TupleValue>(act->Results()[0]);
auto* tuple = dyn_cast<TupleValue>(act->results()[0]);
if (tuple == nullptr) {
FATAL_RUNTIME_ERROR_NO_LINE()
<< "expected a tuple in field access, not " << *act->Results()[0];
<< "expected a tuple in field access, not " << *act->results()[0];
}
std::string f =
std::to_string(cast<IntValue>(*act->Results()[1]).Val());
std::to_string(cast<IntValue>(*act->results()[1]).Val());
std::optional<Nonnull<const Value*>> field = tuple->FindField(f);
if (!field) {
FATAL_RUNTIME_ERROR_NO_LINE()
@@ -511,14 +515,14 @@ auto Interpreter::StepExp() -> Transition {
}
}
case Expression::Kind::TupleLiteral: {
if (act->Pos() <
if (act->pos() <
static_cast<int>(cast<TupleLiteral>(*exp).Fields().size())) {
// { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
// H}
// -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
// H}
Nonnull<const Expression*> elt =
cast<TupleLiteral>(*exp).Fields()[act->Pos()].expression;
cast<TupleLiteral>(*exp).Fields()[act->pos()].expression;
return Spawn{arena->New<ExpressionAction>(elt)};
} else {
return Done{CreateTuple(act, exp)};
@@ -526,93 +530,93 @@ auto Interpreter::StepExp() -> Transition {
}
case Expression::Kind::StructLiteral: {
const auto& literal = cast<StructLiteral>(*exp);
if (act->Pos() < static_cast<int>(literal.fields().size())) {
if (act->pos() < static_cast<int>(literal.fields().size())) {
Nonnull<const Expression*> elt =
literal.fields()[act->Pos()].expression;
literal.fields()[act->pos()].expression;
return Spawn{arena->New<ExpressionAction>(elt)};
} else {
return Done{CreateStruct(literal.fields(), act->Results())};
return Done{CreateStruct(literal.fields(), act->results())};
}
}
case Expression::Kind::StructTypeLiteral: {
const auto& struct_type = cast<StructTypeLiteral>(*exp);
if (act->Pos() < static_cast<int>(struct_type.fields().size())) {
if (act->pos() < static_cast<int>(struct_type.fields().size())) {
return Spawn{arena->New<ExpressionAction>(
struct_type.fields()[act->Pos()].expression)};
struct_type.fields()[act->pos()].expression)};
} else {
VarValues fields;
for (size_t i = 0; i < struct_type.fields().size(); ++i) {
fields.push_back({struct_type.fields()[i].name, act->Results()[i]});
fields.push_back({struct_type.fields()[i].name, act->results()[i]});
}
return Done{arena->New<StructType>(std::move(fields))};
}
}
case Expression::Kind::FieldAccessExpression: {
const auto& access = cast<FieldAccessExpression>(*exp);
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { { e.f :: C, E, F} :: S, H}
// -> { { e :: [].f :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(access.Aggregate())};
} else {
// { { v :: [].f :: C, E, F} :: S, H}
// -> { { v_f :: C, E, F} : S, H}
return Done{act->Results()[0]->GetField(
arena, FieldPath(access.Field()), exp->SourceLoc())};
return Done{act->results()[0]->GetField(
arena, FieldPath(access.Field()), exp->source_loc())};
}
}
case Expression::Kind::IdentifierExpression: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
const auto& ident = cast<IdentifierExpression>(*exp);
// { {x :: C, E, F} :: S, H} -> { {H(E(x)) :: C, E, F} :: S, H}
Address pointer = GetFromEnv(exp->SourceLoc(), ident.Name());
return Done{heap.Read(pointer, exp->SourceLoc())};
Address pointer = GetFromEnv(exp->source_loc(), ident.Name());
return Done{heap.Read(pointer, exp->source_loc())};
}
case Expression::Kind::IntLiteral:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
return Done{arena->New<IntValue>(cast<IntLiteral>(*exp).Val())};
case Expression::Kind::BoolLiteral:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
return Done{arena->New<BoolValue>(cast<BoolLiteral>(*exp).Val())};
case Expression::Kind::PrimitiveOperatorExpression: {
const auto& op = cast<PrimitiveOperatorExpression>(*exp);
if (act->Pos() != static_cast<int>(op.Arguments().size())) {
if (act->pos() != static_cast<int>(op.Arguments().size())) {
// { {v :: op(vs,[],e,es) :: C, E, F} :: S, H}
// -> { {e :: op(vs,v,[],es) :: C, E, F} :: S, H}
Nonnull<const Expression*> arg = op.Arguments()[act->Pos()];
Nonnull<const Expression*> arg = op.Arguments()[act->pos()];
return Spawn{arena->New<ExpressionAction>(arg)};
} else {
// { {v :: op(vs,[]) :: C, E, F} :: S, H}
// -> { {eval_prim(op, (vs,v)) :: C, E, F} :: S, H}
return Done{EvalPrim(op.Op(), act->Results(), exp->SourceLoc())};
return Done{EvalPrim(op.Op(), act->results(), exp->source_loc())};
}
}
case Expression::Kind::CallExpression:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e1(e2) :: C, E, F} :: S, H}
// -> { {e1 :: [](e2) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<CallExpression>(*exp).Function())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
// { { v :: [](e) :: C, E, F} :: S, H}
// -> { { e :: v([]) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<CallExpression>(*exp).Argument())};
} else if (act->Pos() == 2) {
} else if (act->pos() == 2) {
// { { v2 :: v1([]) :: C, E, F} :: S, H}
// -> { {C',E',F'} :: {C, E, F} :: S, H}
switch (act->Results()[0]->Tag()) {
switch (act->results()[0]->kind()) {
case Value::Kind::NominalClassType: {
Nonnull<const Value*> arg =
CopyVal(arena, act->Results()[1], exp->SourceLoc());
return Done{arena->New<NominalClassValue>(act->Results()[0], arg)};
CopyVal(arena, act->results()[1], exp->source_loc());
return Done{arena->New<NominalClassValue>(act->results()[0], arg)};
}
case Value::Kind::AlternativeConstructorValue: {
const auto& alt =
cast<AlternativeConstructorValue>(*act->Results()[0]);
cast<AlternativeConstructorValue>(*act->results()[0]);
Nonnull<const Value*> arg =
CopyVal(arena, act->Results()[1], exp->SourceLoc());
CopyVal(arena, act->results()[1], exp->source_loc());
return Done{arena->New<AlternativeValue>(alt.AltName(),
alt.ChoiceName(), arg)};
}
@@ -621,46 +625,46 @@ auto Interpreter::StepExp() -> Transition {
// TODO: Think about a cleaner way to cast between Ptr types.
// (multiple TODOs)
.function = Nonnull<const FunctionValue*>(
cast<FunctionValue>(act->Results()[0])),
.args = act->Results()[1],
.loc = exp->SourceLoc()};
cast<FunctionValue>(act->results()[0])),
.args = act->results()[1],
.source_loc = exp->source_loc()};
default:
FATAL_RUNTIME_ERROR(exp->SourceLoc())
<< "in call, expected a function, not " << *act->Results()[0];
FATAL_RUNTIME_ERROR(exp->source_loc())
<< "in call, expected a function, not " << *act->results()[0];
}
} else {
FATAL() << "in handle_value with Call pos " << act->Pos();
FATAL() << "in handle_value with Call pos " << act->pos();
}
case Expression::Kind::IntrinsicExpression:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
switch (cast<IntrinsicExpression>(*exp).Intrinsic()) {
case IntrinsicExpression::IntrinsicKind::Print:
Address pointer = GetFromEnv(exp->SourceLoc(), "format_str");
Nonnull<const Value*> pointee = heap.Read(pointer, exp->SourceLoc());
CHECK(pointee->Tag() == Value::Kind::StringValue);
Address pointer = GetFromEnv(exp->source_loc(), "format_str");
Nonnull<const Value*> pointee = heap.Read(pointer, exp->source_loc());
CHECK(pointee->kind() == Value::Kind::StringValue);
// TODO: This could eventually use something like llvm::formatv.
llvm::outs() << cast<StringValue>(*pointee).Val();
return Done{TupleValue::Empty()};
}
case Expression::Kind::IntTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<IntType>()};
}
case Expression::Kind::BoolTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<BoolType>()};
}
case Expression::Kind::TypeTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<TypeType>()};
}
case Expression::Kind::FunctionTypeLiteral: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<ExpressionAction>(
cast<FunctionTypeLiteral>(*exp).Parameter())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
// { { pt :: fn [] -> e :: C, E, F} :: S, H}
// -> { { e :: fn pt -> []) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
@@ -669,23 +673,23 @@ auto Interpreter::StepExp() -> Transition {
// { { rt :: fn pt -> [] :: C, E, F} :: S, H}
// -> { fn pt -> rt :: {C, E, F} :: S, H}
return Done{arena->New<FunctionType>(std::vector<GenericBinding>(),
act->Results()[0],
act->Results()[1])};
act->results()[0],
act->results()[1])};
}
}
case Expression::Kind::ContinuationTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<ContinuationType>()};
}
case Expression::Kind::StringLiteral:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { {n :: C, E, F} :: S, H} -> { {n' :: C, E, F} :: S, H}
return Done{arena->New<StringValue>(cast<StringLiteral>(*exp).Val())};
case Expression::Kind::StringTypeLiteral: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<StringType>()};
}
} // switch (exp->Tag)
} // switch (exp->kind)
}
auto Interpreter::StepPattern() -> Transition {
@@ -693,52 +697,52 @@ auto Interpreter::StepPattern() -> Transition {
Nonnull<const Pattern*> pattern = cast<PatternAction>(*act).Pat();
if (tracing_output) {
llvm::outs() << "--- step pattern " << *pattern << " ("
<< pattern->SourceLoc() << ") --->\n";
<< pattern->source_loc() << ") --->\n";
}
switch (pattern->Tag()) {
switch (pattern->kind()) {
case Pattern::Kind::AutoPattern: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
return Done{arena->New<AutoType>()};
}
case Pattern::Kind::BindingPattern: {
const auto& binding = cast<BindingPattern>(*pattern);
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<PatternAction>(binding.Type())};
} else {
return Done{arena->New<BindingPlaceholderValue>(binding.Name(),
act->Results()[0])};
act->results()[0])};
}
}
case Pattern::Kind::TuplePattern: {
const auto& tuple = cast<TuplePattern>(*pattern);
if (act->Pos() < static_cast<int>(tuple.Fields().size())) {
if (act->pos() < static_cast<int>(tuple.Fields().size())) {
// { { vk :: (f1=v1,..., fk=[],fk+1=ek+1,...) :: C, E, F} :: S,
// H}
// -> { { ek+1 :: (f1=v1,..., fk=vk, fk+1=[],...) :: C, E, F} :: S,
// H}
Nonnull<const Pattern*> elt = tuple.Fields()[act->Pos()].pattern;
Nonnull<const Pattern*> elt = tuple.Fields()[act->pos()].pattern;
return Spawn{arena->New<PatternAction>(elt)};
} else {
std::vector<TupleElement> elements;
for (size_t i = 0; i < tuple.Fields().size(); ++i) {
elements.push_back(
{.name = tuple.Fields()[i].name, .value = act->Results()[i]});
{.name = tuple.Fields()[i].name, .value = act->results()[i]});
}
return Done{arena->New<TupleValue>(std::move(elements))};
}
}
case Pattern::Kind::AlternativePattern: {
const auto& alternative = cast<AlternativePattern>(*pattern);
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<ExpressionAction>(alternative.ChoiceType())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{arena->New<PatternAction>(alternative.Arguments())};
} else {
CHECK(act->Pos() == 2);
const auto& choice_type = cast<ChoiceType>(*act->Results()[0]);
CHECK(act->pos() == 2);
const auto& choice_type = cast<ChoiceType>(*act->results()[0]);
return Done{arena->New<AlternativeValue>(alternative.AlternativeName(),
choice_type.Name(),
act->Results()[1])};
act->results()[1])};
}
}
case Pattern::Kind::ExpressionPattern:
@@ -748,9 +752,9 @@ auto Interpreter::StepPattern() -> Transition {
}
static auto IsWhileAct(Nonnull<Action*> act) -> bool {
switch (act->Tag()) {
switch (act->kind()) {
case Action::Kind::StatementAction:
switch (cast<StatementAction>(*act).Stmt()->Tag()) {
switch (cast<StatementAction>(*act).Stmt()->kind()) {
case Statement::Kind::While:
return true;
default:
@@ -762,9 +766,9 @@ static auto IsWhileAct(Nonnull<Action*> act) -> bool {
}
static auto HasLocalScope(Nonnull<Action*> act) -> bool {
switch (act->Tag()) {
switch (act->kind()) {
case Action::Kind::StatementAction:
switch (cast<StatementAction>(*act).Stmt()->Tag()) {
switch (cast<StatementAction>(*act).Stmt()->kind()) {
case Statement::Kind::Block:
case Statement::Kind::Match:
return true;
@@ -783,27 +787,27 @@ auto Interpreter::StepStmt() -> Transition {
if (tracing_output) {
llvm::outs() << "--- step stmt ";
stmt->PrintDepth(1, llvm::outs());
llvm::outs() << " (" << stmt->SourceLoc() << ") --->\n";
llvm::outs() << " (" << stmt->source_loc() << ") --->\n";
}
switch (stmt->Tag()) {
switch (stmt->kind()) {
case Statement::Kind::Match: {
const auto& match_stmt = cast<Match>(*stmt);
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { { (match (e) ...) :: C, E, F} :: S, H}
// -> { { e :: (match ([]) ...) :: C, E, F} :: S, H}
frame->scopes.Push(arena->New<Scope>(CurrentEnv()));
return Spawn{arena->New<ExpressionAction>(&match_stmt.expression())};
} else {
// Regarding act->Pos():
// Regarding act->pos():
// * odd: start interpreting the pattern of a clause
// * even: finished interpreting the pattern, now try to match
//
// Regarding act->Results():
// Regarding act->results():
// * 0: the value that we're matching
// * 1: the pattern for clause 0
// * 2: the pattern for clause 1
// * ...
auto clause_num = (act->Pos() - 1) / 2;
auto clause_num = (act->pos() - 1) / 2;
if (clause_num >= static_cast<int>(match_stmt.clauses().size())) {
DeallocateScope(frame->scopes.Top());
frame->scopes.Pop();
@@ -811,18 +815,18 @@ auto Interpreter::StepStmt() -> Transition {
}
auto c = match_stmt.clauses()[clause_num];
if (act->Pos() % 2 == 1) {
if (act->pos() % 2 == 1) {
// start interpreting the pattern of the clause
// { {v :: (match ([]) ...) :: C, E, F} :: S, H}
// -> { {pi :: (match ([]) ...) :: C, E, F} :: S, H}
return Spawn{arena->New<PatternAction>(&c.pattern())};
} else { // try to match
auto v = act->Results()[0];
auto pat = act->Results()[clause_num + 1];
std::optional<Env> matches = PatternMatch(pat, v, stmt->SourceLoc());
auto v = act->results()[0];
auto pat = act->results()[clause_num + 1];
std::optional<Env> matches = PatternMatch(pat, v, stmt->source_loc());
if (matches) { // we have a match, start the body
// Ensure we don't process any more clauses.
act->SetPos(2 * match_stmt.clauses().size() + 1);
act->set_pos(2 * match_stmt.clauses().size() + 1);
for (const auto& [name, value] : *matches) {
frame->scopes.Top()->values.Set(name, value);
@@ -836,12 +840,12 @@ auto Interpreter::StepStmt() -> Transition {
}
}
case Statement::Kind::While:
if (act->Pos() % 2 == 0) {
if (act->pos() % 2 == 0) {
// { { (while (e) s) :: C, E, F} :: S, H}
// -> { { e :: (while ([]) s) :: C, E, F} :: S, H}
act->Clear();
return Spawn{arena->New<ExpressionAction>(cast<While>(*stmt).Cond())};
} else if (cast<BoolValue>(*act->Results().back()).Val()) {
} else if (cast<BoolValue>(*act->results().back()).Val()) {
// { {true :: (while ([]) s) :: C, E, F} :: S, H}
// -> { { s :: (while (e) s) :: C, E, F } :: S, H}
return Spawn{arena->New<StatementAction>(cast<While>(*stmt).Body())};
@@ -851,32 +855,32 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::Break: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { { break; :: ... :: (while (e) s) :: C, E, F} :: S, H}
// -> { { C, E', F} :: S, H}
auto it =
std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
if (it == frame->todo.end()) {
FATAL_RUNTIME_ERROR(stmt->SourceLoc())
FATAL_RUNTIME_ERROR(stmt->source_loc())
<< "`break` not inside `while` statement";
}
++it;
return UnwindTo{*it};
}
case Statement::Kind::Continue: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// { { continue; :: ... :: (while (e) s) :: C, E, F} :: S, H}
// -> { { (while (e) s) :: C, E', F} :: S, H}
auto it =
std::find_if(frame->todo.begin(), frame->todo.end(), &IsWhileAct);
if (it == frame->todo.end()) {
FATAL_RUNTIME_ERROR(stmt->SourceLoc())
FATAL_RUNTIME_ERROR(stmt->source_loc())
<< "`continue` not inside `while` statement";
}
return UnwindTo{*it};
}
case Statement::Kind::Block: {
if (act->Pos() == 0) {
if (act->pos() == 0) {
const Block& block = cast<Block>(*stmt);
if (block.Stmt()) {
frame->scopes.Push(arena->New<Scope>(CurrentEnv()));
@@ -892,23 +896,23 @@ auto Interpreter::StepStmt() -> Transition {
}
}
case Statement::Kind::VariableDefinition:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {(var x = e) :: C, E, F} :: S, H}
// -> { {e :: (var x = []) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
cast<VariableDefinition>(*stmt).Init())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
return Spawn{
arena->New<PatternAction>(cast<VariableDefinition>(*stmt).Pat())};
} else {
// { { v :: (x = []) :: C, E, F} :: S, H}
// -> { { C, E(x := a), F} :: S, H(a := copy(v))}
Nonnull<const Value*> v = act->Results()[0];
Nonnull<const Value*> p = act->Results()[1];
Nonnull<const Value*> v = act->results()[0];
Nonnull<const Value*> p = act->results()[1];
std::optional<Env> matches = PatternMatch(p, v, stmt->SourceLoc());
std::optional<Env> matches = PatternMatch(p, v, stmt->source_loc());
CHECK(matches)
<< stmt->SourceLoc()
<< stmt->source_loc()
<< ": internal error in variable definition, match failed";
for (const auto& [name, value] : *matches) {
frame->scopes.Top()->values.Set(name, value);
@@ -917,7 +921,7 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::ExpressionStatement:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {e :: C, E, F} :: S, H}
// -> { {e :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(
@@ -926,28 +930,28 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::Assign:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {(lv = e) :: C, E, F} :: S, H}
// -> { {lv :: ([] = e) :: C, E, F} :: S, H}
return Spawn{arena->New<LValAction>(cast<Assign>(*stmt).Lhs())};
} else if (act->Pos() == 1) {
} else if (act->pos() == 1) {
// { { a :: ([] = e) :: C, E, F} :: S, H}
// -> { { e :: (a = []) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(cast<Assign>(*stmt).Rhs())};
} else {
// { { v :: (a = []) :: C, E, F} :: S, H}
// -> { { C, E, F} :: S, H(a := v)}
auto pat = act->Results()[0];
auto val = act->Results()[1];
PatternAssignment(pat, val, stmt->SourceLoc());
auto pat = act->results()[0];
auto val = act->results()[1];
PatternAssignment(pat, val, stmt->source_loc());
return Done{};
}
case Statement::Kind::If:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {(if (e) then_stmt else else_stmt) :: C, E, F} :: S, H}
// -> { { e :: (if ([]) then_stmt else else_stmt) :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(cast<If>(*stmt).Cond())};
} else if (cast<BoolValue>(*act->Results()[0]).Val()) {
} else if (cast<BoolValue>(*act->results()[0]).Val()) {
// { {true :: if ([]) then_stmt else else_stmt :: C, E, F} ::
// S, H}
// -> { { then_stmt :: C, E, F } :: S, H}
@@ -963,7 +967,7 @@ auto Interpreter::StepStmt() -> Transition {
return Done{};
}
case Statement::Kind::Return:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// { {return e :: C, E, F} :: S, H}
// -> { {e :: return [] :: C, E, F} :: S, H}
return Spawn{arena->New<ExpressionAction>(cast<Return>(*stmt).Exp())};
@@ -971,14 +975,14 @@ auto Interpreter::StepStmt() -> Transition {
// { {v :: return [] :: C, E, F} :: {C', E', F'} :: S, H}
// -> { {v :: C', E', F'} :: S, H}
Nonnull<const Value*> ret_val =
CopyVal(arena, act->Results()[0], stmt->SourceLoc());
CopyVal(arena, act->results()[0], stmt->source_loc());
return UnwindFunctionCall{ret_val};
}
case Statement::Kind::Sequence: {
// { { (s1,s2) :: C, E, F} :: S, H}
// -> { { s1 :: s2 :: C, E, F} :: S, H}
const Sequence& seq = cast<Sequence>(*stmt);
if (act->Pos() == 0) {
if (act->pos() == 0) {
return Spawn{arena->New<StatementAction>(seq.Stmt())};
} else {
if (seq.Next()) {
@@ -990,13 +994,13 @@ auto Interpreter::StepStmt() -> Transition {
}
}
case Statement::Kind::Continuation: {
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// Create a continuation object by creating a frame similar the
// way one is created in a function call.
auto scopes = Stack<Nonnull<Scope*>>(arena->New<Scope>(CurrentEnv()));
Stack<Nonnull<Action*>> todo;
todo.Push(arena->New<StatementAction>(
arena->New<Return>(arena, stmt->SourceLoc())));
arena->New<Return>(arena, stmt->source_loc())));
todo.Push(arena->New<StatementAction>(cast<Continuation>(*stmt).Body()));
auto continuation_frame =
arena->New<Frame>("__continuation", scopes, todo);
@@ -1014,7 +1018,7 @@ auto Interpreter::StepStmt() -> Transition {
return ManualTransition{};
}
case Statement::Kind::Run:
if (act->Pos() == 0) {
if (act->pos() == 0) {
// Evaluate the argument of the run statement.
return Spawn{arena->New<ExpressionAction>(cast<Run>(*stmt).Argument())};
} else {
@@ -1023,12 +1027,12 @@ auto Interpreter::StepStmt() -> Transition {
// value from the continuation.
auto ignore_result =
arena->New<StatementAction>(arena->New<ExpressionStatement>(
stmt->SourceLoc(),
arena->New<TupleLiteral>(stmt->SourceLoc())));
stmt->source_loc(),
arena->New<TupleLiteral>(stmt->source_loc())));
frame->todo.Push(ignore_result);
// Push the continuation onto the current stack.
const std::vector<Nonnull<Frame*>>& continuation_vector =
cast<ContinuationValue>(*act->Results()[0]).Stack();
cast<ContinuationValue>(*act->results()[0]).Stack();
for (auto frame_iter = continuation_vector.rbegin();
frame_iter != continuation_vector.rend(); ++frame_iter) {
stack.Push(*frame_iter);
@@ -1036,7 +1040,7 @@ auto Interpreter::StepStmt() -> Transition {
return ManualTransition{};
}
case Statement::Kind::Await:
CHECK(act->Pos() == 0);
CHECK(act->pos() == 0);
// Pause the current continuation
frame->todo.Pop();
std::vector<Nonnull<Frame*>> paused;
@@ -1045,7 +1049,7 @@ auto Interpreter::StepStmt() -> Transition {
} while (paused.back()->continuation == std::nullopt);
// Update the continuation with the paused stack.
heap.Write(*paused.back()->continuation,
arena->New<ContinuationValue>(paused), stmt->SourceLoc());
arena->New<ContinuationValue>(paused), stmt->source_loc());
return ManualTransition{};
}
}
@@ -1057,7 +1061,7 @@ class Interpreter::DoTransition {
void operator()(const Done& done) {
Nonnull<Frame*> frame = interpreter->stack.Top();
if (frame->todo.Top()->Tag() != Action::Kind::StatementAction) {
if (frame->todo.Top()->kind() != Action::Kind::StatementAction) {
CHECK(done.result);
frame->todo.Pop();
if (frame->todo.IsEmpty()) {
@@ -1074,7 +1078,7 @@ class Interpreter::DoTransition {
void operator()(const Spawn& spawn) {
Nonnull<Frame*> frame = interpreter->stack.Top();
Nonnull<Action*> action = frame->todo.Top();
action->SetPos(action->Pos() + 1);
action->set_pos(action->pos() + 1);
frame->todo.Push(spawn.child);
}
@@ -1086,7 +1090,7 @@ class Interpreter::DoTransition {
void operator()(const RunAgain&) {
Nonnull<Action*> action = interpreter->stack.Top()->todo.Top();
action->SetPos(action->Pos() + 1);
action->set_pos(action->pos() + 1);
}
void operator()(const UnwindTo& unwind_to) {
@@ -1112,8 +1116,8 @@ class Interpreter::DoTransition {
void operator()(const CallFunction& call) {
interpreter->stack.Top()->todo.Pop();
std::optional<Env> matches =
interpreter->PatternMatch(call.function->Param(), call.args, call.loc);
std::optional<Env> matches = interpreter->PatternMatch(
call.function->Param(), call.args, call.source_loc);
CHECK(matches.has_value())
<< "internal error in call_function, pattern match failed";
// Create the new frame and push it on the stack
@@ -1148,7 +1152,7 @@ void Interpreter::Step() {
}
Nonnull<Action*> act = frame->todo.Top();
switch (act->Tag()) {
switch (act->kind()) {
case Action::Kind::LValAction:
std::visit(DoTransition(this), StepLvalue());
break;
@@ -42,7 +42,7 @@ class Interpreter {
// Attempts to match `v` against the pattern `p`. If matching succeeds,
// returns the bindings of pattern variables to their matched values.
auto PatternMatch(Nonnull<const Value*> p, Nonnull<const Value*> v,
SourceLocation loc) -> std::optional<Env>;
SourceLocation source_loc) -> std::optional<Env>;
// Support TypeChecker allocating values on the heap.
auto AllocateValue(Nonnull<const Value*> v) -> Address {
@@ -102,7 +102,7 @@ class Interpreter {
struct CallFunction {
Nonnull<const FunctionValue*> function;
Nonnull<const Value*> args;
SourceLocation loc;
SourceLocation source_loc;
};
// Transition type which does nothing.
@@ -131,7 +131,8 @@ class Interpreter {
void InitGlobals(const std::vector<Nonnull<const Declaration*>>& fs);
auto CurrentEnv() -> Env;
auto GetFromEnv(SourceLocation loc, const std::string& name) -> Address;
auto GetFromEnv(SourceLocation source_loc, const std::string& name)
-> Address;
void DeallocateScope(Nonnull<Scope*> scope);
void DeallocateLocals(Nonnull<Frame*> frame);
@@ -143,10 +144,10 @@ class Interpreter {
-> Nonnull<const Value*>;
auto EvalPrim(Operator op, const std::vector<Nonnull<const Value*>>& args,
SourceLocation loc) -> Nonnull<const Value*>;
SourceLocation source_loc) -> Nonnull<const Value*>;
void PatternAssignment(Nonnull<const Value*> pat, Nonnull<const Value*> val,
SourceLocation loc);
SourceLocation source_loc);
void PrintState(llvm::raw_ostream& out);
+165 -158
View File
@@ -40,72 +40,75 @@ void PrintTypeEnv(TypeEnv types, llvm::raw_ostream& out) {
}
}
static void ExpectType(SourceLocation loc, const std::string& context,
static void ExpectType(SourceLocation source_loc, const std::string& context,
Nonnull<const Value*> expected,
Nonnull<const Value*> actual) {
if (!TypeEqual(expected, actual)) {
FATAL_COMPILATION_ERROR(loc) << "type error in " << context << "\n"
<< "expected: " << *expected << "\n"
<< "actual: " << *actual;
FATAL_COMPILATION_ERROR(source_loc) << "type error in " << context << "\n"
<< "expected: " << *expected << "\n"
<< "actual: " << *actual;
}
}
static void ExpectPointerType(SourceLocation loc, const std::string& context,
static void ExpectPointerType(SourceLocation source_loc,
const std::string& context,
Nonnull<const Value*> actual) {
if (actual->Tag() != Value::Kind::PointerType) {
FATAL_COMPILATION_ERROR(loc) << "type error in " << context << "\n"
<< "expected a pointer type\n"
<< "actual: " << *actual;
if (actual->kind() != Value::Kind::PointerType) {
FATAL_COMPILATION_ERROR(source_loc) << "type error in " << context << "\n"
<< "expected a pointer type\n"
<< "actual: " << *actual;
}
}
auto TypeChecker::ReifyType(Nonnull<const Value*> t, SourceLocation loc)
auto TypeChecker::ReifyType(Nonnull<const Value*> t, SourceLocation source_loc)
-> Nonnull<Expression*> {
switch (t->Tag()) {
switch (t->kind()) {
case Value::Kind::IntType:
return arena->New<IntTypeLiteral>(loc);
return arena->New<IntTypeLiteral>(source_loc);
case Value::Kind::BoolType:
return arena->New<BoolTypeLiteral>(loc);
return arena->New<BoolTypeLiteral>(source_loc);
case Value::Kind::TypeType:
return arena->New<TypeTypeLiteral>(loc);
return arena->New<TypeTypeLiteral>(source_loc);
case Value::Kind::ContinuationType:
return arena->New<ContinuationTypeLiteral>(loc);
return arena->New<ContinuationTypeLiteral>(source_loc);
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*t);
return arena->New<FunctionTypeLiteral>(
loc, ReifyType(fn_type.Param(), loc), ReifyType(fn_type.Ret(), loc),
source_loc, ReifyType(fn_type.Param(), source_loc),
ReifyType(fn_type.Ret(), source_loc),
/*is_omitted_return_type=*/false);
}
case Value::Kind::TupleValue: {
std::vector<FieldInitializer> args;
for (const TupleElement& field : cast<TupleValue>(*t).Elements()) {
args.push_back(
FieldInitializer(field.name, ReifyType(field.value, loc)));
FieldInitializer(field.name, ReifyType(field.value, source_loc)));
}
return arena->New<TupleLiteral>(loc, args);
return arena->New<TupleLiteral>(source_loc, args);
}
case Value::Kind::StructType: {
std::vector<FieldInitializer> args;
for (const auto& [name, type] : cast<StructType>(*t).fields()) {
args.push_back(FieldInitializer(name, ReifyType(type, loc)));
args.push_back(FieldInitializer(name, ReifyType(type, source_loc)));
}
return arena->New<StructTypeLiteral>(loc, args);
return arena->New<StructTypeLiteral>(source_loc, args);
}
case Value::Kind::NominalClassType:
return arena->New<IdentifierExpression>(
loc, cast<NominalClassType>(*t).Name());
source_loc, cast<NominalClassType>(*t).Name());
case Value::Kind::ChoiceType:
return arena->New<IdentifierExpression>(loc, cast<ChoiceType>(*t).Name());
return arena->New<IdentifierExpression>(source_loc,
cast<ChoiceType>(*t).Name());
case Value::Kind::PointerType:
return arena->New<PrimitiveOperatorExpression>(
loc, Operator::Ptr,
source_loc, Operator::Ptr,
std::vector<Nonnull<Expression*>>(
{ReifyType(cast<PointerType>(*t).Type(), loc)}));
{ReifyType(cast<PointerType>(*t).Type(), source_loc)}));
case Value::Kind::VariableType:
return arena->New<IdentifierExpression>(loc,
return arena->New<IdentifierExpression>(source_loc,
cast<VariableType>(*t).Name());
case Value::Kind::StringType:
return arena->New<StringTypeLiteral>(loc);
return arena->New<StringTypeLiteral>(source_loc);
case Value::Kind::AlternativeConstructorValue:
case Value::Kind::AlternativeValue:
case Value::Kind::AutoType:
@@ -128,78 +131,81 @@ auto TypeChecker::ReifyType(Nonnull<const Value*> t, SourceLocation loc)
// inside the argument type.
// The `deduced` parameter is an accumulator, that is, it holds the
// results so-far.
static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
static auto ArgumentDeduction(SourceLocation source_loc, TypeEnv deduced,
Nonnull<const Value*> param,
Nonnull<const Value*> arg) -> TypeEnv {
switch (param->Tag()) {
switch (param->kind()) {
case Value::Kind::VariableType: {
const auto& var_type = cast<VariableType>(*param);
std::optional<Nonnull<const Value*>> d = deduced.Get(var_type.Name());
if (!d) {
deduced.Set(var_type.Name(), arg);
} else {
ExpectType(loc, "argument deduction", *d, arg);
ExpectType(source_loc, "argument deduction", *d, arg);
}
return deduced;
}
case Value::Kind::TupleValue: {
if (arg->Tag() != Value::Kind::TupleValue) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::TupleValue) {
ExpectType(source_loc, "argument deduction", param, arg);
}
const auto& param_tup = cast<TupleValue>(*param);
const auto& arg_tup = cast<TupleValue>(*arg);
if (param_tup.Elements().size() != arg_tup.Elements().size()) {
ExpectType(loc, "argument deduction", param, arg);
ExpectType(source_loc, "argument deduction", param, arg);
}
for (size_t i = 0; i < param_tup.Elements().size(); ++i) {
if (param_tup.Elements()[i].name != arg_tup.Elements()[i].name) {
FATAL_COMPILATION_ERROR(loc)
FATAL_COMPILATION_ERROR(source_loc)
<< "mismatch in tuple names, " << param_tup.Elements()[i].name
<< " != " << arg_tup.Elements()[i].name;
}
deduced = ArgumentDeduction(loc, deduced, param_tup.Elements()[i].value,
deduced = ArgumentDeduction(source_loc, deduced,
param_tup.Elements()[i].value,
arg_tup.Elements()[i].value);
}
return deduced;
}
case Value::Kind::StructType: {
if (arg->Tag() != Value::Kind::StructType) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::StructType) {
ExpectType(source_loc, "argument deduction", param, arg);
}
const auto& param_struct = cast<StructType>(*param);
const auto& arg_struct = cast<StructType>(*arg);
if (param_struct.fields().size() != arg_struct.fields().size()) {
ExpectType(loc, "argument deduction", param, arg);
ExpectType(source_loc, "argument deduction", param, arg);
}
for (size_t i = 0; i < param_struct.fields().size(); ++i) {
if (param_struct.fields()[i].first != arg_struct.fields()[i].first) {
FATAL_COMPILATION_ERROR(loc)
FATAL_COMPILATION_ERROR(source_loc)
<< "mismatch in field names, " << param_struct.fields()[i].first
<< " != " << arg_struct.fields()[i].first;
}
deduced =
ArgumentDeduction(loc, deduced, param_struct.fields()[i].second,
arg_struct.fields()[i].second);
deduced = ArgumentDeduction(source_loc, deduced,
param_struct.fields()[i].second,
arg_struct.fields()[i].second);
}
return deduced;
}
case Value::Kind::FunctionType: {
if (arg->Tag() != Value::Kind::FunctionType) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::FunctionType) {
ExpectType(source_loc, "argument deduction", param, arg);
}
const auto& param_fn = cast<FunctionType>(*param);
const auto& arg_fn = cast<FunctionType>(*arg);
// TODO: handle situation when arg has deduced parameters.
deduced = ArgumentDeduction(source_loc, deduced, param_fn.Param(),
arg_fn.Param());
deduced =
ArgumentDeduction(loc, deduced, param_fn.Param(), arg_fn.Param());
deduced = ArgumentDeduction(loc, deduced, param_fn.Ret(), arg_fn.Ret());
ArgumentDeduction(source_loc, deduced, param_fn.Ret(), arg_fn.Ret());
return deduced;
}
case Value::Kind::PointerType: {
if (arg->Tag() != Value::Kind::PointerType) {
ExpectType(loc, "argument deduction", param, arg);
if (arg->kind() != Value::Kind::PointerType) {
ExpectType(source_loc, "argument deduction", param, arg);
}
return ArgumentDeduction(loc, deduced, cast<PointerType>(*param).Type(),
return ArgumentDeduction(source_loc, deduced,
cast<PointerType>(*param).Type(),
cast<PointerType>(*arg).Type());
}
// Nothing to do in the case for `auto`.
@@ -214,7 +220,7 @@ static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
case Value::Kind::BoolType:
case Value::Kind::TypeType:
case Value::Kind::StringType:
ExpectType(loc, "argument deduction", param, arg);
ExpectType(source_loc, "argument deduction", param, arg);
return deduced;
// The rest of these cases should never happen.
case Value::Kind::IntValue:
@@ -234,7 +240,7 @@ static auto ArgumentDeduction(SourceLocation loc, TypeEnv deduced,
auto TypeChecker::Substitute(TypeEnv dict, Nonnull<const Value*> type)
-> Nonnull<const Value*> {
switch (type->Tag()) {
switch (type->kind()) {
case Value::Kind::VariableType: {
std::optional<Nonnull<const Value*>> t =
dict.Get(cast<VariableType>(*type).Name());
@@ -305,12 +311,12 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
interpreter.PrintEnv(values, llvm::outs());
llvm::outs() << "\n";
}
switch (e->Tag()) {
switch (e->kind()) {
case Expression::Kind::IndexExpression: {
auto& index = cast<IndexExpression>(*e);
auto res = TypeCheckExp(index.Aggregate(), types, values);
auto t = res.type;
switch (t->Tag()) {
switch (t->kind()) {
case Value::Kind::TupleValue: {
auto i =
cast<IntValue>(*interpreter.InterpExp(values, index.Offset()))
@@ -319,16 +325,16 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
std::optional<Nonnull<const Value*>> field_t =
cast<TupleValue>(*t).FindField(f);
if (!field_t) {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "field " << f << " is not in the tuple " << *t;
}
auto new_e = arena->New<IndexExpression>(
e->SourceLoc(), res.exp,
arena->New<IntLiteral>(e->SourceLoc(), i));
e->source_loc(), res.exp,
arena->New<IntLiteral>(e->source_loc(), i));
return TCExpression(new_e, *field_t, res.types);
}
default:
FATAL_COMPILATION_ERROR(e->SourceLoc()) << "expected a tuple";
FATAL_COMPILATION_ERROR(e->source_loc()) << "expected a tuple";
}
}
case Expression::Kind::TupleLiteral: {
@@ -341,7 +347,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
new_args.push_back(FieldInitializer(arg.name, arg_res.exp));
arg_types.push_back({.name = arg.name, .value = arg_res.type});
}
auto tuple_e = arena->New<TupleLiteral>(e->SourceLoc(), new_args);
auto tuple_e = arena->New<TupleLiteral>(e->source_loc(), new_args);
auto tuple_t = arena->New<TupleValue>(std::move(arg_types));
return TCExpression(tuple_e, tuple_t, new_types);
}
@@ -355,7 +361,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
new_args.push_back(FieldInitializer(arg.name, arg_res.exp));
arg_types.push_back({arg.name, arg_res.type});
}
auto new_e = arena->New<StructLiteral>(e->SourceLoc(), new_args);
auto new_e = arena->New<StructLiteral>(e->source_loc(), new_args);
auto type = arena->New<StructType>(std::move(arg_types));
return TCExpression(new_e, type, new_types);
}
@@ -368,9 +374,9 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
new_types = arg_res.types;
Nonnull<const Value*> type = interpreter.InterpExp(values, arg_res.exp);
new_args.push_back(
FieldInitializer(arg.name, ReifyType(type, e->SourceLoc())));
FieldInitializer(arg.name, ReifyType(type, e->source_loc())));
}
auto new_e = arena->New<StructTypeLiteral>(e->SourceLoc(), new_args);
auto new_e = arena->New<StructTypeLiteral>(e->source_loc(), new_args);
Nonnull<const Value*> type;
if (struct_type.fields().empty()) {
// `{}` is the type of `{}`, just as `()` is the type of `()`.
@@ -387,17 +393,17 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
auto& access = cast<FieldAccessExpression>(*e);
auto res = TypeCheckExp(access.Aggregate(), types, values);
auto t = res.type;
switch (t->Tag()) {
switch (t->kind()) {
case Value::Kind::StructType: {
const auto& struct_type = cast<StructType>(*t);
for (const auto& [field_name, field_type] : struct_type.fields()) {
if (access.Field() == field_name) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
access.SourceLoc(), res.exp, access.Field());
access.source_loc(), res.exp, access.Field());
return TCExpression(new_e, field_type, res.types);
}
}
FATAL_COMPILATION_ERROR(access.SourceLoc())
FATAL_COMPILATION_ERROR(access.source_loc())
<< "struct " << struct_type << " does not have a field named "
<< access.Field();
}
@@ -407,7 +413,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (auto& field : t_class.Fields()) {
if (access.Field() == field.first) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
return TCExpression(new_e, field.second, res.types);
}
}
@@ -415,11 +421,11 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (auto& method : t_class.Methods()) {
if (access.Field() == method.first) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
return TCExpression(new_e, method.second, res.types);
}
}
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "class " << t_class.Name() << " does not have a field named "
<< access.Field();
}
@@ -428,11 +434,11 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (const TupleElement& field : tup.Elements()) {
if (access.Field() == field.name) {
auto new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
return TCExpression(new_e, field.value, res.types);
}
}
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "tuple " << tup << " does not have a field named "
<< access.Field();
}
@@ -441,18 +447,18 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
for (const auto& vt : choice.Alternatives()) {
if (access.Field() == vt.first) {
Nonnull<Expression*> new_e = arena->New<FieldAccessExpression>(
e->SourceLoc(), res.exp, access.Field());
e->source_loc(), res.exp, access.Field());
auto fun_ty = arena->New<FunctionType>(
std::vector<GenericBinding>(), vt.second, t);
return TCExpression(new_e, fun_ty, res.types);
}
}
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "choice " << choice.Name() << " does not have a field named "
<< access.Field();
}
default:
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "field access, expected a struct\n"
<< *e;
}
@@ -463,7 +469,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
if (type) {
return TCExpression(e, *type, types);
} else {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "could not find `" << ident.Name() << "`";
}
}
@@ -483,49 +489,49 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
ts.push_back(res.type);
}
auto new_e =
arena->New<PrimitiveOperatorExpression>(e->SourceLoc(), op.Op(), es);
arena->New<PrimitiveOperatorExpression>(e->source_loc(), op.Op(), es);
switch (op.Op()) {
case Operator::Neg:
ExpectType(e->SourceLoc(), "negation", arena->New<IntType>(), ts[0]);
ExpectType(e->source_loc(), "negation", arena->New<IntType>(), ts[0]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::Add:
ExpectType(e->SourceLoc(), "addition(1)", arena->New<IntType>(),
ExpectType(e->source_loc(), "addition(1)", arena->New<IntType>(),
ts[0]);
ExpectType(e->SourceLoc(), "addition(2)", arena->New<IntType>(),
ExpectType(e->source_loc(), "addition(2)", arena->New<IntType>(),
ts[1]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::Sub:
ExpectType(e->SourceLoc(), "subtraction(1)", arena->New<IntType>(),
ExpectType(e->source_loc(), "subtraction(1)", arena->New<IntType>(),
ts[0]);
ExpectType(e->SourceLoc(), "subtraction(2)", arena->New<IntType>(),
ExpectType(e->source_loc(), "subtraction(2)", arena->New<IntType>(),
ts[1]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::Mul:
ExpectType(e->SourceLoc(), "multiplication(1)", arena->New<IntType>(),
ts[0]);
ExpectType(e->SourceLoc(), "multiplication(2)", arena->New<IntType>(),
ts[1]);
ExpectType(e->source_loc(), "multiplication(1)",
arena->New<IntType>(), ts[0]);
ExpectType(e->source_loc(), "multiplication(2)",
arena->New<IntType>(), ts[1]);
return TCExpression(new_e, arena->New<IntType>(), new_types);
case Operator::And:
ExpectType(e->SourceLoc(), "&&(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->SourceLoc(), "&&(2)", arena->New<BoolType>(), ts[1]);
ExpectType(e->source_loc(), "&&(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->source_loc(), "&&(2)", arena->New<BoolType>(), ts[1]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Or:
ExpectType(e->SourceLoc(), "||(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->SourceLoc(), "||(2)", arena->New<BoolType>(), ts[1]);
ExpectType(e->source_loc(), "||(1)", arena->New<BoolType>(), ts[0]);
ExpectType(e->source_loc(), "||(2)", arena->New<BoolType>(), ts[1]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Not:
ExpectType(e->SourceLoc(), "!", arena->New<BoolType>(), ts[0]);
ExpectType(e->source_loc(), "!", arena->New<BoolType>(), ts[0]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Eq:
ExpectType(e->SourceLoc(), "==", ts[0], ts[1]);
ExpectType(e->source_loc(), "==", ts[0], ts[1]);
return TCExpression(new_e, arena->New<BoolType>(), new_types);
case Operator::Deref:
ExpectPointerType(e->SourceLoc(), "*", ts[0]);
ExpectPointerType(e->source_loc(), "*", ts[0]);
return TCExpression(new_e, cast<PointerType>(*ts[0]).Type(),
new_types);
case Operator::Ptr:
ExpectType(e->SourceLoc(), "*", arena->New<TypeType>(), ts[0]);
ExpectType(e->source_loc(), "*", arena->New<TypeType>(), ts[0]);
return TCExpression(new_e, arena->New<TypeType>(), new_types);
}
break;
@@ -533,7 +539,7 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
case Expression::Kind::CallExpression: {
auto& call = cast<CallExpression>(*e);
auto fun_res = TypeCheckExp(call.Function(), types, values);
switch (fun_res.type->Tag()) {
switch (fun_res.type->kind()) {
case Value::Kind::FunctionType: {
const auto& fun_t = cast<FunctionType>(*fun_res.type);
auto arg_res = TypeCheckExp(call.Argument(), fun_res.types, values);
@@ -541,12 +547,12 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
auto return_type = fun_t.Ret();
if (!fun_t.Deduced().empty()) {
auto deduced_args = ArgumentDeduction(
e->SourceLoc(), TypeEnv(arena), parameter_type, arg_res.type);
e->source_loc(), TypeEnv(arena), parameter_type, arg_res.type);
for (auto& deduced_param : fun_t.Deduced()) {
// TODO: change the following to a CHECK once the real checking
// has been added to the type checking of function signatures.
if (!deduced_args.Get(deduced_param.name)) {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "could not deduce type argument for type parameter "
<< deduced_param.name;
}
@@ -554,14 +560,14 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
parameter_type = Substitute(deduced_args, parameter_type);
return_type = Substitute(deduced_args, return_type);
} else {
ExpectType(e->SourceLoc(), "call", parameter_type, arg_res.type);
ExpectType(e->source_loc(), "call", parameter_type, arg_res.type);
}
auto new_e = arena->New<CallExpression>(e->SourceLoc(), fun_res.exp,
auto new_e = arena->New<CallExpression>(e->source_loc(), fun_res.exp,
arg_res.exp);
return TCExpression(new_e, return_type, arg_res.types);
}
default: {
FATAL_COMPILATION_ERROR(e->SourceLoc())
FATAL_COMPILATION_ERROR(e->source_loc())
<< "in call, expected a function\n"
<< *e;
}
@@ -573,8 +579,8 @@ auto TypeChecker::TypeCheckExp(Nonnull<Expression*> e, TypeEnv types,
auto pt = interpreter.InterpExp(values, fn.Parameter());
auto rt = interpreter.InterpExp(values, fn.ReturnType());
auto new_e = arena->New<FunctionTypeLiteral>(
e->SourceLoc(), ReifyType(pt, e->SourceLoc()),
ReifyType(rt, e->SourceLoc()),
e->source_loc(), ReifyType(pt, e->source_loc()),
ReifyType(rt, e->source_loc()),
/*is_omitted_return_type=*/false);
return TCExpression(new_e, arena->New<TypeType>(), types);
}
@@ -608,7 +614,7 @@ auto TypeChecker::TypeCheckPattern(
interpreter.PrintEnv(values, llvm::outs());
llvm::outs() << "\n";
}
switch (p->Tag()) {
switch (p->kind()) {
case Pattern::Kind::AutoPattern: {
return {.pattern = p, .type = arena->New<TypeType>(), .types = types};
}
@@ -620,9 +626,9 @@ auto TypeChecker::TypeCheckPattern(
interpreter.InterpPattern(values, binding_type_result.pattern);
if (expected) {
std::optional<Env> values = interpreter.PatternMatch(
type, *expected, binding.Type()->SourceLoc());
type, *expected, binding.Type()->source_loc());
if (values == std::nullopt) {
FATAL_COMPILATION_ERROR(binding.Type()->SourceLoc())
FATAL_COMPILATION_ERROR(binding.Type()->source_loc())
<< "Type pattern '" << *type << "' does not match actual type '"
<< **expected << "'";
}
@@ -631,8 +637,8 @@ auto TypeChecker::TypeCheckPattern(
type = *expected;
}
auto new_p = arena->New<BindingPattern>(
binding.SourceLoc(), binding.Name(),
arena->New<ExpressionPattern>(ReifyType(type, binding.SourceLoc())));
binding.source_loc(), binding.Name(),
arena->New<ExpressionPattern>(ReifyType(type, binding.source_loc())));
if (binding.Name().has_value()) {
types.Set(*binding.Name(), type);
}
@@ -643,12 +649,12 @@ auto TypeChecker::TypeCheckPattern(
std::vector<TuplePattern::Field> new_fields;
std::vector<TupleElement> field_types;
auto new_types = types;
if (expected && (*expected)->Tag() != Value::Kind::TupleValue) {
FATAL_COMPILATION_ERROR(p->SourceLoc()) << "didn't expect a tuple";
if (expected && (*expected)->kind() != Value::Kind::TupleValue) {
FATAL_COMPILATION_ERROR(p->source_loc()) << "didn't expect a tuple";
}
if (expected && tuple.Fields().size() !=
cast<TupleValue>(**expected).Elements().size()) {
FATAL_COMPILATION_ERROR(tuple.SourceLoc())
FATAL_COMPILATION_ERROR(tuple.source_loc())
<< "tuples of different length";
}
for (size_t i = 0; i < tuple.Fields().size(); ++i) {
@@ -658,7 +664,7 @@ auto TypeChecker::TypeCheckPattern(
const TupleElement& expected_element =
cast<TupleValue>(**expected).Elements()[i];
if (expected_element.name != field.name) {
FATAL_COMPILATION_ERROR(tuple.SourceLoc())
FATAL_COMPILATION_ERROR(tuple.source_loc())
<< "field names do not match, expected "
<< expected_element.name << " but got " << field.name;
}
@@ -671,7 +677,7 @@ auto TypeChecker::TypeCheckPattern(
TuplePattern::Field(field.name, field_result.pattern));
field_types.push_back({.name = field.name, .value = field_result.type});
}
auto new_tuple = arena->New<TuplePattern>(tuple.SourceLoc(), new_fields);
auto new_tuple = arena->New<TuplePattern>(tuple.source_loc(), new_fields);
auto tuple_t = arena->New<TupleValue>(std::move(field_types));
return {.pattern = new_tuple, .type = tuple_t, .types = new_types};
}
@@ -679,19 +685,19 @@ auto TypeChecker::TypeCheckPattern(
auto& alternative = cast<AlternativePattern>(*p);
Nonnull<const Value*> choice_type =
interpreter.InterpExp(values, alternative.ChoiceType());
if (choice_type->Tag() != Value::Kind::ChoiceType) {
FATAL_COMPILATION_ERROR(alternative.SourceLoc())
if (choice_type->kind() != Value::Kind::ChoiceType) {
FATAL_COMPILATION_ERROR(alternative.source_loc())
<< "alternative pattern does not name a choice type.";
}
if (expected) {
ExpectType(alternative.SourceLoc(), "alternative pattern", *expected,
ExpectType(alternative.source_loc(), "alternative pattern", *expected,
choice_type);
}
std::optional<Nonnull<const Value*>> parameter_types =
FindInVarValues(alternative.AlternativeName(),
cast<ChoiceType>(*choice_type).Alternatives());
if (parameter_types == std::nullopt) {
FATAL_COMPILATION_ERROR(alternative.SourceLoc())
FATAL_COMPILATION_ERROR(alternative.source_loc())
<< "'" << alternative.AlternativeName()
<< "' is not an alternative of " << *choice_type;
}
@@ -702,8 +708,8 @@ auto TypeChecker::TypeCheckPattern(
auto arguments =
Nonnull<TuplePattern*>(cast<const TuplePattern>(arg_results.pattern));
return {.pattern = arena->New<AlternativePattern>(
alternative.SourceLoc(),
ReifyType(choice_type, alternative.SourceLoc()),
alternative.source_loc(),
ReifyType(choice_type, alternative.source_loc()),
alternative.AlternativeName(), arguments),
.type = choice_type,
.types = arg_results.types};
@@ -732,7 +738,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
Env values,
Nonnull<ReturnTypeContext*> return_type_context)
-> TCStatement {
switch (s->Tag()) {
switch (s->kind()) {
case Statement::Kind::Match: {
auto& match = cast<Match>(*s);
auto res = TypeCheckExp(&match.expression(), types, values);
@@ -743,18 +749,18 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
&clause.statement(), types, values,
return_type_context));
}
auto new_s = arena->New<Match>(s->SourceLoc(), res.exp, new_clauses);
auto new_s = arena->New<Match>(s->source_loc(), res.exp, new_clauses);
return TCStatement(new_s, types);
}
case Statement::Kind::While: {
auto& while_stmt = cast<While>(*s);
auto cnd_res = TypeCheckExp(while_stmt.Cond(), types, values);
ExpectType(s->SourceLoc(), "condition of `while`", arena->New<BoolType>(),
cnd_res.type);
ExpectType(s->source_loc(), "condition of `while`",
arena->New<BoolType>(), cnd_res.type);
auto body_res =
TypeCheckStmt(while_stmt.Body(), types, values, return_type_context);
auto new_s =
arena->New<While>(s->SourceLoc(), cnd_res.exp, body_res.stmt);
arena->New<While>(s->source_loc(), cnd_res.exp, body_res.stmt);
return TCStatement(new_s, types);
}
case Statement::Kind::Break:
@@ -765,7 +771,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
if (block.Stmt()) {
auto stmt_res =
TypeCheckStmt(*block.Stmt(), types, values, return_type_context);
return TCStatement(arena->New<Block>(s->SourceLoc(), stmt_res.stmt),
return TCStatement(arena->New<Block>(s->source_loc(), stmt_res.stmt),
types);
} else {
return TCStatement(s, types);
@@ -777,7 +783,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
Nonnull<const Value*> rhs_ty = res.type;
auto lhs_res = TypeCheckPattern(var.Pat(), types, values, rhs_ty);
auto new_s =
arena->New<VariableDefinition>(s->SourceLoc(), var.Pat(), res.exp);
arena->New<VariableDefinition>(s->source_loc(), var.Pat(), res.exp);
return TCStatement(new_s, lhs_res.types);
}
case Statement::Kind::Sequence: {
@@ -793,7 +799,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
checked_types = next_res.types;
}
return TCStatement(
arena->New<Sequence>(s->SourceLoc(), stmt_res.stmt, next_stmt),
arena->New<Sequence>(s->source_loc(), stmt_res.stmt, next_stmt),
checked_types);
}
case Statement::Kind::Assign: {
@@ -802,20 +808,21 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
auto rhs_t = rhs_res.type;
auto lhs_res = TypeCheckExp(assign.Lhs(), types, values);
auto lhs_t = lhs_res.type;
ExpectType(s->SourceLoc(), "assign", lhs_t, rhs_t);
auto new_s = arena->New<Assign>(s->SourceLoc(), lhs_res.exp, rhs_res.exp);
ExpectType(s->source_loc(), "assign", lhs_t, rhs_t);
auto new_s =
arena->New<Assign>(s->source_loc(), lhs_res.exp, rhs_res.exp);
return TCStatement(new_s, lhs_res.types);
}
case Statement::Kind::ExpressionStatement: {
auto res =
TypeCheckExp(cast<ExpressionStatement>(*s).Exp(), types, values);
auto new_s = arena->New<ExpressionStatement>(s->SourceLoc(), res.exp);
auto new_s = arena->New<ExpressionStatement>(s->source_loc(), res.exp);
return TCStatement(new_s, types);
}
case Statement::Kind::If: {
auto& if_stmt = cast<If>(*s);
auto cnd_res = TypeCheckExp(if_stmt.Cond(), types, values);
ExpectType(s->SourceLoc(), "condition of `if`", arena->New<BoolType>(),
ExpectType(s->source_loc(), "condition of `if`", arena->New<BoolType>(),
cnd_res.type);
auto then_res =
TypeCheckStmt(if_stmt.ThenStmt(), types, values, return_type_context);
@@ -825,8 +832,8 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
return_type_context);
else_stmt = else_res.stmt;
}
auto new_s =
arena->New<If>(s->SourceLoc(), cnd_res.exp, then_res.stmt, else_stmt);
auto new_s = arena->New<If>(s->source_loc(), cnd_res.exp, then_res.stmt,
else_stmt);
return TCStatement(new_s, types);
}
case Statement::Kind::Return: {
@@ -835,7 +842,7 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
if (return_type_context->is_auto()) {
if (return_type_context->deduced_return_type()) {
// Only one return is allowed when the return type is `auto`.
FATAL_COMPILATION_ERROR(s->SourceLoc())
FATAL_COMPILATION_ERROR(s->source_loc())
<< "Only one return is allowed in a function with an `auto` "
"return type.";
} else {
@@ -843,17 +850,17 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
return_type_context->set_deduced_return_type(res.type);
}
} else {
ExpectType(s->SourceLoc(), "return",
ExpectType(s->source_loc(), "return",
*return_type_context->deduced_return_type(), res.type);
}
if (ret.IsOmittedExp() != return_type_context->is_omitted()) {
FATAL_COMPILATION_ERROR(s->SourceLoc())
FATAL_COMPILATION_ERROR(s->source_loc())
<< *s << " should"
<< (return_type_context->is_omitted() ? " not" : "")
<< " provide a return value, to match the function's signature.";
}
return TCStatement(
arena->New<Return>(s->SourceLoc(), res.exp, ret.IsOmittedExp()),
arena->New<Return>(s->source_loc(), res.exp, ret.IsOmittedExp()),
types);
}
case Statement::Kind::Continuation: {
@@ -861,16 +868,16 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
TCStatement body_result =
TypeCheckStmt(cont.Body(), types, values, return_type_context);
auto new_continuation = arena->New<Continuation>(
s->SourceLoc(), cont.ContinuationVariable(), body_result.stmt);
s->source_loc(), cont.ContinuationVariable(), body_result.stmt);
types.Set(cont.ContinuationVariable(), arena->New<ContinuationType>());
return TCStatement(new_continuation, types);
}
case Statement::Kind::Run: {
TCExpression argument_result =
TypeCheckExp(cast<Run>(*s).Argument(), types, values);
ExpectType(s->SourceLoc(), "argument of `run`",
ExpectType(s->source_loc(), "argument of `run`",
arena->New<ContinuationType>(), argument_result.type);
auto new_run = arena->New<Run>(s->SourceLoc(), argument_result.exp);
auto new_run = arena->New<Run>(s->source_loc(), argument_result.exp);
return TCStatement(new_run, types);
}
case Statement::Kind::Await: {
@@ -882,42 +889,42 @@ auto TypeChecker::TypeCheckStmt(Nonnull<Statement*> s, TypeEnv types,
auto TypeChecker::CheckOrEnsureReturn(
std::optional<Nonnull<Statement*>> opt_stmt, bool omitted_ret_type,
SourceLocation loc) -> Nonnull<Statement*> {
SourceLocation source_loc) -> Nonnull<Statement*> {
if (!opt_stmt) {
if (omitted_ret_type) {
return arena->New<Return>(arena, loc);
return arena->New<Return>(arena, source_loc);
} else {
FATAL_COMPILATION_ERROR(loc)
FATAL_COMPILATION_ERROR(source_loc)
<< "control-flow reaches end of function that provides a `->` return "
"type without reaching a return statement";
}
}
Nonnull<Statement*> stmt = *opt_stmt;
switch (stmt->Tag()) {
switch (stmt->kind()) {
case Statement::Kind::Match: {
auto& match = cast<Match>(*stmt);
std::vector<Match::Clause> new_clauses;
for (auto& clause : match.clauses()) {
auto s = CheckOrEnsureReturn(&clause.statement(), omitted_ret_type,
stmt->SourceLoc());
stmt->source_loc());
new_clauses.push_back(Match::Clause(&clause.pattern(), s));
}
return arena->New<Match>(stmt->SourceLoc(), &match.expression(),
return arena->New<Match>(stmt->source_loc(), &match.expression(),
new_clauses);
}
case Statement::Kind::Block:
return arena->New<Block>(
stmt->SourceLoc(),
stmt->source_loc(),
CheckOrEnsureReturn(cast<Block>(*stmt).Stmt(), omitted_ret_type,
stmt->SourceLoc()));
stmt->source_loc()));
case Statement::Kind::If: {
auto& if_stmt = cast<If>(*stmt);
return arena->New<If>(
stmt->SourceLoc(), if_stmt.Cond(),
stmt->source_loc(), if_stmt.Cond(),
CheckOrEnsureReturn(if_stmt.ThenStmt(), omitted_ret_type,
stmt->SourceLoc()),
stmt->source_loc()),
CheckOrEnsureReturn(if_stmt.ElseStmt(), omitted_ret_type,
stmt->SourceLoc()));
stmt->source_loc()));
}
case Statement::Kind::Return:
return stmt;
@@ -925,12 +932,12 @@ auto TypeChecker::CheckOrEnsureReturn(
auto& seq = cast<Sequence>(*stmt);
if (seq.Next()) {
return arena->New<Sequence>(
stmt->SourceLoc(), seq.Stmt(),
stmt->source_loc(), seq.Stmt(),
CheckOrEnsureReturn(seq.Next(), omitted_ret_type,
stmt->SourceLoc()));
stmt->source_loc()));
} else {
return CheckOrEnsureReturn(seq.Stmt(), omitted_ret_type,
stmt->SourceLoc());
stmt->source_loc());
}
}
case Statement::Kind::Continuation:
@@ -944,10 +951,10 @@ auto TypeChecker::CheckOrEnsureReturn(
case Statement::Kind::Continue:
case Statement::Kind::VariableDefinition:
if (omitted_ret_type) {
return arena->New<Sequence>(stmt->SourceLoc(), stmt,
arena->New<Return>(arena, loc));
return arena->New<Sequence>(stmt->source_loc(), stmt,
arena->New<Return>(arena, source_loc));
} else {
FATAL_COMPILATION_ERROR(stmt->SourceLoc())
FATAL_COMPILATION_ERROR(stmt->source_loc())
<< "control-flow reaches end of function that provides a `->` "
"return type without reaching a return statement";
}
@@ -1010,7 +1017,7 @@ auto TypeChecker::TypeOfFunDef(TypeEnv types, Env values,
TypeCheckPattern(&fun_def->param_pattern(), types, values, std::nullopt);
// Evaluate the return type expression
auto ret = interpreter.InterpPattern(values, &fun_def->return_type());
if (ret->Tag() == Value::Kind::AutoType) {
if (ret->kind() == Value::Kind::AutoType) {
auto f = TypeCheckFunDef(fun_def, types, values);
ret = interpreter.InterpPattern(values, &f->return_type());
}
@@ -1023,17 +1030,17 @@ auto TypeChecker::TypeOfClassDef(const ClassDefinition* sd, TypeEnv /*types*/,
VarValues fields;
VarValues methods;
for (Nonnull<const Member*> m : sd->members()) {
switch (m->Tag()) {
switch (m->kind()) {
case Member::Kind::FieldMember: {
Nonnull<const BindingPattern*> binding =
cast<FieldMember>(*m).Binding();
if (!binding->Name().has_value()) {
FATAL_COMPILATION_ERROR(binding->SourceLoc())
FATAL_COMPILATION_ERROR(binding->source_loc())
<< "Struct members must have names";
}
const auto* binding_type = dyn_cast<ExpressionPattern>(binding->Type());
if (binding_type == nullptr) {
FATAL_COMPILATION_ERROR(binding->SourceLoc())
FATAL_COMPILATION_ERROR(binding->source_loc())
<< "Struct members must have explicit types";
}
auto type = interpreter.InterpExp(ct_top, binding_type->Expression());
@@ -1057,7 +1064,7 @@ static auto GetName(const Declaration& d) -> const std::string& {
case Declaration::Kind::VariableDeclaration: {
const BindingPattern& binding = cast<VariableDeclaration>(d).binding();
if (!binding.Name().has_value()) {
FATAL_COMPILATION_ERROR(binding.SourceLoc())
FATAL_COMPILATION_ERROR(binding.source_loc())
<< "Top-level variable declarations must have names";
}
return *binding.Name();
@@ -1077,7 +1084,7 @@ auto TypeChecker::MakeTypeChecked(Nonnull<Declaration*> d, const TypeEnv& types,
cast<ClassDeclaration>(*d).definition();
std::vector<Nonnull<Member*>> fields;
for (Nonnull<Member*> m : class_def.members()) {
switch (m->Tag()) {
switch (m->kind()) {
case Member::Kind::FieldMember:
// TODO: Interpret the type expression and store the result.
fields.push_back(m);
@@ -140,11 +140,11 @@ class TypeChecker {
void TopLevel(Nonnull<Declaration*> d, TypeCheckContext* tops);
auto CheckOrEnsureReturn(std::optional<Nonnull<Statement*>> opt_stmt,
bool omitted_ret_type, SourceLocation loc)
bool omitted_ret_type, SourceLocation source_loc)
-> Nonnull<Statement*>;
// Reify type to type expression.
auto ReifyType(Nonnull<const Value*> t, SourceLocation loc)
auto ReifyType(Nonnull<const Value*> t, SourceLocation source_loc)
-> Nonnull<Expression*>;
auto Substitute(TypeEnv dict, Nonnull<const Value*> type)
+43 -40
View File
@@ -67,14 +67,14 @@ auto TupleValue::FindField(const std::string& name) const
namespace {
auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
const std::string& f, SourceLocation loc)
const std::string& f, SourceLocation source_loc)
-> Nonnull<const Value*> {
switch (v->Tag()) {
switch (v->kind()) {
case Value::Kind::StructValue: {
std::optional<Nonnull<const Value*>> field =
cast<StructValue>(*v).FindField(f);
if (field == std::nullopt) {
FATAL_RUNTIME_ERROR(loc) << "member " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc) << "member " << f << " not in " << *v;
}
return *field;
}
@@ -82,7 +82,7 @@ auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
std::optional<Nonnull<const Value*>> field =
cast<TupleValue>(*cast<NominalClassValue>(*v).Inits()).FindField(f);
if (field == std::nullopt) {
FATAL_RUNTIME_ERROR(loc) << "member " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc) << "member " << f << " not in " << *v;
}
return *field;
}
@@ -90,14 +90,15 @@ auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
std::optional<Nonnull<const Value*>> field =
cast<TupleValue>(*v).FindField(f);
if (!field) {
FATAL_RUNTIME_ERROR(loc) << "field " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc) << "field " << f << " not in " << *v;
}
return *field;
}
case Value::Kind::ChoiceType: {
const auto& choice = cast<ChoiceType>(*v);
if (!FindInVarValues(f, choice.Alternatives())) {
FATAL_RUNTIME_ERROR(loc) << "alternative " << f << " not in " << *v;
FATAL_RUNTIME_ERROR(source_loc)
<< "alternative " << f << " not in " << *v;
}
return arena->New<AlternativeConstructorValue>(f, choice.Name());
}
@@ -109,10 +110,10 @@ auto GetMember(Nonnull<Arena*> arena, Nonnull<const Value*> v,
} // namespace
auto Value::GetField(Nonnull<Arena*> arena, const FieldPath& path,
SourceLocation loc) const -> Nonnull<const Value*> {
SourceLocation source_loc) const -> Nonnull<const Value*> {
Nonnull<const Value*> value(this);
for (const std::string& field : path.components) {
value = GetMember(arena, value, field, loc);
value = GetMember(arena, value, field, source_loc);
}
return value;
}
@@ -122,12 +123,12 @@ namespace {
auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
std::vector<std::string>::const_iterator path_begin,
std::vector<std::string>::const_iterator path_end,
Nonnull<const Value*> field_value, SourceLocation loc)
Nonnull<const Value*> field_value, SourceLocation source_loc)
-> Nonnull<const Value*> {
if (path_begin == path_end) {
return field_value;
}
switch (value->Tag()) {
switch (value->kind()) {
case Value::Kind::StructValue: {
std::vector<TupleElement> elements = cast<StructValue>(*value).elements();
auto it = std::find_if(elements.begin(), elements.end(),
@@ -135,16 +136,16 @@ auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
return element.name == *path_begin;
});
if (it == elements.end()) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "field " << *path_begin << " not in " << *value;
}
it->value = SetFieldImpl(arena, it->value, path_begin + 1, path_end,
field_value, loc);
field_value, source_loc);
return arena->New<StructValue>(elements);
}
case Value::Kind::NominalClassValue: {
return SetFieldImpl(arena, cast<NominalClassValue>(*value).Inits(),
path_begin, path_end, field_value, loc);
path_begin, path_end, field_value, source_loc);
}
case Value::Kind::TupleValue: {
std::vector<TupleElement> elements = cast<TupleValue>(*value).Elements();
@@ -153,11 +154,11 @@ auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
return element.name == *path_begin;
});
if (it == elements.end()) {
FATAL_RUNTIME_ERROR(loc)
FATAL_RUNTIME_ERROR(source_loc)
<< "field " << *path_begin << " not in " << *value;
}
it->value = SetFieldImpl(arena, it->value, path_begin + 1, path_end,
field_value, loc);
field_value, source_loc);
return arena->New<TupleValue>(elements);
}
default:
@@ -169,14 +170,14 @@ auto SetFieldImpl(Nonnull<Arena*> arena, Nonnull<const Value*> value,
auto Value::SetField(Nonnull<Arena*> arena, const FieldPath& path,
Nonnull<const Value*> field_value,
SourceLocation loc) const -> Nonnull<const Value*> {
SourceLocation source_loc) const -> Nonnull<const Value*> {
return SetFieldImpl(arena, Nonnull<const Value*>(this),
path.components.begin(), path.components.end(),
field_value, loc);
field_value, source_loc);
}
void Value::Print(llvm::raw_ostream& out) const {
switch (Tag()) {
switch (kind()) {
case Value::Kind::AlternativeConstructorValue: {
const auto& alt = cast<AlternativeConstructorValue>(*this);
out << alt.ChoiceName() << "." << alt.AltName();
@@ -309,32 +310,34 @@ void Value::Print(llvm::raw_ostream& out) const {
}
auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
SourceLocation loc) -> Nonnull<const Value*> {
switch (val->Tag()) {
SourceLocation source_loc) -> Nonnull<const Value*> {
switch (val->kind()) {
case Value::Kind::TupleValue: {
std::vector<TupleElement> elements;
for (const TupleElement& element : cast<TupleValue>(*val).Elements()) {
elements.push_back({.name = element.name,
.value = CopyVal(arena, element.value, loc)});
elements.push_back(
{.name = element.name,
.value = CopyVal(arena, element.value, source_loc)});
}
return arena->New<TupleValue>(std::move(elements));
}
case Value::Kind::AlternativeValue: {
const auto& alt = cast<AlternativeValue>(*val);
Nonnull<const Value*> arg = CopyVal(arena, alt.Argument(), loc);
Nonnull<const Value*> arg = CopyVal(arena, alt.Argument(), source_loc);
return arena->New<AlternativeValue>(alt.AltName(), alt.ChoiceName(), arg);
}
case Value::Kind::StructValue: {
std::vector<TupleElement> elements;
for (const TupleElement& element : cast<StructValue>(*val).elements()) {
elements.push_back({.name = element.name,
.value = CopyVal(arena, element.value, loc)});
elements.push_back(
{.name = element.name,
.value = CopyVal(arena, element.value, source_loc)});
}
return arena->New<StructValue>(std::move(elements));
}
case Value::Kind::NominalClassValue: {
const auto& s = cast<NominalClassValue>(*val);
Nonnull<const Value*> inits = CopyVal(arena, s.Inits(), loc);
Nonnull<const Value*> inits = CopyVal(arena, s.Inits(), source_loc);
return arena->New<NominalClassValue>(s.Type(), inits);
}
case Value::Kind::IntValue:
@@ -353,13 +356,13 @@ auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
return val;
case Value::Kind::FunctionType: {
const auto& fn_type = cast<FunctionType>(*val);
return arena->New<FunctionType>(fn_type.Deduced(),
CopyVal(arena, fn_type.Param(), loc),
CopyVal(arena, fn_type.Ret(), loc));
return arena->New<FunctionType>(
fn_type.Deduced(), CopyVal(arena, fn_type.Param(), source_loc),
CopyVal(arena, fn_type.Ret(), source_loc));
}
case Value::Kind::PointerType:
return arena->New<PointerType>(
CopyVal(arena, cast<PointerType>(*val).Type(), loc));
CopyVal(arena, cast<PointerType>(*val).Type(), source_loc));
case Value::Kind::IntType:
return arena->New<IntType>();
case Value::Kind::BoolType:
@@ -377,7 +380,7 @@ auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
case Value::Kind::StructType: {
VarValues fields;
for (const auto& [name, type] : cast<StructType>(*val).fields()) {
fields.push_back({name, CopyVal(arena, type, loc)});
fields.push_back({name, CopyVal(arena, type, source_loc)});
}
return arena->New<StructType>(fields);
}
@@ -392,10 +395,10 @@ auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
}
auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool {
if (t1->Tag() != t2->Tag()) {
if (t1->kind() != t2->kind()) {
return false;
}
switch (t1->Tag()) {
switch (t1->kind()) {
case Value::Kind::PointerType:
return TypeEqual(cast<PointerType>(*t1).Type(),
cast<PointerType>(*t2).Type());
@@ -458,7 +461,7 @@ auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool {
// and returns false otherwise.
static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
const std::vector<TupleElement>& ts2,
SourceLocation loc) -> bool {
SourceLocation source_loc) -> bool {
if (ts1.size() != ts2.size()) {
return false;
}
@@ -469,7 +472,7 @@ static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
if (iter == ts2.end()) {
return false;
}
if (!ValueEqual(element.value, iter->value, loc)) {
if (!ValueEqual(element.value, iter->value, source_loc)) {
return false;
}
}
@@ -480,11 +483,11 @@ static auto FieldsValueEqual(const std::vector<TupleElement>& ts1,
//
// This function implements the `==` operator of Carbon.
auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
SourceLocation loc) -> bool {
if (v1->Tag() != v2->Tag()) {
SourceLocation source_loc) -> bool {
if (v1->kind() != v2->kind()) {
return false;
}
switch (v1->Tag()) {
switch (v1->kind()) {
case Value::Kind::IntValue:
return cast<IntValue>(*v1).Val() == cast<IntValue>(*v2).Val();
case Value::Kind::BoolValue:
@@ -501,10 +504,10 @@ auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
}
case Value::Kind::TupleValue:
return FieldsValueEqual(cast<TupleValue>(*v1).Elements(),
cast<TupleValue>(*v2).Elements(), loc);
cast<TupleValue>(*v2).Elements(), source_loc);
case Value::Kind::StructValue:
return FieldsValueEqual(cast<StructValue>(*v1).elements(),
cast<StructValue>(*v2).elements(), loc);
cast<StructValue>(*v2).elements(), source_loc);
case Value::Kind::StringValue:
return cast<StringValue>(*v1).Val() == cast<StringValue>(*v2).Val();
case Value::Kind::IntType:
+36 -36
View File
@@ -61,31 +61,31 @@ class Value {
Value(const Value&) = delete;
Value& operator=(const Value&) = delete;
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto Tag() const -> Kind { return kind; }
void Print(llvm::raw_ostream& out) const;
LLVM_DUMP_METHOD void Dump() const { Print(llvm::errs()); }
// Returns the sub-Value specified by `path`, which must be a valid field
// path for *this.
auto GetField(Nonnull<Arena*> arena, const FieldPath& path,
SourceLocation loc) const -> Nonnull<const Value*>;
SourceLocation source_loc) const -> Nonnull<const Value*>;
// Returns a copy of *this, but with the sub-Value specified by `path`
// set to `field_value`. `path` must be a valid field path for *this.
auto SetField(Nonnull<Arena*> arena, const FieldPath& path,
Nonnull<const Value*> field_value, SourceLocation loc) const
-> Nonnull<const Value*>;
Nonnull<const Value*> field_value,
SourceLocation source_loc) const -> Nonnull<const Value*>;
// Returns the enumerator corresponding to the most-derived type of this
// object.
auto kind() const -> Kind { return kind_; }
protected:
// Constructs a Value. `tag` must be the enumerator corresponding to the
// Constructs a Value. `kind` must be the enumerator corresponding to the
// most-derived type being constructed.
explicit Value(Kind kind) : kind(kind) {}
explicit Value(Kind kind) : kind_(kind) {}
private:
const Kind kind;
const Kind kind_;
};
using VarValues = std::vector<std::pair<std::string, Nonnull<const Value*>>>;
@@ -115,7 +115,7 @@ class IntValue : public Value {
explicit IntValue(int val) : Value(Kind::IntValue), val(val) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::IntValue;
return value->kind() == Kind::IntValue;
}
auto Val() const -> int { return val; }
@@ -135,7 +135,7 @@ class FunctionValue : public Value {
body(body) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::FunctionValue;
return value->kind() == Kind::FunctionValue;
}
auto Name() const -> const std::string& { return name; }
@@ -155,7 +155,7 @@ class PointerValue : public Value {
: Value(Kind::PointerValue), val(std::move(val)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::PointerValue;
return value->kind() == Kind::PointerValue;
}
auto Val() const -> const Address& { return val; }
@@ -170,7 +170,7 @@ class BoolValue : public Value {
explicit BoolValue(bool val) : Value(Kind::BoolValue), val(val) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::BoolValue;
return value->kind() == Kind::BoolValue;
}
auto Val() const -> bool { return val; }
@@ -195,7 +195,7 @@ class StructValue : public Value {
}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StructValue;
return value->kind() == Kind::StructValue;
}
auto elements() const -> const std::vector<TupleElement>& {
@@ -218,7 +218,7 @@ class NominalClassValue : public Value {
: Value(Kind::NominalClassValue), type(type), inits(inits) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::NominalClassValue;
return value->kind() == Kind::NominalClassValue;
}
auto Type() const -> Nonnull<const Value*> { return type; }
@@ -238,7 +238,7 @@ class AlternativeConstructorValue : public Value {
choice_name(std::move(choice_name)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::AlternativeConstructorValue;
return value->kind() == Kind::AlternativeConstructorValue;
}
auto AltName() const -> const std::string& { return alt_name; }
@@ -260,7 +260,7 @@ class AlternativeValue : public Value {
argument(argument) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::AlternativeValue;
return value->kind() == Kind::AlternativeValue;
}
auto AltName() const -> const std::string& { return alt_name; }
@@ -286,7 +286,7 @@ class TupleValue : public Value {
: Value(Kind::TupleValue), elements(std::move(elements)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::TupleValue;
return value->kind() == Kind::TupleValue;
}
auto Elements() const -> const std::vector<TupleElement>& { return elements; }
@@ -311,7 +311,7 @@ class BindingPlaceholderValue : public Value {
type(type) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::BindingPlaceholderValue;
return value->kind() == Kind::BindingPlaceholderValue;
}
auto Name() const -> const std::optional<std::string>& { return name; }
@@ -328,7 +328,7 @@ class IntType : public Value {
IntType() : Value(Kind::IntType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::IntType;
return value->kind() == Kind::IntType;
}
};
@@ -338,7 +338,7 @@ class BoolType : public Value {
BoolType() : Value(Kind::BoolType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::BoolType;
return value->kind() == Kind::BoolType;
}
};
@@ -348,7 +348,7 @@ class TypeType : public Value {
TypeType() : Value(Kind::TypeType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::TypeType;
return value->kind() == Kind::TypeType;
}
};
@@ -363,7 +363,7 @@ class FunctionType : public Value {
ret(ret) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::FunctionType;
return value->kind() == Kind::FunctionType;
}
auto Deduced() const -> const std::vector<GenericBinding>& { return deduced; }
@@ -383,7 +383,7 @@ class PointerType : public Value {
: Value(Kind::PointerType), type(type) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::PointerType;
return value->kind() == Kind::PointerType;
}
auto Type() const -> Nonnull<const Value*> { return type; }
@@ -398,7 +398,7 @@ class AutoType : public Value {
AutoType() : Value(Kind::AutoType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::AutoType;
return value->kind() == Kind::AutoType;
}
};
@@ -414,7 +414,7 @@ class StructType : public Value {
: Value(Kind::StructType), fields_(std::move(fields)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StructType;
return value->kind() == Kind::StructType;
}
auto fields() const -> const VarValues& { return fields_; }
@@ -433,7 +433,7 @@ class NominalClassType : public Value {
methods(std::move(methods)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::NominalClassType;
return value->kind() == Kind::NominalClassType;
}
auto Name() const -> const std::string& { return name; }
@@ -455,7 +455,7 @@ class ChoiceType : public Value {
alternatives(std::move(alternatives)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::ChoiceType;
return value->kind() == Kind::ChoiceType;
}
auto Name() const -> const std::string& { return name; }
@@ -472,7 +472,7 @@ class ContinuationType : public Value {
ContinuationType() : Value(Kind::ContinuationType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::ContinuationType;
return value->kind() == Kind::ContinuationType;
}
};
@@ -483,7 +483,7 @@ class VariableType : public Value {
: Value(Kind::VariableType), name(std::move(name)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::VariableType;
return value->kind() == Kind::VariableType;
}
auto Name() const -> const std::string& { return name; }
@@ -499,7 +499,7 @@ class ContinuationValue : public Value {
: Value(Kind::ContinuationValue), stack(std::move(stack)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::ContinuationValue;
return value->kind() == Kind::ContinuationValue;
}
auto Stack() const -> const std::vector<Nonnull<Frame*>>& { return stack; }
@@ -514,7 +514,7 @@ class StringType : public Value {
StringType() : Value(Kind::StringType) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StringType;
return value->kind() == Kind::StringType;
}
};
@@ -525,7 +525,7 @@ class StringValue : public Value {
: Value(Kind::StringValue), val(std::move(val)) {}
static auto classof(const Value* value) -> bool {
return value->Tag() == Kind::StringValue;
return value->kind() == Kind::StringValue;
}
auto Val() const -> const std::string& { return val; }
@@ -535,11 +535,11 @@ class StringValue : public Value {
};
auto CopyVal(Nonnull<Arena*> arena, Nonnull<const Value*> val,
SourceLocation loc) -> Nonnull<const Value*>;
SourceLocation source_loc) -> Nonnull<const Value*>;
auto TypeEqual(Nonnull<const Value*> t1, Nonnull<const Value*> t2) -> bool;
auto ValueEqual(Nonnull<const Value*> v1, Nonnull<const Value*> v2,
SourceLocation loc) -> bool;
SourceLocation source_loc) -> bool;
} // namespace Carbon
+2 -2
View File
@@ -251,7 +251,7 @@ string_literal \"([^\\\"\n\v\f\r]|\\.)*\"
// "Reading a token: ".
llvm::errs() << "\n";
}
FATAL_COMPILATION_ERROR(context.SourceLoc())
FATAL_COMPILATION_ERROR(context.source_loc())
<< "Invalid escaping in string: " << yytext;
}
return ARG_TOKEN(string_literal, *unescaped);
@@ -284,7 +284,7 @@ string_literal \"([^\\\"\n\v\f\r]|\\.)*\"
// "Reading a token: ".
llvm::errs() << "\n";
}
FATAL_COMPILATION_ERROR(context.SourceLoc())
FATAL_COMPILATION_ERROR(context.source_loc())
<< "invalid character '\\x" << llvm::toHex(llvm::StringRef(yytext, 1))
<< "' in source file.";
}
@@ -10,7 +10,7 @@ auto ParseAndLexContext::PrintDiagnostic(const std::string& message) -> void {
// TODO: Do we really want this to be fatal? It makes the comment and the
// name a lie, and renders some of the other yyparse() result propagation code
// moot.
FATAL_COMPILATION_ERROR(SourceLoc()) << message;
FATAL_COMPILATION_ERROR(source_loc()) << message;
}
} // namespace Carbon
@@ -23,7 +23,7 @@ class ParseAndLexContext {
// Writes a syntax error diagnostic containing message to standard error.
auto PrintDiagnostic(const std::string& message) -> void;
auto SourceLoc() -> SourceLocation {
auto source_loc() -> SourceLocation {
return SourceLocation(input_file_name,
static_cast<int>(current_token_position.begin.line));
}
+68 -68
View File
@@ -275,126 +275,126 @@ api_or_impl:
;
expression:
identifier
{ $$ = arena->New<IdentifierExpression>(context.SourceLoc(), $1); }
{ $$ = arena->New<IdentifierExpression>(context.source_loc(), $1); }
| expression designator
{ $$ = arena->New<FieldAccessExpression>(context.SourceLoc(), $1, $2); }
{ $$ = arena->New<FieldAccessExpression>(context.source_loc(), $1, $2); }
| expression LEFT_SQUARE_BRACKET expression RIGHT_SQUARE_BRACKET
{ $$ = arena->New<IndexExpression>(context.SourceLoc(), $1, $3); }
{ $$ = arena->New<IndexExpression>(context.source_loc(), $1, $3); }
| integer_literal
{ $$ = arena->New<IntLiteral>(context.SourceLoc(), $1); }
{ $$ = arena->New<IntLiteral>(context.source_loc(), $1); }
| string_literal
{ $$ = arena->New<StringLiteral>(context.SourceLoc(), $1); }
{ $$ = arena->New<StringLiteral>(context.source_loc(), $1); }
| TRUE
{ $$ = arena->New<BoolLiteral>(context.SourceLoc(), true); }
{ $$ = arena->New<BoolLiteral>(context.source_loc(), true); }
| FALSE
{ $$ = arena->New<BoolLiteral>(context.SourceLoc(), false); }
{ $$ = arena->New<BoolLiteral>(context.source_loc(), false); }
| sized_type_literal
{
int val;
CHECK(llvm::to_integer(llvm::StringRef($1).substr(1), val));
CHECK($1[0] == 'i' && val == 32)
<< "Only i32 is supported for now: " << $1;
$$ = arena->New<IntTypeLiteral>(context.SourceLoc());
$$ = arena->New<IntTypeLiteral>(context.source_loc());
}
| STRING
{ $$ = arena->New<StringTypeLiteral>(context.SourceLoc()); }
{ $$ = arena->New<StringTypeLiteral>(context.source_loc()); }
| BOOL
{ $$ = arena->New<BoolTypeLiteral>(context.SourceLoc()); }
{ $$ = arena->New<BoolTypeLiteral>(context.source_loc()); }
| TYPE
{ $$ = arena->New<TypeTypeLiteral>(context.SourceLoc()); }
{ $$ = arena->New<TypeTypeLiteral>(context.source_loc()); }
| CONTINUATION_TYPE
{ $$ = arena->New<ContinuationTypeLiteral>(context.SourceLoc()); }
{ $$ = arena->New<ContinuationTypeLiteral>(context.source_loc()); }
| paren_expression { $$ = $1; }
| struct_literal { $$ = $1; }
| struct_type_literal { $$ = $1; }
| expression EQUAL_EQUAL expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Eq,
context.source_loc(), Operator::Eq,
std::vector<Nonnull<Expression*>>({$1, $3}));
}
| expression PLUS expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Add,
context.source_loc(), Operator::Add,
std::vector<Nonnull<Expression*>>({$1, $3}));
}
| expression MINUS expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Sub,
context.source_loc(), Operator::Sub,
std::vector<Nonnull<Expression*>>({$1, $3}));
}
| expression BINARY_STAR expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Mul,
context.source_loc(), Operator::Mul,
std::vector<Nonnull<Expression*>>({$1, $3}));
}
| expression AND expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::And,
context.source_loc(), Operator::And,
std::vector<Nonnull<Expression*>>({$1, $3}));
}
| expression OR expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Or,
context.source_loc(), Operator::Or,
std::vector<Nonnull<Expression*>>({$1, $3}));
}
| NOT expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Not,
context.source_loc(), Operator::Not,
std::vector<Nonnull<Expression*>>({$2}));
}
| MINUS expression %prec UNARY_MINUS
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Neg,
context.source_loc(), Operator::Neg,
std::vector<Nonnull<Expression*>>({$2}));
}
| PREFIX_STAR expression
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Deref,
context.source_loc(), Operator::Deref,
std::vector<Nonnull<Expression*>>({$2}));
}
| UNARY_STAR expression %prec PREFIX_STAR
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Deref,
context.source_loc(), Operator::Deref,
std::vector<Nonnull<Expression*>>({$2}));
}
| expression tuple
{ $$ = arena->New<CallExpression>(context.SourceLoc(), $1, $2); }
{ $$ = arena->New<CallExpression>(context.source_loc(), $1, $2); }
| expression POSTFIX_STAR
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Ptr,
context.source_loc(), Operator::Ptr,
std::vector<Nonnull<Expression*>>({$1}));
}
| expression UNARY_STAR
{
$$ = arena->New<PrimitiveOperatorExpression>(
context.SourceLoc(), Operator::Ptr,
context.source_loc(), Operator::Ptr,
std::vector<Nonnull<Expression*>>({$1}));
}
| FNTY tuple return_type
{
auto [return_exp, is_omitted_exp] = $3;
$$ = arena->New<FunctionTypeLiteral>(context.SourceLoc(), $2, return_exp,
$$ = arena->New<FunctionTypeLiteral>(context.source_loc(), $2, return_exp,
is_omitted_exp);
}
;
designator: PERIOD identifier { $$ = $2; }
;
paren_expression: paren_expression_base
{ $$ = ExpressionFromParenContents(arena, context.SourceLoc(), $1); }
{ $$ = ExpressionFromParenContents(arena, context.source_loc(), $1); }
;
tuple: paren_expression_base
{ $$ = TupleExpressionFromParenContents(arena, context.SourceLoc(), $1); }
{ $$ = TupleExpressionFromParenContents(arena, context.source_loc(), $1); }
;
paren_expression_element:
expression
@@ -425,9 +425,9 @@ paren_expression_contents:
struct_literal:
LEFT_CURLY_BRACE struct_literal_contents RIGHT_CURLY_BRACE
{ $$ = arena->New<StructLiteral>(context.SourceLoc(), $2); }
{ $$ = arena->New<StructLiteral>(context.source_loc(), $2); }
| LEFT_CURLY_BRACE struct_literal_contents COMMA RIGHT_CURLY_BRACE
{ $$ = arena->New<StructLiteral>(context.SourceLoc(), $2); }
{ $$ = arena->New<StructLiteral>(context.source_loc(), $2); }
;
struct_literal_contents:
designator EQUAL expression
@@ -441,11 +441,11 @@ struct_literal_contents:
struct_type_literal:
LEFT_CURLY_BRACE RIGHT_CURLY_BRACE
{ $$ = arena->New<StructTypeLiteral>(context.SourceLoc()); }
{ $$ = arena->New<StructTypeLiteral>(context.source_loc()); }
| LEFT_CURLY_BRACE struct_type_literal_contents RIGHT_CURLY_BRACE
{ $$ = arena->New<StructTypeLiteral>(context.SourceLoc(), $2); }
{ $$ = arena->New<StructTypeLiteral>(context.source_loc(), $2); }
| LEFT_CURLY_BRACE struct_type_literal_contents COMMA RIGHT_CURLY_BRACE
{ $$ = arena->New<StructTypeLiteral>(context.SourceLoc(), $2); }
{ $$ = arena->New<StructTypeLiteral>(context.source_loc(), $2); }
;
struct_type_literal_contents:
designator COLON expression
@@ -471,20 +471,20 @@ pattern:
;
non_expression_pattern:
AUTO
{ $$ = arena->New<AutoPattern>(context.SourceLoc()); }
{ $$ = arena->New<AutoPattern>(context.source_loc()); }
| binding_lhs COLON pattern
{ $$ = arena->New<BindingPattern>(context.SourceLoc(), $1, $3); }
{ $$ = arena->New<BindingPattern>(context.source_loc(), $1, $3); }
| paren_pattern
{ $$ = $1; }
| expression tuple_pattern
{ $$ = arena->New<AlternativePattern>(context.SourceLoc(), $1, $2); }
{ $$ = arena->New<AlternativePattern>(context.source_loc(), $1, $2); }
;
binding_lhs:
identifier { $$ = $1; }
| UNDERSCORE { $$ = std::nullopt; }
;
paren_pattern: paren_pattern_base
{ $$ = PatternFromParenContents(arena, context.SourceLoc(), $1); }
{ $$ = PatternFromParenContents(arena, context.source_loc(), $1); }
;
paren_pattern_base:
LEFT_PARENTHESIS paren_pattern_contents RIGHT_PARENTHESIS
@@ -527,7 +527,7 @@ paren_pattern_element:
{ $$ = {.name = $1, .term = $3}; }
;
tuple_pattern: paren_pattern_base
{ $$ = TuplePatternFromParenContents(arena, context.SourceLoc(), $1); }
{ $$ = TuplePatternFromParenContents(arena, context.source_loc(), $1); }
;
// Unlike most `pattern` nonterminals, this one overlaps with `expression`,
// so it should be used only when prior context (such as an introducer)
@@ -535,7 +535,7 @@ tuple_pattern: paren_pattern_base
maybe_empty_tuple_pattern:
LEFT_PARENTHESIS RIGHT_PARENTHESIS
{
$$ = arena->New<TuplePattern>(context.SourceLoc(),
$$ = arena->New<TuplePattern>(context.source_loc(),
std::vector<TuplePattern::Field>());
}
| tuple_pattern
@@ -548,8 +548,8 @@ clause:
| DEFAULT DOUBLE_ARROW statement
{
$$ = Match::Clause(arena->New<BindingPattern>(
context.SourceLoc(), std::nullopt,
arena->New<AutoPattern>(context.SourceLoc())),
context.source_loc(), std::nullopt,
arena->New<AutoPattern>(context.source_loc())),
$3);
}
;
@@ -564,23 +564,23 @@ clause_list:
;
statement:
expression EQUAL expression SEMICOLON
{ $$ = arena->New<Assign>(context.SourceLoc(), $1, $3); }
{ $$ = arena->New<Assign>(context.source_loc(), $1, $3); }
| VAR pattern EQUAL expression SEMICOLON
{ $$ = arena->New<VariableDefinition>(context.SourceLoc(), $2, $4); }
{ $$ = arena->New<VariableDefinition>(context.source_loc(), $2, $4); }
| expression SEMICOLON
{ $$ = arena->New<ExpressionStatement>(context.SourceLoc(), $1); }
{ $$ = arena->New<ExpressionStatement>(context.source_loc(), $1); }
| if_statement
{ $$ = $1; }
| WHILE LEFT_PARENTHESIS expression RIGHT_PARENTHESIS block
{ $$ = arena->New<While>(context.SourceLoc(), $3, $5); }
{ $$ = arena->New<While>(context.source_loc(), $3, $5); }
| BREAK SEMICOLON
{ $$ = arena->New<Break>(context.SourceLoc()); }
{ $$ = arena->New<Break>(context.source_loc()); }
| CONTINUE SEMICOLON
{ $$ = arena->New<Continue>(context.SourceLoc()); }
{ $$ = arena->New<Continue>(context.source_loc()); }
| RETURN return_expression SEMICOLON
{
auto [return_exp, is_omitted_exp] = $2;
$$ = arena->New<Return>(context.SourceLoc(), return_exp, is_omitted_exp);
$$ = arena->New<Return>(context.source_loc(), return_exp, is_omitted_exp);
}
// We disallow empty blocks in places where an arbitrary statement can occur
// in order to avoid ambiguity with the empty struct literal `{}`. We can
@@ -593,17 +593,17 @@ statement:
{ $$ = $1; }
| MATCH LEFT_PARENTHESIS expression RIGHT_PARENTHESIS LEFT_CURLY_BRACE
clause_list RIGHT_CURLY_BRACE
{ $$ = arena->New<Match>(context.SourceLoc(), $3, $6); }
{ $$ = arena->New<Match>(context.source_loc(), $3, $6); }
| CONTINUATION identifier statement
{ $$ = arena->New<Continuation>(context.SourceLoc(), $2, $3); }
{ $$ = arena->New<Continuation>(context.source_loc(), $2, $3); }
| RUN expression SEMICOLON
{ $$ = arena->New<Run>(context.SourceLoc(), $2); }
{ $$ = arena->New<Run>(context.source_loc(), $2); }
| AWAIT SEMICOLON
{ $$ = arena->New<Await>(context.SourceLoc()); }
{ $$ = arena->New<Await>(context.source_loc()); }
;
if_statement:
IF LEFT_PARENTHESIS expression RIGHT_PARENTHESIS block optional_else
{ $$ = arena->New<If>(context.SourceLoc(), $3, $5, $6); }
{ $$ = arena->New<If>(context.source_loc(), $3, $5, $6); }
;
optional_else:
// Empty
@@ -615,7 +615,7 @@ optional_else:
;
return_expression:
// Empty
{ $$ = {arena->New<TupleLiteral>(context.SourceLoc()), true}; }
{ $$ = {arena->New<TupleLiteral>(context.source_loc()), true}; }
| expression
{ $$ = {$1, false}; }
;
@@ -627,18 +627,18 @@ statement_list:
;
nonempty_statement_list:
statement statement_list
{ $$ = arena->New<Sequence>(context.SourceLoc(), $1, $2); }
{ $$ = arena->New<Sequence>(context.source_loc(), $1, $2); }
;
block:
LEFT_CURLY_BRACE statement_list RIGHT_CURLY_BRACE
{ $$ = arena->New<Block>(context.SourceLoc(), $2); }
{ $$ = arena->New<Block>(context.source_loc(), $2); }
;
nonempty_block:
LEFT_CURLY_BRACE nonempty_statement_list RIGHT_CURLY_BRACE
{ $$ = arena->New<Block>(context.SourceLoc(), $2); }
{ $$ = arena->New<Block>(context.source_loc(), $2); }
return_type:
// Empty
{ $$ = {arena->New<TupleLiteral>(context.SourceLoc()), true}; }
{ $$ = {arena->New<TupleLiteral>(context.source_loc()), true}; }
| ARROW expression %prec FNARROW
{ $$ = {$2, false}; }
;
@@ -671,15 +671,15 @@ function_definition:
{
auto [return_exp, is_omitted_exp] = $5;
$$ = arena->New<FunctionDefinition>(
context.SourceLoc(), $2, $3, $4,
context.source_loc(), $2, $3, $4,
arena->New<ExpressionPattern>(return_exp), is_omitted_exp, $6);
}
| FN identifier deduced_params maybe_empty_tuple_pattern ARROW AUTO block
{
// The return type is not considered "omitted" because it's `auto`.
$$ = arena->New<FunctionDefinition>(
context.SourceLoc(), $2, $3, $4,
arena->New<AutoPattern>(context.SourceLoc()),
context.source_loc(), $2, $3, $4,
arena->New<AutoPattern>(context.source_loc()),
/*is_omitted_exp=*/false, $7);
}
;
@@ -688,16 +688,16 @@ function_declaration:
{
auto [return_exp, is_omitted_exp] = $5;
$$ = arena->New<FunctionDefinition>(
context.SourceLoc(), $2, $3, $4,
context.source_loc(), $2, $3, $4,
arena->New<ExpressionPattern>(return_exp), is_omitted_exp,
std::nullopt);
}
;
variable_declaration: identifier COLON pattern
{ $$ = arena->New<BindingPattern>(context.SourceLoc(), $1, $3); }
{ $$ = arena->New<BindingPattern>(context.source_loc(), $1, $3); }
;
member: VAR variable_declaration SEMICOLON
{ $$ = arena->New<FieldMember>(context.SourceLoc(), $2); }
{ $$ = arena->New<FieldMember>(context.source_loc(), $2); }
;
member_list:
// Empty
@@ -714,7 +714,7 @@ alternative:
| identifier
{
$$ = ChoiceDeclaration::Alternative(
$1, arena->New<TupleLiteral>(context.SourceLoc()));
$1, arena->New<TupleLiteral>(context.source_loc()));
}
;
alternative_list:
@@ -740,11 +740,11 @@ declaration:
| function_declaration
{ $$ = arena->New<FunctionDeclaration>($1); }
| CLASS identifier LEFT_CURLY_BRACE member_list RIGHT_CURLY_BRACE
{ $$ = arena->New<ClassDeclaration>(context.SourceLoc(), $2, $4); }
{ $$ = arena->New<ClassDeclaration>(context.source_loc(), $2, $4); }
| CHOICE identifier LEFT_CURLY_BRACE alternative_list RIGHT_CURLY_BRACE
{ $$ = arena->New<ChoiceDeclaration>(context.SourceLoc(), $2, $4); }
{ $$ = arena->New<ChoiceDeclaration>(context.source_loc(), $2, $4); }
| VAR variable_declaration EQUAL expression SEMICOLON
{ $$ = arena->New<VariableDeclaration>(context.SourceLoc(), $2, $4); }
{ $$ = arena->New<VariableDeclaration>(context.source_loc(), $2, $4); }
;
declaration_list:
// Empty