Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

test(format/grit): add tests for grit formatter #3937

Merged
merged 24 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 12 additions & 3 deletions crates/biome_grit_formatter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,18 @@ biome_grit_syntax = { workspace = true }
biome_rowan = { workspace = true }

[dev-dependencies]
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }

biome_formatter_test = { path = "../biome_formatter_test" }
biome_grit_factory = { path = "../biome_grit_factory" }
biome_grit_parser = { path = "../biome_grit_parser" }
biome_parser = { path = "../biome_parser" }
biome_service = { path = "../biome_service" }
countme = { workspace = true, features = ["enable"] }
iai = "0.1.1"
quickcheck = { workspace = true }
quickcheck_macros = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tests_macros = { path = "../tests_macros" }
# cargo-workspaces metadata
[package.metadata.workspaces]
independent = true
Expand Down
24 changes: 20 additions & 4 deletions crates/biome_grit_formatter/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::comments::{FormatGritLeadingComment, GritCommentStyle, GritComments};
use biome_formatter::{
CstFormatContext, FormatContext, FormatOptions, IndentStyle, IndentWidth, LineEnding,
LineWidth, QuoteStyle, TransformSourceMap,
AttributePosition, CstFormatContext, FormatContext, FormatOptions, IndentStyle, IndentWidth,
LineEnding, LineWidth, QuoteStyle, TransformSourceMap,
};
use biome_grit_syntax::GritLanguage;
use std::fmt::Display;
use std::rc::Rc;

#[allow(dead_code)]
Expand Down Expand Up @@ -50,14 +51,14 @@ impl CstFormatContext for GritFormatContext {
}
}

#[derive(Debug, Default, Clone, PartialEq)]

#[derive(Debug, Default, Clone)]
pub struct GritFormatOptions {
indent_style: IndentStyle,
indent_width: IndentWidth,
line_ending: LineEnding,
line_width: LineWidth,
quote_style: QuoteStyle,
attribute_position: AttributePosition,
}

impl GritFormatOptions {
Expand All @@ -68,6 +69,7 @@ impl GritFormatOptions {
line_ending: LineEnding::default(),
line_width: LineWidth::default(),
quote_style: QuoteStyle::default(),
attribute_position: AttributePosition::default(),
}
}
pub fn with_indent_style(mut self, indent_style: IndentStyle) -> Self {
Expand Down Expand Up @@ -118,6 +120,20 @@ impl GritFormatOptions {
pub fn quote_style(&self) -> QuoteStyle {
self.quote_style
}

pub fn attribute_position(&self) -> AttributePosition {
self.attribute_position
}
}

impl Display for GritFormatOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Indent style: {}", self.indent_style)?;
writeln!(f, "Indent width: {}", self.indent_width.value())?;
writeln!(f, "Line ending: {}", self.line_ending)?;
writeln!(f, "Line width: {}", self.line_width.value())?;
writeln!(f, "Attribute Position: {}", self.attribute_position)
}
}

impl FormatOptions for GritFormatOptions {
Expand Down
26 changes: 26 additions & 0 deletions crates/biome_grit_formatter/tests/language.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use biome_formatter_test::TestFormatLanguage;
use biome_grit_formatter::{context::GritFormatContext, GritFormatLanguage};
use biome_grit_syntax::GritLanguage;

#[derive(Default)]

pub struct GritTestFormatLanguage;

impl TestFormatLanguage for GritTestFormatLanguage {
type ServiceLanguage = GritLanguage;
type Context = GritFormatContext;

type FormatLanguage = GritFormatLanguage;

fn parse(&self, text: &str) -> biome_parser::AnyParse {
todo!()
}

fn to_format_language(
&self,
settings: &biome_service::settings::Settings,
file_source: &biome_service::workspace::DocumentFileSource,
) -> Self::FormatLanguage {
todo!()
}
}
21 changes: 21 additions & 0 deletions crates/biome_grit_formatter/tests/spec_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use biome_formatter_test::spec::{SpecSnapshot, SpecTestFile};
use std::path::Path;

mod language {
include!("language.rs");
}

pub fn run(spec_input_file: &str, _expected_file: &str, test_directory: &str, _file_type: &str) {
let root_path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/specs/"));

let Some(test_file) = SpecTestFile::try_from_file(spec_input_file, root_path, Some(settings))
else {
return;
dyc3 marked this conversation as resolved.
Show resolved Hide resolved
};

let language = language::GritTestFormatLanguage::default();

let snapshot = SpecSnapshot::new(test_file, test_directory, language, ());

snapshot.test()
}
8 changes: 8 additions & 0 deletions crates/biome_grit_formatter/tests/spec_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mod spec_test;

mod formatter {

mod grit_module {
tests_macros::gen_tests! {"tests/specs/grit/**/*.grit", crate::spec_test::run, ""}
}
}
10 changes: 9 additions & 1 deletion crates/biome_grit_parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ mod token_source;

use biome_grit_factory::GritSyntaxFactory;
use biome_grit_syntax::{GritLanguage, GritRoot, GritSyntaxNode};
use biome_parser::diagnostic::ParseDiagnostic;
use biome_parser::tree_sink::LosslessTreeSink;
use biome_parser::{diagnostic::ParseDiagnostic, AnyParse};
use biome_rowan::{AstNode, NodeCache};
use parser::{parse_root, GritParser};

Expand Down Expand Up @@ -100,3 +100,11 @@ impl GritParse {
GritRoot::unwrap_cast(self.syntax())
}
}

