restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,55 @@
import HelderCore
import Testing
@Suite struct CSSGrammarTests {
@Test("selectors, properties and values")
func basics() {
let text = ".btn:hover > a, #main { color: #fff; margin: 0 4px 1.5em; display: flex !important; }"
#expect(role(".btn", in: text, .css) == .number)
#expect(role(":hover", in: text, .css) == .keyword)
#expect(role(">", in: text, .css) == .keyword)
#expect(role("#main", in: text, .css) == .number)
#expect(role("color", in: text, .css) == .variable)
#expect(role("#fff", in: text, .css) == .number)
#expect(role("4px", in: text, .css) == .number)
#expect(role("1.5em", in: text, .css) == .number)
#expect(role("flex", in: text, .css) == .string)
#expect(role("!important", in: text, .css) == .keyword)
}
@Test("at-rules, functions, urls and custom properties")
func atRulesAndFunctions() {
let text = "@media (max-width: 600px) {\n nav { background: url(img/x.png); width: calc(100% - var(--gap)); }\n}"
#expect(role("@media", in: text, .css) == .keyword)
#expect(role("img/x.png", in: text, .css) == .string)
#expect(role("calc", in: text, .css) == .plain)
#expect(role("100%", in: text, .css) == .number)
#expect(role("--gap", in: text, .css) == .variable)
#expect(role("nav", in: text, .css) == .number)
}
@Test("SCSS nesting tells a nested selector from a declaration")
func scssNesting() {
let text = ".card {\n $pad: 4px;\n padding: $pad;\n &:hover {\n color: red;\n }\n}"
#expect(role("$pad", in: text, .css) == .variable)
#expect(role("padding", in: text, .css) == .variable)
#expect(role("&", in: text, .css) == .keyword)
#expect(role(":hover", in: text, .css) == .keyword)
#expect(role("color", in: text, .css) == .variable)
}
@Test("a value may continue on the next line")
func multiLineValue() {
let text = "a {\n grid-template-areas:\n \"head head\"\n main;\n color: red;\n}"
#expect(role("\"head head\"", in: text, .css) == .string)
#expect(role("main", in: text, .css) == .string)
#expect(role("color", in: text, .css) == .variable)
}
@Test("comments, including SCSS line comments")
func comments() {
let text = "/* a\n b */\n// scss\na { b: c; }"
#expect(role(" b */", in: text, .css) == .comment)
#expect(role("// scss", in: text, .css) == .comment)
}
}
@@ -0,0 +1,30 @@
import Foundation
import HelderCore
/// The role painted over `fragment` (its `occurrence`-th appearance), or nil when the
/// fragment is missing or split over tokens of different roles.
func role(
_ fragment: String, in text: String, _ language: Language?,
occurrence: Int = 0, symbols: Set<String> = []
) -> TokenRole? {
let source = text as NSString
var searchFrom = 0
var range = NSRange(location: NSNotFound, length: 0)
for _ in 0...occurrence {
range = source.range(of: fragment, range: NSRange(location: searchFrom, length: source.length - searchFrom))
guard range.location != NSNotFound else { return nil }
searchFrom = range.location + max(range.length, 1)
}
let tokens = SyntaxHighlighter.tokens(for: text, language: language, knownSymbols: symbols)
let covering = tokens.filter { $0.location < range.location + range.length && $0.location + $0.length > range.location }
guard let first = covering.first, covering.allSatisfy({ $0.role == first.role }) else { return nil }
return first.role
}
/// The non-plain runs of a text as `text:role` strings, for compact whole-line expectations.
func paintedRuns(_ text: String, _ language: Language?) -> [String] {
let source = text as NSString
return SyntaxHighlighter.tokens(for: text, language: language)
.filter { $0.role != .plain }
.map { "\(source.substring(with: NSRange(location: $0.location, length: $0.length))):\($0.role.rawValue)" }
}
@@ -0,0 +1,27 @@
import HelderCore
import Testing
@Suite struct JSONGrammarTests {
@Test("keys read as properties, values keep their own roles")
func keysAndValues() {
let text = "{\"name\": \"helder\", \"n\": -1.5e2, \"ok\": true, \"none\": null, \"list\": [\"a\"]}"
#expect(role("\"name\"", in: text, .json) == .variable)
#expect(role("\"helder\"", in: text, .json) == .string)
#expect(role("-1.5e2", in: text, .json) == .number)
#expect(role("true", in: text, .json) == .number)
#expect(role("null", in: text, .json) == .number)
#expect(role("\"a\"", in: text, .json) == .string)
}
@Test("an escaped quote does not end the string")
func escapedQuote() {
#expect(role("\"a \\\" b\"", in: "{\"k\": \"a \\\" b\"}", .json) == .string)
}
@Test("tsconfig-style comments are allowed")
func comments() {
let text = "{\n // line\n /* block */ \"a\": 1\n}"
#expect(role("// line", in: text, .json) == .comment)
#expect(role("/* block */", in: text, .json) == .comment)
}
}
@@ -0,0 +1,138 @@
import HelderCore
import Testing
@Suite struct JavaScriptGrammarTests {
@Test("keywords, strings, numbers and comments")
func basics() {
let text = "const a = 'x' + \"y\" // note\nlet b = 1.5e3"
#expect(paintedRuns(text, .javascript) == [
"const:keyword", "=:keyword", "'x':string", "+:keyword", "\"y\":string", "// note:comment",
"let:keyword", "=:keyword", "1.5e3:number",
])
}
@Test("a template literal spans lines and highlights its interpolation as code")
func templateLiteral() {
let text = "const s = `a ${fn(1)} b\nstill string ${x}`\nconst after = 2"
#expect(role("`a ", in: text, .javascript) == .string)
#expect(role("1", in: text, .javascript) == .number)
#expect(role("still string ", in: text, .javascript) == .string)
#expect(role("after", in: text, .javascript) == .plain)
#expect(role("2", in: text, .javascript) == .number)
}
@Test("an interpolation holding braces returns to the template at its own brace")
func nestedBraces() {
let text = "`${ {a: 1}.a } tail`"
#expect(role(" tail`", in: text, .javascript) == .string)
}
@Test("a regex literal after an operator is a string, a slash after a value divides")
func regexVersusDivision() {
#expect(role("/ab+c/gi", in: "const r = /ab+c/gi", .javascript) == .string)
#expect(role("/", in: "const q = a / b / c", .javascript) == .keyword)
}
@Test("block comments carry over lines")
func blockComment() {
let text = "/**\n * Docs\n */\nfunction f() {}"
#expect(role(" * Docs", in: text, .javascript) == .comment)
#expect(role("function", in: text, .javascript) == .keyword)
}
@Test("class names follow class, extends and new")
func classNames() {
let text = "class A extends B { m() { return new C() } }"
#expect(role("A", in: text, .javascript) == .variable)
#expect(role("B", in: text, .javascript) == .variable)
#expect(role("C", in: text, .javascript) == .variable)
#expect(role("m", in: text, .javascript) == .plain)
}
@Test("constants and booleans read in the number colour")
func constants() {
let text = "if (x === undefined || y === true) MAX_SIZE"
#expect(role("undefined", in: text, .javascript) == .number)
#expect(role("true", in: text, .javascript) == .number)
#expect(role("MAX_SIZE", in: text, .javascript) == .number)
}
@Test("TypeScript adds its keywords and builtin types")
func typescript() {
let text = "interface A { readonly n: number }\ntype B = keyof A"
#expect(role("readonly", in: text, .typescript) == .keyword)
#expect(role("number", in: text, .typescript) == .number)
#expect(role("keyof", in: text, .typescript) == .keyword)
#expect(role("type", in: text, .javascript) == .plain)
}
@Test("JSX tags, attributes and expressions", arguments: [Language.jsx, .tsx])
func jsx(language: Language) {
let text = "return <Card title=\"x\" onClick={() => go(1)}>\n Hi\n</Card>"
#expect(role("Card", in: text, language) == .number)
#expect(role("title", in: text, language) == .variable)
#expect(role("\"x\"", in: text, language) == .string)
#expect(role("=>", in: text, language) == .keyword)
#expect(role("1", in: text, language) == .number)
#expect(role("Card", in: text, language, occurrence: 1) == .number)
}
@Test("a JSX tag may wrap its attributes over lines")
func multiLineTag() {
let text = "const a = <div\n className=\"x\"\n/>\nlet b"
#expect(role("className", in: text, .jsx) == .variable)
#expect(role("let", in: text, .jsx) == .keyword)
}
@Test("a less-than between values stays an operator in JSX")
func lessThan() {
#expect(role("<", in: "if (a <b) {}", .jsx) == .keyword)
}
@Test("an unterminated string ends at the line end")
func unterminatedString() {
let text = "const a = 'open\nconst b = 1"
#expect(role("const", in: text, .javascript, occurrence: 1) == .keyword)
}
@Test("JSX children are plain text, so an apostrophe opens no string")
func childrenText() {
let text = "const a = <p>Don't {name} if</p>\nconst b = 'x'"
#expect(role("Don't ", in: text, .jsx) == .plain)
#expect(role("if", in: text, .jsx) == .plain)
#expect(role("p", in: text, .jsx, occurrence: 1) == .number)
#expect(role("'x'", in: text, .jsx) == .string)
}
@Test("nested elements and expressions over several lines return to code at the end")
func nestedChildren() {
let text = """
const list = (
<ul className="x">
{items.map((item) => (
<li key={item.id}>{item.label}</li>
))}
</ul>
)
let after = 1
"""
#expect(role("ul", in: text, .jsx) == .number)
#expect(role("=>", in: text, .jsx) == .keyword)
#expect(role("li", in: text, .jsx, occurrence: 1) == .number)
#expect(role("key", in: text, .jsx) == .variable)
#expect(role("ul", in: text, .jsx, occurrence: 1) == .number)
#expect(role("let", in: text, .jsx) == .keyword)
}
@Test("a fragment opens and closes like an element")
func fragments() {
let text = "return <>it's <b>x</b></>\nlet y"
#expect(role("it's ", in: text, .tsx) == .plain)
#expect(role("let", in: text, .tsx) == .keyword)
}
@Test("a self-closing element at the top leaves code mode at once")
func selfClosing() {
#expect(role("let", in: "x = <Br />; let z", .jsx) == .keyword)
}
}
@@ -0,0 +1,50 @@
@testable import HelderCore
import Testing
@Suite struct LexerTests {
private func lexer(_ text: String) -> Lexer {
Lexer(units: Array(text.utf16), symbols: [])
}
@Test("numbers take prefixes, separators, fractions, exponents and suffixes",
arguments: ["0x1F", "0b1010", "1_000_000", "3.14", "1e10", "2.5E-3", "10n"])
func numbers(literal: String) {
var lx = lexer(literal + " rest")
lx.number()
#expect(lx.i == literal.utf16.count)
#expect(lx.tokens == [Token(location: 0, length: literal.utf16.count, role: .number)])
}
@Test("an unterminated string stops at the line end and says so")
func unterminatedString() {
var lx = lexer("'abc")
lx.i = 1
let closed = lx.quoted(from: 0, quote: Unit.apostrophe)
#expect(!closed)
#expect(lx.i == 4)
}
@Test("an escape at the very end of a line never runs past it")
func escapeAtLineEnd() {
var lx = lexer("'ab\\")
lx.i = 1
let closed = lx.quoted(from: 0, quote: Unit.apostrophe)
#expect(!closed)
#expect(lx.i == 4)
}
@Test("emitting next to a run of the same role extends it")
func mergesAdjacentRuns() {
var lx = lexer("abcd")
lx.emit(0, 2, .keyword)
lx.emit(2, 4, .keyword)
#expect(lx.tokens == [Token(location: 0, length: 4, role: .keyword)])
}
@Test("non-ASCII units count as identifier letters")
func unicodeIdentifiers() {
#expect(Unit.isIdentStart(Array("é".utf16)[0]))
#expect(Array("😀".utf16).allSatisfy(Unit.isIdentPart))
#expect(!Unit.isIdentStart(Unit.minus))
}
}
@@ -0,0 +1,50 @@
import HelderCore
import Testing
@Suite struct MarkdownGrammarTests {
@Test("headings read as keywords")
func headings() {
#expect(role("## Title", in: "## Title\ntext", .markdown) == .keyword)
#expect(role("#hashtag", in: "#hashtag", .markdown) == .plain)
}
@Test("a fenced block is highlighted in its own language and closes on its fence")
func fencedCode() {
let text = "```php\n$x = new Agent();\n```\nafter $x"
#expect(role("```php", in: text, .markdown) == .comment)
#expect(role("$x", in: text, .markdown) == .variable)
#expect(role("new", in: text, .markdown) == .keyword)
#expect(role("$x", in: text, .markdown, occurrence: 1) == .plain)
}
@Test("a fence in an unknown language stays plain")
func unknownFence() {
let text = "~~~text\nif x\n~~~"
#expect(role("if x", in: text, .markdown) == .plain)
}
@Test("a fenced block comment carries over lines inside the fence")
func fenceCarriesState() {
let text = "```js\n/* a\nb */ let c\n```"
#expect(role("b */", in: text, .markdown) == .comment)
#expect(role("let", in: text, .markdown) == .keyword)
}
@Test("inline code, link targets and autolinks")
func inline() {
let text = "Use `npm test` and [docs](https://x.test) or <https://y.test>."
#expect(role("`npm test`", in: text, .markdown) == .keyword)
#expect(role("(https://x.test)", in: text, .markdown) == .variable)
#expect(role("docs", in: text, .markdown) == .plain)
#expect(role("<https://y.test>", in: text, .markdown) == .variable)
}
@Test("list markers, quotes and rules read as punctuation")
func punctuation() {
let text = "- one\n1. two\n> quote\n---"
#expect(role("-", in: text, .markdown) == .comment)
#expect(role("1.", in: text, .markdown) == .comment)
#expect(role(">", in: text, .markdown) == .comment)
#expect(role("---", in: text, .markdown) == .comment)
}
}
@@ -0,0 +1,56 @@
import HelderCore
import Testing
@Suite struct MarkupGrammarTests {
@Test("tags, attributes, values and entities")
func basics() {
let text = "<a href=\"/x\" data-id=1 hidden>Tom &amp; Jerry</a>"
#expect(paintedRuns(text, .markup) == [
"a:number", "href:variable", "\"/x\":string", "data-id:variable", "1:string", "hidden:variable",
"&amp;:variable", "a:number",
])
}
@Test("comments, doctype and CDATA read as comments")
func comments() {
let text = "<!DOCTYPE html>\n<!-- a\n b -->\n<![CDATA[ x ]]>\n<p>"
#expect(role("<!DOCTYPE html>", in: text, .markup) == .comment)
#expect(role(" b -->", in: text, .markup) == .comment)
#expect(role("<![CDATA[ x ]]>", in: text, .markup) == .comment)
#expect(role("p", in: text, .markup) == .number)
}
@Test("a script body is JavaScript and a style body is CSS")
func embedded() {
let text = "<script>\nconst a = 1 // c\n</script>\n<style>\n.b { color: red; }\n</style>\n<p>const</p>"
#expect(role("const", in: text, .markup) == .keyword)
#expect(role("// c", in: text, .markup) == .comment)
#expect(role("script", in: text, .markup, occurrence: 1) == .number)
#expect(role(".b", in: text, .markup) == .number)
#expect(role("color", in: text, .markup) == .variable)
#expect(role("const", in: text, .markup, occurrence: 1) == .plain)
}
@Test("a JavaScript line comment stops at the closing script tag")
func scriptCloseInsideComment() {
let text = "<script>// x</script><p>"
#expect(role("// x", in: text, .markup) == .comment)
#expect(role("p", in: text, .markup) == .number)
}
@Test("a tag may wrap over lines, with a value that wraps too")
func multiLineTag() {
let text = "<img\n alt=\"a\n b\"\n src=\"x\">\nafter"
#expect(role(" b\"", in: text, .markup) == .string)
#expect(role("src", in: text, .markup) == .variable)
#expect(role("after", in: text, .markup) == .plain)
}
@Test("Vue single-file components read their script block")
func vue() {
let text = "<template><div :class=\"a\" @click=\"go\"/></template>\n<script setup>\nimport x from 'y'\n</script>"
#expect(role(":class", in: text, .markup) == .variable)
#expect(role("@click", in: text, .markup) == .variable)
#expect(role("import", in: text, .markup) == .keyword)
}
}
@@ -0,0 +1,147 @@
import HelderCore
import Testing
@Suite struct PHPGrammarTests {
private let source = """
<?php
namespace App\\Domain;
use Illuminate\\Support\\Str;
#[Attribute]
final class Agent extends Model implements HasLabel
{
use HasFactory;
public const STATUS_ACTIVE = 'active';
public function label(?string $prefix = null): string
{
// line comment
return Str::upper("{$this->name} $prefix") . self::STATUS_ACTIVE . 0x1F;
}
}
"""
@Test("the open tag and keywords read as keywords")
func keywords() {
#expect(role("<?php", in: source, .php) == .keyword)
#expect(role("final", in: source, .php) == .keyword)
#expect(role("function", in: source, .php) == .keyword)
#expect(role("string", in: source, .php, occurrence: 0) == .keyword)
}
@Test("a namespace path reads as a type path")
func namespacePath() {
#expect(role("App\\Domain", in: source, .php) == .string)
#expect(role("Illuminate\\Support\\", in: source, .php) == .string)
}
@Test("class names read as variables, known ones as symbols", arguments: ["Agent", "Model", "HasLabel", "HasFactory", "Attribute", "Str"])
func classNames(name: String) {
#expect(role(name, in: source, .php) == .variable)
#expect(role(name, in: source, .php, symbols: [name]) == .symbol)
}
@Test("the last segment of an imported path is a class name")
func importedClass() {
#expect(role("Str", in: source, .php, symbols: ["Str"]) == .symbol)
}
@Test("variables, properties and constants get their own roles")
func variablesAndConstants() {
#expect(role("$prefix", in: source, .php) == .variable)
#expect(role("STATUS_ACTIVE", in: source, .php) == .number)
#expect(role("STATUS_ACTIVE", in: source, .php, occurrence: 1) == .number)
#expect(role("null", in: source, .php) == .number)
#expect(role("0x1F", in: source, .php) == .number)
}
@Test("a method call after -> is a function name, a property is a variable")
func arrowAccess() {
let text = "<?php $a->save(); $a->name;"
#expect(role("save", in: text, .php) == .plain)
#expect(role("name", in: text, .php) == .variable)
#expect(role("->", in: text, .php) == .keyword)
}
@Test("strings interpolate variables, single quotes do not")
func interpolation() {
let text = "<?php $a = \"hi $name!\"; $b = 'hi $name';"
#expect(role("\"hi ", in: text, .php) == .string)
#expect(role("$name", in: text, .php, occurrence: 0) == .variable)
#expect(role("'hi $name'", in: text, .php) == .string)
#expect(role("{$this->name}", in: source, .php) == .variable)
}
@Test("comments: //, # and block comments")
func comments() {
#expect(role("// line comment", in: source, .php) == .comment)
#expect(role("# hash", in: "<?php # hash\n$a;", .php) == .comment)
let block = "<?php /* one\n two */ $x;"
#expect(role("two */", in: block, .php) == .comment)
#expect(role("$x", in: block, .php) == .variable)
}
@Test("a multi-line string carries over lines")
func multiLineString() {
let text = "<?php $sql = \"select *\n from users\n where id = 1\";\n$next = 2;"
#expect(role(" from users", in: text, .php) == .string)
#expect(role("$next", in: text, .php) == .variable)
}
@Test("a heredoc runs to its closing marker, a nowdoc does not interpolate")
func heredoc() {
let text = "<?php\n$a = <<<EOT\n Hello $name\n EOT;\n$b = <<<'RAW'\n $raw\nRAW;\n$c = 1;"
#expect(role(" Hello ", in: text, .php) == .string)
#expect(role("$name", in: text, .php) == .variable)
#expect(role("$raw", in: text, .php) == .string)
#expect(role("$c", in: text, .php) == .variable)
#expect(role("1", in: text, .php, occurrence: 0) == .number)
}
@Test("a file with <?php is HTML with PHP islands")
func template() {
let text = "<div class=\"<?= $cls ?>\">\n<?php if ($x): ?>\n <b>hi</b>\n<?php endif; ?>\n</div>"
#expect(role("div", in: text, .php) == .number)
#expect(role("$cls", in: text, .php) == .variable)
#expect(role("?>", in: text, .php) == .keyword)
#expect(role("if", in: text, .php) == .keyword)
#expect(role("hi", in: text, .php) == .plain)
#expect(role("endif", in: text, .php) == .keyword)
}
@Test("a PHP line comment ends at ?>")
func lineCommentEndsAtCloseTag() {
let text = "<p><?php // note ?> after</p>"
#expect(role("// note ", in: text, .php) == .comment)
#expect(role("?>", in: text, .php) == .keyword)
#expect(role("after", in: text, .php) == .plain)
}
@Test("a Blade file without <?php is read as PHP")
func bladeReadsAsPHP() {
let text = "@if($user)\n {{ $user->name }}\n@endif"
#expect(role("$user", in: text, .php) == .variable)
}
@Test("static, self and parent stay keywords before ::")
func scopeKeywords() {
let text = "<?php static::make(); self::X; parent::boot(); Carbon::now();"
#expect(role("static", in: text, .php) == .keyword)
#expect(role("self", in: text, .php) == .keyword)
#expect(role("parent", in: text, .php) == .keyword)
#expect(role("Carbon", in: text, .php, symbols: ["Carbon"]) == .symbol)
}
@Test("a qualified name marks only its last segment as the class")
func qualifiedName() {
let text = "<?php new \\App\\Models\\Agent();"
#expect(role("\\App\\Models\\", in: text, .php) == .string)
#expect(role("Agent", in: text, .php, symbols: ["Agent"]) == .symbol)
}
@Test("PHP keywords are case-insensitive")
func caseInsensitiveKeywords() {
#expect(role("NEW", in: "<?php $a = NEW Foo;", .php) == .keyword)
}
}
@@ -0,0 +1,39 @@
import HelderCore
import Testing
@Suite struct PythonGrammarTests {
@Test("keywords, builtins, constants and comments")
func basics() {
let text = "def run(x):\n if x is None: # guard\n return len(x)\n return True"
#expect(role("def", in: text, .python) == .keyword)
#expect(role("run", in: text, .python) == .plain)
#expect(role("None", in: text, .python) == .number)
#expect(role("# guard", in: text, .python) == .comment)
#expect(role("len", in: text, .python) == .number)
#expect(role("True", in: text, .python) == .number)
}
@Test("a triple-quoted string carries over lines")
func tripleQuoted() {
let text = "x = '''one\ntwo # not a comment\nthree'''\ny = 1"
#expect(role("two # not a comment", in: text, .python) == .string)
#expect(role("1", in: text, .python) == .number)
}
@Test("string prefixes belong to the string", arguments: ["f\"a{b}\"", "rb'raw'", "u\"x\""])
func prefixes(literal: String) {
#expect(role(literal, in: "v = \(literal)", .python) == .string)
}
@Test("a decorator at the start of a line reads as a keyword; matrix @ does not")
func decorators() {
let text = "@app.route('/')\ndef f(): return a @ b"
#expect(role("@app.route", in: text, .python) == .keyword)
#expect(role("@", in: text, .python, occurrence: 1) == .plain)
}
@Test("the name after class reads as a class")
func className() {
#expect(role("Agent", in: "class Agent(Base):", .python) == .variable)
}
}
@@ -0,0 +1,52 @@
import HelderCore
import Testing
@Suite struct ShellGrammarTests {
@Test("keywords, builtins, variables and strings")
func basics() {
let text = "if [ -n \"$HOME\" ]; then echo \"dir: ${HOME}/x\" 'no $sub'; fi"
#expect(role("if", in: text, .bash) == .keyword)
#expect(role("$HOME", in: text, .bash) == .variable)
#expect(role("echo", in: text, .bash) == .number)
#expect(role("${HOME}", in: text, .bash) == .variable)
#expect(role("'no $sub'", in: text, .bash) == .string)
#expect(role("fi", in: text, .bash) == .keyword)
}
@Test("a hash inside a word is not a comment")
func hashInWord() {
let text = "echo a#b # real"
#expect(role("a#b", in: text, .bash) == .plain)
#expect(role("# real", in: text, .bash) == .comment)
}
@Test("a heredoc runs to its marker; a quoted marker turns interpolation off")
func heredoc() {
let text = "cat <<EOF\nhi $USER\nEOF\ncat <<'RAW'\n$keep\nRAW\necho done"
#expect(role("hi ", in: text, .bash) == .string)
#expect(role("$USER", in: text, .bash) == .variable)
#expect(role("$keep", in: text, .bash) == .string)
#expect(role("echo", in: text, .bash) == .number)
}
@Test("a .env file reads keys as assignments")
func dotenv() {
let text = "APP_NAME=Helder\n# comment\nDB_PASSWORD=\"s3cret\""
#expect(role("APP_NAME", in: text, .bash) == .variable)
#expect(role("# comment", in: text, .bash) == .comment)
#expect(role("\"s3cret\"", in: text, .bash) == .string)
}
@Test("a quoted string may span lines")
func multiLineString() {
let text = "msg=\"one\ntwo\"\necho x"
#expect(role("two\"", in: text, .bash) == .string)
#expect(role("echo", in: text, .bash) == .number)
}
@Test("dashes in a command name do not start a keyword")
func dashedWords() {
#expect(role("apt-get", in: "apt-get install -y done-thing", .bash) == .plain)
#expect(role("done-thing", in: "apt-get install -y done-thing", .bash) == .plain)
}
}
@@ -0,0 +1,131 @@
import Foundation
import HelderCore
import Testing
@Suite struct SyntaxHighlighterTests {
private static let samples: [(String, Language)] = [
("<?php\nnamespace App;\n/* a\n block */\nclass A extends B {\n public function run(): string { return \"x $y\"; }\n}\n", .php),
("const a = `x ${b} y`\n/* c\n d */ let e = /re/g\n", .javascript),
("export const App = () => (\n <div className=\"x\">\n {n.map((i) => <b key={i}>{i}</b>)}\n </div>\n)\n", .tsx),
("<html>\n<!-- c\n -->\n<script>\nlet a = 1\n</script>\n<style>a { color: red }</style>\n", .markup),
("a {\n color: #fff;\n margin: 0 4px;\n}\n", .css),
("{\n \"a\": [1, true, null]\n}\n", .json),
("# T\n\n```php\n$x = 1;\n```\n- item `code`\n", .markdown),
("#!/bin/sh\nif [ -f x ]; then echo \"$HOME\"; fi\ncat <<EOF\nhi $USER\nEOF\n", .bash),
("def f(x):\n \"\"\"doc\n string\"\"\"\n return None\n", .python),
("a: 1\nb: |\n text\nc: true # note\n", .yaml),
]
@Test("tokens tile the text end to end with no gaps or overlaps", arguments: samples)
func tokensTileTheText(sample: (String, Language)) {
let (text, language) = sample
let tokens = SyntaxHighlighter.tokens(for: text, language: language)
var position = 0
for token in tokens {
#expect(token.location == position)
#expect(token.length > 0)
position = token.location + token.length
}
#expect(position == text.utf16.count)
}
@Test("adjacent runs of one role are merged", arguments: samples)
func adjacentRunsAreMerged(sample: (String, Language)) {
let tokens = SyntaxHighlighter.tokens(for: sample.0, language: sample.1)
for (a, b) in zip(tokens, tokens.dropFirst()) {
#expect(a.role != b.role)
}
}
@Test("line-by-line tokens with carried state equal whole-buffer tokens", arguments: samples)
func incrementalMatchesWholeBuffer(sample: (String, Language)) {
let (text, language) = sample
var state = HighlightState(language: language, text: text)
var offset = 0
var painted: [Token] = []
for line in text.components(separatedBy: "\n") {
for token in SyntaxHighlighter.lineTokens(for: line, state: &state) where token.role != .plain {
painted.append(Token(location: token.location + offset, length: token.length, role: token.role))
}
offset += line.utf16.count + 1
}
let whole = SyntaxHighlighter.tokens(for: text, language: language).filter { $0.role != .plain }
#expect(painted == whole)
}
@Test("an unknown language is one plain run")
func unknownLanguageIsPlain() {
#expect(SyntaxHighlighter.tokens(for: "a = 1", language: nil) == [Token(location: 0, length: 5, role: .plain)])
}
@Test("an empty buffer has no tokens")
func emptyBuffer() {
#expect(SyntaxHighlighter.tokens(for: "", language: .php).isEmpty)
#expect(SyntaxHighlighter.lineTokens(for: "", language: .javascript).isEmpty)
}
@Test("offsets count UTF-16 units, so text after an emoji lines up")
func utf16Offsets() {
let text = "const s = \"😀\"; const n = 42"
let tokens = SyntaxHighlighter.tokens(for: text, language: .javascript)
let number = tokens.first { $0.role == .number }
#expect(number?.location == (text as NSString).range(of: "42").location)
#expect(number?.length == 2)
}
@Test("CRLF line endings keep the carriage return inside the line")
func crlfLines() {
let text = "/* a\r\n b */\r\nlet x = 1\r\n"
#expect(role("b */", in: text, .javascript) == .comment)
#expect(role("let", in: text, .javascript) == .keyword)
#expect(role("1", in: text, .javascript, occurrence: 0) == .number)
}
@Test("a single diff line is highlighted on its own, without state from the lines above")
func lineStandsAlone() {
let tokens = SyntaxHighlighter.lineTokens(for: " end */ let x", language: .javascript)
#expect(tokens.contains { $0.role == .keyword })
#expect(!tokens.contains { $0.role == .comment })
}
@Test("the state reports an open construct at a line break")
func stateReportsOpenConstruct() {
var state = HighlightState(language: .javascript)
_ = SyntaxHighlighter.lineTokens(for: "/* open", state: &state)
#expect(state.isInsideConstruct)
_ = SyntaxHighlighter.lineTokens(for: "close */", state: &state)
#expect(!state.isInsideConstruct)
#expect(state == HighlightState(language: .javascript))
}
@Test("every language survives hostile input without hanging", arguments: Language.allCases)
func hostileInput(language: Language) {
let text = "<?php \"'`/*<!--<<<EOT\n${{[(\\\n\u{0}é😀\t\r\n?> </script> ``` ---\n" + String(repeating: "\\", count: 20)
let tokens = SyntaxHighlighter.tokens(for: text, language: language)
#expect(tokens.map(\.length).reduce(0, +) == text.utf16.count)
}
@Test("a 5,000-line file tokenizes well within a second, even in a debug build")
func performanceSanity() {
let block = """
<?php
namespace App\\Http\\Controllers;
/** Docblock for the class. */
final class UserController extends Controller implements HasMiddleware
{
public function show(Request $request, int $id): JsonResponse
{
$user = User::query()->where('id', $id)->firstOrFail(); // fetch
return response()->json(["name" => "{$user->name} #{$id}", 'count' => 42]);
}
}
"""
let text = String(repeating: block, count: 5000 / 12 + 1)
let clock = ContinuousClock()
let elapsed = clock.measure {
_ = SyntaxHighlighter.tokens(for: text, language: .php, knownSymbols: ["User"])
}
#expect(elapsed < .seconds(1))
}
}
@@ -0,0 +1,42 @@
import HelderCore
import Testing
@Suite struct YAMLGrammarTests {
@Test("keys, scalars, booleans, numbers and comments")
func basics() {
let text = "name: helder # app\nport: 8080\ndebug: true\nempty: ~\nurl: http://x.test:80\n\"quoted key\": 'v'"
#expect(role("name", in: text, .yaml) == .keyword)
#expect(role("# app", in: text, .yaml) == .comment)
#expect(role("8080", in: text, .yaml) == .number)
#expect(role("true", in: text, .yaml) == .keyword)
#expect(role("~", in: text, .yaml) == .keyword)
#expect(role("http://x.test:80", in: text, .yaml) == .plain)
#expect(role("\"quoted key\"", in: text, .yaml) == .keyword)
#expect(role("'v'", in: text, .yaml) == .string)
}
@Test("a block scalar runs while the lines stay indented")
func blockScalar() {
let text = "script: |\n echo: hi\n\n more\nnext: 1"
#expect(role(" echo: hi", in: text, .yaml) == nil)
#expect(role("echo: hi", in: text, .yaml) == .string)
#expect(role("more", in: text, .yaml) == .string)
#expect(role("next", in: text, .yaml) == .keyword)
}
@Test("lists, anchors, aliases and tags")
func listsAndAnchors() {
let text = "base: &base\n - item: !!str 1\nuse: *base"
#expect(role("&base", in: text, .yaml) == .keyword)
#expect(role("item", in: text, .yaml) == .keyword)
#expect(role("!!str", in: text, .yaml) == .number)
#expect(role("*base", in: text, .yaml) == .keyword)
}
@Test("flow collections split on commas")
func flow() {
let text = "tags: [a, 2, true]"
#expect(role("2", in: text, .yaml) == .number)
#expect(role("true", in: text, .yaml) == .keyword)
}
}