Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 217 additions & 0 deletions src/cm/modes/nim/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
import {
LanguageSupport,
StreamLanguage,
type StringStream,
} from "@codemirror/language";

interface NimState {
blockCommentClosers: string[];
inTripleString: boolean;
}

const NUMBER_PATTERN =
/^(?:0[xX][0-9a-fA-F_]+|0[oO][0-7_]+|0[bB][01_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:[eE][+-]?\d+)?)(?:'[iuf]\d*)?/;

const keywords = new Set([
"addr",
"and",
"as",
"asm",
"bind",
"block",
"break",
"case",
"cast",
"concept",
"const",
"continue",
"converter",
"defer",
"discard",
"distinct",
"div",
"do",
"elif",
"else",
"end",
"enum",
"except",
"export",
"finally",
"for",
"from",
"func",
"if",
"import",
"in",
"include",
"interface",
"is",
"isnot",
"iterator",
"let",
"macro",
"method",
"mixin",
"mod",
"not",
"notin",
"object",
"of",
"or",
"out",
"proc",
"ptr",
"raise",
"ref",
"return",
"shl",
"shr",
"static",
"template",
"try",
"tuple",
"type",
"using",
"var",
"when",
"while",
"xor",
"yield",
]);

const atoms = new Set(["true", "false", "nil"]);

const builtinTypes = new Set([
"bool",
"byte",
"char",
"cstring",
"float",
"float32",
"float64",
"int",
"int8",
"int16",
"int32",
"int64",
"pointer",
"seq",
"string",
"uint",
"uint8",
"uint16",
"uint32",
"uint64",
"void",
]);

const nimLanguage = StreamLanguage.define<NimState>({
name: "nim",
startState() {
return { blockCommentClosers: [], inTripleString: false };
},
copyState(state) {
return {
...state,
blockCommentClosers: [...state.blockCommentClosers],
};
},
token(stream, state) {
if (state.blockCommentClosers.length > 0) {
return readBlockComment(stream, state);
}
if (state.inTripleString) return readTripleString(stream, state);
if (stream.eatSpace()) return null;

if (stream.match("##[")) {
state.blockCommentClosers.push("]##");
return readBlockComment(stream, state);
}
if (stream.match("#[")) {
state.blockCommentClosers.push("]#");
return readBlockComment(stream, state);
}
if (stream.match("#")) {
Comment on lines +131 to +135

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Documentation looks like code

Nim uses ##[ ... ]## for multiline documentation comments, but ##[ fails the #[ check and falls into the single-line comment branch. The following documentation lines are then colored as code. Recognize documentation comment delimiters before the line-comment branch, track their matching closer, and test a multiline example.

stream.skipToEnd();
return "comment";
}
if (stream.match('"""')) {
state.inTripleString = true;
return readTripleString(stream, state);
}
if (stream.match(/^[A-Za-z_]\w*"/)) return readRawString(stream);
if (stream.match('"')) return readString(stream);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Raw strings swallow comments

For valid Nim such as let path = r"C:\" # note, the prefix is read separately, then readString treats the backslash as escaping the closing quote. The trailing comment is colored as part of the string. Recognize raw and generalized string prefixes before applying ordinary string escapes, and add a regression test.

if (stream.match(/^'(?:\\.|[^'\\])*'?/)) return "string";
if (stream.match(NUMBER_PATTERN)) return "number";
if (stream.match(/^[A-Za-z_]\w*/)) return identifierStyle(stream.current());
if (stream.match(/^[-+*/<>=!~^&|@$%?.:\\]+/)) return "operator";

stream.next();
return null;
},
languageData: {
commentTokens: { line: "#" },
},
});

export function nim(): LanguageSupport {
return new LanguageSupport(nimLanguage);
}

function identifierStyle(word: string): string | null {
if (keywords.has(word)) return "keyword";
if (atoms.has(word)) return "atom";
if (builtinTypes.has(word)) return "typeName";
return null;
}

function readBlockComment(stream: StringStream, state: NimState): string {
while (!stream.eol()) {
if (stream.match("##[")) {
state.blockCommentClosers.push("]##");
} else if (stream.match("#[")) {
state.blockCommentClosers.push("]#");
} else if (
stream.match(
state.blockCommentClosers[state.blockCommentClosers.length - 1],
)
) {
state.blockCommentClosers.pop();
if (state.blockCommentClosers.length === 0) break;
} else {
stream.next();
}
}
return "comment";
}

function readTripleString(stream: StringStream, state: NimState): string {
while (!stream.eol()) {
if (stream.match('"""')) {
state.inTripleString = false;
break;
}
stream.next();
}
return "string";
}

function readString(stream: StringStream): string {
while (!stream.eol()) {
const character = stream.next();
if (character === "\\") stream.next();
else if (character === '"') break;
}
return "string";
}

function readRawString(stream: StringStream): string {
while (!stream.eol()) {
if (stream.next() === '"') {
if (stream.eat('"')) continue;
break;
}
}
return "string";
}
7 changes: 7 additions & 0 deletions src/cm/supportedModes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,13 @@ addMode("Luau", "luau", "Luau", async () => {
return luau();
});

// Nim isn't bundled in @codemirror/language-data, and the Ace editor's Nim
// mode was lost when the editor moved to CodeMirror.
addMode("nim", "nim|nims|nimble", "Nim", async () => {
const { nim } = await import("./modes/nim");
return nim();
});

// Astro isn't bundled in @codemirror/language-data. Register it with HTML as
// the structural parser plus Astro frontmatter and expression highlighting.
addMode("Astro", "astro", "Astro", async () => {
Expand Down
69 changes: 69 additions & 0 deletions tests/unit/nimHighlighting.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import "cm/supportedModes";
import { ensureSyntaxTree } from "@codemirror/language";
import { EditorState } from "@codemirror/state";
import { highlightTree } from "@lezer/highlight";
import { getModeForPath } from "cm/modelist";
import { describe, expect, it } from "vitest";

const sample = `proc add*(a: int): int =
# line note
let s = "hi \\" there" # trailing
discard 0x1F + 2.5e3
var ok = true
#[ block
note ]#
let raw = """multi
line"""
`;

async function highlightedTexts(doc: string) {
const { nim } = await import("cm/modes/nim");
const state = EditorState.create({ doc, extensions: nim() });
const tree = ensureSyntaxTree(state, doc.length, 5000);
if (!tree) throw new Error("parse did not finish");
const out: [string, string][] = [];
highlightTree(
tree,
{ style: (tags) => tags.map(String).join(" ") },
(from, to, tags) => {
const text = doc.slice(from, to);
if (text.trim()) out.push([tags, text]);
},
);
return out;
}

function textsWith(highlights: [string, string][], tags: string) {
return highlights.filter(([style]) => style === tags).map(([, text]) => text);
}

describe("Nim syntax highlighting", () => {
it("selects the Nim mode for .nim files", () => {
expect(getModeForPath("src/main.nim").caption).toBe("Nim");
});

it("colours keywords, types, numbers, strings and comments", async () => {
const highlights = await highlightedTexts(sample);
expect(textsWith(highlights, "keyword")).toEqual([
"proc",
"let",
"discard",
"var",
"let",
]);
expect(textsWith(highlights, "typeName")).toEqual(["int", "int"]);
expect(textsWith(highlights, "atom")).toEqual(["true"]);
expect(textsWith(highlights, "number")).toEqual(["0x1F", "2.5e3"]);
expect(textsWith(highlights, "string")).toEqual([
'"hi \\" there"',
'"""multi',
'line"""',
]);
expect(textsWith(highlights, "comment")).toEqual([
"# line note",
"# trailing",
"#[ block",
" note ]#",
]);
});
});
24 changes: 24 additions & 0 deletions tests/unit/nimSyntax.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import { nim } from "../../src/cm/modes/nim";

describe("Nim syntax mode", () => {
it("keeps raw and generalized string contents inside the string token", () => {
const parser = nim().language.parser;
const tree = parser.parse(
'let path = r"C:\\" # note\nlet pattern = re"[a-z]+" # end',
);
expect(tree.toString()).toBe(
"Document(keyword,operator,string,comment,keyword,operator,string,comment)",
);
});

it("recognizes multiline documentation comments", () => {
const parser = nim().language.parser;
const tree = parser.parse(
"##[ docs\nlet thisIsComment = true\n]##\nlet code = true",
);
expect(tree.toString()).toBe(
"Document(comment,comment,comment,keyword,operator,atom)",
);
});
});