impl From<GritParse> for AnyParse {
fn from(parse: GritParse) -> Self {
let root = parse.syntax();
let diagnostics = parse.into_diagnostics();
Self::new(root.as_send().unwrap(), diagnostics)
}
}
68 changes: 36 additions & 32 deletions crates/biome_service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,39 +31,43 @@ biome_graphql_analyze = { workspace = true }
biome_graphql_formatter = { workspace = true }
biome_graphql_parser = { workspace = true }
biome_graphql_syntax = { workspace = true }
biome_grit_formatter = { workspace = true }
biome_grit_parser = { workspace = true }
biome_grit_patterns = { workspace = true }
biome_html_formatter = { workspace = true }
biome_html_parser = { workspace = true }
biome_html_syntax = { workspace = true }
biome_js_analyze = { workspace = true }
biome_js_factory = { workspace = true, optional = true }
biome_js_formatter = { workspace = true, features = ["serde"] }
biome_js_parser = { workspace = true }
biome_js_semantic = { workspace = true }
biome_js_syntax = { workspace = true, features = ["schema"] }
biome_json_analyze = { workspace = true }
biome_json_formatter = { workspace = true, features = ["serde"] }
biome_json_parser = { workspace = true }
biome_json_syntax = { workspace = true }
biome_parser = { workspace = true }
biome_project = { workspace = true }
biome_rowan = { workspace = true, features = ["serde"] }
biome_string_case = { workspace = true }
biome_text_edit = { workspace = true }
bpaf = { workspace = true }
dashmap = { workspace = true }
enumflags2 = { workspace = true, features = ["serde"] }
getrandom = { workspace = true, features = ["js"] }
ignore = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }
oxc_resolver = { workspace = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
schemars = { workspace = true, features = ["indexmap1"], optional = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] }
slotmap = { workspace = true, features = ["serde"] }
tracing = { workspace = true, features = ["attributes", "log"] }
biome_grit_syntax = { workspace = true }

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the formatting changes might have been due to the newline here.

biome_html_formatter = { workspace = true }
biome_html_parser = { workspace = true }
biome_html_syntax = { workspace = true }
biome_js_analyze = { workspace = true }
biome_js_factory = { workspace = true, optional = true }
biome_js_formatter = { workspace = true, features = ["serde"] }
biome_js_parser = { workspace = true }
biome_js_semantic = { workspace = true }
biome_js_syntax = { workspace = true, features = ["schema"] }
biome_json_analyze = { workspace = true }
biome_json_formatter = { workspace = true, features = ["serde"] }
biome_json_parser = { workspace = true }
biome_json_syntax = { workspace = true }
biome_parser = { workspace = true }
biome_project = { workspace = true }
biome_rowan = { workspace = true, features = ["serde"] }
biome_string_case = { workspace = true }
biome_text_edit = { workspace = true }
bpaf = { workspace = true }
dashmap = { workspace = true }
enumflags2 = { workspace = true, features = ["serde"] }
getrandom = { workspace = true, features = ["js"] }
ignore = { workspace = true }
indexmap = { workspace = true, features = ["serde"] }
oxc_resolver = { workspace = true }
regex = { workspace = true }
rustc-hash = { workspace = true }
schemars = { workspace = true, features = ["indexmap1"], optional = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] }
slotmap = { workspace = true, features = ["serde"] }
tracing = { workspace = true, features = ["attributes", "log"] }

