biomejs / biome

A toolchain for web projects, aimed to provide functionalities to maintain them. Biome offers formatter and linter, usable via CLI and LSP.
https://biomejs.dev
Apache License 2.0
12.53k stars 393 forks source link

📎 Embedded language formatting #3334

Open ah-yu opened 5 days ago

ah-yu commented 5 days ago

Preface

Some popular libraries allow code snippets in other languages to be embedded within JavaScript code. Users want to format these embedded code snippets within JavaScript to enhance the development experience.

Design

Simply put, the idea is to extract the code snippets from template strings, format them using the respective language's formatter, and then replace them back into the template string.

Handling Interpolation

We need to parse the entire template string and then format it based on the parsing results. However, template strings with interpolations are not valid CSS code (using CSS as an example here). Therefore, we need to preprocess the interpolations, turning the template string into a more valid CSS code. We plan to replace interpolations with a special string and then reinsert them after formatting.

To maximize parsing success, we chose to replace interpolations with grit metavariables. The reason for this choice you can find in https://github.com/biomejs/biome/pull/3228#issuecomment-2173404022

Changes to the Public API

Since JavaScript formatters cannot directly format code in other languages, we need to use external tools to format these other languages' code. To achieve this, we designed a generic trait instead of relying on specific implementations, maximizing the decoupling between different language formatters.

enum JsForeignLanguage {
    Css,
}

trait JsForeignLanguageFormatter {
    fn format(&self, language: JsForeignLanguage, source: &str) -> FormatResult<Document>;
}

Then we can add a new parameter to the format_node function to pass in the formatter for other languages.

pub fn format_node(
    options: JsFormatOptions,
+   foreign_language_formatter: impl JsForeignLanguageFormatter,
    root: &JsSyntaxNode,
) -> FormatResult<Formatted<JsFormatContext>> {
    biome_formatter::format_node(
        root,
        JsFormatLanguage::new(options, foreign_language_formatter),
    )
}

CLI

When formatting JavaScript files, we need to be aware of other languages' settings. For example, when formatting CSS code, we need to know the CSS formatter's settings.

LSP

The LSP provides a feature called format_range that formats code snippets. This feature relies on SourceMarkers generated during the printing process. Generating a SourceMarker depends on the position information of tokens in the source code. This position information is contained in the following two FormatElements:

https://github.com/biomejs/biome/blob/ce0068501c1c57e6382ca5e6d6b51fb45779eab5/crates/biome_formatter/src/format_element.rs#L36-L50

Since the formatting of embedded languages is done by extracting, preprocessing, and then separately parsing and formatting them, the source_position in these two FormatElement is inaccurate, and the entire template string is handled as a whole. Therefore, I recommend erasing these inaccurate source_position. It is acceptable to erase them because the format_range function will still be able to find the SourceMarker closest to the range start and end. If there is a need to format parts of the embedded code in the future, we can revisit this issue.

Tasks

Sec-ant commented 5 days ago

Great great work :rocket: . I'd like to add some additional notes. I will update them in this comment later.


TLDR, I think we should broaden the concept of embedded language. I'll provide my rationale below, gradually (been struggling with a tight schedule).

The Concept and Scope of Embedded Language

We should envision the introduction of embedded language to serve two primary purposes:

  1. Enhancing the Developer Experience: This feature aims to improve the developer experience when formatting foreign languages within their code. For example, when writing CSS template literals in a JavaScript file, it could be structured as follows and the formatter should be able to format the CSS code:

    const style = css`
     div {
       color: red;
     }
    `;
  2. Supporting Composable Parsing Infrastructure: This feature should also strengthen our parser infrastructure to support languages composed of multiple embedded languages. For instance, an HTML file can contain <style> tags with embedded CSS and <script> tags with embedded JavaScript. This composable parsing infrastructure allows us to fully support modern frameworks like Vue, Svelte, and Astro. By reusing the same parsing infrastructure for each embedded language (HTML, JavaScript, and CSS), we can seamlessly integrate and compose them in various ways.

Configuration of Embedded Language

Possible Configuration

I believe the configuration of embedded languages includes these aspects at least:

  1. Identifying CST Structures: The first step is to determine which CST (Concrete Syntax Tree) structures within a language can be considered as embedded languages. For example, in JavaScript, we might consider JsTemplateExpression as a block to have embedded languages in it.

  2. Determining the Language/Parser: Next, we need to identify the language or parser for the embedded language. For instance, we would use the tag within a JsTemplateExpression to identify the language and select the appropriate parser to parse this embedded language.

  3. Providing Language-Specific Options: We should offer language-specific options for embedded languages that can override the global language-specific options. So they can be parsed / formatted / linted with a different set of options.

  4. A Switch to Opt Out: There should be a switch for users to fully opt out from embedded language detection.

For the first two configuration items, I believe we can leverage our plugin infrastructure. This means users can configure different Grit patterns to inform Biome which CST structures in a language should be considered embedded language blocks and which parser should be used to parse them.

Regarding the third configuration item, we should utilize our existing configuration file structure for language-specific options. This can be done in a way similar to overrides, allowing users to specify different configurations for embedded languages.

Regarding the fourth configuration item, the opt-out option should be configurable for each language, and it should also be a top-level option.

Extent of Configurability

Relating to the two primary purposes mentioned earlier:

For the first purpose (enhancing the developer experience), users should be able to configure the above aforementioned settings freely. This is because the support for embedded languages in this context is not inherently part of the language itself. For example, different libraries may have different APIs for embedding CSS, such as css`...`, style`...`, or css.style`...`. Additionally, users might have their own SDKs or coding styles. Therefore, we should not hardcode these configurations into our infrastructure. Instead, we should provide users with a configuration interface using Grit patterns. I believe we can provide sane default presets to provide a nice out-of-box experience, but users should be able to override them as they want.

For the second purpose (supporting composable parsing infrastructure), there should be more restrictions. For example, when parsing Astro files, the frontmatter is defined as JavaScript code according to Astro's specification. In this case, we should not let users to override this behavior, but rather enforce the logic by our parser. Users shouldn't be allowed to opt out from the enforced logic. However, I think we should still offer the configurablity to the extent that users are allowed to add more patterns to target certain CST nodes as embedded language blocks.

[!NOTE] I will add an example of how the configuration would be like here.

Integration Phase of Embedded Language

Another critical consideration is determining at which phase embedded language support should be implemented: the parsing phase or the formatting phase. In #3228, we placed it in the formatting phase, which aligns with Prettier's approach. However, I believe Biome can improve on this.

The ideal phase for supporting embedded languages is the parsing phase. The rationale behind this is that, for languages like Astro (related to purpose 2), in the CST, the frontmatter can be mapped to JavaScript CST nodes, rather than being treated as a literal text node. This approach enhances the support experience for such compositional languages. Additionally, it allows our plugin and linter systems to reuse the same CST structure to handle the content within these embedded languages, so we can add embedded linting/checking support for them later.

One thing to consider in this approach is that we might also want to preserve the original CST nodes, so, for example, linter or formatter rules will still work for the container of the embedded language. Also, for languages that have interpolations, such as template literals in JavaScript, we should also keep the nodes of the expressions in the CST.

Nested Embedded Languages

[!NOTE] TBD. One example you can think of is embedded HTML in a JS file, in which there're inline <style> tags.

Indentation Handling in Embedded Language Formatting

[!NOTE] This is a tricky one because spaces at line starting can be significant when they appear in multi-line template literals. I'll elaborate later.

Interpolation Handling

[!NOTE] This has been discussed in #3228

Examples of Embedded Languages

[!NOTE] TBD. I'll come back later.