From 8f38f4264ade9564cd9ce911dbd78998a60c2d7c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:15:21 +0000 Subject: [PATCH 1/2] feat(server): navigation and block checks for Liquid templates Liquid had highlighting only. For 1.0 it gets what ERB, Haml and Slim have: go to definition, links, hover and completion for render, include and include_relative (Jekyll's _includes under _config.yml, otherwise the liquid gem's _name.liquid next to the file), and errors for unclosed {{ and {%, unclosed or stray block tags and mismatched end tags, also in `ruby-templates check`. Liquid is no longer marked experimental, and rubyTemplates.liquid.disabledDiagnostics switches the new rules off in the editor. Closes #98 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012jSfzj1UNFUHV9YmmbjLg4 --- CHANGELOG.md | 2 +- demo/README.md | 5 +- .../views/playground/broken/bad.html.liquid | 5 + .../app/views/playground/liquid/_card.liquid | 1 + .../app/views/playground/liquid/_config.yml | 1 + .../playground/liquid/_includes/nav.html | 1 + .../playground/liquid/product.html.liquid | 1 + package.json | 15 + server/src/checks.rs | 19 +- server/src/lib.rs | 1 + server/src/liquid.rs | 428 ++++++++++++++++++ server/src/lsp.rs | 36 +- server/src/options.rs | 5 +- server/src/rules.rs | 7 +- site/src/content/docs/guides/file-types.md | 22 +- .../docs/guides/highlighting-and-editing.md | 4 +- site/src/content/docs/guides/settings.md | 1 + .../content/docs/reference/diagnostics.mdx | 2 +- site/src/content/docs/reference/stability.md | 2 +- site/src/data/diagnostics.ts | 73 ++- src/client.js | 4 + test/broken/bad.html.liquid | 5 + test/cli.js | 9 +- test/e2e.js | 69 ++- 24 files changed, 691 insertions(+), 27 deletions(-) create mode 100644 demo/rails_app/app/views/playground/broken/bad.html.liquid create mode 100644 demo/rails_app/app/views/playground/liquid/_card.liquid create mode 100644 demo/rails_app/app/views/playground/liquid/_config.yml create mode 100644 demo/rails_app/app/views/playground/liquid/_includes/nav.html create mode 100644 server/src/liquid.rs create mode 100644 test/broken/bad.html.liquid diff --git a/CHANGELOG.md b/CHANGELOG.md index 8433b5c0..873db483 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ - **Breaking:** the `source` of every diagnostic is `ruby-templates`, for templates and for problems in a `.ruby-templates.toml` (it was `erb`, `haml`, `slim`, `ruby`, `liquid` and `ruby-templates-ls`). - **Breaking:** `Rails/I18nMissingKey` is renamed `Rails/MissingTranslation`, in diagnostics, `.ruby-templates.toml` and `disabledDiagnostics`; the old name is an unknown rule. - **Breaking:** the `rubyTemplates.reindentHaml` command is removed; Format Document and Format Selection do the same. -- Liquid is documented as experimental: the `liquid` language id, its extensions and its grammar are outside the 1.0 stability guarantees. +- Liquid is finished for 1.0: Go to Definition, document links, hover and completion for the files `{% render %}`, `{% include %}` and `{% include_relative %}` name (Jekyll `_includes/` under the nearest `_config.yml`, otherwise `_.liquid` next to the file), and errors for a `{{` or `{%` that is never closed, a block tag without its end tag, a stray end tag and a mismatched one (`Syntax/LiquidUnclosedTag`, `Syntax/LiquidUnclosedBlock`, `Syntax/LiquidStrayEndTag`, `Syntax/LiquidMismatchedEndTag`; `rubyTemplates.liquid.disabledDiagnostics`), also from `ruby-templates check`. Liquid is no longer labelled experimental. - The rules reference and the guides no longer describe shipped rules as a draft, a roadmap or planned, and no longer mention `ruby-templates-ls --check`. - `ruby-templates --version` and `ruby-templates-ls --version` (or `-V`) print the version and exit 0 (the language server no longer starts for them); `ruby-templates --help`, `check --help` and `format --help` exit 0 instead of 2. - `ruby-templates check` is faster on apps with many locale files or a large `app/javascript` (one template: about 700 ms to 45 ms on an app with 500 locale files, 700 scripts and `config.i18n.fallbacks = true`): `Rails/MissingTranslation` reads the default locale's files, once, and the other locales only when a key is missing there; the Stimulus check runs its patterns only over scripts that can register controllers. diff --git a/demo/README.md b/demo/README.md index 5621fa04..5f13de3e 100644 --- a/demo/README.md +++ b/demo/README.md @@ -126,6 +126,7 @@ - [ ] **D-30** `engine_render.html.erb` (партіали engine `blog`): рядок 1 «missing local: :post for app/views/blog/_post.html.erb» (сигнатура береться з engine). Рядок 2 (`blog/summary`, якого немає) не підкреслюється: `blog` це гем із `Gemfile.lock`, а гем може мати власні в'ю. Без блоку `PATH` у `Gemfile.lock` (див. D-28) з'являється й «Missing partial blog/_summary». Власні в'ю engine (`engines/blog/app/views/…`) render-перевірок не мають. - [ ] **D-31** `$B check demo/shop_app` (див. розділ 7) дає єдине попередження: `pages/index.html.erb:2`, `render "banner"` → «Missing partial pages/_banner, application/_banner». `products/index.html.erb:3`, `render "badge"` без попередження: `ProductsController` робить `include Themeable`, а `lib/themeable.rb` викликає `prepend_view_path`, тож Rails шукає ще й у `themes/` (там `products/_badge.html.erb`). `PagesController` нічого не підключає, тому там перевірка працює. - [ ] **D-32** Без файлу: `Ctrl+N`, мова _ERB_, встав ``, `
` і `<%= render "users/card" %>` окремими рядками. З'являються «`` without `alt`» і «`
` is never closed» (HTML-перевірки діють і в безіменному документі). Hover і F12 на `"users/card"` нічого не дають, а Output без помилок. +- [ ] **D-33** `bad.html.liquid`: чотири помилки (error), по одній на проблему. Рядок 1 `{% endunless %}` «has no open `unless` tag to close» (`Syntax/LiquidStrayEndTag`); рядок 4 `{% endfor %}` «doesn't close the open `if` tag; Liquid expects `endif`» (`Syntax/LiquidMismatchedEndTag`), `if` з рядка 2 окремо не підкреслюється; рядок 5 `{{` «is never closed» (`Syntax/LiquidUnclosedTag`), бо `}}` далі немає. Видали `{% endfor %}`: з'являється «`if` is never closed; add `endif`» на рядку 2 (`Syntax/LiquidUnclosedBlock`). `"rubyTemplates.liquid.disabledDiagnostics": ["Syntax/LiquidStrayEndTag"]` ховає перше. Вміст `{% comment %}` і `{% raw %}` не перевіряється. ## 4. Rails-навігація (`rails_app`) @@ -192,7 +193,7 @@ - [ ] **N-46** Перенесення партіала в `app/views`. `shared/_notice.html.erb` викликають два різні layout-и (вони не рендеряться разом). У Explorer перетягни файл у `app/views`: `render "shared/notice"` у `layouts/application.html.erb` (рядок 10) і `layouts/admin.html.slim` (рядок 7) стають `render "/notice"`. F12 на `"/notice"` відкриває `app/views/_notice.html.erb`. Після перевірки поверни файл (`git checkout -- demo && git clean -fd demo`). - [ ] **N-47** Підказки посилань (`Ctrl`/`Cmd` + наведення) показують шлях від кореня застосунку, а не повний шлях на диску: `"users/card"` (`users/index.html.erb:6`) → `app/views/users/_card.html.erb`, `data-controller="hello"` (там само, рядок 24) → `app/javascript/controllers/hello_controller.js`, `stylesheet_link_tag "application"` (`layouts/application.html.erb:6`) → `app/assets/stylesheets/application.css`, `layout "admin"` (`admin/base_controller.rb:3`) → `app/views/layouts/admin.html.slim`. - [ ] **N-48** Два застосунки (`demo/run.sh demo.code-workspace`). У `shop_app/app/views/products/index.html.erb` усе береться зі `shop_app`: F12 на `"users/card"` (рядок 4) і `"shared/footer"` (5) відкриває файли `shop_app/app/views/…`, а не `rails_app/…`; після `render "users/card", ` пропонується `customer:` (не `user:`); hover на `t(".title")` (2) показує лише `en: Products`; hover на `about_path` (6) дає `/about` → `pages#index`, F12 веде в `shop_app/config/routes.rb:5`. У `rails_app` лишається своє (N-01…N-25): `new_user_path` там є, а `about_path` ні. -- [ ] **N-49** Liquid не дає відповідей Rails. `playground/liquid/product.html.liquid`: F12, hover і `Ctrl`+клік на `"card"` (рядок 5) та `"users/card"` (6) нічого не роблять, посилань немає, у Problems порожньо, _Format Document_ нічого не змінює. `playground/liquid/_includes/header.html` це Liquid лише завдяки `files.associations` (S-07): звичайні `.html` розширення не забирає. +- [ ] **N-49** Liquid має власну навігацію, а не Rails-ну. `playground/liquid/product.html.liquid`: F12, hover і `Ctrl`+клік на `"card"` (рядок 5) ведуть у `liquid/_card.liquid` (hover показує цей файл, посилання є), на `header.html` (рядок 10) в `_includes/header.html` (тека з `_config.yml` це корінь Jekyll-сайту), на `"users/card"` (6) нікуди («No matching file found.» у hover), хоч поруч у Rails є `users/_card.html.*`. На новому рядку набери `{% include '`: пропонуються `header.html` і `nav.html`. `playground/liquid/_includes/header.html` це Liquid лише завдяки `files.associations` (S-07): `nav.html` у рядку 4 веде в `_includes/nav.html`. _Format Document_ нічого не змінює. **Контролери, суміжні файли, outline** @@ -241,7 +242,7 @@ B=server/target/release/ruby-templates $B check demo/rails_app/app/views # exit 1: playground/broken, format/heredoc (html_safe, F-12), format/unsafe.*, rules/*, shared/_nav (R-04), users/new $B check demo/rails_app/app/views/users # exit 1, рівно 3 попередження з new.html.erb $B check demo/rails_app/app/views/playground/preview # exit 0, нічого -$B check demo/rails_app/app/views/playground/liquid # exit 0, Liquid CLI не перевіряє +$B check demo/rails_app/app/views/playground/liquid # exit 0, нічого (теги збалансовані) $B check demo/rails_app/app/views/playground/rules # exit 1, 83 попередження: 78 у файлах правил (R-01…R-19), 5 у rules/format (R-27); routes.* без жодного (R-11) $B check demo/rails_app/app/views/playground/rules/img.html.erb # exit 0, нічого (C-04) $B check demo/rails_app/app/views/playground/rules/format # exit 1, 5 попереджень: Layout/LineLength і Style/ErbTrimMode (R-27) diff --git a/demo/rails_app/app/views/playground/broken/bad.html.liquid b/demo/rails_app/app/views/playground/broken/bad.html.liquid new file mode 100644 index 00000000..cbb69290 --- /dev/null +++ b/demo/rails_app/app/views/playground/broken/bad.html.liquid @@ -0,0 +1,5 @@ +{% endunless %} +{% if user %} +

{{ user.name }}

+{% endfor %} +

{{ title

diff --git a/demo/rails_app/app/views/playground/liquid/_card.liquid b/demo/rails_app/app/views/playground/liquid/_card.liquid new file mode 100644 index 00000000..f4b74da6 --- /dev/null +++ b/demo/rails_app/app/views/playground/liquid/_card.liquid @@ -0,0 +1 @@ +
{{ product.title }}
diff --git a/demo/rails_app/app/views/playground/liquid/_config.yml b/demo/rails_app/app/views/playground/liquid/_config.yml new file mode 100644 index 00000000..4179400a --- /dev/null +++ b/demo/rails_app/app/views/playground/liquid/_config.yml @@ -0,0 +1 @@ +title: Demo diff --git a/demo/rails_app/app/views/playground/liquid/_includes/nav.html b/demo/rails_app/app/views/playground/liquid/_includes/nav.html new file mode 100644 index 00000000..e684ac30 --- /dev/null +++ b/demo/rails_app/app/views/playground/liquid/_includes/nav.html @@ -0,0 +1 @@ + diff --git a/demo/rails_app/app/views/playground/liquid/product.html.liquid b/demo/rails_app/app/views/playground/liquid/product.html.liquid index 824f90ae..3d16f77c 100644 --- a/demo/rails_app/app/views/playground/liquid/product.html.liquid +++ b/demo/rails_app/app/views/playground/liquid/product.html.liquid @@ -8,3 +8,4 @@ Buy {% endif %} +{% include header.html %} diff --git a/package.json b/package.json index a1bd8489..4c432868 100644 --- a/package.json +++ b/package.json @@ -791,6 +791,21 @@ "uniqueItems": true, "description": "Built-in diagnostics to turn off in Jbuilder and Builder views, by rule name (`Department/Name`). A rule a `.ruby-templates.toml` switches with `enabled` follows the file." }, + "rubyTemplates.liquid.disabledDiagnostics": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "Syntax/LiquidUnclosedTag", + "Syntax/LiquidUnclosedBlock", + "Syntax/LiquidStrayEndTag", + "Syntax/LiquidMismatchedEndTag" + ] + }, + "default": [], + "uniqueItems": true, + "description": "Built-in Liquid diagnostics to turn off, by rule name (`Department/Name`). A rule a `.ruby-templates.toml` switches with `enabled` follows the file." + }, "rubyTemplates.slim.disabledDiagnostics": { "type": "array", "items": { diff --git a/server/src/checks.rs b/server/src/checks.rs index d1d40095..bfb57d84 100644 --- a/server/src/checks.rs +++ b/server/src/checks.rs @@ -7,6 +7,7 @@ use crate::erb::{html_lint, tags}; use crate::haml; use crate::lang::{haml_html_host, html_host, is_partial, slim_html_host, TemplateLang}; use crate::line_length; +use crate::liquid; use crate::rails::project::{Framework, Project, Projects}; use crate::rails::render_call::HamlPipes; use crate::rails::{ @@ -77,9 +78,14 @@ pub(crate) fn diagnostics_in( ) -> Vec { // Thor templates (`*.html.erb.tt`, `*.haml.tt`) mix the generator's ERB with the template's own tags or // lines, and their partials live outside app/views, so no check applies. - if doc.lang == TemplateLang::Liquid || uri.path().as_str().to_ascii_lowercase().ends_with(".tt") || !rules.diagnostics_enabled() { + if uri.path().as_str().to_ascii_lowercase().ends_with(".tt") || !rules.diagnostics_enabled() { return vec![]; } + // Liquid has none of the Rails lookups, so only its own tags are checked. + if doc.lang == TemplateLang::Liquid { + let reported = liquid::diagnostics(&doc.text).into_iter().filter(|d| util::code(d).is_none_or(|code| rules.reports(code))); + return reported.map(|d| Diagnostic { source: Some(DIAGNOSTIC_SOURCE.into()), ..d }).collect(); + } let path = util::file_path(uri); let project = path.as_deref().map(|path| Project::memoized(projects, path, None)); let ruby = path.as_deref().zip(project).map_or_else(RubyContext::outside_project, |(path, project)| project.ruby_context(path)); @@ -686,9 +692,13 @@ mod tests { let items = |lang: &str| { manifest["contributes"]["configuration"]["properties"][format!("rubyTemplates.{lang}.disabledDiagnostics")]["items"].clone() }; - for (section, lang) in - [("erb", TemplateLang::Erb), ("haml", TemplateLang::Haml), ("slim", TemplateLang::Slim), ("jbuilder", TemplateLang::Ruby)] - { + for (section, lang) in [ + ("erb", TemplateLang::Erb), + ("haml", TemplateLang::Haml), + ("slim", TemplateLang::Slim), + ("jbuilder", TemplateLang::Ruby), + ("liquid", TemplateLang::Liquid), + ] { let items = items(section); let listed: BTreeSet<&str> = items["enum"].as_array().unwrap().iter().map(|c| c.as_str().unwrap()).collect(); let lints = || crate::rules::RULES.iter().filter(|rule| rule.kind == crate::rules::Kind::Lint); @@ -711,6 +721,7 @@ mod tests { include_str!("rails/unknown_route.rs"), include_str!("haml/indent.rs"), include_str!("slim/indent.rs"), + include_str!("liquid.rs"), ] { assert!(!literal.is_match(src.split("#[cfg(test)]").next().unwrap()), "coded(…, \"literal\")"); } diff --git a/server/src/lib.rs b/server/src/lib.rs index 2f4775a0..4bfc296e 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -16,6 +16,7 @@ mod helpers; mod html; mod lang; mod line_length; +mod liquid; mod lsp; mod nested_interactive; mod options; diff --git a/server/src/liquid.rs b/server/src/liquid.rs new file mode 100644 index 00000000..ec50f8b9 --- /dev/null +++ b/server/src/liquid.rs @@ -0,0 +1,428 @@ +//! Liquid (Jekyll, the `liquid` gem): the files `render` and `include` name, and unbalanced tags. + +use crate::rails::paths::files_under; +use crate::util::{coded, error, slash_path, LineIndex}; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; +use tower_lsp_server::ls_types::Diagnostic; + +/// Stable diagnostic codes. +pub mod code { + pub const UNCLOSED_TAG: &str = "Syntax/LiquidUnclosedTag"; + pub const UNCLOSED_BLOCK: &str = "Syntax/LiquidUnclosedBlock"; + pub const STRAY_END_TAG: &str = "Syntax/LiquidStrayEndTag"; + pub const MISMATCHED_END_TAG: &str = "Syntax/LiquidMismatchedEndTag"; +} + +const JEKYLL_CONFIG: &str = "_config.yml"; +const JEKYLL_INCLUDES: &str = "_includes"; +/// The suffixes of a partial `render` finds next to the template: `_card.liquid`, `_card.html.liquid`. +const PARTIAL_SUFFIXES: [&str; 2] = [".html.liquid", ".liquid"]; +/// How deep below the template's folder completion looks for partials. +const COMPLETION_DEPTH: usize = 3; + +/// Tags that open a block; an unknown `endfoo` belongs to a custom tag the app registers and is left alone. +const BLOCKS: &[&str] = &["if", "unless", "for", "case", "capture", "comment", "raw", "tablerow", "form", "paginate", "highlight"]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tag { + Render, + Include, + IncludeRelative, +} + +impl Tag { + fn name(self) -> &'static str { + match self { + Tag::Render => "Render", + Tag::Include => "Include", + Tag::IncludeRelative => "Include relative", + } + } +} + +/// The file a `{% render %}` or `{% include %}` names, as byte columns of its line. +#[derive(Debug, PartialEq, Eq)] +pub struct LiquidRef { + pub tag: Tag, + pub name: String, + pub start: usize, + pub end: usize, +} + +fn tag_of(word: &str) -> Tag { + match word { + "render" => Tag::Render, + "include" => Tag::Include, + _ => Tag::IncludeRelative, + } +} + +/// The names of the `render`, `include` and `include_relative` tags on `line`. Jekyll's unquoted `include footer.html` +/// counts; a dynamic name (`{{ var }}`) and an unquoted `render` argument (a variable) do not. +pub fn refs(line: &str) -> Vec { + static NAME: LazyLock = LazyLock::new(|| { + regex::Regex::new(r#"\{%-?\s*(render|include_relative|include)\s+(?:'([^'{}]*)'|"([^"{}]*)"|([^\s'"{}%,]+))"#).unwrap() + }); + NAME.captures_iter(line) + .filter_map(|found| { + let tag = tag_of(&found[1]); + let name = found.get(2).or(found.get(3)).or_else(|| found.get(4).filter(|_| tag != Tag::Render))?; + (!name.as_str().is_empty()).then(|| LiquidRef { tag, name: name.as_str().to_string(), start: name.start(), end: name.end() }) + }) + .collect() +} + +/// The reference whose name the cursor, at byte `col`, is in or next to. +pub fn ref_at(line: &str, col: usize) -> Option { + refs(line).into_iter().find(|r| (r.start..=r.end).contains(&col)) +} + +/// The tag and the part of the quoted name typed before byte `col`, inside `{% render '…` or `{% include "…`. +pub fn name_prefix(line: &str, col: usize) -> Option<(Tag, String)> { + static TYPING: LazyLock = + LazyLock::new(|| regex::Regex::new(r#"\{%-?\s*(render|include_relative|include)\s+['"]([^'"{}%]*)$"#).unwrap()); + let found = TYPING.captures(line.get(..col)?)?; + Some((tag_of(&found[1]), found[2].to_string())) +} + +/// The nearest folder above `current` with a Jekyll `_config.yml`. +fn jekyll_root(current: &Path) -> Option<&Path> { + current.ancestors().skip(1).find(|dir| dir.join(JEKYLL_CONFIG).is_file()) +} + +/// The files the reference stands for: Jekyll's `_includes/` and the file next to the template for +/// `include_relative`; otherwise the `liquid` gem's `_.liquid` next to the template. +pub fn resolve(current: &Path, r: &LiquidRef) -> Vec { + let name = Path::new(&r.name); + let Some(dir) = current.parent().filter(|_| !name.is_absolute()) else { return vec![] }; + let named = match (r.tag, jekyll_root(current)) { + (Tag::IncludeRelative, _) => vec![dir.join(name)], + (Tag::Include, Some(root)) => vec![root.join(JEKYLL_INCLUDES).join(name)], + _ => { + let Some(file) = name.file_name().and_then(|file| file.to_str()) else { return vec![] }; + PARTIAL_SUFFIXES.iter().map(|suffix| dir.join(name.with_file_name(format!("_{file}{suffix}")))).collect() + } + }; + named.into_iter().filter(|file| file.is_file()).collect() +} + +/// The names the reference's quotes can hold, with the file each stands for. +pub fn candidates(current: &Path, tag: Tag) -> Vec<(String, PathBuf)> { + let Some(dir) = current.parent() else { return vec![] }; + let (root, partials) = match (tag, jekyll_root(current)) { + (Tag::IncludeRelative, _) => (dir.to_path_buf(), false), + (Tag::Include, Some(root)) => (root.join(JEKYLL_INCLUDES), false), + _ => (dir.to_path_buf(), true), + }; + let depth = if root == dir { COMPLETION_DEPTH } else { usize::MAX }; + let mut named: Vec<(String, PathBuf)> = files_under(&root, depth) + .into_iter() + .filter(|file| file != current) + .filter_map(|file| { + let relative = slash_path(file.strip_prefix(&root).ok()?); + let name = if partials { partial_name(&relative)? } else { relative }; + Some((name, file)) + }) + .collect(); + named.sort(); + named +} + +/// `shared/_card.liquid` is `shared/card`. +fn partial_name(relative: &str) -> Option { + let (folder, file) = relative.rsplit_once('/').map_or(("", relative), |(folder, file)| (folder, file)); + let stem = PARTIAL_SUFFIXES.iter().find_map(|suffix| file.strip_suffix(suffix))?.strip_prefix('_')?; + Some(if folder.is_empty() { stem.to_string() } else { format!("{folder}/{stem}") }) +} + +/// What hovering a reference shows: the files it resolves to, from the Jekyll site's or the template's folder. +pub fn hover(current: &Path, r: &LiquidRef) -> String { + let found = resolve(current, r); + if found.is_empty() { + return format!("**{}** `{}`\n\nNo matching file found.", r.tag.name(), r.name); + } + let base = jekyll_root(current).or(current.parent()); + let list: Vec = + found.iter().map(|file| format!("- `{}`", slash_path(base.and_then(|b| file.strip_prefix(b).ok()).unwrap_or(file)))).collect(); + format!("**{}** `{}`\n\n{}", r.tag.name(), r.name, list.join("\n")) +} + +/// What `{% comment %}` and `{% raw %}` hold is text, up to their end tag. +struct Verbatim { + end: &'static str, + /// Comments nest: Liquid counts the `{% comment %}` inside one. + nested: usize, +} + +struct OpenBlock { + name: &'static str, + start: usize, + end: usize, +} + +struct Scanner { + stack: Vec, + verbatim: Option, + /// Byte spans, code and message of each problem. + found: Vec<(usize, usize, &'static str, String)>, +} + +impl Scanner { + /// A tag called `name` whose `{% … %}`, or statement of a `{% liquid %}`, spans `start..end`. + fn tag(&mut self, name: &str, start: usize, end: usize) { + if let Some(verbatim) = &mut self.verbatim { + if name == "comment" && verbatim.end == "endcomment" { + verbatim.nested += 1; + } else if name == verbatim.end && verbatim.nested > 0 { + verbatim.nested -= 1; + } else if name == verbatim.end { + self.verbatim = None; + self.stack.pop(); + } + return; + } + if let Some(block) = BLOCKS.iter().find(|block| **block == name) { + self.stack.push(OpenBlock { name: block, start, end }); + self.verbatim = match *block { + "comment" => Some(Verbatim { end: "endcomment", nested: 0 }), + "raw" => Some(Verbatim { end: "endraw", nested: 0 }), + _ => None, + }; + } else if let Some(block) = name.strip_prefix("end").filter(|block| BLOCKS.contains(block)) { + self.close(block, name, start, end); + } + } + + /// An end tag closes the innermost open block of its kind; the blocks inside it were left open. + fn close(&mut self, block: &str, name: &str, start: usize, end: usize) { + if let Some(index) = self.stack.iter().rposition(|open| open.name == block) { + for open in self.stack.split_off(index + 1) { + self.unclosed(&open); + } + self.stack.pop(); + } else if let Some(open) = self.stack.last() { + let message = format!("`{name}` doesn't close the open `{}` tag; Liquid expects `end{}`", open.name, open.name); + self.found.push((start, end, code::MISMATCHED_END_TAG, message)); + // Read as a typo for the end tag it should be, so the block isn't reported a second time. + self.stack.pop(); + } else { + self.found.push((start, end, code::STRAY_END_TAG, format!("`{name}` has no open `{block}` tag to close"))); + } + } + + fn unclosed(&mut self, open: &OpenBlock) { + let message = format!("`{}` is never closed; add `end{}`", open.name, open.name); + self.found.push((open.start, open.end, code::UNCLOSED_BLOCK, message)); + } +} + +/// The offset of the next `{{` or `{%` at or after `from`. +fn next_opener(text: &str, from: usize) -> Option { + let mut at = from; + while let Some(found) = text[at..].find('{') { + at += found; + if matches!(text.as_bytes().get(at + 1), Some(b'{' | b'%')) { + return Some(at); + } + at += 1; + } + None +} + +fn word_at(text: &str) -> &str { + let end = text.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')).unwrap_or(text.len()); + &text[..end] +} + +/// Tags and outputs that are never closed, block tags without their end tag and end tags without their block. +pub fn diagnostics(text: &str) -> Vec { + let mut scanner = Scanner { stack: vec![], verbatim: None, found: vec![] }; + let mut at = 0; + while let Some(open) = next_opener(text, at) { + let is_tag = text[open..].starts_with("{%"); + if !is_tag && scanner.verbatim.is_some() { + at = open + 2; + continue; + } + let Some(length) = text[open + 2..].find(if is_tag { "%}" } else { "}}" }) else { + if scanner.verbatim.is_none() { + scanner.found.push((open, open + 2, code::UNCLOSED_TAG, format!("`{}` is never closed", &text[open..open + 2]))); + } + break; + }; + let close = open + 2 + length; + at = close + 2; + if !is_tag { + continue; + } + let body = &text[open + 2..close]; + let inner = body.strip_prefix('-').unwrap_or(body); + let name = word_at(inner.trim_start()); + if name == "liquid" && scanner.verbatim.is_none() { + let statements = open + 2 + (body.len() - inner.len()) + (inner.len() - inner.trim_start().len()) + name.len(); + for (offset, line) in crate::util::lines_with_offsets(&text[statements..close]) { + let trimmed = line.trim_start(); + let word = word_at(trimmed); + let start = statements + offset + (line.len() - trimmed.len()); + scanner.tag(word, start, start + word.len()); + } + } else { + scanner.tag(name, open, close + 2); + } + } + for open in std::mem::take(&mut scanner.stack) { + scanner.unclosed(&open); + } + let lines = LineIndex::new(text); + scanner.found.sort_by_key(|(start, ..)| *start); + scanner.found.into_iter().map(|(start, end, code, message)| coded(error(lines.range(start, end), message), code)).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::util::{code as code_of, write_files}; + + #[test] + fn refs_read_literal_names_only() { + let line = r#"{% render 'card' %}{%- include "a/b.html", x: 1 -%} {% include footer.html %} {% include_relative x.md %}"#; + let found: Vec<_> = refs(line).into_iter().map(|r| (r.tag, r.name)).collect(); + assert_eq!( + found, + [ + (Tag::Render, "card".to_string()), + (Tag::Include, "a/b.html".to_string()), + (Tag::Include, "footer.html".to_string()), + (Tag::IncludeRelative, "x.md".to_string()), + ] + ); + assert_eq!(&line[refs(line)[0].start..refs(line)[0].end], "card"); + for dynamic in + ["{{ x }}", "{% render '{{ x }}' %}", "{% render card %}", "{% render '' %}", "{% included 'a' %}", "{% assign render = 'a' %}"] + { + assert!(refs(dynamic).is_empty(), "{dynamic}"); + } + let accented = "é {% render 'card' %}"; + assert_eq!(refs(accented).iter().map(|r| &accented[r.start..r.end]).collect::>(), ["card"]); + } + + #[test] + fn the_cursor_finds_its_reference_and_typed_prefix() { + let line = "{% render 'ca' %}"; + assert_eq!(ref_at(line, 12).map(|r| r.name), Some("ca".to_string())); + assert!(ref_at(line, 3).is_none()); + assert_eq!(name_prefix(line, 12), Some((Tag::Render, "c".to_string()))); + assert_eq!(name_prefix("{%- include_relative \"", 22), Some((Tag::IncludeRelative, String::new()))); + assert!(name_prefix("{% render 'ca' %} ", 18).is_none()); + assert!(name_prefix("{% assign x = 'ca", 17).is_none()); + } + + fn temp(name: &str) -> PathBuf { + let root = std::env::temp_dir().join(format!("rt-liquid-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + root + } + + fn lookup(current: &Path, line: &str) -> Vec { + refs(line).first().map(|r| resolve(current, r)).unwrap_or_default() + } + + #[test] + fn jekyll_includes_come_from_the_site_root() { + let root = temp("jekyll"); + write_files( + &root, + &[ + ("_config.yml", ""), + ("_includes/footer.html", ""), + ("_includes/shared/nav.html", ""), + ("blog/post.md", ""), + ("blog/side.html", ""), + ], + ); + let post = root.join("blog/post.md"); + assert_eq!(lookup(&post, "{% include footer.html %}"), [root.join("_includes/footer.html")]); + assert_eq!(lookup(&post, "{% include 'shared/nav.html' %}"), [root.join("_includes/shared/nav.html")]); + assert_eq!(lookup(&post, "{% include_relative side.html %}"), [root.join("blog/side.html")]); + assert!(lookup(&post, "{% include 'missing.html' %}").is_empty()); + assert!(lookup(&post, "{% include '/etc/passwd' %}").is_empty()); + let included: Vec<_> = candidates(&post, Tag::Include).into_iter().map(|(name, _)| name).collect(); + assert_eq!(included, ["footer.html", "shared/nav.html"]); + let relative: Vec<_> = candidates(&post, Tag::IncludeRelative).into_iter().map(|(name, _)| name).collect(); + assert_eq!(relative, ["side.html"]); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn without_jekyll_a_partial_is_underscored_next_to_the_template() { + let root = temp("gem"); + write_files( + &root, + &[("show.liquid", ""), ("_card.liquid", ""), ("_row.html.liquid", ""), ("shared/_nav.liquid", ""), ("plain.liquid", "")], + ); + let show = root.join("show.liquid"); + assert_eq!(lookup(&show, "{% render 'card' %}"), [root.join("_card.liquid")]); + assert_eq!(lookup(&show, "{% include 'row' %}"), [root.join("_row.html.liquid")]); + assert_eq!(lookup(&show, "{% render 'shared/nav' %}"), [root.join("shared/_nav.liquid")]); + assert!(lookup(&show, "{% render 'plain' %}").is_empty()); + let named: Vec<_> = candidates(&show, Tag::Render).into_iter().map(|(name, _)| name).collect(); + assert_eq!(named, ["card", "row", "shared/nav"]); + assert!(hover(&show, &refs("{% render 'card' %}")[0]).contains("- `_card.liquid`")); + assert!(hover(&show, &refs("{% render 'nope' %}")[0]).contains("No matching file found.")); + std::fs::remove_dir_all(&root).unwrap(); + } + + fn found(text: &str) -> Vec<(String, u32, u32)> { + let at = |d: &Diagnostic| (code_of(d).unwrap().to_string(), d.range.start.line, d.range.start.character); + diagnostics(text).iter().map(at).collect() + } + + fn at(code: &str, line: u32, column: u32) -> (String, u32, u32) { + (code.to_string(), line, column) + } + + #[test] + fn balanced_blocks_are_clean() { + for text in [ + "{% if a %}x{% elsif b %}y{% else %}z{% endif %}", + "{%- for i in (1..3) -%}{% case i %}{% when 1 %}a{% endcase %}{%- endfor -%}", + "{% unless a %}{% capture b %}{{ c }}{% endcapture %}{% endunless %}", + "{% form 'x' %}{% paginate a by 2 %}{% tablerow i in a %}{% endtablerow %}{% endpaginate %}{% endform %}", + "{% comment %}{% if a %} {{ never closed {% endcomment %}{% raw %}{% for %}{{ x {% endraw %}", + "{% comment %}{% comment %}inner{% endcomment %}{% endcomment %}", + "{% custom %}x{% endcustom %}{% assign a = 1 %}{% # note %}{%- liquid\n if a\n echo b\n endif\n-%}", + "{% highlight ruby %}{{ x }}{% endhighlight %}", + "", + ] { + assert_eq!(found(text), [], "{text}"); + } + } + + #[test] + fn unbalanced_tags_are_reported_where_they_are() { + assert_eq!(found("{% if a %}\n x\n"), [at(code::UNCLOSED_BLOCK, 0, 0)]); + assert_eq!(found("x\n{% endif %}"), [at(code::STRAY_END_TAG, 1, 0)]); + assert_eq!(found("{% if a %}{% endfor %}"), [at(code::MISMATCHED_END_TAG, 0, 10)]); + assert_eq!(found("{% if a %}{% for b in c %}{% endif %}"), [at(code::UNCLOSED_BLOCK, 0, 10)]); + assert_eq!(found("é {{ x"), [at(code::UNCLOSED_TAG, 0, 2)]); + assert_eq!(found("{% comment %}never ends"), [at(code::UNCLOSED_BLOCK, 0, 0)]); + assert_eq!(found("{% raw %}{{ {% endraw %}{% endraw %}"), [at(code::STRAY_END_TAG, 0, 24)]); + assert_eq!(found("{% if a %}{% endif %}{% if b %}{{ c"), [at(code::UNCLOSED_BLOCK, 0, 21), at(code::UNCLOSED_TAG, 0, 31)]); + } + + #[test] + fn a_liquid_tag_holds_statements_one_per_line() { + assert_eq!(found("{% liquid\n if a\n echo b\n%}"), [at(code::UNCLOSED_BLOCK, 1, 2)]); + assert_eq!(found("{%- liquid\n endfor\n-%}"), [at(code::STRAY_END_TAG, 1, 2)]); + assert_eq!(found("{% liquid\n comment\n if a\n endcomment\n%}"), []); + assert_eq!(found("{% liquid if a %}{% endif %}"), []); + } + + #[test] + fn broken_fixture() { + let got = found(include_str!("../../test/broken/bad.html.liquid")); + let want = [at(code::STRAY_END_TAG, 0, 0), at(code::MISMATCHED_END_TAG, 3, 0), at(code::UNCLOSED_TAG, 4, 3)]; + assert_eq!(got, want); + } +} diff --git a/server/src/lsp.rs b/server/src/lsp.rs index 62bf5b35..4b7b084e 100644 --- a/server/src/lsp.rs +++ b/server/src/lsp.rs @@ -9,6 +9,7 @@ use crate::completion::helpers_for; use crate::erb::output_control_flow::OUTPUT_CONTROL_FLOW; use crate::erb::tags; use crate::lang::{file_name, is_partial, TemplateLang}; +use crate::liquid; use crate::options::Options; use crate::rails::controllers::Target; use crate::rails::output_lints::{output_marker_edit, SILENT_HELPER, SILENT_RENDER}; @@ -340,6 +341,11 @@ impl LanguageServer for Backend { async fn goto_definition(&self, p: GotoDefinitionParams) -> Result> { let uri = p.text_document_position_params.text_document.uri; let pos = p.text_document_position_params.position; + if let Some((path, doc)) = self.liquid_doc(&uri) { + let (_, line, col) = util::line_at(&doc.text, pos); + let found = liquid::ref_at(line, col).map(|r| liquid::resolve(&path, &r)).unwrap_or_default(); + return Ok(locations_response(found.into_iter().filter_map(file_location).collect())); + } if self.is_liquid(&uri) { return Ok(None); } @@ -403,6 +409,16 @@ impl LanguageServer for Backend { async fn document_link(&self, p: DocumentLinkParams) -> Result>> { let uri = p.text_document.uri; + if let Some((path, doc)) = self.liquid_doc(&uri) { + let mut links = Vec::new(); + for (i, (_, line)) in util::lines_with_offsets(&doc.text).enumerate() { + for r in liquid::refs(line) { + let range = util::span_range(i, line, r.start, r.end); + links.extend(liquid::resolve(&path, &r).first().and_then(|target| file_link(range, target, &path))); + } + } + return Ok(Some(links)); + } if self.is_liquid(&uri) { return Ok(None); } @@ -439,6 +455,10 @@ impl LanguageServer for Backend { async fn hover(&self, p: HoverParams) -> Result> { let uri = p.text_document_position_params.text_document.uri; let pos = p.text_document_position_params.position; + if let Some((path, doc)) = self.liquid_doc(&uri) { + let (_, line, col) = util::line_at(&doc.text, pos); + return Ok(liquid::ref_at(line, col).and_then(|r| markdown_hover(liquid::hover(&path, &r)))); + } if self.is_liquid(&uri) { return Ok(None); } @@ -845,6 +865,14 @@ impl LanguageServer for Backend { async fn completion(&self, p: CompletionParams) -> Result> { let uri = p.text_document_position.text_document.uri; let pos = p.text_document_position.position; + if let Some((path, doc)) = self.liquid_doc(&uri) { + let (_, line, col) = util::line_at(&doc.text, pos); + let Some((tag, prefix)) = liquid::name_prefix(line, col) else { return Ok(None) }; + let names = off_server_task(move || liquid::candidates(&path, tag)).await?; + let named = names.into_iter().filter(|(name, _)| name.starts_with(&prefix)); + let items = named.map(|(name, file)| util::completion_item(name, CompletionItemKind::FILE, file_name_of(&file))).collect(); + return Ok(Some(CompletionResponse::Array(items))); + } if self.is_liquid(&uri) { return Ok(None); } @@ -908,11 +936,17 @@ impl Backend { } } - /// Liquid is highlighted only: every Rails lookup would misfire on it. + /// Liquid has its own lookups and none of Rails': every Rails one would misfire on it. fn is_liquid(&self, uri: &Uri) -> bool { self.docs.get(uri).is_some_and(|doc| doc.lang == TemplateLang::Liquid) } + /// The path and a copy of the open Liquid file at `uri`. + fn liquid_doc(&self, uri: &Uri) -> Option<(PathBuf, Doc)> { + let doc = self.docs.get(uri).filter(|doc| doc.lang == TemplateLang::Liquid).map(|doc| doc.clone())?; + Some((util::file_path(uri)?, doc)) + } + /// A copy of the open template at `uri`, so no `docs` guard is held across an `.await` (it would block the next /// `did_change`) or while other documents are read; none for Liquid. fn template_doc(&self, uri: &Uri) -> Option { diff --git a/server/src/options.rs b/server/src/options.rs index 5b3858bb..e9d47f40 100644 --- a/server/src/options.rs +++ b/server/src/options.rs @@ -1,13 +1,14 @@ -//! `initializationOptions`, from the `rubyTemplates.{slim,erb,haml,jbuilder}.*` settings. +//! `initializationOptions`, from the `rubyTemplates.{slim,erb,haml,jbuilder,liquid}.*` settings. use crate::lang::TemplateLang; /// The settings sections with a `disabledDiagnostics` list, and the languages each covers. -const SECTIONS: [(&str, &[TemplateLang]); 4] = [ +const SECTIONS: [(&str, &[TemplateLang]); 5] = [ ("slim", &[TemplateLang::Slim, TemplateLang::Skim]), ("erb", &[TemplateLang::Erb]), ("haml", &[TemplateLang::Haml]), ("jbuilder", &[TemplateLang::Ruby]), + ("liquid", &[TemplateLang::Liquid]), ]; /// The sections whose `diagnostics.enabled` and `format.enabled` switch their languages off. const SWITCHED_SECTIONS: [&str; 3] = ["erb", "haml", "slim"]; diff --git a/server/src/rules.rs b/server/src/rules.rs index f54dfbad..116da846 100644 --- a/server/src/rules.rs +++ b/server/src/rules.rs @@ -5,7 +5,7 @@ pub mod resolve; use crate::lang::TemplateLang; use crate::line_length::LINE_LENGTH; -use TemplateLang::{Erb, Haml, Ruby, Slim}; +use TemplateLang::{Erb, Haml, Liquid, Ruby, Slim}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { @@ -150,6 +150,10 @@ pub const RULES: &[Rule] = &[ lint("Syntax/UnclosedAttribute", "An attribute list or value that is never closed.", HAML_SLIM), lint("Syntax/BadDedent", "A line un-indented to a level no open line has.", &[Slim]), lint("Syntax/UnknownEngine", "An embedded engine Slim doesn't know.", &[Slim]), + lint("Syntax/LiquidUnclosedTag", "A `{{` or `{%` with no `}}` or `%}` after it.", &[Liquid]), + lint("Syntax/LiquidUnclosedBlock", "A block tag such as `if` or `for` with no end tag.", &[Liquid]), + lint("Syntax/LiquidStrayEndTag", "An end tag with no open block to close.", &[Liquid]), + lint("Syntax/LiquidMismatchedEndTag", "An end tag that doesn't match the innermost open block.", &[Liquid]), lint("Html/UnexpectedCloseTag", "An end tag with no open element of that name.", &[Erb]), lint("Html/MismatchedCloseTag", "An end tag that doesn't close the innermost open element.", &[Erb]), lint("Html/UnclosedElement", "An element whose end tag never comes.", &[Erb]), @@ -264,6 +268,7 @@ mod tests { include_str!("erb/output_control_flow.rs"), include_str!("haml/indent.rs"), include_str!("slim/indent.rs"), + include_str!("liquid.rs"), include_str!("ruby/generated.rs"), ]; let declared: HashSet<&str> = sources.iter().flat_map(|src| re.captures_iter(src).map(|c| c.get(1).unwrap().as_str())).collect(); diff --git a/site/src/content/docs/guides/file-types.md b/site/src/content/docs/guides/file-types.md index e4c6cbcd..41464f28 100644 --- a/site/src/content/docs/guides/file-types.md +++ b/site/src/content/docs/guides/file-types.md @@ -22,7 +22,7 @@ The file name picks the language id, which decides the comment syntax and the `[ | `.md.erb` | `erb-markdown` | `` | Markdown + Ruby | none | no | | `.rb.erb` | `erb-ruby` | `#` | Ruby | none | no | | `.yml.erb`, `.yaml.erb` | `erb-yaml` | `#` | YAML + Ruby | none | no | -| `.liquid`, `.html.liquid` | `liquid` (experimental) | `{% comment %}` | HTML + Liquid | none | no | +| `.liquid`, `.html.liquid` | `liquid` | `{% comment %}` | HTML + Liquid | `Syntax/Liquid*` | no | Every ERB row gets the ERB and Ruby checks and, under `app/views`, the `render` checks (`unresolved-render`, `strict-locals`). Only HTML hosts add the HTML ones (unclosed or unbalanced tags, missing `alt`, duplicate `id`), linked tag renaming and attribute completion. Any other bare `.erb` (`nginx.conf.erb`) gets the ERB and Ruby checks only. @@ -80,9 +80,7 @@ Items: <%= @items.size %> ## Liquid -Liquid support is experimental and not covered by the 1.0 stability guarantees: the `liquid` language id, its file extensions and its grammar may change in a minor release. - -`liquid` (Shopify themes, Jekyll) is highlighting, comment toggling, bracket and `{{ }}` / `{% %}` auto-closing and indentation only: none of the Rails lookups or checks apply to it. +`liquid` (Shopify themes, Jekyll, the `liquid` gem) has highlighting, comment toggling, bracket and `{{ }}` / `{% %}` auto-closing, indentation, navigation to the files `render` and `include` name, and a check of its tags. None of the Rails lookups or checks apply to it, and it is not formatted. ```liquid title="_includes/card.html.liquid" {% if page.author %} @@ -98,4 +96,20 @@ Plain `.html` files are not claimed, so Jekyll includes need an association: } ``` +With the association, an include opens as Liquid, with its own navigation and checks. + +### Navigation and completion + +Go to Definition, Ctrl/Cmd+click links and hover work on the name in `{% render 'card' %}`, `{% include 'card' %}`, `{% include_relative 'card.html' %}` and Jekyll's unquoted `{% include footer.html %}`. Completion offers the names inside the quotes. A dynamic name (`{{ var }}`, a variable) is left alone. Where the name is looked up: + +| Tag | Where | +| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `include` under a Jekyll site | `_includes/`; the site is the nearest folder above the file with a `_config.yml` | +| `include_relative` | ``, relative to the file | +| `render`, and `include` without Jekyll | `_.liquid` or `_.html.liquid` in the file's folder, as the `liquid` gem looks it up; `shared/card` is `shared/_card.liquid` | + +### Checks + +The language server reports, as errors, the tags that stop a template from rendering: a `{{` or `{%` that is never closed (`Syntax/LiquidUnclosedTag`), a block tag (`if`, `unless`, `for`, `case`, `capture`, `comment`, `raw`, `tablerow`, `form`, `paginate`, `highlight`, also on the lines of a `{% liquid %}` tag) without its end tag (`Syntax/LiquidUnclosedBlock`), an end tag with nothing to close (`Syntax/LiquidStrayEndTag`) and an end tag for another block (`Syntax/LiquidMismatchedEndTag`). `{% comment %}` and `{% raw %}` are not read as tags, and tags you register yourself are left alone. `ruby-templates check` reports them too, and `rubyTemplates.liquid.disabledDiagnostics` turns them off. See [Diagnostics](/vscode-ruby-templates/reference/diagnostics/). + If Shopify's Liquid extension also contributes `liquid`, disable one of the two for the workspace: VS Code uses one grammar per language id. diff --git a/site/src/content/docs/guides/highlighting-and-editing.md b/site/src/content/docs/guides/highlighting-and-editing.md index 81e0eeb2..03010c1e 100644 --- a/site/src/content/docs/guides/highlighting-and-editing.md +++ b/site/src/content/docs/guides/highlighting-and-editing.md @@ -1,13 +1,13 @@ --- title: Highlighting and editing -description: Syntax highlighting, semantic colours, tag closing, linked editing, snippets and Emmet for ERB, Haml, Slim, Skim and Liquid (experimental). +description: Syntax highlighting, semantic colours, tag closing, linked editing, snippets and Emmet for ERB, Haml, Slim, Skim and Liquid. sidebar: order: 4 --- ## Syntax highlighting -Full syntax highlighting for ERB (`.html.erb`, `.erubi`, `.js.erb`, `.css.erb`, `.json.erb`, `.yml.erb`, …), Haml, Slim, Skim and Liquid (experimental), including embedded JavaScript, CSS, SCSS, CoffeeScript and Markdown blocks. Every code example on this site is highlighted with the extension's own grammars. +Full syntax highlighting for ERB (`.html.erb`, `.erubi`, `.js.erb`, `.css.erb`, `.json.erb`, `.yml.erb`, …), Haml, Slim, Skim and Liquid, including embedded JavaScript, CSS, SCSS, CoffeeScript and Markdown blocks. Every code example on this site is highlighted with the extension's own grammars. ```slim title="app/views/users/show.html.slim" .card diff --git a/site/src/content/docs/guides/settings.md b/site/src/content/docs/guides/settings.md index e173cfe4..16377db6 100644 --- a/site/src/content/docs/guides/settings.md +++ b/site/src/content/docs/guides/settings.md @@ -26,6 +26,7 @@ Editor settings for one template language use its language id, such as `[erb]`, | `rubyTemplates.erb.disabledDiagnostics` | `[]` | Built-in ERB diagnostics to turn off, by rule name. | | `rubyTemplates.haml.disabledDiagnostics` | `[]` | Built-in Haml diagnostics to turn off, by rule name. | | `rubyTemplates.jbuilder.disabledDiagnostics` | `[]` | Built-in diagnostics to turn off in Jbuilder and Builder views, by rule name. | +| `rubyTemplates.liquid.disabledDiagnostics` | `[]` | Built-in Liquid diagnostics to turn off, by rule name. | | `rubyTemplates.slim.disabledDiagnostics` | `[]` | Built-in Slim diagnostics to turn off, by rule name. | | `rubyTemplates.erb.diagnostics.enabled` | `true` | Show the language server's diagnostics in ERB files. Turn off to silence them all. | | `rubyTemplates.haml.diagnostics.enabled` | `true` | Show the language server's diagnostics in Haml files. Turn off to silence them all. | diff --git a/site/src/content/docs/reference/diagnostics.mdx b/site/src/content/docs/reference/diagnostics.mdx index a05c8b5d..7ab1eda5 100644 --- a/site/src/content/docs/reference/diagnostics.mdx +++ b/site/src/content/docs/reference/diagnostics.mdx @@ -34,7 +34,7 @@ Or list the codes to turn off for a language in your `settings.json`: "rubyTemplates.haml.disabledDiagnostics": ["Rails/MissingPartial"] ``` -`rubyTemplates.slim.disabledDiagnostics` also applies to Skim templates, and `rubyTemplates.jbuilder.disabledDiagnostics` to Jbuilder and Builder views. To silence a whole language, set `rubyTemplates.erb.diagnostics.enabled`, `rubyTemplates.haml.diagnostics.enabled` or `rubyTemplates.slim.diagnostics.enabled` to `false` (in a `.ruby-templates.toml`: `diagnostics.enabled = false` under `[erb]`, `[haml]` or `[slim]`). Liquid templates and Thor templates (`*.tt`) get no diagnostics. +`rubyTemplates.slim.disabledDiagnostics` also applies to Skim templates, and `rubyTemplates.jbuilder.disabledDiagnostics` to Jbuilder and Builder views; `rubyTemplates.liquid.disabledDiagnostics` turns off the Liquid ones. To silence a whole language, set `rubyTemplates.erb.diagnostics.enabled`, `rubyTemplates.haml.diagnostics.enabled` or `rubyTemplates.slim.diagnostics.enabled` to `false` (in a `.ruby-templates.toml`: `diagnostics.enabled = false` under `[erb]`, `[haml]` or `[slim]`). Thor templates (`*.tt`) get no diagnostics. The [rules reference](/vscode-ruby-templates/reference/rules/) lists the formatter rules next to the ones that report these codes. diff --git a/site/src/content/docs/reference/stability.md b/site/src/content/docs/reference/stability.md index a85b7ad4..165dda79 100644 --- a/site/src/content/docs/reference/stability.md +++ b/site/src/content/docs/reference/stability.md @@ -20,7 +20,7 @@ These may change in any release: - Which cases a rule reports, within its documented purpose: fixing false positives or catching more of the same problem is a fix. - `--verbose` output. - The language server protocol between the extension and its server: `initializationOptions`, custom requests and notifications such as `rubyTemplates/routes`, and `Diagnostic.data`. The server ships inside the extension, and other editors are not supported yet. -- Experimental features: [Liquid](/vscode-ruby-templates/guides/file-types/#liquid), and anything a page labels experimental. +- Experimental features: anything a page labels experimental. ## Rules in minor versions diff --git a/site/src/data/diagnostics.ts b/site/src/data/diagnostics.ts index 486a33ea..7c0b2c41 100644 --- a/site/src/data/diagnostics.ts +++ b/site/src/data/diagnostics.ts @@ -3,13 +3,14 @@ import fs from "node:fs"; import path from "node:path"; -export type Language = "erb" | "haml" | "slim" | "jbuilder"; +export type Language = "erb" | "haml" | "slim" | "jbuilder" | "liquid"; export const LANGUAGE_NAMES: Record = { erb: "ERB", haml: "Haml", slim: "Slim", jbuilder: "Jbuilder", + liquid: "Liquid", }; export interface Diagnostic { @@ -476,6 +477,76 @@ export const diagnostics: Diagnostic[] = [ line: 1, column: 9, }, + { + code: "Syntax/LiquidUnclosedTag", + languages: ["liquid"], + summary: "A `{{` or `{%` with no `}}` or `%}` after it.", + explanation: + "Liquid reads the rest of the template as part of the output or tag, so it fails to render (\"Variable '{{' was not properly terminated\", \"Tag '{%' was not properly terminated\"). Checking stops at the first one, since what follows is inside it. Not reported inside `{% raw %}` and `{% comment %}`, whose content is not parsed.", + example: { + file: "_includes/card.html", + lang: "liquid", + code: `

{{ page.title

+

{{ page.excerpt

+`, + }, + message: "`{{` is never closed", + line: 1, + column: 5, + }, + { + code: "Syntax/LiquidUnclosedBlock", + languages: ["liquid"], + summary: "A block tag such as `if` or `for` with no end tag.", + explanation: + "Liquid raises \"'if' tag was never closed\" and renders nothing. Reported on the opening tag, for `if`, `unless`, `for`, `case`, `capture`, `comment`, `raw`, `tablerow`, `form`, `paginate` and `highlight`, also inside a multi-line `{% liquid %}` tag. A block left open by an end tag for an outer block is reported here too. Tags the app registers itself are not checked.", + example: { + file: "_includes/card.html", + lang: "liquid", + code: `{% if page.author %} +

{{ page.author }}

+

{{ page.date }}

+`, + }, + message: "`if` is never closed; add `endif`", + line: 1, + column: 1, + }, + { + code: "Syntax/LiquidStrayEndTag", + languages: ["liquid"], + summary: "An end tag with no open block to close.", + explanation: + "Liquid raises \"Unknown tag 'endif'\": the tag closes nothing. Often the opening tag was deleted or sits in another file; Liquid reads each template on its own.", + example: { + file: "_includes/card.html", + lang: "liquid", + code: `

{{ page.author }}

+{% endif %} +`, + }, + message: "`endif` has no open `if` tag to close", + line: 2, + column: 1, + }, + { + code: "Syntax/LiquidMismatchedEndTag", + languages: ["liquid"], + summary: "An end tag that doesn't match the innermost open block.", + explanation: + "Liquid raises \"'endfor' is not a valid delimiter for if tags. use endif\". When the end tag belongs to an outer block, the blocks inside it are reported as `Syntax/LiquidUnclosedBlock` instead; otherwise the end tag is taken for a typo and closes the innermost block.", + example: { + file: "_includes/card.html", + lang: "liquid", + code: `{% if page.tags %} +

{{ page.tags }}

+{% endfor %} +`, + }, + message: "`endfor` doesn't close the open `if` tag; Liquid expects `endif`", + line: 3, + column: 1, + }, { code: "Syntax/Ruby", languages: ["erb", "haml", "slim", "jbuilder"], diff --git a/src/client.js b/src/client.js index ba396f88..8ac00809 100644 --- a/src/client.js +++ b/src/client.js @@ -73,6 +73,9 @@ function initializationOptions(config) { jbuilder: { disabledDiagnostics: config.get("jbuilder.disabledDiagnostics", []), }, + liquid: { + disabledDiagnostics: config.get("liquid.disabledDiagnostics", []), + }, }; } @@ -84,6 +87,7 @@ const SERVER_SETTINGS = [ "erb.disabledDiagnostics", "haml.disabledDiagnostics", "jbuilder.disabledDiagnostics", + "liquid.disabledDiagnostics", "erb.format.alignComments", ...["erb", "haml", "slim"].flatMap((lang) => [ `${lang}.diagnostics.enabled`, diff --git a/test/broken/bad.html.liquid b/test/broken/bad.html.liquid new file mode 100644 index 00000000..cbb69290 --- /dev/null +++ b/test/broken/bad.html.liquid @@ -0,0 +1,5 @@ +{% endunless %} +{% if user %} +

{{ user.name }}

+{% endfor %} +

{{ title

diff --git a/test/cli.js b/test/cli.js index 52e71a69..889e482a 100644 --- a/test/cli.js +++ b/test/cli.js @@ -138,11 +138,18 @@ try { ); r = run(["check", liquid]); assert.strictEqual(r.status, 0, r.stdout + r.stderr); - assert.strictEqual(r.stdout, "", "Liquid has no checks"); + assert.strictEqual(r.stdout, "", "balanced Liquid has nothing to report"); r = run(["format", liquid]); assert.strictEqual(r.status, 0, r.stderr); assert.strictEqual(r.stdout, fs.readFileSync(liquid, "utf8"), "kept as is"); assert.match(r.stderr, /card\.liquid: left unchanged: /); + fs.writeFileSync(liquid, "

ok

\n{% if a %}\n x\n"); + r = run(["check", liquid]); + assert.strictEqual(r.status, 1, r.stdout + r.stderr); + assert.match( + r.stdout, + /card\.liquid:2:1: error: `if` is never closed; add `endif` \[Syntax\/LiquidUnclosedBlock\]/, + ); fs.unlinkSync(liquid); // Ruby 3.3 rejects a line that starts with `&&`; the latest grammar, used without a project Ruby, takes it. diff --git a/test/e2e.js b/test/e2e.js index cbcfcf73..691fb4ed 100644 --- a/test/e2e.js +++ b/test/e2e.js @@ -330,18 +330,66 @@ const check = (label, actual, expected) => { [], ); check( - "document links: none in liquid", + "document links: none for a liquid render without a _card.liquid", ( await send("textDocument/documentLink", { textDocument: { uri: liquidUri }, }) - ).result ?? null, - null, + ).result, + [], ); check( - "hover: none on a liquid render", - (await req("textDocument/hover", liquidUri, 0, 14)).result ?? null, - null, + "hover: a liquid render without a _card.liquid finds nothing", + (await req("textDocument/hover", liquidUri, 0, 14)).result.contents.value, + "**Render** `card`\n\nNo matching file found.", + ); + const site = path.join(root, "site"); + fs.mkdirSync(path.join(site, "_includes"), { recursive: true }); + fs.writeFileSync(path.join(site, "_config.yml"), "title: x\n"); + fs.writeFileSync(path.join(site, "_includes", "footer.html"), "