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 13 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
11 changes: 11 additions & 0 deletions Cargo.lock

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

8 changes: 7 additions & 1 deletion crates/biome_formatter/CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -424,9 +424,15 @@ pub fn run(spec_input_file: &str, _expected_file: &str, test_directory: &str, _f
return;
};

let options = HtmlFormatOptions::default();
let language = language::HtmlTestFormatLanguage::default();

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

snapshot.test()
}
Expand Down
13 changes: 10 additions & 3 deletions crates/biome_grit_formatter/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,16 @@ biome_grit_syntax = { workspace = true }
biome_rowan = { workspace = true }

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

biome_configuration = { path = "../biome_configuration" }
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"] }
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
24 changes: 24 additions & 0 deletions crates/biome_grit_formatter/tests/language.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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!()
}
}
27 changes: 27 additions & 0 deletions crates/biome_grit_formatter/tests/spec_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use biome_formatter_test::spec::{SpecSnapshot, SpecTestFile};
use biome_grit_formatter::{context::GritFormatOptions, GritFormatLanguage};
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, None) else {
panic!("Failed to set up snapshot test");
};

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

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

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, ""}
}
}
4 changes: 4 additions & 0 deletions crates/biome_grit_formatter/tests/specs/grit/as_modifier.grit
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
`function $name ($args) { $body }` as $func where {
$func => `const $name = ($args) => { $body }`,
$args <: contains `apple` => `mango`
}
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)
}
}
3 changes: 3 additions & 0 deletions crates/biome_service/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ 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_grit_syntax = { workspace = true }
biome_html_formatter = { workspace = true }
biome_html_parser = { workspace = true }
biome_html_syntax = { workspace = true }
Expand Down
115 changes: 115 additions & 0 deletions crates/biome_service/src/file_handlers/grit.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
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())),
}
}
5 changes: 5 additions & 0 deletions crates/biome_service/src/file_handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ use biome_parser::AnyParse;
use biome_project::PackageJson;
use biome_rowan::{FileSourceError, NodeCache};
use biome_string_case::StrExtension;
use grit::GritFileHandler;
use html::HtmlFileHandler;
pub use javascript::JsFormatterSettings;
use std::borrow::Cow;
Expand All @@ -48,6 +49,7 @@ use tracing::instrument;
mod astro;
mod css;
mod graphql;
mod grit;
mod html;
mod javascript;
mod json;
Expand Down Expand Up @@ -527,6 +529,8 @@ pub(crate) struct Features {
unknown: UnknownFileHandler,
graphql: GraphqlFileHandler,
html: HtmlFileHandler,
#[expect(unused)]
grit: GritFileHandler,
}

impl Features {
Expand All @@ -540,6 +544,7 @@ impl Features {
svelte: SvelteFileHandler {},
graphql: GraphqlFileHandler {},
html: HtmlFileHandler {},
grit: GritFileHandler {},
unknown: UnknownFileHandler::default(),
}
}
Expand Down
Loading