@exercism/codemirror-lang-crystal
v1.0.2
Published
Crystal language support for the CodeMirror code editor, with completion, as used on Exercism
Readme
@exercism/codemirror-lang-crystal 
[ CHANGELOG ]
This package implements Crystal language support for the CodeMirror code editor, using a Lezer grammar written for this package.
Exercism uses this package in the Crystal editor on exercism.org.
This code is released under an MIT license.
Install
npm install @exercism/codemirror-lang-crystalUsage
import {EditorView, basicSetup} from "codemirror"
import {crystal} from "@exercism/codemirror-lang-crystal"
const view = new EditorView({
parent: document.body,
doc: `class Greeter
def initialize(@name : String)
end
def greet : Nil
puts "Hello, #{@name}!"
end
end
`,
extensions: [basicSetup, crystal()]
})Completion
Completion offers:
- Keywords, the top-level methods and macros (such as
puts,getterandrecord), and the common standard library types. - Snippets for methods, constructors, classes, structs, modules, enums,
records, conditionals, loops,
case,beginandrescue, blocks and procs. - The names declared in the file. A local variable or parameter is offered in
the scope that declares it, once it has been declared. Methods, types,
constants, enum members and the methods made by
getter,propertyandrecordare offered everywhere. After@, the instance variables of the surrounding type are offered. - The common methods of the standard library types, after a
..
Nothing is offered inside strings, comments, characters or symbols. Code inside
#{...} is completed like any other code.
Coverage
Crystal 1.x. The type language, macros, lib bindings and the whole of the
Ruby-shaped surface underneath them: heredocs, percent literals with any
delimiter, operator methods, begin blocks with their rescue and ensure, and
blocks in both spellings. The grammar also reads a !~ /x/, a when :-
branch that comes after another when branch, and a method parameter with a
bare proc type (fn : Acc, T -> Acc).
Measured against the Crystal compiler, its standard library and the shards people depend on, 18998 files and 65 MiB, 96.32% parse with no error node. What is left is a long tail: no shape in it costs more than a handful of files, and the ones worth naming are under What the tree does not say below.
Crystal is not Ruby
Crystal borrows Ruby's surface and puts a static type language underneath it,
so this grammar started as the one in @codincod/codemirror-lang-ruby and had
three things added.
Types are their own language. x : Int32, Array(String?),
(Int32, String) -> Bool and Foo::Bar* are read by rules of their own,
reached from the places a type may stand. Reading them as expressions would
work until the first ?, which an expression reads as a ternary.
A macro is a program about the program. {{ … }} holds an expression and
is parsed as one. {% … %} holds a directive, is written between the
statements it decides about rather than around them, and is skipped like a
comment.
A lib is C. Inside one, fun declares rather than defines, a struct
holds fields and nothing else, and type names a type.
Going the other way, Crystal has no =begin comments, no __END__, no ?c
character literals, no defined?, undef, redo, retry or for, no
numbered block parameters, no singleton classes, no heredocs opened without a
dash, and none of the words and, or and not, which it spells &&, ||
and ! and leaves free to be method names.
What a tokenizer has to settle
Almost all of Crystal can be written down as a grammar. What cannot is the
whole of tokens.ts, and most of it is one question asked in different places:
the tokenizer asks the parser what could stand here, and the answer picks the
token.
A slash is a pattern or a division. a / b divides and a =~ /b/ matches.
Where a division cannot stand the parser has already ruled it out; where both
could, Crystal's own rule decides, which is that a /b/ with a space in front
and none behind is a call taking a pattern.
A brace is a block, a hash, or a collection with a name. each { |x| }
passes a block, {a: 1} is a value, and Set{1, 2} is a set. The first two
are told apart by asking whether a block could stand here; the third by the
name being written against the brace.
A parenthesis is a parameter list, an argument list, or a generic's
arguments. def f(x), f(x) and Array(Int32) all spell it the same way,
and the three are asked about in that order. Without the third,
record T, x : Array(Type), y : Int32 reads the generic as an argument list
and swallows the name in front of it.
A question mark is a nilable type, a lookup that may fail, or a ternary.
String?, a[0]? and a ? b : c. The first two are written against what they
follow and nothing that follows them opens an expression.
A colon is a declaration, a label, a ternary's middle, or half of a path.
x : Int32, name: 1, a ? b : c and A::B. A regular token takes the
longer match and reads A::B as the label A: followed by the symbol :B, so
the second colon is looked at before the first is believed.
A comma may belong to a type. &block : String, Int32 -> Nil takes two
arguments where the parameter list it stands in takes one. Crystal settles it
by looking at whether a type follows the comma, and so does this.
A comma may be the last one. Every list in the language may be written with
a comma after its last thing, and [foo "a",] hands the call one argument
where [foo "a", b] hands it two. Which of the two this is cannot be known
until the bracket, one token further on than a parser reads, so the comma in
front of something that closes arrives as a token of its own. What the parser
skips the look ahead skips too, or the comma of {% for … %} x, {% end %})
would be an ordinary one promising an argument the parenthesis never delivers.
A block belongs to the innermost call. each(&.foo { |x| x }) gives the
block to foo rather than to each, whose block the &. already is. Both
readings want a brace where the brace stands, so this one arrives as its own
token as well, and only the inner call may take it. do is the same block
written the other way and is settled the same way.
A path goes on where it was written. def f : String ends at the end of
its line, so the ::JWT.encode on the next one begins a statement rather than
continuing the name of the type returned. This grammar skips newlines, so the
colons that carry a path on are marked in front, and the mark is only made on
the line the path began on.
A newline ends a statement. x = 1 followed by if y is two statements;
x = 1 if y is one. rescue splits the same way. So does the end of an
argument list written without parentheses. This grammar skips newlines like any
other space, so each of those is decided by looking at where the line began.
A heredoc's body is nowhere near its name. <<-SQL promises a body that
starts on the next line, and one line may promise several. The body is read at
the newline by looking back over the line that just ended, then skipped like
whitespace. The name has to be the whole of the line that closes it, or a body
opening <<-HTTP would be closed by its own HTTP/1.1 200.
A brace against a word continues that word. Int{{n}} is one type per
size and int{{bits}} the method that reads one, where {{ n }} on its own is
a macro standing where a value goes. Whether the brace is written against what
precedes it is the whole of the difference.
A word may be a name after all. property end : Int32 calls a field after
a word the language spells out. Read as the keyword it would close something,
so where a name may stand and a declaration's colon follows, the word is handed
over as a name. self? is the same problem from the other side: a name may end
in a question mark, so self? arrives as one word where Int32? arrives as
two.
A string holds code. "total: #{a + b}" is a string with an expression
inside it, and that expression may hold another string. The tokenizer cuts the
string into pieces and the grammar parses what lies between them.
What the tree does not say
Some things are deliberately shallower than the language reference.
A macro directive is skipped. {% if flag?(:win32) %} is written between
the statements it decides about rather than around them, so a grammar that gave
it a place in the tree would have to give it one inside every list, and
[{% for x in y %} {{x}}, {% end %}] would be an error rather than a list of
one thing. Skipping it costs the directive its own colours and buys a parse
that holds.
What it does not buy is a directive that chooses between two halves of one construct. Where the standard library writes
{% if compare_versions(Crystal::VERSION, "1.1.1") >= 0 %}
def map!(& : T -> _) : self
{% else %}
def map!(&)
{% end %}
# ...
endskipping the directives leaves two method headers and one end, and the first
of them swallows the rest of the file. Reading only the first branch would fix
it and would grey out every {% else %} body in the language, which is the
worse trade for an editor.
Inline assembly is read to its closing parenthesis. What stands between the
colons of an asm is a constraint language of its own, and nothing that reads
Crystal has any use for a tree of it.
A macro cannot stand where an operator does. @x {{op.id}} other.x builds
an expression around a spliced operator. A name may be spliced into and a
method may be named by a macro, but an infix position asks the grammar to take
the macro's word for what binds to what.
Building and testing
The package uses pnpm.
pnpm install # installs the dependencies and builds the package into dist/
pnpm run build # generates the parser if the grammar changed, then builds
pnpm test # builds the package, then runs the tests
pnpm run rebuild # generates the parser from scratch, then buildsGenerating the parser takes about 6 minutes and 8 GB of memory. The build
script gives Node that much, and skips the step if src/parser.js is newer than
the grammar.
Contributing
Please read about how to contribute to Exercism. Be sure to read the Exercism Code of Conduct.
