difftreelog
feat(fmt) basic comment formatting in objects
in: master
21 files changed
.cargo/configdiffbeforeafterboth--- a/.cargo/config
+++ /dev/null
@@ -1,2 +0,0 @@
-[alias]
-xtask = "run --manifest-path ./xtask/Cargo.toml --"
.cargo/config.tomldiffbeforeafterboth--- /dev/null
+++ b/.cargo/config.toml
@@ -0,0 +1,2 @@
+[alias]
+xtask = "run --package xtask --bin xtask --"
cmds/jrsonnet-fmt/Cargo.tomldiffbeforeafterboth--- a/cmds/jrsonnet-fmt/Cargo.toml
+++ b/cmds/jrsonnet-fmt/Cargo.toml
@@ -6,3 +6,5 @@
[dependencies]
dprint-core = "0.58.2"
jrsonnet-rowan-parser = { path = "../../crates/jrsonnet-rowan-parser" }
+insta = "1.15"
+indoc = "1.0"
cmds/jrsonnet-fmt/src/children.rsdiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-fmt/src/children.rs
@@ -0,0 +1,168 @@
+use std::{fmt::Debug, marker::PhantomData, mem};
+
+use jrsonnet_rowan_parser::{
+ nodes::{Trivia, TriviaKind},
+ AstNode, AstToken, SyntaxElement,
+ SyntaxKind::*,
+ SyntaxNode, TS,
+};
+
+pub type ChildTrivia = Vec<Trivia>;
+
+pub struct ChildIterator<I, T> {
+ inner: I,
+ _marker: PhantomData<T>,
+}
+
+pub fn children_between<T: AstNode + Debug>(
+ node: SyntaxNode,
+ start: Option<&SyntaxElement>,
+ end: Option<&SyntaxElement>,
+) -> (Vec<Child<T>>, ChildTrivia) {
+ let mut iter = node.children_with_tokens().peekable();
+ while iter.peek() == start {
+ iter.next();
+ }
+ children(
+ iter.take_while(|i| Some(i) != end),
+ start.is_none() || end.is_none(),
+ )
+}
+
+pub fn should_start_with_newline(tt: &ChildTrivia) -> bool {
+ // First for previous item end
+ count_newlines_before(&tt) >= 2
+}
+
+fn count_newlines_before(tt: &ChildTrivia) -> usize {
+ let mut nl_count = 0;
+ for t in tt {
+ match t.kind() {
+ TriviaKind::Whitespace => {
+ nl_count += t.text().bytes().filter(|b| *b == b'\n').count();
+ }
+ _ => break,
+ }
+ }
+ nl_count
+}
+fn count_newlines_after(tt: &ChildTrivia) -> usize {
+ let mut nl_count = 0;
+ for t in tt.iter().rev() {
+ match t.kind() {
+ TriviaKind::Whitespace => {
+ nl_count += t.text().bytes().filter(|b| *b == b'\n').count();
+ }
+ TriviaKind::SingleLineHashComment => {
+ nl_count += 1;
+ break;
+ }
+ TriviaKind::SingleLineSlashComment => {
+ nl_count += 1;
+ break;
+ }
+ _ => {}
+ }
+ }
+ nl_count
+}
+
+pub fn children<'a, T: AstNode + Debug>(
+ items: impl Iterator<Item = SyntaxElement>,
+ loose: bool,
+) -> (Vec<Child<T>>, ChildTrivia) {
+ let mut out = Vec::new();
+ let mut current_child = None::<Child<T>>;
+ let mut next = ChildTrivia::new();
+ // Previous element ended, do not add more inline comments
+ let mut started_next = false;
+ let mut had_some = false;
+
+ for item in items {
+ if let Some(value) = item.as_node().cloned().and_then(T::cast) {
+ let before_trivia = mem::take(&mut next);
+ let last_child = current_child.replace(Child {
+ newlines_above: if had_some {
+ count_newlines_before(&before_trivia)
+ + current_child
+ .as_ref()
+ .map(|c| count_newlines_after(&c.inline_trivia))
+ .unwrap_or_default()
+ } else {
+ 0
+ },
+ before_trivia,
+ value,
+ inline_trivia: Vec::new(),
+ });
+ if let Some(last_child) = last_child {
+ out.push(last_child)
+ }
+ had_some = true;
+ started_next = false;
+ } else if let Some(trivia) = item.as_token().cloned().and_then(Trivia::cast) {
+ let is_single_line_comment = trivia.kind() == TriviaKind::SingleLineHashComment
+ || trivia.kind() == TriviaKind::SingleLineSlashComment;
+ if started_next
+ || current_child.is_none()
+ || trivia.text().contains('\n') && !is_single_line_comment
+ {
+ next.push(trivia.clone());
+ started_next = true;
+ } else {
+ let cur = current_child.as_mut().expect("checked not none");
+ cur.inline_trivia.push(trivia);
+ if is_single_line_comment {
+ started_next = true;
+ }
+ }
+ had_some = true;
+ } else if loose {
+ if had_some {
+ break;
+ }
+ started_next = true;
+ } else {
+ assert!(
+ TS![, ;].contains(item.kind()) || item.kind() == ERROR,
+ "silently eaten token: {:?}",
+ item.kind()
+ )
+ }
+ }
+
+ if let Some(current_child) = current_child {
+ out.push(current_child);
+ }
+
+ (out, next)
+}
+
+#[derive(Debug)]
+pub struct Child<T> {
+ newlines_above: usize,
+ /// Comment before item, i.e
+ ///
+ /// ```ignore
+ /// // Comment
+ /// item
+ /// ```
+ pub before_trivia: ChildTrivia,
+ pub value: T,
+ /// Comment after line, but located at same line
+ ///
+ /// ```ignore
+ /// item1, // Inline comment
+ /// // Not inline comment
+ /// item2,
+ /// ```
+ pub inline_trivia: ChildTrivia,
+}
+
+impl<T> Child<T> {
+ /// If this child has two newlines above in source code, so it needs to have it in output
+ pub fn needs_newline_above(&self) -> bool {
+ // First line for end of previous item
+ self.newlines_above >= 2
+ }
+}
cmds/jrsonnet-fmt/src/comments.rsdiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-fmt/src/comments.rs
@@ -0,0 +1,159 @@
+use dprint_core::formatting::PrintItems;
+use jrsonnet_rowan_parser::{nodes::TriviaKind, AstToken};
+
+use crate::{children::ChildTrivia, p, pi};
+
+pub enum CommentLocation {
+ /// Above local, field, other things
+ AboveItem,
+ /// After item
+ ItemInline,
+ /// After all items in object
+ EndOfItems,
+}
+
+pub fn format_comments(comments: &ChildTrivia, loc: CommentLocation) -> PrintItems {
+ let mut pi = p!(new:);
+
+ for c in comments {
+ match c.kind() {
+ TriviaKind::Whitespace => {}
+ TriviaKind::MultiLineComment => {
+ let mut text = c
+ .text()
+ .strip_prefix("/*")
+ .expect("ml comment starts with /*")
+ .strip_suffix("*/")
+ .expect("ml comment ends with */");
+ // doc-style comment, /**
+ let doc = if text.starts_with('*') {
+ text = &text[1..];
+ true
+ } else {
+ false
+ };
+ // Is comment starts with text immediatly, i.e /*text
+ let mut immediate_start = true;
+ let mut lines = text
+ .split('\n')
+ .map(|l| l.trim_end())
+ .skip_while(|l| {
+ if l.is_empty() {
+ immediate_start = false;
+ true
+ } else {
+ false
+ }
+ })
+ .collect::<Vec<_>>();
+ while lines.last().map(|l| l.is_empty()).unwrap_or(false) {
+ lines.pop();
+ }
+ if lines.len() == 1 && !doc {
+ p!(pi: str("/* ") str(lines[0].trim()) str(" */") nl)
+ } else if !lines.is_empty() {
+ fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {
+ let offset = a
+ .bytes()
+ .zip(b.bytes())
+ .take_while(|(a, b)| a == b && (a.is_ascii_whitespace() || *a == b'*'))
+ .count();
+ &a[..offset]
+ }
+ // First line is not empty, extract ws prefix of it
+ let mut common_ws_padding = if immediate_start && lines.len() > 1 {
+ common_ws_prefix(lines[1], lines[1])
+ } else {
+ common_ws_prefix(lines[0], lines[0])
+ };
+ for line in lines
+ .iter()
+ .skip(if immediate_start { 2 } else { 1 })
+ .filter(|l| !l.is_empty())
+ {
+ common_ws_padding = common_ws_prefix(common_ws_padding, line);
+ }
+ for line in lines
+ .iter_mut()
+ .skip(if immediate_start { 1 } else { 0 })
+ .filter(|l| !l.is_empty())
+ {
+ *line = line
+ .strip_prefix(common_ws_padding)
+ .expect("all non-empty lines start with this padding");
+ }
+
+ p!(pi: str("/*"));
+ if doc {
+ p!(pi: str("*"));
+ }
+ p!(pi: nl);
+ for mut line in lines {
+ if doc {
+ p!(pi: str(" *"));
+ }
+ if line.is_empty() {
+ p!(pi: nl);
+ } else {
+ if doc {
+ p!(pi: str(" "));
+ }
+ while let Some(new_line) = line.strip_prefix('\t') {
+ if doc {
+ p!(pi: str(" "));
+ } else {
+ p!(pi: tab);
+ }
+ line = new_line;
+ }
+ p!(pi: str(line) nl)
+ }
+ }
+ if doc {
+ p!(pi: str(" "));
+ }
+ p!(pi: str("*/") nl)
+ }
+ }
+ // TODO: Keep common padding for multiple continous lines of single-line comments
+ // I.e
+ // ```
+ // # Line1
+ // # Line2
+ // ```
+ // Should be reformatted as
+ // ```
+ // # Line1
+ // # Line2
+ // ```
+ // But currently comment formatter is not aware of continous comment lines, and reformats it as
+ // ```
+ // # Line1
+ // # Line2
+ // ```
+ TriviaKind::SingleLineHashComment => {
+ if matches!(loc, CommentLocation::ItemInline) {
+ p!(pi: str(" "))
+ }
+ p!(pi: str("# ") str(c.text().strip_prefix('#').expect("hash comment starts with #").trim()));
+ if !matches!(loc, CommentLocation::ItemInline) {
+ p!(pi: nl)
+ }
+ }
+ TriviaKind::SingleLineSlashComment => {
+ if matches!(loc, CommentLocation::ItemInline) {
+ p!(pi: str(" "))
+ }
+ p!(pi: str("// ") str(c.text().strip_prefix("//").expect("comment starts with //").trim()));
+ if !matches!(loc, CommentLocation::ItemInline) {
+ p!(pi: nl)
+ }
+ }
+ // Garbage in - garbage out
+ TriviaKind::ErrorCommentTooShort => p!(pi: str("/*/")),
+ TriviaKind::ErrorCommentUnterminated => p!(pi: str(c.text())),
+ }
+ }
+
+ pi
+}
cmds/jrsonnet-fmt/src/main.rsdiffbeforeafterboth--- a/cmds/jrsonnet-fmt/src/main.rs
+++ b/cmds/jrsonnet-fmt/src/main.rs
@@ -1,6 +1,7 @@
use std::any::type_name;
-use dprint_core::formatting::{PrintItems, PrintOptions, Signal};
+use children::children_between;
+use dprint_core::formatting::{PrintItems, PrintOptions};
use jrsonnet_rowan_parser::{
nodes::{
ArgsDesc, Assertion, BinaryOperator, Bind, CompSpec, Destruct, DestructArrayPart,
@@ -8,9 +9,19 @@
Member, Name, Number, ObjBody, ObjLocal, ParamsDesc, SliceDesc, SourceFile, Text,
UnaryOperator,
},
- AstToken, SyntaxToken,
+ AstNode, AstToken, SyntaxToken,
};
+use crate::{
+ children::should_start_with_newline,
+ comments::{format_comments, CommentLocation},
+};
+
+mod children;
+mod comments;
+#[cfg(test)]
+mod tests;
+
pub trait Printable {
fn print(&self) -> PrintItems;
}
@@ -18,7 +29,7 @@
macro_rules! pi {
(@i; $($t:tt)*) => {{
#[allow(unused_mut)]
- let mut o = PrintItems::new();
+ let mut o = dprint_core::formatting::PrintItems::new();
pi!(@s; o: $($t)*);
o
}};
@@ -27,21 +38,29 @@
pi!(@s; $o: $($t)*);
}};
(@s; $o:ident: nl $($t:tt)*) => {{
- $o.push_signal(Signal::NewLine);
+ $o.push_signal(dprint_core::formatting::Signal::NewLine);
pi!(@s; $o: $($t)*);
}};
+ (@s; $o:ident: tab $($t:tt)*) => {{
+ $o.push_signal(dprint_core::formatting::Signal::Tab);
+ pi!(@s; $o: $($t)*);
+ }};
(@s; $o:ident: >i $($t:tt)*) => {{
- $o.push_signal(Signal::StartIndent);
+ $o.push_signal(dprint_core::formatting::Signal::StartIndent);
pi!(@s; $o: $($t)*);
}};
(@s; $o:ident: <i $($t:tt)*) => {{
- $o.push_signal(Signal::FinishIndent);
+ $o.push_signal(dprint_core::formatting::Signal::FinishIndent);
pi!(@s; $o: $($t)*);
}};
(@s; $o:ident: {$expr:expr} $($t:tt)*) => {{
$o.extend($expr.print());
pi!(@s; $o: $($t)*);
}};
+ (@s; $o:ident: items($expr:expr) $($t:tt)*) => {{
+ $o.extend($expr);
+ pi!(@s; $o: $($t)*);
+ }};
(@s; $o:ident: if ($e:expr)($($then:tt)*) $($t:tt)*) => {{
if $e {
pi!(@s; $o: $($then)*);
@@ -66,6 +85,8 @@
pi!(@s; $o: $($t)*)
};
}
+pub(crate) use p;
+pub(crate) use pi;
impl<P> Printable for Option<P>
where
@@ -266,9 +287,18 @@
match self {
ObjBody::ObjBodyComp(_) => todo!(),
ObjBody::ObjBodyMemberList(l) => {
- let mut pi = p!(new:);
- for mem in l.members() {
- match mem {
+ let mut pi = p!(new: str("{") >i nl);
+ let (children, end_comments) = children_between::<Member>(
+ l.syntax().clone(),
+ l.l_brace_token().map(Into::into).as_ref(),
+ l.r_brace_token().map(Into::into).as_ref(),
+ );
+ for mem in children.into_iter() {
+ if mem.needs_newline_above() {
+ p!(pi: nl);
+ }
+ p!(pi: items(format_comments(&mem.before_trivia, CommentLocation::AboveItem)));
+ match mem.value {
Member::MemberBindStmt(b) => {
p!(pi: {b.obj_local()})
}
@@ -279,8 +309,17 @@
p!(pi: {f.field()})
}
}
- p!(pi: str(",") nl)
+ p!(pi: str(","));
+ p!(pi: items(format_comments(&mem.inline_trivia, CommentLocation::ItemInline)));
+ p!(pi: nl)
}
+
+ // TODO: implement same thing as needs_newline_above, but for end comments
+ if should_start_with_newline(&end_comments) {
+ p!(pi: nl);
+ }
+ p!(pi: items(format_comments(&end_comments, CommentLocation::EndOfItems)));
+ p!(pi: <i str("}"));
pi
}
}
@@ -382,7 +421,7 @@
pi
}
Expr::ExprObject(o) => {
- p!(new: str("{") >i nl {o.obj_body()} <i str("}"))
+ p!(new: {o.obj_body()})
}
Expr::ExprArrayComp(arr) => {
let mut pi = p!(new: str("[") {arr.expr()});
@@ -485,6 +524,47 @@
],
m: a[1::],
m: b[::],
+
+ comments: {
+ _: '',
+ // Plain comment
+ a: '',
+
+ # Plain comment with empty line before
+ b: '',
+ /*Single-line multiline comment
+
+ */
+ c: '',
+
+ /**Single-line multiline doc comment
+
+ */
+ c: '',
+
+ /**multiline doc comment
+ s
+ */
+ c: '',
+
+ /*
+
+ Multi-line
+
+ comment
+ */
+ d: '',
+
+ e: '', // Inline comment
+
+ k: '',
+
+ // Text after everything
+ },
+ comments2: {
+ k: '',
+ // Text after everything, but no newline above
+ },
k: if a == b then
cmds/jrsonnet-fmt/src/snapshots/jrsonnet_fmt__tests__complex_comments_snapshot.snapdiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-fmt/src/snapshots/jrsonnet_fmt__tests__complex_comments_snapshot.snap
@@ -0,0 +1,53 @@
+---
+source: cmds/jrsonnet-fmt/src/tests.rs
+expression: "reformat(indoc!(\"{\n\t\t comments: {\n\t\t\t_: '',\n\t\t\t// Plain comment\n\t\t\ta: '',\n\n\t\t\t# Plain comment with empty line before\n\t\t\tb: '',\n\t\t\t/*Single-line multiline comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Single-line multiline doc comment\n\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/**Multiline doc\n\t\t\tComment\n\t\t\t*/\n\t\t\tc: '',\n\n\t\t\t/*\n\n\tMulti-line\n\n\tcomment\n\t\t\t*/\n\t\t\td: '',\n\n\t\t\te: '', // Inline comment\n\n\t\t\tk: '',\n\n\t\t\t// Text after everything\n\t\t },\n\t\t comments2: {\n\t\t\tk: '',\n\t\t\t// Text after everything, but no newline above\n\t\t },\n spacing: {\n a: '',\n\n b: '',\n },\n noSpacing: {\n a: '',\n b: '',\n },\n }\"))"
+---
+{
+ comments: {
+ _: '',
+ // Plain comment
+ a: '',
+
+ # Plain comment with empty line before
+ b: '',
+ /* Single-line multiline comment */
+ c: '',
+
+ /**
+ * Single-line multiline doc comment
+ */
+ c: '',
+
+ /**
+ * Multiline doc
+ * Comment
+ */
+ c: '',
+
+ /*
+ Multi-line
+
+ comment
+ */
+ d: '',
+
+ e: '', // Inline comment
+
+ k: '',
+
+ // Text after everything
+ },
+ comments2: {
+ k: '',
+ // Text after everything, but no newline above
+ },
+ spacing: {
+ a: '',
+
+ b: '',
+ },
+ noSpacing: {
+ a: '',
+ b: '',
+ },
+}
cmds/jrsonnet-fmt/src/tests.rsdiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-fmt/src/tests.rs
@@ -0,0 +1,124 @@
+use dprint_core::formatting::PrintOptions;
+use indoc::indoc;
+
+use crate::Printable;
+
+fn reformat(input: &str) -> String {
+ let (source, _) = jrsonnet_rowan_parser::parse(input);
+
+ dprint_core::formatting::format(
+ || source.print(),
+ PrintOptions {
+ indent_width: 2,
+ max_width: 100,
+ use_tabs: false,
+ new_line_text: "\n",
+ },
+ )
+}
+
+macro_rules! assert_formatted {
+ ($input:literal, $output:literal) => {
+ let formatted = reformat(indoc!($input));
+ let expected = indoc!($output);
+ if formatted != expected {
+ panic!(
+ "bad formatting, expected\n```\n{formatted}\n```\nto be equal to\n```\n{expected}\n```",
+ )
+ }
+ };
+}
+
+#[test]
+fn padding_stripped_for_multiline_comment() {
+ assert_formatted!(
+ "{
+ /*
+ Hello
+ World
+ */
+ _: null,
+ }",
+ "{
+ /*
+ Hello
+ World
+ */
+ _: null,
+ }"
+ );
+}
+
+// Fails
+#[test]
+fn last_comment_respects_spacing_with_inline_comment_above() {
+ assert_formatted!(
+ "{
+ a: '', // Inline
+
+ // Comment
+ }",
+ "{
+ a: '', // Inline
+
+ // Comment
+ }"
+ );
+}
+
+#[test]
+fn complex_comments_snapshot() {
+ insta::assert_display_snapshot!(reformat(indoc!(
+ "{
+ comments: {
+ _: '',
+ // Plain comment
+ a: '',
+
+ # Plain comment with empty line before
+ b: '',
+ /*Single-line multiline comment
+
+ */
+ c: '',
+
+ /**Single-line multiline doc comment
+
+ */
+ c: '',
+
+ /**Multiline doc
+ Comment
+ */
+ c: '',
+
+ /*
+
+ Multi-line
+
+ comment
+ */
+ d: '',
+
+ e: '', // Inline comment
+
+ k: '',
+
+ // Text after everything
+ },
+ comments2: {
+ k: '',
+ // Text after everything, but no newline above
+ },
+ spacing: {
+ a: '',
+
+ b: '',
+ },
+ noSpacing: {
+ a: '',
+ b: '',
+ },
+ }"
+ )))
+}
cmds/jrsonnet-lsp/Cargo.tomldiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-lsp/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "jrsonnet-lsp"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+anyhow = "1.0.48"
+jrsonnet-evaluator = { path = "../../crates/jrsonnet-evaluator" }
+jrsonnet-rowan-parser = { path = "../../crates/jrsonnet-rowan-parser" }
+lsp-server = "0.6.0"
+lsp-types = "0.93.0"
+serde = "1.0.130"
+serde_json = "1.0.71"
cmds/jrsonnet-lsp/src/main.rsdiffbeforeafterboth--- /dev/null
+++ b/cmds/jrsonnet-lsp/src/main.rs
@@ -0,0 +1,188 @@
+use std::{fs::File, io::Write, path::PathBuf, str::FromStr};
+
+use lsp_server::{Connection, ErrorCode, Message, Request, RequestId, Response};
+use lsp_types::{
+ notification::{DidChangeTextDocument, DidOpenTextDocument, Notification},
+ request::{DocumentLinkRequest, HoverRequest},
+ CompletionOptions, DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentLink,
+ DocumentLinkOptions, ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind,
+ TextDocumentSyncOptions, Url, WorkDoneProgressOptions,
+};
+
+fn main() {
+ let mut log = File::create("test").unwrap();
+ writeln!(log, "start").unwrap();
+ let (connection, io_threads) = Connection::stdio();
+ let capabilities = serde_json::to_value(&ServerCapabilities {
+ completion_provider: Some(CompletionOptions::default()),
+ definition_provider: Some(lsp_types::OneOf::Left(true)),
+ document_link_provider: Some(DocumentLinkOptions {
+ resolve_provider: Some(false),
+ work_done_progress_options: WorkDoneProgressOptions::default(),
+ }),
+ hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)),
+ text_document_sync: Some(TextDocumentSyncCapability::Options(
+ TextDocumentSyncOptions {
+ change: Some(TextDocumentSyncKind::FULL),
+ open_close: Some(true),
+ ..TextDocumentSyncOptions::default()
+ },
+ )),
+ ..ServerCapabilities::default()
+ })
+ .expect("failed to convert capabilities to json");
+
+ connection
+ .initialize(capabilities)
+ .expect("failed to initialize connection");
+
+ writeln!(log, "initialized").unwrap();
+
+ main_loop(&mut log, &connection).expect("main loop failed");
+
+ io_threads.join().expect("failed to join io_threads");
+}
+fn main_loop(log: &mut File, connection: &Connection) -> anyhow::Result<()> {
+ // let mut es = EvaluationState::default();
+ // es.set_import_resolver(Box::new(FileImportResolver::default()));
+
+ let reply = |response: Response| {
+ connection
+ .sender
+ .send(Message::Response(response))
+ .expect("failed to respond");
+ };
+
+ for msg in &connection.receiver {
+ match msg {
+ Message::Response(_) => (),
+ Message::Request(req) => {
+ if connection.handle_shutdown(&req)? {
+ return Ok(());
+ }
+ if let Some((id, params)) = cast::<DocumentLinkRequest>(&req) {
+ reply(Response::new_ok(id, <Vec<DocumentLink>>::new()));
+ } else if let Some((id, params)) = cast::<HoverRequest>(&req) {
+ let pos = params
+ .text_document_position_params
+ .text_document
+ .uri
+ .path();
+ let buf = PathBuf::from_str(pos).unwrap();
+ // let pos = es
+ // .map_from_source_location(
+ // &buf,
+ // params.text_document_position_params.position.line as usize + 1,
+ // params.text_document_position_params.position.character as usize + 1,
+ // )
+ // .unwrap();
+ // let el = ExprLocation(buf.clone().into(), pos as usize, pos as usize);
+ // let es2 = es.clone();
+ // reply(Response::new_ok(
+ // id,
+ // Some(Hover {
+ // range: None,
+ // contents: HoverContents::Markup(MarkupContent {
+ // kind: MarkupKind::Markdown,
+ // value: es
+ // .run_in_state_with_breakpoint(el, move || {
+ // es2.reset_evaluation_state(&buf);
+ // es2.import_file(&PathBuf::new(), &buf)?
+ // .to_string()
+ // .map(|_| ())
+ // })
+ // .unwrap()
+ // .unwrap_or_else(|| Val::Null)
+ // .value_type()
+ // .to_string(),
+ // }),
+ // }),
+ // ));
+ } else {
+ reply(Response::new_err(
+ req.id,
+ ErrorCode::MethodNotFound as i32,
+ format!("unrecognized request {}", req.method),
+ ))
+ }
+ /*
+ if let Some((id, params)) = cast::<DocumentLinkRequest>(&req) {
+ let links = handle_links(&files, params).unwrap_or_default();
+ reply(Response::new_ok(id, links));
+ } else if let Some((id, params)) = cast::<GotoDefinition>(&req) {
+ if let Some(loc) = handle_goto(&files, params) {
+ reply(Response::new_ok(id, loc))
+ } else {
+ reply(Response::new_ok(id, ()))
+ }
+ } else if let Some((id, params)) = cast::<HoverRequest>(&req) {
+ match handle_hover(&files, params) {
+ Some((range, markdown)) => {
+ reply(Response::new_ok(
+ id,
+ Hover {
+ contents: HoverContents::Markup(MarkupContent {
+ kind: MarkupKind::Markdown,
+ value: markdown,
+ }),
+ range,
+ },
+ ));
+ }
+ None => {
+ reply(Response::new_ok(id, ()));
+ }
+ }
+ } else if let Some((id, params)) = cast::<Completion>(&req) {
+ let completions = handle_completion(&files, params.text_document_position)
+ .unwrap_or_default();
+ reply(Response::new_ok(id, completions));
+ } else
+ */
+ }
+ Message::Notification(req) => {
+ let mut handle = |text: String, uri: Url| {
+ writeln!(log, "updated file: {:?}", uri).unwrap();
+ let path = match PathBuf::from_str(uri.path()) {
+ Ok(x) => x,
+ Err(_) => return,
+ };
+ let (ast, errors) = jrsonnet_rowan_parser::parse(&text);
+ // es.add_parsed_file(path.into(), text.into(), parsed)
+ // .unwrap();
+ writeln!(log, "parsed: {:?}", uri).unwrap();
+ };
+
+ match &*req.method {
+ DidOpenTextDocument::METHOD => {
+ let params: DidOpenTextDocumentParams =
+ match serde_json::from_value(req.params) {
+ Ok(x) => x,
+ Err(_) => continue,
+ };
+ handle(params.text_document.text, params.text_document.uri);
+ }
+ DidChangeTextDocument::METHOD => {
+ let params: DidChangeTextDocumentParams =
+ match serde_json::from_value(req.params) {
+ Ok(x) => x,
+ Err(_) => continue,
+ };
+ for change in params.content_changes.into_iter() {
+ handle(change.text, params.text_document.uri.clone());
+ }
+ }
+ _ => continue,
+ }
+ }
+ }
+ }
+ Ok(())
+}
+fn cast<R>(req: &Request) -> Option<(RequestId, R::Params)>
+where
+ R: lsp_types::request::Request,
+ R::Params: serde::de::DeserializeOwned,
+{
+ req.clone().extract(R::METHOD).ok()
+}
crates/jrsonnet-rowan-parser/Cargo.tomldiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/Cargo.toml
+++ b/crates/jrsonnet-rowan-parser/Cargo.toml
@@ -4,19 +4,19 @@
edition = "2021"
[dependencies]
-anyhow = "1.0.51"
+anyhow = "1.0"
backtrace = "0.3.63"
drop_bomb = "0.1.5"
-indoc = "1.0.3"
-logos = "0.12.0"
-miette = { version = "4.2.1", features = ["fancy"] }
-rowan = "0.15.0"
-text-size = "1.1.0"
-thiserror = "1.0.30"
+indoc = "1.0"
+logos = "0.12"
+miette = { version = "4.2", features = ["fancy"] }
+rowan = "0.15"
+text-size = "1.1"
+thiserror = "1.0"
[dev-dependencies]
backtrace = "0.3.63"
-indoc = "1.0.3"
-insta = "1.10.0"
-anyhow = "1.0.57"
+indoc = "1.0"
+insta = "1.15"
+anyhow = "1.0"
jrsonnet-stdlib = { path = "../jrsonnet-stdlib" }
crates/jrsonnet-rowan-parser/jsonnet.ungramdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/jsonnet.ungram
+++ b/crates/jrsonnet-rowan-parser/jsonnet.ungram
@@ -56,9 +56,7 @@
(Expr (',' Expr)* ','?)?
']'
ExprObject =
- '{'
ObjBody
- '}'
ExprArrayComp =
'['
Expr
@@ -168,6 +166,7 @@
(name:Name '=')? Expr
ObjBodyComp =
+ '{'
pre:ObjLocalPostComma*
'['
key:LhsExpr
@@ -177,8 +176,11 @@
value:Expr
post:ObjLocalPreComma*
CompSpec*
+ '}'
ObjBodyMemberList =
+ '{'
(Member (',' Member)* ','?)?
+ '}'
ObjBody =
ObjBodyComp
| ObjBodyMemberList
crates/jrsonnet-rowan-parser/src/event.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/event.rs
+++ b/crates/jrsonnet-rowan-parser/src/event.rs
@@ -24,6 +24,10 @@
Token {
kind: SyntaxKind,
},
+ /// Push token, but do not eat anything,
+ VirtualToken {
+ kind: SyntaxKind,
+ },
/// Position of finished node
Finish {
/// Same as forward_parent of Start, but for wrapping
@@ -105,6 +109,13 @@
self.token(kind);
eat_start_whitespace = true;
}
+ Event::VirtualToken { kind } => {
+ if eat_start_whitespace {
+ self.skip_whitespace();
+ }
+ self.virtual_token(kind);
+ eat_start_whitespace = false;
+ }
Event::Finish { wrapper } => {
self.builder.finish_node();
depth -= 1;
@@ -124,7 +135,7 @@
}
eat_start_whitespace = true;
}
- Event::Pending => panic!("placeholder should not end in events"),
+ Event::Pending => panic!("pending event should not appear in finished events"),
Event::Noop => {}
Event::Error(e) => {
self.errors.push(e);
@@ -137,6 +148,9 @@
errors: self.errors,
}
}
+ fn virtual_token(&mut self, kind: SyntaxKind) {
+ self.builder.token(JsonnetLanguage::kind_to_raw(kind), "")
+ }
fn token(&mut self, kind: SyntaxKind) {
let lexeme = self.lexemes[self.offset];
self.builder
crates/jrsonnet-rowan-parser/src/generated/nodes.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/generated/nodes.rs
+++ b/crates/jrsonnet-rowan-parser/src/generated/nodes.rs
@@ -291,15 +291,9 @@
pub(crate) syntax: SyntaxNode,
}
impl ExprObject {
- pub fn l_brace_token(&self) -> Option<SyntaxToken> {
- support::token(&self.syntax, T!['{'])
- }
pub fn obj_body(&self) -> Option<ObjBody> {
support::child(&self.syntax)
}
- pub fn r_brace_token(&self) -> Option<SyntaxToken> {
- support::token(&self.syntax, T!['}'])
- }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -538,6 +532,9 @@
pub(crate) syntax: SyntaxNode,
}
impl ObjBodyComp {
+ pub fn l_brace_token(&self) -> Option<SyntaxToken> {
+ support::token(&self.syntax, T!['{'])
+ }
pub fn pre(&self) -> AstChildren<ObjLocalPostComma> {
support::children(&self.syntax)
}
@@ -565,6 +562,9 @@
pub fn comp_specs(&self) -> AstChildren<CompSpec> {
support::children(&self.syntax)
}
+ pub fn r_brace_token(&self) -> Option<SyntaxToken> {
+ support::token(&self.syntax, T!['}'])
+ }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -598,9 +598,15 @@
pub(crate) syntax: SyntaxNode,
}
impl ObjBodyMemberList {
+ pub fn l_brace_token(&self) -> Option<SyntaxToken> {
+ support::token(&self.syntax, T!['{'])
+ }
pub fn members(&self) -> AstChildren<Member> {
support::children(&self.syntax)
}
+ pub fn r_brace_token(&self) -> Option<SyntaxToken> {
+ support::token(&self.syntax, T!['}'])
+ }
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
crates/jrsonnet-rowan-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/lib.rs
+++ b/crates/jrsonnet-rowan-parser/src/lib.rs
@@ -1,5 +1,11 @@
#![deny(unused_must_use)]
+use event::Sink;
+use generated::nodes::{SourceFile, Trivia};
+use lex::lex;
+use parser::{Parser, SyntaxError};
+pub use rowan;
+
mod ast;
mod event;
mod generated;
@@ -13,18 +19,18 @@
mod token_set;
pub use ast::{AstChildren, AstNode, AstToken};
-use event::Sink;
-use generated::nodes::SourceFile;
pub use generated::{nodes, syntax_kinds::SyntaxKind};
-pub use language::{
- JsonnetLanguage, PreorderWithTokens, SyntaxElement, SyntaxElementChildren, SyntaxNode,
- SyntaxNodeChildren, SyntaxToken,
-};
-use lex::lex;
-use parser::{Parser, SyntaxError};
+pub use language::*;
+pub use token_set::SyntaxKindSet;
+
pub fn parse(input: &str) -> (SourceFile, Vec<SyntaxError>) {
let lexemes = lex(input);
- let parser = Parser::new(&lexemes);
+ let kinds = lexemes
+ .iter()
+ .map(|l| l.kind)
+ .filter(|k| !Trivia::can_cast(*k))
+ .collect();
+ let parser = Parser::new(kinds);
let events = parser.parse();
let sink = Sink::new(events, &lexemes);
crates/jrsonnet-rowan-parser/src/marker.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/marker.rs
+++ b/crates/jrsonnet-rowan-parser/src/marker.rs
@@ -113,21 +113,3 @@
completed
}
}
-
-pub trait AsRange {
- fn as_range(&self, p: &Parser) -> TextRange;
- fn end_token(&self) -> usize;
-}
-
-impl AsRange for FinishedRanger {
- fn as_range(&self, p: &Parser) -> TextRange {
- TextRange::new(
- p.start_of_token(self.start_token),
- p.end_of_token(self.end_token),
- )
- }
-
- fn end_token(&self) -> usize {
- self.end_token
- }
-}
crates/jrsonnet-rowan-parser/src/parser.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/parser.rs
+++ b/crates/jrsonnet-rowan-parser/src/parser.rs
@@ -6,7 +6,7 @@
use crate::{
event::Event,
lex::Lexeme,
- marker::{AsRange, CompletedMarker, Marker, Ranger},
+ marker::{CompletedMarker, Marker, Ranger},
nodes::{BinaryOperatorKind, Literal, Number, Text, Trivia, UnaryOperatorKind},
token_set::SyntaxKindSet,
AstToken, SyntaxKind,
@@ -33,9 +33,9 @@
}
}
-pub struct Parser<'i> {
+pub struct Parser {
// TODO: remove all trivia before feeding to parser?
- lexemes: &'i [Lexeme<'i>],
+ kinds: Vec<SyntaxKind>,
pub offset: usize,
pub events: Vec<Event>,
pub entered: u32,
@@ -103,10 +103,10 @@
}
}
-impl<'i> Parser<'i> {
- pub fn new(lexemes: &'i [Lexeme<'i>]) -> Self {
+impl Parser {
+ pub fn new(kinds: Vec<SyntaxKind>) -> Self {
Self {
- lexemes,
+ kinds,
offset: 0,
events: vec![],
entered: 0,
@@ -134,14 +134,12 @@
.set(ExpectedSyntaxTrackingState::Unnamed);
}
pub fn start(&mut self) -> Marker {
- self.skip_trivia();
let start_event_idx = self.events.len();
self.events.push(Event::Pending);
self.entered += 1;
Marker::new(start_event_idx)
}
pub fn start_ranger(&mut self) -> Ranger {
- self.skip_trivia();
let pos = self.offset;
Ranger { pos }
}
@@ -178,45 +176,7 @@
} else {
self.error_with_no_skip();
}
- }
- fn current_token(&self) -> Lexeme<'i> {
- self.lexemes[self.offset]
- }
- fn previous_token(&mut self) -> Option<Lexeme<'i>> {
- if self.offset == 0 {
- return None;
- }
- let mut previous_token_idx = self.offset - 1;
- while self
- .lexemes
- .get(previous_token_idx)
- .map_or(false, |l| Trivia::can_cast(l.kind))
- && previous_token_idx != 0
- {
- previous_token_idx -= 1;
- }
-
- Some(self.lexemes[previous_token_idx])
- }
- pub fn start_of_token(&self, mut idx: usize) -> TextSize {
- while Trivia::can_cast(self.lexemes[idx].kind) {
- idx += 1;
- }
- self.lexemes[idx].range.start()
}
- pub fn end_of_token(&self, mut idx: usize) -> TextSize {
- while Trivia::can_cast(self.lexemes[idx].kind) {
- idx -= 1;
- }
- self.lexemes[idx].range.end()
- }
- pub(crate) fn custom_error(&mut self, marker: impl AsRange, error: impl AsRef<str>) {
- self.last_error_token = marker.end_token();
- self.events.push(Event::Error(SyntaxError::Custom {
- error: error.as_ref().to_string(),
- range: marker.as_range(self),
- }));
- }
pub(crate) fn error_with_recovery_set(
&mut self,
recovery_set: SyntaxKindSet,
@@ -238,27 +198,26 @@
self.expected_syntax_tracking_state
.set(ExpectedSyntaxTrackingState::Unnamed);
- self.skip_trivia();
if self.at_end() || self.at_ts(recovery_set) {
- let range = self
- .previous_token()
- .map(|t| t.range)
- .unwrap_or_else(|| TextRange::at(TextSize::from(0), TextSize::from(0)));
+ // let range = self
+ // .previous_token()
+ // .map(|t| t.range)
+ // .unwrap_or_else(|| TextRange::at(TextSize::from(0), TextSize::from(0)));
- self.events.push(Event::Error(SyntaxError::Missing {
- expected: expected_syntax,
- offset: range.end(),
- }));
+ // self.events.push(Event::Error(SyntaxError::Missing {
+ // expected: expected_syntax,
+ // offset: range.end(),
+ // }));
return None;
}
- let current_token = self.current_token();
+ let current_token = self.current();
- self.events.push(Event::Error(SyntaxError::Unexpected {
- expected: expected_syntax,
- found: current_token.kind,
- range: current_token.range,
- }));
+ // self.events.push(Event::Error(SyntaxError::Unexpected {
+ // expected: expected_syntax,
+ // found: current_token.kind,
+ // range: current_token.range,
+ // }));
self.clear_expected_syntaxes();
self.last_error_token = self.offset;
@@ -267,17 +226,14 @@
Some(m.complete(self, SyntaxKind::ERROR))
}
fn bump_assert(&mut self, kind: SyntaxKind) {
- self.skip_trivia();
assert!(self.at(kind), "expected {:?}", kind);
self.bump_remap(self.current());
}
fn bump(&mut self) {
- self.skip_trivia();
self.bump_remap(self.current());
}
fn bump_remap(&mut self, kind: SyntaxKind) {
- self.skip_trivia();
- assert_ne!(self.offset, self.lexemes.len(), "already at end");
+ assert_ne!(self.offset, self.kinds.len(), "already at end");
self.events.push(Event::Token { kind });
self.offset += 1;
self.clear_expected_syntaxes();
@@ -302,7 +258,7 @@
{
let next = 20;
write!(out, "\n\nNext {next} tokens:").unwrap();
- for (i, tok) in self.lexemes.iter().skip(self.offset).take(next).enumerate() {
+ for (i, tok) in self.kinds.iter().skip(self.offset).take(next).enumerate() {
write!(out, "\n{i}. {tok:?}").unwrap();
}
}
@@ -314,39 +270,12 @@
self.step();
let mut offset = self.offset;
for _ in 0..i {
- while self
- .lexemes
- .get(offset)
- .map(|l| Trivia::can_cast(l.kind))
- .unwrap_or(false)
- {
- offset += 1;
- }
offset += 1;
}
- while self
- .lexemes
- .get(offset)
- .map(|l| Trivia::can_cast(l.kind))
- .unwrap_or(false)
- {
- offset += 1;
- }
- self.lexemes.get(offset).map(|l| l.kind).unwrap_or(EOF)
+ self.kinds.get(offset).copied().unwrap_or(EOF)
}
fn current(&self) -> SyntaxKind {
self.nth(0)
- }
- fn skip_trivia(&mut self) {
- while Trivia::can_cast(self.peek_raw()) {
- self.offset += 1;
- }
- }
- fn peek_raw(&mut self) -> SyntaxKind {
- self.lexemes
- .get(self.offset)
- .map(|l| l.kind)
- .unwrap_or(SyntaxKind::EOF)
}
#[must_use]
pub(crate) fn expected_syntax_name(&mut self, name: &'static str) -> ExpectedSyntaxGuard {
@@ -507,15 +436,15 @@
None
};
let params = if p.at(T!['(']) {
- if let Some(plus) = plus {
- p.custom_error(plus, "can't extend with method");
- }
+ // if let Some(plus) = plus {
+ // p.custom_error(plus, "can't extend with method");
+ // }
params_desc(p);
- if p.at(T![+]) {
- let r = p.start_ranger();
- p.bump();
- p.custom_error(r.finish(p), "can't extend with method");
- }
+ // if p.at(T![+]) {
+ // let r = p.start_ranger();
+ // p.bump();
+ // p.custom_error(r.finish(p), "can't extend with method");
+ // }
true
} else {
false
@@ -669,10 +598,10 @@
if elems > 1 && !compspecs.is_empty() {
for spec in compspecs {
- p.custom_error(
- spec,
- "compspec may only be used if there is only one array element",
- )
+ // p.custom_error(
+ // spec,
+ // "compspec may only be used if there is only one array element",
+ // )
}
m.complete(p, EXPR_ARRAY)
@@ -797,9 +726,9 @@
} else if p.at(T![...]) {
let m_err = p.start_ranger();
destruct_rest(p);
- if had_rest {
- p.custom_error(m_err.finish(p), "only one rest can be present in array");
- }
+ // if had_rest {
+ // p.custom_error(m_err.finish(p), "only one rest can be present in array");
+ // }
had_rest = true;
} else {
destruct(p);
@@ -822,9 +751,9 @@
} else if p.at(T![...]) {
let m_err = p.start_ranger();
destruct_rest(p);
- if had_rest {
- p.custom_error(m_err.finish(p), "only one rest can be present in object");
- }
+ // if had_rest {
+ // p.custom_error(m_err.finish(p), "only one rest can be present in object");
+ // }
had_rest = true;
} else {
if had_rest {
crates/jrsonnet-rowan-parser/src/token_set.rsdiffbeforeafterboth--- a/crates/jrsonnet-rowan-parser/src/token_set.rs
+++ b/crates/jrsonnet-rowan-parser/src/token_set.rs
@@ -34,9 +34,9 @@
#[macro_export]
macro_rules! TS {
($($tt:tt)*) => {
- SyntaxKindSet::new(&[
+ $crate::SyntaxKindSet::new(&[
$(
- T![$tt]
+ $crate::T![$tt]
),*
])
};
jrsonnet-lsp/Cargo.tomldiffbeforeafterboth--- a/jrsonnet-lsp/Cargo.toml
+++ /dev/null
@@ -1,15 +0,0 @@
-[package]
-name = "jrsonnet-lsp"
-version = "0.1.0"
-edition = "2021"
-
-# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
-
-[dependencies]
-anyhow = "1.0.48"
-jrsonnet-evaluator = { path = "../jrsonnet-evaluator" }
-jrsonnet-parser = { path = "../jrsonnet-parser" }
-lsp-server = "0.5.2"
-lsp-types = "0.92.0"
-serde = "1.0.130"
-serde_json = "1.0.71"
jrsonnet-lsp/src/main.rsdiffbeforeafterboth--- a/jrsonnet-lsp/src/main.rs
+++ /dev/null
@@ -1,211 +0,0 @@
-use std::{
- collections::HashMap,
- fs::File,
- path::{Path, PathBuf},
- str::FromStr,
-};
-
-use jrsonnet_evaluator::{EvaluationState, FileImportResolver, Val};
-use jrsonnet_parser::{ExprLocation, ParserSettings};
-use lsp_server::{Connection, ErrorCode, Message, Request, RequestId, Response};
-use lsp_types::{
- notification::{DidChangeTextDocument, DidOpenTextDocument, Notification},
- request::{DocumentLinkRequest, HoverRequest},
- CompletionOptions, DidChangeTextDocumentParams, DidOpenTextDocumentParams, DocumentLink,
- DocumentLinkOptions, Hover, HoverContents, MarkupContent, MarkupKind, ServerCapabilities,
- TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, Url,
- WorkDoneProgressOptions,
-};
-
-use std::io::Write;
-
-fn main() {
- let mut log = File::create("test").unwrap();
- writeln!(log, "start").unwrap();
- let (connection, io_threads) = Connection::stdio();
- let capabilities = serde_json::to_value(&ServerCapabilities {
- completion_provider: Some(CompletionOptions::default()),
- definition_provider: Some(lsp_types::OneOf::Left(true)),
- document_link_provider: Some(DocumentLinkOptions {
- resolve_provider: Some(false),
- work_done_progress_options: WorkDoneProgressOptions::default(),
- }),
- hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)),
- text_document_sync: Some(TextDocumentSyncCapability::Options(
- TextDocumentSyncOptions {
- change: Some(TextDocumentSyncKind::FULL),
- open_close: Some(true),
- ..TextDocumentSyncOptions::default()
- },
- )),
- ..ServerCapabilities::default()
- })
- .expect("failed to convert capabilities to json");
-
- connection
- .initialize(capabilities)
- .expect("failed to initialize connection");
-
- writeln!(log, "initialized").unwrap();
-
- main_loop(&mut log, &connection).expect("main loop failed");
-
- io_threads.join().expect("failed to join io_threads");
-}
-fn main_loop(log: &mut File, connection: &Connection) -> anyhow::Result<()> {
- let mut es = EvaluationState::default();
- es.set_import_resolver(Box::new(FileImportResolver::default()));
-
- let reply = |response: Response| {
- connection
- .sender
- .send(Message::Response(response))
- .expect("failed to respond");
- };
-
- for msg in &connection.receiver {
- match msg {
- Message::Response(_) => (),
- Message::Request(req) => {
- if connection.handle_shutdown(&req)? {
- return Ok(());
- }
- if let Some((id, params)) = cast::<DocumentLinkRequest>(&req) {
- reply(Response::new_ok(id, <Vec<DocumentLink>>::new()));
- } else if let Some((id, params)) = cast::<HoverRequest>(&req) {
- let pos = params
- .text_document_position_params
- .text_document
- .uri
- .path();
- let buf = PathBuf::from_str(pos).unwrap();
- let pos = es
- .map_from_source_location(
- &buf,
- params.text_document_position_params.position.line as usize + 1,
- params.text_document_position_params.position.character as usize + 1,
- )
- .unwrap();
- let el = ExprLocation(buf.clone().into(), pos as usize, pos as usize);
- let es2 = es.clone();
- // reply(Response::new_ok(
- // id,
- // Some(Hover {
- // range: None,
- // contents: HoverContents::Markup(MarkupContent {
- // kind: MarkupKind::Markdown,
- // value: es
- // .run_in_state_with_breakpoint(el, move || {
- // es2.reset_evaluation_state(&buf);
- // es2.import_file(&PathBuf::new(), &buf)?
- // .to_string()
- // .map(|_| ())
- // })
- // .unwrap()
- // .unwrap_or_else(|| Val::Null)
- // .value_type()
- // .to_string(),
- // }),
- // }),
- // ));
- } else
- /*
- if let Some((id, params)) = cast::<DocumentLinkRequest>(&req) {
- let links = handle_links(&files, params).unwrap_or_default();
- reply(Response::new_ok(id, links));
- } else if let Some((id, params)) = cast::<GotoDefinition>(&req) {
- if let Some(loc) = handle_goto(&files, params) {
- reply(Response::new_ok(id, loc))
- } else {
- reply(Response::new_ok(id, ()))
- }
- } else if let Some((id, params)) = cast::<HoverRequest>(&req) {
- match handle_hover(&files, params) {
- Some((range, markdown)) => {
- reply(Response::new_ok(
- id,
- Hover {
- contents: HoverContents::Markup(MarkupContent {
- kind: MarkupKind::Markdown,
- value: markdown,
- }),
- range,
- },
- ));
- }
- None => {
- reply(Response::new_ok(id, ()));
- }
- }
- } else if let Some((id, params)) = cast::<Completion>(&req) {
- let completions = handle_completion(&files, params.text_document_position)
- .unwrap_or_default();
- reply(Response::new_ok(id, completions));
- } else
- */
- {
- reply(Response::new_err(
- req.id,
- ErrorCode::MethodNotFound as i32,
- format!("unrecognized request {}", req.method),
- ))
- }
- }
- Message::Notification(req) => {
- let mut handle = |text: String, uri: Url| {
- writeln!(log, "updated file: {:?}", uri).unwrap();
- let path = match PathBuf::from_str(uri.path()) {
- Ok(x) => x,
- Err(_) => return,
- };
- let parsed = match jrsonnet_parser::parse(
- &text,
- &ParserSettings {
- file_name: path.clone().into(),
- },
- ) {
- Ok(v) => v,
- Err(e) => {
- writeln!(log, "fuck D: {:?}", e).unwrap();
- return;
- // connection.sender.send(Message::Notification(Notification::new_err(req.id, ErrorCode::ParseError as i32, format!("Fuck D: {:?}", e))))
- }
- };
- es.add_parsed_file(path.into(), text.into(), parsed)
- .unwrap();
- writeln!(log, "parsed: {:?}", uri).unwrap();
- };
-
- match &*req.method {
- DidOpenTextDocument::METHOD => {
- let params: DidOpenTextDocumentParams =
- match serde_json::from_value(req.params) {
- Ok(x) => x,
- Err(_) => continue,
- };
- handle(params.text_document.text, params.text_document.uri);
- }
- DidChangeTextDocument::METHOD => {
- let params: DidChangeTextDocumentParams =
- match serde_json::from_value(req.params) {
- Ok(x) => x,
- Err(_) => continue,
- };
- for change in params.content_changes.into_iter() {
- handle(change.text, params.text_document.uri.clone());
- }
- }
- _ => continue,
- }
- }
- }
- }
- Ok(())
-}
-fn cast<R>(req: &Request) -> Option<(RequestId, R::Params)>
-where
- R: lsp_types::request::Request,
- R::Params: serde::de::DeserializeOwned,
-{
- req.clone().extract(R::METHOD).ok()
-}
xtask/src/sourcegen/ast.rsdiffbeforeafterboth1use std::collections::{BTreeSet, HashMap};23use proc_macro2::TokenStream;4use quote::format_ident;5use ungrammar::{Grammar, Rule};67use super::{8 util::{pluralize, to_lower_snake_case},9 KindsSrc,10};1112impl AstNodeSrc {13 pub fn remove_field(&mut self, to_remove: Vec<usize>) {14 to_remove.into_iter().rev().for_each(|idx| {15 self.fields.remove(idx);16 });17 }18}1920#[allow(dead_code)]21#[derive(Default, Debug)]22pub struct AstSrc {23 pub nodes: Vec<AstNodeSrc>,24 pub enums: Vec<AstEnumSrc>,25 pub token_enums: Vec<AstTokenEnumSrc>,26}27#[derive(Debug)]28pub struct AstNodeSrc {29 pub doc: Vec<String>,30 pub name: String,31 pub traits: Vec<String>,32 pub fields: Vec<Field>,33}3435#[derive(Debug, Eq, PartialEq)]36pub enum Field {37 Token(String),38 Node {39 name: String,40 ty: String,41 cardinality: Cardinality,42 },43}4445#[derive(Debug, Eq, PartialEq)]46pub enum Cardinality {47 /// This field may not exist in code48 Optional,49 /// This field should exist in correctly parsed code50 Required,51 /// There may be multiple field values of this kind52 Many,53}5455#[derive(Debug, Clone)]56pub struct AstEnumSrc {57 pub doc: Vec<String>,58 pub name: String,59 pub traits: Vec<String>,60 pub variants: Vec<String>,61}6263#[derive(Debug, Clone)]64pub struct AstTokenEnumSrc {65 pub doc: Vec<String>,66 pub name: String,67 pub variants: Vec<String>,68}6970impl Field {71 pub fn is_many(&self) -> bool {72 matches!(73 self,74 Field::Node {75 cardinality: Cardinality::Many,76 ..77 }78 )79 }8081 pub fn token_name(&self) -> Option<String> {82 match self {83 Field::Token(token) => Some(token.clone()),84 _ => None,85 }86 }87 pub fn token_kind(&self, kinds: &KindsSrc) -> Option<TokenStream> {88 match self {89 Field::Token(token) => Some(kinds.token(token).expect("token exists").reference()),90 _ => None,91 }92 }93 pub fn is_token_enum(&self, grammar: &AstSrc) -> bool {94 match self {95 Field::Node { ty, .. } => grammar.token_enums.iter().any(|e| &e.name == ty),96 _ => false,97 }98 }99100 pub fn method_name(&self, kinds: &KindsSrc) -> proc_macro2::Ident {101 match self {102 Field::Token(name) => kinds.token(name).expect("token exists").method_name(),103 Field::Node { name, .. } => {104 format_ident!("{}", name)105 }106 }107 }108 pub fn ty(&self) -> proc_macro2::Ident {109 match self {110 Field::Token(_) => format_ident!("SyntaxToken"),111 Field::Node { ty, .. } => format_ident!("{}", ty),112 }113 }114}115116pub fn lower(kinds: &KindsSrc, grammar: &Grammar) -> AstSrc {117 let mut res = AstSrc {118 // tokens,119 ..Default::default()120 };121122 let nodes = grammar.iter().collect::<Vec<_>>();123124 for &node in &nodes {125 let name = grammar[node].name.clone();126 let rule = &grammar[node].rule;127 match lower_enum(grammar, rule) {128 Some(variants) => {129 let enum_src = AstEnumSrc {130 doc: Vec::new(),131 name,132 traits: Vec::new(),133 variants,134 };135 res.enums.push(enum_src);136 }137 None => match lower_token_enum(grammar, rule) {138 Some(variants) => {139 let tokens_enum_src = AstTokenEnumSrc {140 doc: Vec::new(),141 name,142 variants,143 };144 res.token_enums.push(tokens_enum_src);145 }146 None => {147 let mut fields = Vec::new();148 lower_rule(&mut fields, grammar, None, rule, false);149 let mut types = HashMap::new();150 for field in fields.iter().filter(|f| f.token_name().is_none()) {151 if let Some(old) = types.insert(field.ty(), field.method_name(kinds)) {152 panic!("{name}.{} has same type as {name}.{}, resolve conflict by wrapping one field: {}", old, field.method_name(kinds), field.ty());153 }154 }155 res.nodes.push(AstNodeSrc {156 doc: Vec::new(),157 name,158 traits: Vec::new(),159 fields,160 });161 }162 },163 }164 }165166 deduplicate_fields(&mut res);167 extract_struct_traits(kinds, &mut res);168 extract_enum_traits(&mut res);169 res170}171172fn lower_enum(grammar: &Grammar, rule: &Rule) -> Option<Vec<String>> {173 let alternatives = match rule {174 Rule::Alt(it) => it,175 _ => return None,176 };177 let mut variants = Vec::new();178 for alternative in alternatives {179 match alternative {180 Rule::Node(it) => variants.push(grammar[*it].name.clone()),181 Rule::Token(it) if grammar[*it].name == ";" => (),182 _ => return None,183 }184 }185 Some(variants)186}187fn lower_token_enum(grammar: &Grammar, rule: &Rule) -> Option<Vec<String>> {188 let alternatives = match rule {189 Rule::Alt(it) => it,190 _ => return None,191 };192 let mut variants = Vec::new();193 for alternative in alternatives {194 match alternative {195 Rule::Token(it) => variants.push(grammar[*it].name.clone()),196 _ => return None,197 }198 }199 Some(variants)200}201202fn lower_rule(203 acc: &mut Vec<Field>,204 grammar: &Grammar,205 label: Option<&String>,206 rule: &Rule,207 in_optional: bool,208) {209 if lower_comma_list(acc, grammar, label, rule) {210 return;211 }212213 match rule {214 Rule::Node(node) => {215 let ty = grammar[*node].name.clone();216 let name = label.cloned().unwrap_or_else(|| to_lower_snake_case(&ty));217 let field = Field::Node {218 name,219 ty,220 cardinality: if in_optional {221 Cardinality::Optional222 } else {223 Cardinality::Required224 },225 };226 acc.push(field);227 }228 Rule::Token(token) => {229 assert!(label.is_none(), "uexpected label: {:?}", label);230 let name = grammar[*token].name.clone();231 let field = Field::Token(name);232 acc.push(field);233 }234 Rule::Rep(inner) => {235 if let Rule::Node(node) = &**inner {236 let ty = grammar[*node].name.clone();237 let name = label238 .cloned()239 .unwrap_or_else(|| pluralize(&to_lower_snake_case(&ty)));240 let field = Field::Node {241 name,242 ty,243 cardinality: Cardinality::Many,244 };245 acc.push(field);246 return;247 }248 todo!("unsupported repitition: {:?}", rule)249 }250 Rule::Labeled { label: l, rule } => {251 assert!(label.is_none());252 lower_rule(acc, grammar, Some(l), rule, in_optional);253 }254 Rule::Seq(rules) | Rule::Alt(rules) => {255 for rule in rules {256 lower_rule(acc, grammar, label, rule, in_optional)257 }258 }259 Rule::Opt(rule) => lower_rule(acc, grammar, label, rule, true),260 }261}262263// (T (',' T)* ','?)264fn lower_comma_list(265 acc: &mut Vec<Field>,266 grammar: &Grammar,267 label: Option<&String>,268 rule: &Rule,269) -> bool {270 let rule = match rule {271 Rule::Seq(it) => it,272 _ => return false,273 };274 let (node, repeat, trailing_comma) = match rule.as_slice() {275 [Rule::Node(node), Rule::Rep(repeat), Rule::Opt(trailing_comma)] => {276 (node, repeat, trailing_comma)277 }278 _ => return false,279 };280 let repeat = match &**repeat {281 Rule::Seq(it) => it,282 _ => return false,283 };284 match repeat.as_slice() {285 [comma, Rule::Node(n)] if comma == &**trailing_comma && n == node => (),286 _ => return false,287 }288 let ty = grammar[*node].name.clone();289 let name = label290 .cloned()291 .unwrap_or_else(|| pluralize(&to_lower_snake_case(&ty)));292 let field = Field::Node {293 name,294 ty,295 cardinality: Cardinality::Many,296 };297 acc.push(field);298 true299}300301fn deduplicate_fields(ast: &mut AstSrc) {302 for node in &mut ast.nodes {303 let mut i = 0;304 'outer: while i < node.fields.len() {305 for j in 0..i {306 let f1 = &node.fields[i];307 let f2 = &node.fields[j];308 if f1 == f2 {309 node.fields.remove(i);310 continue 'outer;311 }312 }313 i += 1;314 }315 }316}317318fn extract_struct_traits(kinds: &KindsSrc, ast: &mut AstSrc) {319 // TODO: add common accessor traits here.320 let traits: &[(&str, &[&str])] = &[];321322 for node in &mut ast.nodes {323 for (name, methods) in traits {324 extract_struct_trait(kinds, node, name, methods);325 }326 }327}328329fn extract_struct_trait(330 kinds: &KindsSrc,331 node: &mut AstNodeSrc,332 trait_name: &str,333 methods: &[&str],334) {335 let mut to_remove = Vec::new();336 for (i, field) in node.fields.iter().enumerate() {337 let method_name = field.method_name(kinds).to_string();338 if methods.iter().any(|&it| it == method_name) {339 to_remove.push(i);340 }341 }342 if to_remove.len() == methods.len() {343 node.traits.push(trait_name.to_string());344 node.remove_field(to_remove);345 }346}347348fn extract_enum_traits(ast: &mut AstSrc) {349 let enums = ast.enums.clone();350 for enm in &mut ast.enums {351 let nodes = &ast.nodes;352353 let mut variant_traits = enm.variants.iter().map(|var| {354 nodes355 .iter()356 .find_map(|node| {357 if &node.name != var {358 return None;359 }360 Some(node.traits.iter().cloned().collect::<BTreeSet<_>>())361 })362 .unwrap_or_else(|| {363 enums364 .iter()365 .find_map(|node| {366 if &node.name != var {367 return None;368 }369 Some(node.traits.iter().cloned().collect::<BTreeSet<_>>())370 })371 .unwrap_or_else(|| {372 panic!("could not find struct {var} for enum {}::{var}", enm.name)373 })374 })375 });376377 let mut enum_traits = match variant_traits.next() {378 Some(it) => it,379 None => continue,380 };381 for traits in variant_traits {382 enum_traits = enum_traits.intersection(&traits).cloned().collect();383 }384 enm.traits = enum_traits.into_iter().collect();385 }386}1use std::collections::{BTreeSet, HashMap};23use proc_macro2::TokenStream;4use quote::format_ident;5use ungrammar::{Grammar, Rule};67use super::{8 util::{pluralize, to_lower_snake_case},9 KindsSrc,10};1112impl AstNodeSrc {13 pub fn remove_field(&mut self, to_remove: Vec<usize>) {14 to_remove.into_iter().rev().for_each(|idx| {15 self.fields.remove(idx);16 });17 }18}1920#[allow(dead_code)]21#[derive(Default, Debug)]22pub struct AstSrc {23 pub nodes: Vec<AstNodeSrc>,24 pub enums: Vec<AstEnumSrc>,25 pub token_enums: Vec<AstTokenEnumSrc>,26}27#[derive(Debug)]28pub struct AstNodeSrc {29 pub doc: Vec<String>,30 pub name: String,31 pub traits: Vec<String>,32 pub fields: Vec<Field>,33}3435#[derive(Debug, Eq, PartialEq)]36pub enum Field {37 Token(String),38 Node {39 name: String,40 ty: String,41 cardinality: Cardinality,42 },43}4445#[derive(Debug, Eq, PartialEq)]46pub enum Cardinality {47 /// This field may not exist in code48 Optional,49 /// This field should exist in correctly parsed code50 Required,51 /// There may be multiple field values of this kind52 Many,53}5455#[derive(Debug, Clone)]56pub struct AstEnumSrc {57 pub doc: Vec<String>,58 pub name: String,59 pub traits: Vec<String>,60 pub variants: Vec<String>,61}6263#[derive(Debug, Clone)]64pub struct AstTokenEnumSrc {65 pub doc: Vec<String>,66 pub name: String,67 pub variants: Vec<String>,68}6970impl Field {71 pub fn is_many(&self) -> bool {72 matches!(73 self,74 Field::Node {75 cardinality: Cardinality::Many,76 ..77 }78 )79 }8081 pub fn token_name(&self) -> Option<String> {82 match self {83 Field::Token(token) => Some(token.clone()),84 _ => None,85 }86 }87 pub fn token_kind(&self, kinds: &KindsSrc) -> Option<TokenStream> {88 match self {89 Field::Token(token) => Some(kinds.token(token).expect("token exists").reference()),90 _ => None,91 }92 }93 pub fn is_token_enum(&self, grammar: &AstSrc) -> bool {94 match self {95 Field::Node { ty, .. } => grammar.token_enums.iter().any(|e| &e.name == ty),96 _ => false,97 }98 }99100 pub fn method_name(&self, kinds: &KindsSrc) -> proc_macro2::Ident {101 match self {102 Field::Token(name) => kinds.token(name).expect("token exists").method_name(),103 Field::Node { name, .. } => {104 format_ident!("{}", name)105 }106 }107 }108 pub fn ty(&self) -> proc_macro2::Ident {109 match self {110 Field::Token(_) => format_ident!("SyntaxToken"),111 Field::Node { ty, .. } => format_ident!("{}", ty),112 }113 }114}115116pub fn lower(kinds: &KindsSrc, grammar: &Grammar) -> AstSrc {117 let mut res = AstSrc {118 // tokens,119 ..Default::default()120 };121122 let nodes = grammar.iter().collect::<Vec<_>>();123124 for &node in &nodes {125 let name = grammar[node].name.clone();126 let rule = &grammar[node].rule;127 match lower_enum(grammar, rule) {128 Some(variants) => {129 let enum_src = AstEnumSrc {130 doc: Vec::new(),131 name,132 traits: Vec::new(),133 variants,134 };135 res.enums.push(enum_src);136 }137 None => match lower_token_enum(grammar, rule) {138 Some(variants) => {139 let tokens_enum_src = AstTokenEnumSrc {140 doc: Vec::new(),141 name,142 variants,143 };144 res.token_enums.push(tokens_enum_src);145 }146 None => {147 let mut fields = Vec::new();148 lower_rule(&mut fields, grammar, None, rule, false);149 let mut types = HashMap::new();150 for field in fields.iter().filter(|f| f.token_name().is_none()) {151 if let Some(old) = types.insert(field.ty(), field.method_name(kinds)) {152 panic!("{name}.{} has same type as {name}.{}, resolve conflict by wrapping one field: {}", old, field.method_name(kinds), field.ty());153 }154 // TODO: check for assignable field types, i.e you can have155 // ```156 // SomeEnum =157 // SomeItem158 // | SomeOtherItem159 // ```160 // And check above will fail to detect conflict in161 // ```162 // SomeStruct =163 // SomeEnum164 // SomeItem165 // ```166 // Despite generating getters, which will both return SomeEnum167 }168 res.nodes.push(AstNodeSrc {169 doc: Vec::new(),170 name,171 traits: Vec::new(),172 fields,173 });174 }175 },176 }177 }178179 deduplicate_fields(&mut res);180 extract_struct_traits(kinds, &mut res);181 extract_enum_traits(&mut res);182 res183}184185fn lower_enum(grammar: &Grammar, rule: &Rule) -> Option<Vec<String>> {186 let alternatives = match rule {187 Rule::Alt(it) => it,188 _ => return None,189 };190 let mut variants = Vec::new();191 for alternative in alternatives {192 match alternative {193 Rule::Node(it) => variants.push(grammar[*it].name.clone()),194 Rule::Token(it) if grammar[*it].name == ";" => (),195 _ => return None,196 }197 }198 Some(variants)199}200fn lower_token_enum(grammar: &Grammar, rule: &Rule) -> Option<Vec<String>> {201 let alternatives = match rule {202 Rule::Alt(it) => it,203 _ => return None,204 };205 let mut variants = Vec::new();206 for alternative in alternatives {207 match alternative {208 Rule::Token(it) => variants.push(grammar[*it].name.clone()),209 _ => return None,210 }211 }212 Some(variants)213}214215fn lower_rule(216 acc: &mut Vec<Field>,217 grammar: &Grammar,218 label: Option<&String>,219 rule: &Rule,220 in_optional: bool,221) {222 if lower_comma_list(acc, grammar, label, rule) {223 return;224 }225226 match rule {227 Rule::Node(node) => {228 let ty = grammar[*node].name.clone();229 let name = label.cloned().unwrap_or_else(|| to_lower_snake_case(&ty));230 let field = Field::Node {231 name,232 ty,233 cardinality: if in_optional {234 Cardinality::Optional235 } else {236 Cardinality::Required237 },238 };239 acc.push(field);240 }241 Rule::Token(token) => {242 assert!(label.is_none(), "uexpected label: {:?}", label);243 let name = grammar[*token].name.clone();244 let field = Field::Token(name);245 acc.push(field);246 }247 Rule::Rep(inner) => {248 if let Rule::Node(node) = &**inner {249 let ty = grammar[*node].name.clone();250 let name = label251 .cloned()252 .unwrap_or_else(|| pluralize(&to_lower_snake_case(&ty)));253 let field = Field::Node {254 name,255 ty,256 cardinality: Cardinality::Many,257 };258 acc.push(field);259 return;260 }261 todo!("unsupported repitition: {:?}", rule)262 }263 Rule::Labeled { label: l, rule } => {264 assert!(label.is_none());265 lower_rule(acc, grammar, Some(l), rule, in_optional);266 }267 Rule::Seq(rules) | Rule::Alt(rules) => {268 for rule in rules {269 lower_rule(acc, grammar, label, rule, in_optional)270 }271 }272 Rule::Opt(rule) => lower_rule(acc, grammar, label, rule, true),273 }274}275276// (T (',' T)* ','?)277fn lower_comma_list(278 acc: &mut Vec<Field>,279 grammar: &Grammar,280 label: Option<&String>,281 rule: &Rule,282) -> bool {283 let rule = match rule {284 Rule::Seq(it) => it,285 _ => return false,286 };287 let (node, repeat, trailing_comma) = match rule.as_slice() {288 [Rule::Node(node), Rule::Rep(repeat), Rule::Opt(trailing_comma)] => {289 (node, repeat, trailing_comma)290 }291 _ => return false,292 };293 let repeat = match &**repeat {294 Rule::Seq(it) => it,295 _ => return false,296 };297 match repeat.as_slice() {298 [comma, Rule::Node(n)] if comma == &**trailing_comma && n == node => (),299 _ => return false,300 }301 let ty = grammar[*node].name.clone();302 let name = label303 .cloned()304 .unwrap_or_else(|| pluralize(&to_lower_snake_case(&ty)));305 let field = Field::Node {306 name,307 ty,308 cardinality: Cardinality::Many,309 };310 acc.push(field);311 true312}313314fn deduplicate_fields(ast: &mut AstSrc) {315 for node in &mut ast.nodes {316 let mut i = 0;317 'outer: while i < node.fields.len() {318 for j in 0..i {319 let f1 = &node.fields[i];320 let f2 = &node.fields[j];321 if f1 == f2 {322 node.fields.remove(i);323 continue 'outer;324 }325 }326 i += 1;327 }328 }329}330331fn extract_struct_traits(kinds: &KindsSrc, ast: &mut AstSrc) {332 // TODO: add common accessor traits here.333 let traits: &[(&str, &[&str])] = &[];334335 for node in &mut ast.nodes {336 for (name, methods) in traits {337 extract_struct_trait(kinds, node, name, methods);338 }339 }340}341342fn extract_struct_trait(343 kinds: &KindsSrc,344 node: &mut AstNodeSrc,345 trait_name: &str,346 methods: &[&str],347) {348 let mut to_remove = Vec::new();349 for (i, field) in node.fields.iter().enumerate() {350 let method_name = field.method_name(kinds).to_string();351 if methods.iter().any(|&it| it == method_name) {352 to_remove.push(i);353 }354 }355 if to_remove.len() == methods.len() {356 node.traits.push(trait_name.to_string());357 node.remove_field(to_remove);358 }359}360361fn extract_enum_traits(ast: &mut AstSrc) {362 let enums = ast.enums.clone();363 for enm in &mut ast.enums {364 let nodes = &ast.nodes;365366 let mut variant_traits = enm.variants.iter().map(|var| {367 nodes368 .iter()369 .find_map(|node| {370 if &node.name != var {371 return None;372 }373 Some(node.traits.iter().cloned().collect::<BTreeSet<_>>())374 })375 .unwrap_or_else(|| {376 enums377 .iter()378 .find_map(|node| {379 if &node.name != var {380 return None;381 }382 Some(node.traits.iter().cloned().collect::<BTreeSet<_>>())383 })384 .unwrap_or_else(|| {385 panic!("could not find struct {var} for enum {}::{var}", enm.name)386 })387 })388 });389390 let mut enum_traits = match variant_traits.next() {391 Some(it) => it,392 None => continue,393 };394 for traits in variant_traits {395 enum_traits = enum_traits.intersection(&traits).cloned().collect();396 }397 enm.traits = enum_traits.into_iter().collect();398 }399}