[features]
schema = [
Expand Down
116 changes: 116 additions & 0 deletions crates/biome_service/src/file_handlers/grit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
use crate::{
settings::{ServiceLanguage, Settings, WorkspaceSettingsHandle},
WorkspaceError,
};
use biome_formatter::Printed;
use biome_fs::BiomePath;
use biome_grit_formatter::{context::GritFormatOptions, format_node};
use biome_grit_parser::parse_grit_with_cache;
use biome_grit_syntax::GritLanguage;
use biome_parser::AnyParse;
use biome_rowan::NodeCache;

use super::{
AnalyzerCapabilities, Capabilities, DebugCapabilities, DocumentFileSource, ExtensionHandler,
FormatterCapabilities, ParseResult, ParserCapabilities, SearchCapabilities,
};

impl ServiceLanguage for GritLanguage {
type FormatterSettings = ();
type LinterSettings = ();
type OrganizeImportsSettings = ();
type FormatOptions = GritFormatOptions;
type ParserSettings = ();
type EnvironmentSettings = ();
fn lookup_settings(
_languages: &crate::settings::LanguageListSettings,
) -> &crate::settings::LanguageSettings<Self> {
todo!()
}

fn resolve_format_options(
_global: Option<&crate::settings::FormatSettings>,
_overrides: Option<&crate::settings::OverrideSettings>,
_language: Option<&Self::FormatterSettings>,
_path: &biome_fs::BiomePath,
_file_source: &super::DocumentFileSource,
) -> Self::FormatOptions {
GritFormatOptions::default()
}

fn resolve_analyzer_options(
_global: Option<&crate::settings::Settings>,
_linter: Option<&crate::settings::LinterSettings>,
_overrides: Option<&crate::settings::OverrideSettings>,
_language: Option<&Self::LinterSettings>,
_path: &biome_fs::BiomePath,
_file_source: &super::DocumentFileSource,
) -> biome_analyze::AnalyzerOptions {
todo!()
}
}

#[derive(Debug, Default, PartialEq, Eq)]

pub(crate) struct GritFileHandler;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like that we're adding a file handler for Grit 👍

Copy link
Contributor Author

@branberry branberry Sep 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Glad to hear! Haha. I've been following some of the other examples, and I've seen that we typically create a file handler struct as a part of the testing process.

Not sure if I'm doing too much work here, but it sounds like I'm working in the right direction!

As a side note, I'm a Rust newbie so any pointers on how I can improve my Rust code is welcome and appreciated :D


impl ExtensionHandler for GritFileHandler {
fn capabilities(&self) -> Capabilities {
Capabilities {
parser: ParserCapabilities { parse: Some(parse) },
debug: DebugCapabilities {
debug_syntax_tree: None,
debug_control_flow: None,
debug_formatter_ir: None,
},
analyzer: AnalyzerCapabilities {
lint: None,
code_actions: None,
rename: None,
fix_all: None,
organize_imports: None,
},
formatter: FormatterCapabilities {
format: Some(format),
format_range: None,
format_on_type: None,
},
search: SearchCapabilities { search: None },
}
}
}

fn parse(
_biome_path: &BiomePath,
file_source: DocumentFileSource,
text: &str,
_settings: Option<&Settings>,
cache: &mut NodeCache,
) -> ParseResult {
let parse = parse_grit_with_cache(text, cache);

ParseResult {
any_parse: parse.into(),
language: Some(file_source),
}
}

#[tracing::instrument(level = "debug", skip(parse, settings))]
fn format(
biome_path: &BiomePath,
document_file_source: &DocumentFileSource,
parse: AnyParse,
settings: WorkspaceSettingsHandle,
) -> Result<Printed, WorkspaceError> {
let options = settings.format_options::<GritLanguage>(biome_path, document_file_source);

tracing::debug!("Format with the following options: \n{}", options);

let tree = parse.syntax();
let formatted = format_node(options, &tree)?;

match formatted.print() {
Ok(printed) => Ok(printed),
Err(error) => Err(WorkspaceError::FormatError(error.into())),
}
}
1 change: 1 addition & 0 deletions crates/biome_service/src/file_handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ use tracing::instrument;
mod astro;
mod css;
mod graphql;
mod grit;
mod html;
mod javascript;
mod json;
Expand Down
Loading