Skip to content

Add Located::start, Located::end and impl Deref #4929

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 26, 2023
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
18 changes: 18 additions & 0 deletions compiler/ast/asdl_rs.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,6 +671,24 @@ def write_ast_def(mod, typeinfo, f):
pub fn new(location: Location, end_location: Location, node: T) -> Self {
Self { location, end_location: Some(end_location), custom: (), node }
}

pub const fn start(&self) -> Location {
self.location
}

/// Returns the node's [`end_location`](Located::end_location) or [`location`](Located::start) if
/// [`end_location`](Located::end_location) is `None`.
pub fn end(&self) -> Location {
self.end_location.unwrap_or(self.location)
}
}

impl<T, U> std::ops::Deref for Located<T, U> {
type Target = T;

fn deref(&self) -> &Self::Target {
&self.node
}
}
\n
""".lstrip()
Expand Down
18 changes: 18 additions & 0 deletions compiler/ast/src/ast_gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,24 @@ impl<T> Located<T> {
node,
}
}

pub const fn start(&self) -> Location {
self.location
}

/// Returns the node's [`end_location`](Located::end_location) or [`location`](Located::start) if
/// [`end_location`](Located::end_location) is `None`.
pub fn end(&self) -> Location {
self.end_location.unwrap_or(self.location)
}
}

impl<T, U> std::ops::Deref for Located<T, U> {
type Target = T;

fn deref(&self) -> &Self::Target {
&self.node
}
}

#[derive(Clone, Debug, PartialEq)]
Expand Down
55 changes: 24 additions & 31 deletions compiler/parser/python.lalrpop
Original file line number Diff line number Diff line change
Expand Up @@ -348,8 +348,7 @@ MatchStatement: ast::Stmt = {
.body
.last()
.unwrap()
.end_location
.unwrap();
.end();
ast::Stmt::new(
location,
end_location,
Expand All @@ -366,8 +365,7 @@ MatchStatement: ast::Stmt = {
.body
.last()
.unwrap()
.end_location
.unwrap();
.end();
ast::Stmt::new(
location,
end_location,
Expand All @@ -384,8 +382,7 @@ MatchStatement: ast::Stmt = {
.body
.last()
.unwrap()
.end_location
.unwrap();
.end();
let mut subjects = subjects;
subjects.insert(0, subject);
ast::Stmt::new(
Expand Down Expand Up @@ -803,8 +800,7 @@ IfStatement: ast::Stmt = {
.or_else(|| s2.last().and_then(|last| last.4.last()))
.or_else(|| body.last())
.unwrap()
.end_location
.unwrap();
.end();
// handle elif:
for i in s2.into_iter().rev() {
let x = ast::Stmt::new(
Expand All @@ -830,8 +826,7 @@ WhileStatement: ast::Stmt = {
.last()
.or_else(|| body.last())
.unwrap()
.end_location
.unwrap();
.end();
ast::Stmt::new(
location,
end_location,
Expand All @@ -851,8 +846,7 @@ ForStatement: ast::Stmt = {
.last()
.or_else(|| body.last())
.unwrap()
.end_location
.unwrap();
.end();
let target = Box::new(set_context(target, ast::ExprContext::Store));
let iter = Box::new(iter);
let type_comment = None;
Expand All @@ -871,9 +865,9 @@ TryStatement: ast::Stmt = {
let finalbody = finally.map(|s| s.2).unwrap_or_default();
let end_location = finalbody
.last()
.and_then(|last| last.end_location)
.or_else(|| orelse.last().and_then(|last| last.end_location))
.or_else(|| handlers.last().and_then(|last| last.end_location))
.map(|last| last.end())
.or_else(|| orelse.last().map(|last| last.end()))
.or_else(|| handlers.last().map(|last| last.end()))
.unwrap();
ast::Stmt::new(
location,
Expand All @@ -892,8 +886,8 @@ TryStatement: ast::Stmt = {
let end_location = finalbody
.last()
.or_else(|| orelse.last())
.and_then(|last| last.end_location)
.or_else(|| handlers.last().and_then(|last| last.end_location))
.map(|last| last.end())
.or_else(|| handlers.last().map(|last| last.end()))
.unwrap();
ast::Stmt::new(
location,
Expand All @@ -910,7 +904,7 @@ TryStatement: ast::Stmt = {
let handlers = vec![];
let orelse = vec![];
let finalbody = finally.2;
let end_location = finalbody.last().unwrap().end_location.unwrap();
let end_location = finalbody.last().unwrap().end();
ast::Stmt::new(
location,
end_location,
Expand All @@ -926,7 +920,7 @@ TryStatement: ast::Stmt = {

ExceptStarClause: ast::Excepthandler = {
<location:@L> "except" "*" <typ:Test<"all">> ":" <body:Suite> => {
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
ast::Excepthandler::new(
location,
end_location,
Expand All @@ -938,7 +932,7 @@ ExceptStarClause: ast::Excepthandler = {
)
},
<location:@L> "except" "*" <x:(Test<"all"> "as" Identifier)> ":" <body:Suite> => {
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
ast::Excepthandler::new(
location,
end_location,
Expand All @@ -954,7 +948,7 @@ ExceptStarClause: ast::Excepthandler = {

ExceptClause: ast::Excepthandler = {
<location:@L> "except" <typ:Test<"all">?> ":" <body:Suite> => {
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
ast::Excepthandler::new(
location,
end_location,
Expand All @@ -966,7 +960,7 @@ ExceptClause: ast::Excepthandler = {
)
},
<location:@L> "except" <x:(Test<"all"> "as" Identifier)> ":" <body:Suite> => {
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
ast::Excepthandler::new(
location,
end_location,
Expand All @@ -981,7 +975,7 @@ ExceptClause: ast::Excepthandler = {

WithStatement: ast::Stmt = {
<location:@L> <is_async:"async"?> "with" <items:WithItems> ":" <body:Suite> => {
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
let type_comment = None;
let node = if is_async.is_some() {
ast::StmtKind::AsyncWith { items, body, type_comment }
Expand Down Expand Up @@ -1022,7 +1016,7 @@ FuncDef: ast::Stmt = {
<decorator_list:Decorator*> <location:@L> <is_async:"async"?> "def" <name:Identifier> <args:Parameters> <r:("->" Test<"all">)?> ":" <body:Suite> => {
let args = Box::new(args);
let returns = r.map(|x| Box::new(x.1));
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
let type_comment = None;
let node = if is_async.is_some() {
ast::StmtKind::AsyncFunctionDef { name, args, body, decorator_list, returns, type_comment }
Expand Down Expand Up @@ -1197,7 +1191,7 @@ ClassDef: ast::Stmt = {
Some((_, arg, _)) => (arg.args, arg.keywords),
None => (vec![], vec![]),
};
let end_location = body.last().unwrap().end_location.unwrap();
let end_location = body.last().unwrap().end();
ast::Stmt::new(
location,
end_location,
Expand Down Expand Up @@ -1253,19 +1247,18 @@ NamedExpressionTest: ast::Expr = {

NamedExpression: ast::Expr = {
<location:@L> <id:Identifier> <end_location:@R> ":=" <value:Test<"all">> => {
ast::Expr {
ast::Expr::new(
location,
end_location: value.end_location,
custom: (),
node: ast::ExprKind::NamedExpr {
value.end(),
ast::ExprKind::NamedExpr {
target: Box::new(ast::Expr::new(
location,
end_location,
ast::ExprKind::Name { id, ctx: ast::ExprContext::Store },
)),
value: Box::new(value),
}
}
)
},
};

Expand Down Expand Up @@ -1564,7 +1557,7 @@ Atom<Goal>: ast::Expr = {
if matches!(mid.node, ast::ExprKind::Starred { .. }) {
Err(LexicalError{
error: LexicalErrorType::OtherError("cannot use starred expression here".to_string()),
location: mid.location,
location: mid.start(),
})?
}
Ok(mid)
Expand Down
10 changes: 5 additions & 5 deletions compiler/parser/src/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ pub(crate) fn validate_arguments(

let mut all_arg_names = FxHashSet::with_hasher(Default::default());
for arg in all_args {
let arg_name = &arg.node.arg;
let arg_name = &arg.arg;
// Check for duplicate arguments in the function definition.
if !all_arg_names.insert(arg_name) {
return Err(LexicalError {
error: LexicalErrorType::DuplicateArgumentError(arg_name.to_string()),
location: arg.location,
location: arg.start(),
});
}
}
Expand All @@ -64,7 +64,7 @@ pub(crate) fn parse_params(
// have defaults.
return Err(LexicalError {
error: LexicalErrorType::DefaultArgumentError,
location: name.location,
location: name.start(),
});
}
Ok(())
Expand Down Expand Up @@ -126,14 +126,14 @@ pub(crate) fn parse_args(func_args: Vec<FunctionArgument>) -> Result<ArgumentLis
if !keywords.is_empty() && !is_starred(&value) {
return Err(LexicalError {
error: LexicalErrorType::PositionalArgumentError,
location: value.location,
location: value.start(),
});
// Allow starred arguments after keyword arguments but
// not after double-starred arguments.
} else if double_starred {
return Err(LexicalError {
error: LexicalErrorType::UnpackedArgumentError,
location: value.location,
location: value.start(),
});
}

Expand Down