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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions starlark/ast.h
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,17 @@ struct CallExpr;
struct DictExpr;
struct ListExpr;
struct ListComp;
using Expression =
std::variant<CallExpr, StringLiteral, IntLiteral, Identifier, ListComp, ListExpr, DictExpr>;
struct SliceExpr;

using Expression = std::variant<
CallExpr,
StringLiteral,
IntLiteral,
Identifier,
ListComp,
ListExpr,
DictExpr,
SliceExpr>;

struct Argument;

Expand All @@ -51,6 +60,12 @@ struct DictExpr {
constexpr bool operator==(DictExpr const &) const;
};

struct SliceExpr {
std::shared_ptr<Expression> target;
std::shared_ptr<Expression> index;
constexpr bool operator==(SliceExpr const &) const;
};

// TODO(robinlinden): shared_ptr is silly here, but right now the ast has to be
// copyable for some reason.
struct ListComp {
Expand All @@ -77,6 +92,10 @@ constexpr bool CallExpr::operator==(CallExpr const &o) const {

constexpr bool DictExpr::operator==(DictExpr const &o) const { return entries == o.entries; }

constexpr bool SliceExpr::operator==(SliceExpr const &o) const {
return *target == *o.target && *index == *o.index;
}

constexpr bool ListComp::operator==(ListComp const &o) const {
return *element == *o.element && iterator_var == o.iterator_var && *iterable == *o.iterable;
}
Expand Down
23 changes: 21 additions & 2 deletions starlark/parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -292,9 +292,28 @@ class Parser {
.target = std::make_shared<Expression>(std::move(*operand)),
.args = std::move(*args),
};
}
} else if (std::holds_alternative<token::LBracket>(*next)) {
next = next_token();
if (!next) {
std::cerr << "Unexpected end of input after '['.\n";
return std::nullopt;
}

auto index_expr = parse_expression(*next);
if (!index_expr) {
std::cerr << "Failed to parse index expression.\n";
return std::nullopt;
}

if (next) {
if (!expect_next_token(token::RBracket{})) {
return std::nullopt;
}

return SliceExpr{
.target = std::make_shared<Expression>(std::move(*operand)),
.index = std::make_shared<Expression>(std::move(*index_expr)),
};
} else {
reconsume(std::move(*next));
}

Expand Down
17 changes: 17 additions & 0 deletions starlark/parser_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,23 @@ int main() {
},
},
},
{
"42[5]",
starlark::Program{
.statements{
starlark::ExpressionStmt{
.expr{
starlark::SliceExpr{
.target = std::make_shared<starlark::Expression>(
starlark::IntLiteral{42}),
.index =
std::make_shared<starlark::Expression>(starlark::IntLiteral{5}),
},
},
},
},
},
},
});

// TODO(robinlinden): Return error codes from parser and use that here.
Expand Down