difftreelog
refactor split lexer from rowan parser
in: master
15 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -716,6 +716,13 @@
]
[[package]]
+name = "jrsonnet-lexer"
+version = "0.5.0-pre97"
+dependencies = [
+ "logos",
+]
+
+[[package]]
name = "jrsonnet-macros"
version = "0.5.0-pre97"
dependencies = [
@@ -744,7 +751,7 @@
"hi-doc",
"indoc",
"insta",
- "logos",
+ "jrsonnet-lexer",
"rowan",
"strip-ansi-escapes",
"thiserror",
Cargo.tomldiffbeforeafterboth--- a/Cargo.toml
+++ b/Cargo.toml
@@ -81,9 +81,6 @@
itertools = "0.14.0"
xshell = "0.2.7"
-lsp-server = "0.7.9"
-lsp-types = "0.97.0"
-
regex = "1.12"
lru = "0.16.3"
crates/jrsonnet-lexer/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-lexer/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "jrsonnet-lexer"
+authors.workspace = true
+edition.workspace = true
+license.workspace = true
+repository.workspace = true
+version.workspace = true
+
+[dependencies]
+logos.workspace = true
+
+[lints]
+workspace = true
crates/jrsonnet-lexer/src/generated/mod.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-lexer/src/generated/mod.rs
@@ -0,0 +1 @@
+pub mod syntax_kinds;
crates/jrsonnet-lexer/src/generated/syntax_kinds.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-lexer/src/generated/syntax_kinds.rs
@@ -0,0 +1,210 @@
+//! This is a generated file, please do not edit manually. Changes can be
+//! made in codegeneration that lives in `xtask` top-level dir.
+
+#![allow(
+ bad_style,
+ missing_docs,
+ unreachable_pub,
+ clippy::manual_non_exhaustive,
+ clippy::match_like_matches_macro
+)]
+#[doc = r" The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT`."]
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, logos :: Logos)]
+#[repr(u16)]
+pub enum SyntaxKind {
+ #[doc(hidden)]
+ TOMBSTONE,
+ #[doc(hidden)]
+ EOF,
+ #[token("||")]
+ OR,
+ #[token("??")]
+ NULL_COAELSE,
+ #[token("&&")]
+ AND,
+ #[token("|")]
+ BIT_OR,
+ #[token("^")]
+ BIT_XOR,
+ #[token("&")]
+ BIT_AND,
+ #[token("==")]
+ EQ,
+ #[token("!=")]
+ NE,
+ #[token("<")]
+ LT,
+ #[token(">")]
+ GT,
+ #[token("<=")]
+ LE,
+ #[token(">=")]
+ GE,
+ #[token("<<")]
+ LHS,
+ #[token(">>")]
+ RHS,
+ #[token("+")]
+ PLUS,
+ #[token("-")]
+ MINUS,
+ #[token("*")]
+ MUL,
+ #[token("/")]
+ DIV,
+ #[token("%")]
+ MODULO,
+ #[token("!")]
+ NOT,
+ #[token("~")]
+ BIT_NOT,
+ #[token("[")]
+ L_BRACK,
+ #[token("]")]
+ R_BRACK,
+ #[token("(")]
+ L_PAREN,
+ #[token(")")]
+ R_PAREN,
+ #[token("{")]
+ L_BRACE,
+ #[token("}")]
+ R_BRACE,
+ #[token(":")]
+ COLON,
+ #[token("::")]
+ COLONCOLON,
+ #[token(":::")]
+ COLONCOLONCOLON,
+ #[token(";")]
+ SEMI,
+ #[token(".")]
+ DOT,
+ #[token("...")]
+ DOTDOTDOT,
+ #[token(",")]
+ COMMA,
+ #[token("$")]
+ DOLLAR,
+ #[token("=")]
+ ASSIGN,
+ #[token("?")]
+ QUESTION_MARK,
+ #[regex("(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")]
+ FLOAT,
+ #[regex("(?:0|[1-9][0-9]*)\\.[^0-9]")]
+ ERROR_FLOAT_JUNK_AFTER_POINT,
+ #[regex("(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?[eE][^+\\-0-9]")]
+ ERROR_FLOAT_JUNK_AFTER_EXPONENT,
+ #[regex("(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?[eE][+-][^0-9]")]
+ ERROR_FLOAT_JUNK_AFTER_EXPONENT_SIGN,
+ #[regex("\"(?s:[^\"\\\\]|\\\\.)*\"")]
+ STRING_DOUBLE,
+ #[regex("\"(?s:[^\"\\\\]|\\\\.)*")]
+ ERROR_STRING_DOUBLE_UNTERMINATED,
+ #[regex("'(?s:[^'\\\\]|\\\\.)*'")]
+ STRING_SINGLE,
+ #[regex("'(?s:[^'\\\\]|\\\\.)*")]
+ ERROR_STRING_SINGLE_UNTERMINATED,
+ #[regex("@\"(?:[^\"]|\"\")*\"")]
+ STRING_DOUBLE_VERBATIM,
+ #[regex("@\"(?:[^\"]|\"\")*")]
+ ERROR_STRING_DOUBLE_VERBATIM_UNTERMINATED,
+ #[regex("@'(?:[^']|'')*'")]
+ STRING_SINGLE_VERBATIM,
+ #[regex("@'(?:[^']|'')*")]
+ ERROR_STRING_SINGLE_VERBATIM_UNTERMINATED,
+ #[regex("@[^\"'\\s]\\S+")]
+ ERROR_STRING_VERBATIM_MISSING_QUOTES,
+ #[regex("\\|\\|\\|", crate::string_block::lex_str_block_test)]
+ STRING_BLOCK,
+ ERROR_STRING_BLOCK_UNEXPECTED_END,
+ ERROR_STRING_BLOCK_MISSING_NEW_LINE,
+ ERROR_STRING_BLOCK_MISSING_TERMINATION,
+ ERROR_STRING_BLOCK_MISSING_INDENT,
+ #[regex("[_a-zA-Z][_a-zA-Z0-9]*")]
+ IDENT,
+ #[regex("[ \\t\\n\\r]+")]
+ WHITESPACE,
+ #[regex("//[^\\r\\n]*?(\\r\\n|\\n)?")]
+ SINGLE_LINE_SLASH_COMMENT,
+ #[regex("#[^\\r\\n]*?(\\r\\n|\\n)?")]
+ SINGLE_LINE_HASH_COMMENT,
+ #[regex("/\\*([^*]|\\*[^/])*\\*/")]
+ MULTI_LINE_COMMENT,
+ #[regex("/\\*/")]
+ ERROR_COMMENT_TOO_SHORT,
+ #[regex("/\\*([^*/]|\\*[^/])+")]
+ ERROR_COMMENT_UNTERMINATED,
+ #[token("tailstrict")]
+ TAILSTRICT_KW,
+ #[token("local")]
+ LOCAL_KW,
+ #[token("importstr")]
+ IMPORTSTR_KW,
+ #[token("importbin")]
+ IMPORTBIN_KW,
+ #[token("import")]
+ IMPORT_KW,
+ #[token("if")]
+ IF_KW,
+ #[token("then")]
+ THEN_KW,
+ #[token("else")]
+ ELSE_KW,
+ #[token("function")]
+ FUNCTION_KW,
+ #[token("error")]
+ ERROR_KW,
+ #[token("in")]
+ IN_KW,
+ META_OBJECT_APPLY,
+ ERROR_NO_OPERATOR,
+ #[token("null")]
+ NULL_KW,
+ #[token("true")]
+ TRUE_KW,
+ #[token("false")]
+ FALSE_KW,
+ #[token("self")]
+ SELF_KW,
+ #[token("super")]
+ SUPER_KW,
+ #[token("for")]
+ FOR_KW,
+ #[token("assert")]
+ ASSERT_KW,
+ ERROR_MISSING_TOKEN,
+ ERROR_UNEXPECTED_TOKEN,
+ ERROR_CUSTOM,
+ LEXING_ERROR,
+ __LAST_TOKEN,
+ #[doc(hidden)]
+ __LAST,
+}
+use self::SyntaxKind::*;
+impl SyntaxKind {
+ pub fn is_keyword(self) -> bool {
+ match self {
+ OR | NULL_COAELSE | AND | BIT_OR | BIT_XOR | BIT_AND | EQ | NE | LT | GT | LE | GE
+ | LHS | RHS | PLUS | MINUS | MUL | DIV | MODULO | NOT | BIT_NOT | L_BRACK | R_BRACK
+ | L_PAREN | R_PAREN | L_BRACE | R_BRACE | COLON | COLONCOLON | COLONCOLONCOLON
+ | SEMI | DOT | DOTDOTDOT | COMMA | DOLLAR | ASSIGN | QUESTION_MARK | TAILSTRICT_KW
+ | LOCAL_KW | IMPORTSTR_KW | IMPORTBIN_KW | IMPORT_KW | IF_KW | THEN_KW | ELSE_KW
+ | FUNCTION_KW | ERROR_KW | IN_KW | NULL_KW | TRUE_KW | FALSE_KW | SELF_KW
+ | SUPER_KW | FOR_KW | ASSERT_KW => true,
+ _ => false,
+ }
+ }
+ pub fn from_raw(r: u16) -> Self {
+ assert!(r < Self::__LAST as u16);
+ unsafe { std::mem::transmute(r) }
+ }
+ pub fn into_raw(self) -> u16 {
+ self as u16
+ }
+}
+#[macro_export]
+macro_rules ! T { [||] => { $ crate :: SyntaxKind :: OR } ; [??] => { $ crate :: SyntaxKind :: NULL_COAELSE } ; [&&] => { $ crate :: SyntaxKind :: AND } ; [|] => { $ crate :: SyntaxKind :: BIT_OR } ; [^] => { $ crate :: SyntaxKind :: BIT_XOR } ; [&] => { $ crate :: SyntaxKind :: BIT_AND } ; [==] => { $ crate :: SyntaxKind :: EQ } ; [!=] => { $ crate :: SyntaxKind :: NE } ; [<] => { $ crate :: SyntaxKind :: LT } ; [>] => { $ crate :: SyntaxKind :: GT } ; [<=] => { $ crate :: SyntaxKind :: LE } ; [>=] => { $ crate :: SyntaxKind :: GE } ; [<<] => { $ crate :: SyntaxKind :: LHS } ; [>>] => { $ crate :: SyntaxKind :: RHS } ; [+] => { $ crate :: SyntaxKind :: PLUS } ; [-] => { $ crate :: SyntaxKind :: MINUS } ; [*] => { $ crate :: SyntaxKind :: MUL } ; [/] => { $ crate :: SyntaxKind :: DIV } ; [%] => { $ crate :: SyntaxKind :: MODULO } ; [!] => { $ crate :: SyntaxKind :: NOT } ; [~] => { $ crate :: SyntaxKind :: BIT_NOT } ; ['['] => { $ crate :: SyntaxKind :: L_BRACK } ; [']'] => { $ crate :: SyntaxKind :: R_BRACK } ; ['('] => { $ crate :: SyntaxKind :: L_PAREN } ; [')'] => { $ crate :: SyntaxKind :: R_PAREN } ; ['{'] => { $ crate :: SyntaxKind :: L_BRACE } ; ['}'] => { $ crate :: SyntaxKind :: R_BRACE } ; [:] => { $ crate :: SyntaxKind :: COLON } ; [::] => { $ crate :: SyntaxKind :: COLONCOLON } ; [:::] => { $ crate :: SyntaxKind :: COLONCOLONCOLON } ; [;] => { $ crate :: SyntaxKind :: SEMI } ; [.] => { $ crate :: SyntaxKind :: DOT } ; [...] => { $ crate :: SyntaxKind :: DOTDOTDOT } ; [,] => { $ crate :: SyntaxKind :: COMMA } ; ['$'] => { $ crate :: SyntaxKind :: DOLLAR } ; [=] => { $ crate :: SyntaxKind :: ASSIGN } ; [?] => { $ crate :: SyntaxKind :: QUESTION_MARK } ; [tailstrict] => { $ crate :: SyntaxKind :: TAILSTRICT_KW } ; [local] => { $ crate :: SyntaxKind :: LOCAL_KW } ; [importstr] => { $ crate :: SyntaxKind :: IMPORTSTR_KW } ; [importbin] => { $ crate :: SyntaxKind :: IMPORTBIN_KW } ; [import] => { $ crate :: SyntaxKind :: IMPORT_KW } ; [if] => { $ crate :: SyntaxKind :: IF_KW } ; [then] => { $ crate :: SyntaxKind :: THEN_KW } ; [else] => { $ crate :: SyntaxKind :: ELSE_KW } ; [function] => { $ crate :: SyntaxKind :: FUNCTION_KW } ; [error] => { $ crate :: SyntaxKind :: ERROR_KW } ; [in] => { $ crate :: SyntaxKind :: IN_KW } ; [null] => { $ crate :: SyntaxKind :: NULL_KW } ; [true] => { $ crate :: SyntaxKind :: TRUE_KW } ; [false] => { $ crate :: SyntaxKind :: FALSE_KW } ; [self] => { $ crate :: SyntaxKind :: SELF_KW } ; [super] => { $ crate :: SyntaxKind :: SUPER_KW } ; [for] => { $ crate :: SyntaxKind :: FOR_KW } ; [assert] => { $ crate :: SyntaxKind :: ASSERT_KW } }
+#[allow(unused_imports)]
+pub use T;
crates/jrsonnet-lexer/src/lex.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-lexer/src/lex.rs
@@ -0,0 +1,78 @@
+use core::ops::Range;
+
+use logos::Logos;
+// use rowan::{TextRange, TextSize};
+
+use crate::{
+ generated::syntax_kinds::SyntaxKind,
+ string_block::{lex_str_block, StringBlockError},
+ Span,
+};
+
+pub struct Lexer<'a> {
+ inner: logos::Lexer<'a, SyntaxKind>,
+}
+
+impl<'a> Lexer<'a> {
+ pub fn new(input: &'a str) -> Self {
+ Self {
+ inner: SyntaxKind::lexer(input),
+ }
+ }
+}
+
+impl<'a> Iterator for Lexer<'a> {
+ type Item = Lexeme<'a>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ use SyntaxKind::*;
+
+ let mut kind = self.inner.next()?;
+ let text = self.inner.slice();
+
+ if kind == Ok(STRING_BLOCK) {
+ // We use custom lexer, which skips enough bytes, but not returns error
+ // Instead we should call lexer again to verify if there is something wrong with string block
+ let mut lexer = logos::Lexer::<SyntaxKind>::new(text);
+ // In kinds, string blocks is parsed at least as `|||`
+ lexer.bump(3);
+ let res = lex_str_block(&mut lexer);
+ let next = lexer.next();
+ assert!(next.is_none(), "str_block is lexed");
+ match res {
+ Ok(()) => {}
+ Err(e) => {
+ kind = Ok(match e {
+ StringBlockError::UnexpectedEnd => ERROR_STRING_BLOCK_UNEXPECTED_END,
+ StringBlockError::MissingNewLine => ERROR_STRING_BLOCK_MISSING_NEW_LINE,
+ StringBlockError::MissingTermination => {
+ ERROR_STRING_BLOCK_MISSING_TERMINATION
+ }
+ StringBlockError::MissingIndent => ERROR_STRING_BLOCK_MISSING_INDENT,
+ });
+ }
+ }
+ }
+
+ Some(Self::Item {
+ kind: kind.unwrap_or(SyntaxKind::LEXING_ERROR),
+ text,
+ range: {
+ let Range { start, end } = self.inner.span();
+
+ Span(start as u32, end as u32)
+ },
+ })
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Lexeme<'s> {
+ pub kind: SyntaxKind,
+ pub text: &'s str,
+ pub range: Span,
+}
+
+pub fn lex(input: &str) -> Vec<Lexeme<'_>> {
+ Lexer::new(input).collect()
+}
crates/jrsonnet-lexer/src/lib.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-lexer/src/lib.rs
@@ -0,0 +1,8 @@
+mod generated;
+mod lex;
+mod string_block;
+
+#[derive(Clone, Copy, Debug)]
+pub struct Span(pub u32, pub u32);
+
+pub use lex::{Lexeme, Lexer};
crates/jrsonnet-lexer/src/string_block.rsdiffbeforeafterboth--- /dev/null
+++ b/crates/jrsonnet-lexer/src/string_block.rs
@@ -0,0 +1,282 @@
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum StringBlockError {
+ UnexpectedEnd,
+ MissingNewLine,
+ MissingTermination,
+ MissingIndent,
+}
+
+use logos::Lexer;
+use StringBlockError::*;
+
+use crate::generated::syntax_kinds::SyntaxKind;
+
+pub(crate) fn lex_str_block_test(lex: &mut Lexer<'_, SyntaxKind>) {
+ let _ = lex_str_block(lex);
+}
+
+pub(crate) struct Context<'a> {
+ source: &'a str,
+ index: usize,
+}
+
+impl<'a> Context<'a> {
+ fn rest(&self) -> &'a str {
+ &self.source[self.index..]
+ }
+
+ fn next(&mut self) -> Option<char> {
+ if self.index == self.source.len() {
+ return None;
+ }
+
+ match self.rest().chars().next() {
+ None => None,
+ Some(c) => {
+ self.index += c.len_utf8();
+ Some(c)
+ }
+ }
+ }
+
+ fn peek(&self) -> Option<char> {
+ if self.index == self.source.len() {
+ return None;
+ }
+
+ self.rest().chars().next()
+ }
+
+ fn eat_if(&mut self, f: impl Fn(char) -> bool) -> usize {
+ if self.peek().is_some_and(f) {
+ self.index += 1;
+ return 1;
+ }
+ 0
+ }
+
+ fn eat_while(&mut self, f: impl Fn(char) -> bool) -> usize {
+ if self.index == self.source.len() {
+ return 0;
+ }
+
+ let next_char = self.rest().char_indices().find(|(_, c)| !f(*c));
+
+ match next_char {
+ None => {
+ let diff = self.source.len() - self.index;
+ self.index = self.source.len();
+ diff
+ }
+ Some((idx, _)) => {
+ self.index += idx;
+ idx
+ }
+ }
+ }
+
+ fn skip(&mut self, len: usize) {
+ self.index = match self.index + len {
+ n if n > self.source.len() => self.source.len(),
+ n => n,
+ };
+ }
+}
+
+// Check that b has at least the same whitespace prefix as a and returns the
+// amount of this whitespace, otherwise returns 0. If a has no whitespace
+// prefix than return 0.
+fn check_whitespace(a: &str, b: &str) -> usize {
+ let a = a.as_bytes();
+ let b = b.as_bytes();
+
+ for i in 0..a.len() {
+ if a[i] != b' ' && a[i] != b'\t' {
+ // a has run out of whitespace and b matched up to this point. Return result.
+ return i;
+ }
+
+ if i >= b.len() {
+ // We ran off the edge of b while a still has whitespace. Return 0 as failure.
+ return 0;
+ }
+
+ if a[i] != b[i] {
+ // a has whitespace but b does not. Return 0 as failure.
+ return 0;
+ }
+ }
+
+ // We ran off the end of a and b kept up
+ a.len()
+}
+
+pub(crate) trait StrBlockLexCtx<'d> {
+ fn remainder(&self) -> &'d str;
+ fn eat_error(&mut self, ctx: &Context<'d>);
+ fn bump_pos(&mut self, s: usize);
+ fn mark_truncating(&mut self);
+ fn mark_line(&mut self, line: &'d str);
+}
+
+impl<'d> StrBlockLexCtx<'d> for Lexer<'d, SyntaxKind> {
+ fn remainder(&self) -> &'d str {
+ self.remainder()
+ }
+ fn eat_error(&mut self, ctx: &Context<'d>) {
+ let end_index = ctx
+ .rest()
+ .find("|||")
+ .map_or_else(|| ctx.rest().len(), |v| v + 3);
+ self.bump(ctx.index + end_index);
+ }
+ fn bump_pos(&mut self, s: usize) {
+ self.bump(s);
+ }
+ fn mark_truncating(&mut self) {
+ // Lexer test doesn't collect anything
+ }
+ fn mark_line(&mut self, _line: &'d str) {
+ // Lexer test doesn't collect anything
+ }
+}
+
+pub fn collect_lexed_str_block(input: &str) -> Result<CollectStrBlock<'_>, StringBlockError> {
+ let mut collect = CollectStrBlock {
+ truncate: false,
+ lines: vec![],
+ input,
+ offset: 0,
+ };
+ lex_str_block(&mut collect)?;
+ Ok(collect)
+}
+
+pub struct CollectStrBlock<'s> {
+ pub truncate: bool,
+ pub lines: Vec<&'s str>,
+ input: &'s str,
+ offset: usize,
+}
+
+impl<'d> StrBlockLexCtx<'d> for CollectStrBlock<'d> {
+ fn remainder(&self) -> &'d str {
+ self.input
+ }
+
+ fn eat_error(&mut self, _ctx: &Context<'d>) {
+ // Error will be returned, no need to record it here
+ }
+
+ fn bump_pos(&mut self, s: usize) {
+ self.offset += s;
+ }
+
+ fn mark_truncating(&mut self) {
+ self.truncate = true;
+ }
+
+ fn mark_line(&mut self, line: &'d str) {
+ self.lines.push(line);
+ }
+}
+
+pub(crate) fn lex_str_block<'a>(lex: &mut impl StrBlockLexCtx<'a>) -> Result<(), StringBlockError> {
+ // debug_assert_eq!(lex.slice(), "|||");
+ let mut ctx = Context::<'a> {
+ source: lex.remainder(),
+ index: 0,
+ };
+
+ if ctx.eat_if(|v| v == '-') != 0 {
+ lex.mark_truncating();
+ }
+
+ // Skip whitespaces
+ ctx.eat_while(|r| r == ' ' || r == '\t' || r == '\r');
+
+ // Skip \n
+ match ctx.next() {
+ Some('\n') => (),
+ None => {
+ lex.eat_error(&ctx);
+ return Err(UnexpectedEnd);
+ }
+ // Text block requires new line after |||.
+ Some(_) => {
+ lex.eat_error(&ctx);
+ return Err(MissingNewLine);
+ }
+ }
+
+ // Process leading blank lines before calculating string block indent
+ while ctx.peek() == Some('\n') {
+ ctx.next();
+ }
+
+ let mut num_whitespace = check_whitespace(ctx.rest(), ctx.rest());
+ let str_block_indent = &ctx.rest()[..num_whitespace];
+
+ if num_whitespace == 0 {
+ // Text block's first line must start with whitespace
+ lex.eat_error(&ctx);
+ return Err(MissingIndent);
+ }
+
+ loop {
+ debug_assert_ne!(num_whitespace, 0, "Unexpected value for num_whitespace");
+ ctx.skip(num_whitespace);
+
+ let line_start = ctx.index;
+ let mut line_size = 0;
+ loop {
+ match ctx.next() {
+ None => {
+ lex.eat_error(&ctx);
+ return Err(UnexpectedEnd);
+ }
+ Some('\n') => {
+ lex.mark_line(&ctx.source[line_start..line_start + line_size]);
+ break;
+ }
+ Some(c) => {
+ line_size += c.len_utf8();
+ }
+ }
+ }
+
+ // Skip any blank lines
+ while ctx.peek() == Some('\n') {
+ lex.mark_line("");
+ ctx.next();
+ }
+
+ // Look at the next line
+ num_whitespace = check_whitespace(str_block_indent, ctx.rest());
+ if num_whitespace == 0 {
+ // End of the text block
+ // let mut term_indent = String::with_capacity(num_whitespace);
+ while let Some(' ' | '\t') = ctx.peek() {
+ // term_indent.push(
+ ctx.next().unwrap();
+ // );
+ }
+
+ if !ctx.rest().starts_with("|||") {
+ if ctx.rest().is_empty() {
+ lex.bump_pos(ctx.index);
+ return Err(UnexpectedEnd);
+ }
+ lex.eat_error(&ctx);
+ return Err(MissingTermination);
+ }
+
+ // Skip '|||'
+ ctx.skip(3);
+ break;
+ }
+ }
+
+ lex.bump_pos(ctx.index);
+ Ok(())
+}
crates/jrsonnet-rowan-parser/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/Cargo.toml
+++ b/crates/jrsonnet-rowan-parser/Cargo.toml
@@ -14,7 +14,7 @@
drop_bomb.workspace = true
hi-doc.workspace = true
indoc.workspace = true
-logos.workspace = true
+jrsonnet-lexer = { version = "0.5.0-pre97", path = "../jrsonnet-lexer" }
rowan.workspace = true
thiserror.workspace = true
crates/jrsonnet-rowan-parser/src/generated/syntax_kinds.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/generated/syntax_kinds.rs
+++ b/crates/jrsonnet-rowan-parser/src/generated/syntax_kinds.rs
@@ -8,172 +8,95 @@
clippy::manual_non_exhaustive,
clippy::match_like_matches_macro
)]
-use logos::Logos;
#[doc = r" The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT`."]
-#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Logos)]
+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(u16)]
pub enum SyntaxKind {
#[doc(hidden)]
TOMBSTONE,
#[doc(hidden)]
EOF,
- #[token("||")]
OR,
- #[token("??")]
NULL_COAELSE,
- #[token("&&")]
AND,
- #[token("|")]
BIT_OR,
- #[token("^")]
BIT_XOR,
- #[token("&")]
BIT_AND,
- #[token("==")]
EQ,
- #[token("!=")]
NE,
- #[token("<")]
LT,
- #[token(">")]
GT,
- #[token("<=")]
LE,
- #[token(">=")]
GE,
- #[token("<<")]
LHS,
- #[token(">>")]
RHS,
- #[token("+")]
PLUS,
- #[token("-")]
MINUS,
- #[token("*")]
MUL,
- #[token("/")]
DIV,
- #[token("%")]
MODULO,
- #[token("!")]
NOT,
- #[token("~")]
BIT_NOT,
- #[token("[")]
L_BRACK,
- #[token("]")]
R_BRACK,
- #[token("(")]
L_PAREN,
- #[token(")")]
R_PAREN,
- #[token("{")]
L_BRACE,
- #[token("}")]
R_BRACE,
- #[token(":")]
COLON,
- #[token("::")]
COLONCOLON,
- #[token(":::")]
COLONCOLONCOLON,
- #[token(";")]
SEMI,
- #[token(".")]
DOT,
- #[token("...")]
DOTDOTDOT,
- #[token(",")]
COMMA,
- #[token("$")]
DOLLAR,
- #[token("=")]
ASSIGN,
- #[token("?")]
QUESTION_MARK,
- #[regex("(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")]
FLOAT,
- #[regex("(?:0|[1-9][0-9]*)\\.[^0-9]")]
ERROR_FLOAT_JUNK_AFTER_POINT,
- #[regex("(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?[eE][^+\\-0-9]")]
ERROR_FLOAT_JUNK_AFTER_EXPONENT,
- #[regex("(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?[eE][+-][^0-9]")]
ERROR_FLOAT_JUNK_AFTER_EXPONENT_SIGN,
- #[regex("\"(?s:[^\"\\\\]|\\\\.)*\"")]
STRING_DOUBLE,
- #[regex("\"(?s:[^\"\\\\]|\\\\.)*")]
ERROR_STRING_DOUBLE_UNTERMINATED,
- #[regex("'(?s:[^'\\\\]|\\\\.)*'")]
STRING_SINGLE,
- #[regex("'(?s:[^'\\\\]|\\\\.)*")]
ERROR_STRING_SINGLE_UNTERMINATED,
- #[regex("@\"(?:[^\"]|\"\")*\"")]
STRING_DOUBLE_VERBATIM,
- #[regex("@\"(?:[^\"]|\"\")*")]
ERROR_STRING_DOUBLE_VERBATIM_UNTERMINATED,
- #[regex("@'(?:[^']|'')*'")]
STRING_SINGLE_VERBATIM,
- #[regex("@'(?:[^']|'')*")]
ERROR_STRING_SINGLE_VERBATIM_UNTERMINATED,
- #[regex("@[^\"'\\s]\\S+")]
ERROR_STRING_VERBATIM_MISSING_QUOTES,
- #[regex("\\|\\|\\|", crate::string_block::lex_str_block_test)]
STRING_BLOCK,
ERROR_STRING_BLOCK_UNEXPECTED_END,
ERROR_STRING_BLOCK_MISSING_NEW_LINE,
ERROR_STRING_BLOCK_MISSING_TERMINATION,
ERROR_STRING_BLOCK_MISSING_INDENT,
- #[regex("[_a-zA-Z][_a-zA-Z0-9]*")]
IDENT,
- #[regex("[ \\t\\n\\r]+")]
WHITESPACE,
- #[regex("//[^\\r\\n]*?(\\r\\n|\\n)?")]
SINGLE_LINE_SLASH_COMMENT,
- #[regex("#[^\\r\\n]*?(\\r\\n|\\n)?")]
SINGLE_LINE_HASH_COMMENT,
- #[regex("/\\*([^*]|\\*[^/])*\\*/")]
MULTI_LINE_COMMENT,
- #[regex("/\\*/")]
ERROR_COMMENT_TOO_SHORT,
- #[regex("/\\*([^*/]|\\*[^/])+")]
ERROR_COMMENT_UNTERMINATED,
- #[token("tailstrict")]
TAILSTRICT_KW,
- #[token("local")]
LOCAL_KW,
- #[token("importstr")]
IMPORTSTR_KW,
- #[token("importbin")]
IMPORTBIN_KW,
- #[token("import")]
IMPORT_KW,
- #[token("if")]
IF_KW,
- #[token("then")]
THEN_KW,
- #[token("else")]
ELSE_KW,
- #[token("function")]
FUNCTION_KW,
- #[token("error")]
ERROR_KW,
- #[token("in")]
IN_KW,
META_OBJECT_APPLY,
ERROR_NO_OPERATOR,
- #[token("null")]
NULL_KW,
- #[token("true")]
TRUE_KW,
- #[token("false")]
FALSE_KW,
- #[token("self")]
SELF_KW,
- #[token("super")]
SUPER_KW,
- #[token("for")]
FOR_KW,
- #[token("assert")]
ASSERT_KW,
ERROR_MISSING_TOKEN,
ERROR_UNEXPECTED_TOKEN,
crates/jrsonnet-rowan-parser/src/lex.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/lex.rs
+++ b/crates/jrsonnet-rowan-parser/src/lex.rs
@@ -1,81 +1,19 @@
-use core::ops::Range;
-use std::convert::TryFrom;
-
-use logos::Logos;
+use jrsonnet_lexer::Lexer;
use rowan::{TextRange, TextSize};
-use crate::{
- string_block::{lex_str_block, StringBlockError},
- SyntaxKind,
-};
-
-pub struct Lexer<'a> {
- inner: logos::Lexer<'a, SyntaxKind>,
-}
-
-impl<'a> Lexer<'a> {
- pub fn new(input: &'a str) -> Self {
- Self {
- inner: SyntaxKind::lexer(input),
- }
- }
-}
-
-impl<'a> Iterator for Lexer<'a> {
- type Item = Lexeme<'a>;
-
- fn next(&mut self) -> Option<Self::Item> {
- use SyntaxKind::*;
-
- let mut kind = self.inner.next()?;
- let text = self.inner.slice();
-
- if kind == Ok(STRING_BLOCK) {
- // We use custom lexer, which skips enough bytes, but not returns error
- // Instead we should call lexer again to verify if there is something wrong with string block
- let mut lexer = logos::Lexer::<SyntaxKind>::new(text);
- // In kinds, string blocks is parsed at least as `|||`
- lexer.bump(3);
- let res = lex_str_block(&mut lexer);
- let next = lexer.next();
- assert!(next.is_none(), "str_block is lexed");
- match res {
- Ok(()) => {}
- Err(e) => {
- kind = Ok(match e {
- StringBlockError::UnexpectedEnd => ERROR_STRING_BLOCK_UNEXPECTED_END,
- StringBlockError::MissingNewLine => ERROR_STRING_BLOCK_MISSING_NEW_LINE,
- StringBlockError::MissingTermination => {
- ERROR_STRING_BLOCK_MISSING_TERMINATION
- }
- StringBlockError::MissingIndent => ERROR_STRING_BLOCK_MISSING_INDENT,
- });
- }
- }
- }
-
- Some(Self::Item {
- kind: kind.unwrap_or(SyntaxKind::LEXING_ERROR),
- text,
- range: {
- let Range { start, end } = self.inner.span();
-
- TextRange::new(
- TextSize::try_from(start).unwrap(),
- TextSize::try_from(end).unwrap(),
- )
- },
- })
- }
-}
+use crate::SyntaxKind;
#[derive(Clone, Copy, Debug)]
-pub struct Lexeme<'i> {
+pub struct Lexeme<'s> {
pub kind: SyntaxKind,
- pub text: &'i str,
+ pub text: &'s str,
pub range: TextRange,
}
pub fn lex(input: &str) -> Vec<Lexeme<'_>> {
- Lexer::new(input).collect()
+ Lexer::new(input).map(|l| Lexeme {
+ kind: SyntaxKind::from_raw(l.kind.into_raw()),
+ text: l.text,
+ range: TextRange::new(TextSize::from(l.range.0), TextSize::from(l.range.1)),
+ }).collect()
}
crates/jrsonnet-rowan-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/lib.rs
+++ b/crates/jrsonnet-rowan-parser/src/lib.rs
@@ -2,7 +2,6 @@
use event::Sink;
use generated::nodes::{SourceFile, Trivia};
-use lex::lex;
use parser::{LocatedSyntaxError, Parser};
pub use rowan;
@@ -14,14 +13,12 @@
mod marker;
mod parser;
mod precedence;
-mod string_block;
mod tests;
mod token_set;
pub use ast::{AstChildren, AstNode, AstToken};
pub use generated::{nodes, syntax_kinds::SyntaxKind};
pub use language::*;
-pub use string_block::{collect_lexed_str_block, CollectStrBlock};
pub use token_set::SyntaxKindSet;
use self::{
@@ -30,7 +27,7 @@
};
pub fn parse(input: &str) -> (SourceFile, Vec<LocatedSyntaxError>) {
- let lexemes = lex(input);
+ let lexemes = lex::lex(input);
let kinds = lexemes
.iter()
.map(|l| l.kind)
crates/jrsonnet-rowan-parser/src/string_block.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/string_block.rs
+++ /dev/null
@@ -1,282 +0,0 @@
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum StringBlockError {
- UnexpectedEnd,
- MissingNewLine,
- MissingTermination,
- MissingIndent,
-}
-
-use logos::Lexer;
-use StringBlockError::*;
-
-use crate::SyntaxKind;
-
-pub(crate) fn lex_str_block_test(lex: &mut Lexer<'_, SyntaxKind>) {
- let _ = lex_str_block(lex);
-}
-
-pub(crate) struct Context<'a> {
- source: &'a str,
- index: usize,
-}
-
-impl<'a> Context<'a> {
- fn rest(&self) -> &'a str {
- &self.source[self.index..]
- }
-
- fn next(&mut self) -> Option<char> {
- if self.index == self.source.len() {
- return None;
- }
-
- match self.rest().chars().next() {
- None => None,
- Some(c) => {
- self.index += c.len_utf8();
- Some(c)
- }
- }
- }
-
- fn peek(&self) -> Option<char> {
- if self.index == self.source.len() {
- return None;
- }
-
- self.rest().chars().next()
- }
-
- fn eat_if(&mut self, f: impl Fn(char) -> bool) -> usize {
- if self.peek().is_some_and(f) {
- self.index += 1;
- return 1;
- }
- 0
- }
-
- fn eat_while(&mut self, f: impl Fn(char) -> bool) -> usize {
- if self.index == self.source.len() {
- return 0;
- }
-
- let next_char = self.rest().char_indices().find(|(_, c)| !f(*c));
-
- match next_char {
- None => {
- let diff = self.source.len() - self.index;
- self.index = self.source.len();
- diff
- }
- Some((idx, _)) => {
- self.index += idx;
- idx
- }
- }
- }
-
- fn skip(&mut self, len: usize) {
- self.index = match self.index + len {
- n if n > self.source.len() => self.source.len(),
- n => n,
- };
- }
-}
-
-// Check that b has at least the same whitespace prefix as a and returns the
-// amount of this whitespace, otherwise returns 0. If a has no whitespace
-// prefix than return 0.
-fn check_whitespace(a: &str, b: &str) -> usize {
- let a = a.as_bytes();
- let b = b.as_bytes();
-
- for i in 0..a.len() {
- if a[i] != b' ' && a[i] != b'\t' {
- // a has run out of whitespace and b matched up to this point. Return result.
- return i;
- }
-
- if i >= b.len() {
- // We ran off the edge of b while a still has whitespace. Return 0 as failure.
- return 0;
- }
-
- if a[i] != b[i] {
- // a has whitespace but b does not. Return 0 as failure.
- return 0;
- }
- }
-
- // We ran off the end of a and b kept up
- a.len()
-}
-
-pub(crate) trait StrBlockLexCtx<'d> {
- fn remainder(&self) -> &'d str;
- fn eat_error(&mut self, ctx: &Context<'d>);
- fn bump_pos(&mut self, s: usize);
- fn mark_truncating(&mut self);
- fn mark_line(&mut self, line: &'d str);
-}
-
-impl<'d> StrBlockLexCtx<'d> for Lexer<'d, SyntaxKind> {
- fn remainder(&self) -> &'d str {
- self.remainder()
- }
- fn eat_error(&mut self, ctx: &Context<'d>) {
- let end_index = ctx
- .rest()
- .find("|||")
- .map_or_else(|| ctx.rest().len(), |v| v + 3);
- self.bump(ctx.index + end_index);
- }
- fn bump_pos(&mut self, s: usize) {
- self.bump(s);
- }
- fn mark_truncating(&mut self) {
- // Lexer test doesn't collect anything
- }
- fn mark_line(&mut self, _line: &'d str) {
- // Lexer test doesn't collect anything
- }
-}
-
-pub fn collect_lexed_str_block(input: &str) -> Result<CollectStrBlock<'_>, StringBlockError> {
- let mut collect = CollectStrBlock {
- truncate: false,
- lines: vec![],
- input,
- offset: 0,
- };
- lex_str_block(&mut collect)?;
- Ok(collect)
-}
-
-pub struct CollectStrBlock<'s> {
- pub truncate: bool,
- pub lines: Vec<&'s str>,
- input: &'s str,
- offset: usize,
-}
-
-impl<'d> StrBlockLexCtx<'d> for CollectStrBlock<'d> {
- fn remainder(&self) -> &'d str {
- self.input
- }
-
- fn eat_error(&mut self, _ctx: &Context<'d>) {
- // Error will be returned, no need to record it here
- }
-
- fn bump_pos(&mut self, s: usize) {
- self.offset += s;
- }
-
- fn mark_truncating(&mut self) {
- self.truncate = true;
- }
-
- fn mark_line(&mut self, line: &'d str) {
- self.lines.push(line);
- }
-}
-
-pub(crate) fn lex_str_block<'a>(lex: &mut impl StrBlockLexCtx<'a>) -> Result<(), StringBlockError> {
- // debug_assert_eq!(lex.slice(), "|||");
- let mut ctx = Context::<'a> {
- source: lex.remainder(),
- index: 0,
- };
-
- if ctx.eat_if(|v| v == '-') != 0 {
- lex.mark_truncating();
- }
-
- // Skip whitespaces
- ctx.eat_while(|r| r == ' ' || r == '\t' || r == '\r');
-
- // Skip \n
- match ctx.next() {
- Some('\n') => (),
- None => {
- lex.eat_error(&ctx);
- return Err(UnexpectedEnd);
- }
- // Text block requires new line after |||.
- Some(_) => {
- lex.eat_error(&ctx);
- return Err(MissingNewLine);
- }
- }
-
- // Process leading blank lines before calculating string block indent
- while ctx.peek() == Some('\n') {
- ctx.next();
- }
-
- let mut num_whitespace = check_whitespace(ctx.rest(), ctx.rest());
- let str_block_indent = &ctx.rest()[..num_whitespace];
-
- if num_whitespace == 0 {
- // Text block's first line must start with whitespace
- lex.eat_error(&ctx);
- return Err(MissingIndent);
- }
-
- loop {
- debug_assert_ne!(num_whitespace, 0, "Unexpected value for num_whitespace");
- ctx.skip(num_whitespace);
-
- let line_start = ctx.index;
- let mut line_size = 0;
- loop {
- match ctx.next() {
- None => {
- lex.eat_error(&ctx);
- return Err(UnexpectedEnd);
- }
- Some('\n') => {
- lex.mark_line(&ctx.source[line_start..line_start + line_size]);
- break;
- }
- Some(c) => {
- line_size += c.len_utf8();
- }
- }
- }
-
- // Skip any blank lines
- while ctx.peek() == Some('\n') {
- lex.mark_line("");
- ctx.next();
- }
-
- // Look at the next line
- num_whitespace = check_whitespace(str_block_indent, ctx.rest());
- if num_whitespace == 0 {
- // End of the text block
- // let mut term_indent = String::with_capacity(num_whitespace);
- while let Some(' ' | '\t') = ctx.peek() {
- // term_indent.push(
- ctx.next().unwrap();
- // );
- }
-
- if !ctx.rest().starts_with("|||") {
- if ctx.rest().is_empty() {
- lex.bump_pos(ctx.index);
- return Err(UnexpectedEnd);
- }
- lex.eat_error(&ctx);
- return Err(MissingTermination);
- }
-
- // Skip '|||'
- ctx.skip(3);
- break;
- }
- }
-
- lex.bump_pos(ctx.index);
- Ok(())
-}
xtask/src/sourcegen/kinds.rsdiffbeforeafterboth--- a/xtask/src/sourcegen/kinds.rs
+++ b/xtask/src/sourcegen/kinds.rs
@@ -56,7 +56,7 @@
| Self::Error { name, .. } => name,
}
}
- pub fn expand_kind(&self) -> TokenStream {
+ pub fn expand_kind(&self, lexer: bool) -> TokenStream {
let name = format_ident!("{}", self.name());
let attr = match self {
Self::Keyword { code, .. } => quote! {#[token(#code)]},
@@ -75,6 +75,11 @@
}
_ => quote! {},
};
+ let attr = if lexer {
+ attr
+ } else {
+ quote! {}
+ };
quote! {
#attr
#name
xtask/src/sourcegen/mod.rsdiffbeforeafterboth1use std::{collections::HashMap, path::PathBuf};23use anyhow::Result;4use ast::{lower, AstSrc};5use itertools::Itertools;6use kinds::{KindsSrc, TokenKind};7use proc_macro2::{Ident, Punct, Spacing, Span, TokenStream};8use quote::{format_ident, quote};9use ungrammar::Grammar;10use util::{ensure_file_contents, reformat, to_pascal_case, to_upper_snake_case};1112mod ast;13mod kinds;14mod util;1516enum SpecialName {17 Literal,18 Meta,19 Error,20}21fn classify_special(name: &str) -> Option<(SpecialName, &str)> {22 let name = name.strip_suffix('!')?;23 Some(if let Some(name) = name.strip_prefix("LIT_") {24 (SpecialName::Literal, name)25 } else if let Some(name) = name.strip_prefix("META_") {26 (SpecialName::Meta, name)27 } else if let Some(name) = name.strip_prefix("ERROR_") {28 (SpecialName::Error, name)29 } else {30 return None;31 })32}3334pub fn generate_ungrammar() -> Result<()> {35 let grammar: Grammar = include_str!(concat!(36 env!("CARGO_MANIFEST_DIR"),37 "/../crates/jrsonnet-rowan-parser/jsonnet.ungram"38 ))39 .parse()?;4041 let mut kinds = kinds::jsonnet_kinds();42 let ast = lower(&kinds, &grammar);4344 for token in grammar.tokens() {45 let token = &grammar[token];46 let token = &token.name.clone();47 if !kinds.is_token(token) {48 if let Some((special, name)) = classify_special(token) {49 match special {50 SpecialName::Literal => panic!("literal is not defined: {name}"),51 SpecialName::Meta => {52 eprintln!("implicit meta: {name}");53 kinds.define_token(TokenKind::Meta {54 grammar_name: token.to_owned(),55 name: format!("META_{name}"),56 });57 }58 SpecialName::Error => {59 eprintln!("implicit error: {name}");60 kinds.define_token(TokenKind::Error {61 grammar_name: token.to_owned(),62 name: format!("ERROR_{name}"),63 regex: None,64 priority: None,65 is_lexer_error: true,66 });67 }68 }69 continue;70 }71 let name = to_upper_snake_case(token);72 eprintln!("implicit kw: {token}");73 kinds.define_token(TokenKind::Keyword {74 code: token.to_owned(),75 name: format!("{name}_KW"),76 });77 }78 }79 for node in &ast.nodes {80 let name = to_upper_snake_case(&node.name);81 kinds.define_node(&name);82 }83 for enum_ in &ast.enums {84 let name = to_upper_snake_case(&enum_.name);85 kinds.define_node(&name);86 }87 for token_enum in &ast.token_enums {88 let name = to_upper_snake_case(&token_enum.name);89 kinds.define_node(&name);90 }9192 let syntax_kinds = generate_syntax_kinds(&kinds, &ast)?;9394 let nodes = generate_nodes(&kinds, &ast)?;95 ensure_file_contents(96 &PathBuf::from(concat!(97 env!("CARGO_MANIFEST_DIR"),98 "/../crates/jrsonnet-rowan-parser/src/generated/syntax_kinds.rs",99 )),100 &syntax_kinds,101 );102 ensure_file_contents(103 &PathBuf::from(concat!(104 env!("CARGO_MANIFEST_DIR"),105 "/../crates/jrsonnet-rowan-parser/src/generated/nodes.rs",106 )),107 &nodes,108 );109 Ok(())110}111112fn generate_syntax_kinds(kinds: &KindsSrc, grammar: &AstSrc) -> Result<String> {113 let t_macros = kinds.tokens().filter_map(TokenKind::expand_t_macros);114 let token_kinds = kinds.tokens().map(TokenKind::expand_kind);115116 let keywords = kinds117 .tokens()118 .filter(|k| matches!(k, TokenKind::Keyword { .. }))119 .map(TokenKind::name)120 .map(|n| format_ident!("{n}"));121122 let nodes = kinds123 .nodes124 .iter()125 .map(|name| format_ident!("{}", name))126 .collect::<Vec<_>>();127128 let enums = grammar129 .enums130 .iter()131 .map(|e| format_ident!("{}", to_upper_snake_case(&e.name)))132 .chain(133 grammar134 .token_enums135 .iter()136 .map(|e| format_ident!("{}", to_upper_snake_case(&e.name))),137 );138139 let ast = quote! {140 #![allow(bad_style, missing_docs, unreachable_pub, clippy::manual_non_exhaustive, clippy::match_like_matches_macro)]141 use logos::Logos;142143 /// The kind of syntax node, e.g. `IDENT`, `USE_KW`, or `STRUCT`.144 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Logos)]145 #[repr(u16)]146 pub enum SyntaxKind {147 #[doc(hidden)]148 TOMBSTONE,149 #[doc(hidden)]150 EOF,151 #(#token_kinds,)*152 LEXING_ERROR,153 __LAST_TOKEN,154 #(#nodes,)*155 #[doc(hidden)]156 __LAST,157 }158 use self::SyntaxKind::*;159160 impl SyntaxKind {161 pub fn is_keyword(self) -> bool {162 match self {163 #(#keywords)|* => true,164 _ => false,165 }166 }167 pub fn is_enum(self) -> bool {168 match self {169 #(#enums)|* => true,170 _ => false,171 }172 }173174 pub fn from_raw(r: u16) -> Self {175 assert!(r < Self::__LAST as u16);176 unsafe { std::mem::transmute(r) }177 }178 pub fn into_raw(self) -> u16 {179 self as u16180 }181 }182183 #[macro_export]184 macro_rules! T {#(#t_macros);*}185 #[allow(unused_imports)]186 pub use T;187 };188189 reformat(&ast.to_string())190}191192#[allow(clippy::too_many_lines, clippy::cognitive_complexity)]193fn generate_nodes(kinds: &KindsSrc, grammar: &AstSrc) -> Result<String> {194 let (node_defs, node_boilerplate_impls): (Vec<_>, Vec<_>) = grammar195 .nodes196 .iter()197 .map(|node| {198 let name = format_ident!("{}", node.name);199 let kind = format_ident!("{}", to_upper_snake_case(&node.name));200 let traits = node.traits.iter().map(|trait_name| {201 let trait_name = format_ident!("{}", trait_name);202 quote!(impl ast::#trait_name for #name {})203 });204205 let mut type_positions: HashMap<String, usize> = HashMap::new();206 let field_positions: Vec<_> = node207 .fields208 .iter()209 .map(|field| {210 let ty_str = field.ty().to_string();211 let pos = *type_positions.get(&ty_str).unwrap_or(&0);212 type_positions.insert(ty_str, pos + 1);213 pos214 })215 .collect();216217 let methods = node218 .fields219 .iter()220 .zip(field_positions.iter())221 .map(|(field, &pos)| {222 let method_name = field.method_name(kinds);223 let ty = field.ty();224225 if field.is_many() {226 quote! {227 pub fn #method_name(&self) -> AstChildren<#ty> {228 support::children(&self.syntax)229 }230 }231 } else if let Some(token_kind) = field.token_kind(kinds) {232 quote! {233 pub fn #method_name(&self) -> Option<#ty> {234 support::token(&self.syntax, #token_kind)235 }236 }237 } else if field.is_token_enum(grammar) {238 quote! {239 pub fn #method_name(&self) -> Option<#ty> {240 support::token_child(&self.syntax)241 }242 }243 } else if pos == 0 {244 quote! {245 pub fn #method_name(&self) -> Option<#ty> {246 support::children(&self.syntax).next()247 }248 }249 } else {250 quote! {251 pub fn #method_name(&self) -> Option<#ty> {252 support::children(&self.syntax).nth(#pos)253 }254 }255 }256 });257 (258 quote! {259 #[pretty_doc_comment_placeholder_workaround]260 #[derive(Debug, Clone, PartialEq, Eq, Hash)]261 pub struct #name {262 pub(crate) syntax: SyntaxNode,263 }264265 #(#traits)*266267 impl #name {268 #(#methods)*269 }270 },271 quote! {272 impl AstNode for #name {273 fn can_cast(kind: SyntaxKind) -> bool {274 kind == #kind275 }276 fn cast(syntax: SyntaxNode) -> Option<Self> {277 if Self::can_cast(syntax.kind()) { Some(Self { syntax }) } else { None }278 }279 fn syntax(&self) -> &SyntaxNode { &self.syntax }280 }281 },282 )283 })284 .unzip();285286 let (enum_defs, enum_boilerplate_impls): (Vec<_>, Vec<_>) = grammar287 .enums288 .iter()289 .map(|en| {290 let variants: Vec<_> = en291 .variants292 .iter()293 .map(|var| format_ident!("{}", var))294 .collect();295 let name = format_ident!("{}", en.name);296 let kinds: Vec<_> = variants297 .iter()298 .map(|name| format_ident!("{}", to_upper_snake_case(&name.to_string())))299 .collect();300 let traits = en.traits.iter().map(|trait_name| {301 let trait_name = format_ident!("{}", trait_name);302 quote!(impl ast::#trait_name for #name {})303 });304305 let ast_node = quote! {306 impl AstNode for #name {307 fn can_cast(kind: SyntaxKind) -> bool {308 match kind {309 #(#kinds)|* => true,310 _ => false,311 }312 }313 fn cast(syntax: SyntaxNode) -> Option<Self> {314 let res = match syntax.kind() {315 #(316 #kinds => #name::#variants(#variants { syntax }),317 )*318 _ => return None,319 };320 Some(res)321 }322 fn syntax(&self) -> &SyntaxNode {323 match self {324 #(325 #name::#variants(it) => &it.syntax,326 )*327 }328 }329 }330 };331332 (333 quote! {334 #[pretty_doc_comment_placeholder_workaround]335 #[derive(Debug, Clone, PartialEq, Eq, Hash)]336 pub enum #name {337 #(#variants(#variants),)*338 }339340 #(#traits)*341 },342 quote! {343 #(344 impl From<#variants> for #name {345 fn from(node: #variants) -> #name {346 #name::#variants(node)347 }348 }349 )*350 #ast_node351 },352 )353 })354 .unzip();355356 let (token_enum_defs, token_enum_boilerplate_impls): (Vec<_>, Vec<_>) = grammar357 .token_enums358 .iter()359 .map(|en| {360 let variants: Vec<_> = en361 .variants362 .iter()363 .map(|token| {364 format_ident!(365 "{}",366 to_pascal_case(kinds.token(token).expect("token exists").name())367 )368 })369 .collect();370 let name = format_ident!("{}", en.name);371 let kind_name = format_ident!("{}Kind", en.name);372 let kinds: Vec<_> = variants373 .iter()374 .map(|name| format_ident!("{}", to_upper_snake_case(&name.to_string())))375 .collect();376377 let ast_node = quote! {378 impl AstToken for #name {379 fn can_cast(kind: SyntaxKind) -> bool {380 #kind_name::can_cast(kind)381 }382 fn cast(syntax: SyntaxToken) -> Option<Self> {383 let kind = #kind_name::cast(syntax.kind())?;384 Some(#name { syntax, kind })385 }386 fn syntax(&self) -> &SyntaxToken {387 &self.syntax388 }389 }390391 impl #kind_name {392 fn can_cast(kind: SyntaxKind) -> bool {393 match kind {394 #(#kinds)|* => true,395 _ => false,396 }397 }398 pub fn cast(kind: SyntaxKind) -> Option<Self> {399 let res = match kind {400 #(#kinds => Self::#variants,)*401 _ => return None,402 };403 Some(res)404 }405 }406 };407408 (409 quote! {410 #[pretty_doc_comment_placeholder_workaround]411 #[derive(Debug, Clone, PartialEq, Eq, Hash)]412 pub struct #name { syntax: SyntaxToken, kind: #kind_name }413414 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]415 pub enum #kind_name {416 #(#variants,)*417 }418 },419 quote! {420 #ast_node421422 impl #name {423 pub fn kind(&self) -> #kind_name {424 self.kind425 }426 }427428 impl std::fmt::Display for #name {429 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {430 std::fmt::Display::fmt(self.syntax(), f)431 }432 }433 },434 )435 })436 .unzip();437438 let (any_node_defs, any_node_boilerplate_impls): (Vec<_>, Vec<_>) = grammar439 .nodes440 .iter()441 .flat_map(|node| node.traits.iter().map(move |t| (t, node)))442 .into_group_map()443 .into_iter()444 .sorted_by_key(|(k, _)| *k)445 .map(|(trait_name, nodes)| {446 let name = format_ident!("Any{}", trait_name);447 let trait_name = format_ident!("{}", trait_name);448 let kinds: Vec<_> = nodes449 .iter()450 .map(|name| format_ident!("{}", to_upper_snake_case(&name.name)))451 .collect();452453 (454 quote! {455 #[pretty_doc_comment_placeholder_workaround]456 #[derive(Debug, Clone, PartialEq, Eq, Hash)]457 pub struct #name {458 pub(crate) syntax: SyntaxNode,459 }460 impl ast::#trait_name for #name {}461 },462 quote! {463 impl #name {464 #[inline]465 pub fn new<T: ast::#trait_name>(node: T) -> #name {466 #name {467 syntax: node.syntax().clone()468 }469 }470 }471 impl AstNode for #name {472 fn can_cast(kind: SyntaxKind) -> bool {473 match kind {474 #(#kinds)|* => true,475 _ => false,476 }477 }478 fn cast(syntax: SyntaxNode) -> Option<Self> {479 Self::can_cast(syntax.kind()).then(|| #name { syntax })480 }481 fn syntax(&self) -> &SyntaxNode {482 &self.syntax483 }484 }485 },486 )487 })488 .unzip();489490 let enum_names = grammar.enums.iter().map(|it| &it.name);491 let node_names = grammar.nodes.iter().map(|it| &it.name);492493 let display_impls = enum_names494 .chain(node_names.clone())495 .map(|it| format_ident!("{}", it))496 .map(|name| {497 quote! {498 impl std::fmt::Display for #name {499 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {500 std::fmt::Display::fmt(self.syntax(), f)501 }502 }503 }504 });505506 let ast = quote! {507 #![allow(non_snake_case, clippy::match_like_matches_macro)]508509 use crate::{510 SyntaxNode, SyntaxToken, SyntaxKind::{self, *},511 ast::{AstNode, AstToken, AstChildren, support},512 T,513 };514515 #(#node_defs)*516 #(#enum_defs)*517 #(#token_enum_defs)*518 #(#any_node_defs)*519 #(#node_boilerplate_impls)*520 #(#enum_boilerplate_impls)*521 #(#token_enum_boilerplate_impls)*522 #(#any_node_boilerplate_impls)*523 #(#display_impls)*524 };525526 let ast = ast.to_string().replace("T ! [", "T![");527528 let mut res = String::with_capacity(ast.len() * 2);529530 let mut docs = grammar531 .nodes532 .iter()533 .map(|it| &it.doc)534 .chain(grammar.enums.iter().map(|it| &it.doc));535536 for chunk in ast.split("# [pretty_doc_comment_placeholder_workaround] ") {537 res.push_str(chunk);538 if let Some(doc) = docs.next() {539 write_doc_comment(doc, &mut res);540 }541 }542543 let res = reformat(&res)?;544 Ok(res.replace("#[derive", "\n#[derive"))545}546547fn write_doc_comment(contents: &[String], dest: &mut String) {548 use std::fmt::Write;549 for line in contents {550 writeln!(dest, "///{line}").unwrap();551 }552}553554pub fn escape_token_macro(token: &str) -> TokenStream {555 if "{}[]()$".contains(token) {556 let c = token.chars().next().unwrap();557 quote! { #c }558 } else if token.contains('$') {559 quote! { #token }560 } else if token.chars().all(|v: char| v.is_ascii_lowercase()) {561 let i = Ident::new(token, Span::call_site());562 quote! { #i }563 } else {564 let cs = token.chars().map(|c| Punct::new(c, Spacing::Joint));565 quote! { #(#cs)* }566 }567}