Skip to content

Commit ce9ea09

Browse files
bors[bot]sinkuu
andcommitted
Merge #1407
1407: Skip attrs in `ast::Literal::token` r=matklad a=sinkuu `ast::Literal::token` panics on literals containing attributes. rust-analyzer crashed on the `rust-lang/rust` repository by parsing [a test containing this](https://github.com/rust-lang/rust/blob/9ebf47851a357faa4cd97f4b1dc7835f6376e639/src/test/run-pass/proc-macro/attr-stmt-expr.rs#L22-L25). Co-authored-by: Shotaro Yamada <[email protected]>
2 parents 41c56c8 + 774537f commit ce9ea09

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

crates/ra_syntax/src/ast/expr_extensions.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,8 +229,12 @@ pub enum LiteralKind {
229229

230230
impl ast::Literal {
231231
pub fn token(&self) -> SyntaxToken {
232-
match self.syntax().first_child_or_token().unwrap() {
233-
SyntaxElement::Token(token) => token,
232+
let elem = self
233+
.syntax()
234+
.children_with_tokens()
235+
.find(|e| e.kind() != ATTR && !e.kind().is_trivia());
236+
match elem {
237+
Some(SyntaxElement::Token(token)) => token,
234238
_ => unreachable!(),
235239
}
236240
}
@@ -268,6 +272,13 @@ impl ast::Literal {
268272
}
269273
}
270274

275+
#[test]
276+
fn test_literal_with_attr() {
277+
let parse = ast::SourceFile::parse(r#"const _: &str = { #[attr] "Hello" };"#);
278+
let lit = parse.tree.syntax().descendants().find_map(ast::Literal::cast).unwrap();
279+
assert_eq!(lit.token().text(), r#""Hello""#);
280+
}
281+
271282
impl ast::NamedField {
272283
pub fn parent_struct_lit(&self) -> &ast::StructLit {
273284
self.syntax().ancestors().find_map(ast::StructLit::cast).unwrap()

0 commit comments

Comments
 (0)