-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhl_fsharp.js
471 lines (439 loc) · 14.3 KB
/
hl_fsharp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
/**
* @param {string} value
* @returns {RegExp}
* */
function escape(value) {
return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm')
}
/**
* @param {RegExp | string } re
* @returns {string}
*/
function source(re) {
if (!re) return null
if (typeof re === 'string') return re
return re.source
}
/**
* @param {RegExp | string } re
* @returns {string}
*/
function lookahead(re) {
return concat('(?=', re, ')')
}
/**
* @param {...(RegExp | string) } args
* @returns {string}
*/
function concat(...args) {
const joined = args.map((x) => source(x)).join('')
return joined
}
/**
* @param { Array<string | RegExp | Object> } args
* @returns {object}
*/
function stripOptionsFromArgs(args) {
const opts = args[args.length - 1]
if (typeof opts === 'object' && opts.constructor === Object) {
args.splice(args.length - 1, 1)
return opts
} else {
return {}
}
}
/** @typedef { {capture?: boolean} } RegexEitherOptions */
/**
* Any of the passed expresssions may match
*
* Creates a huge this | this | that | that match
* @param {(RegExp | string)[] | [...(RegExp | string)[], RegexEitherOptions]} args
* @returns {string}
*/
function either(...args) {
/** @type { object & {capture?: boolean} } */
const opts = stripOptionsFromArgs(args)
const joined =
'(' +
(opts.capture ? '' : '?:') +
args.map((x) => source(x)).join('|') +
')'
return joined
}
/*
Language: F#
Author: Jonas Follesø <[email protected]>
Contributors: Troy Kershaw <[email protected]>, Henrik Feldt <[email protected]>, Melvyn Laïly <[email protected]>
Website: https://docs.microsoft.com/en-us/dotnet/fsharp/
Category: functional
*/
/** @type LanguageFn */
export default function (hljs) {
const KEYWORDS = []
const BANG_KEYWORD_MODE = {
// monad builder keywords (matches before non-bang keywords)
scope: 'keyword',
match: /\b(yield|return|let|do|match|use)!/,
}
const PREPROCESSOR_KEYWORDS = []
const LITERALS = ['true', 'false']
const SPECIAL_IDENTIFIERS = [
'__LINE__',
'__SOURCE_DIRECTORY__',
'__SOURCE_FILE__',
]
// Since it's possible to re-bind/shadow names (e.g. let char = 'c'),
// these builtin types should only be matched when a type name is expected.
const KNOWN_TYPES = [
// basic types
]
const BUILTINS = [
// Somewhat arbitrary list of builtin functions and values.
// Most of them are declared in Microsoft.FSharp.Core
// I tried to stay relevant by adding only the most idiomatic
// and most used symbols that are not already declared as types.
'Attr',
'attr',
'Html',
'Elem',
'prop',
'text',
'Text',
'str',
]
const ALL_KEYWORDS = {
keyword: KEYWORDS,
literal: LITERALS,
built_in: BUILTINS,
'variable.constant': SPECIAL_IDENTIFIERS,
}
// (* potentially multi-line Meta Language style comment *)
const ML_COMMENT = hljs.COMMENT(/\(\*(?!\))/, /\*\)/, {
contains: ['self'],
})
// Either a multi-line (* Meta Language style comment *) or a single line // C style comment.
const COMMENT = {
variants: [ML_COMMENT, hljs.C_LINE_COMMENT_MODE],
}
// Most identifiers can contain apostrophes
const IDENTIFIER_RE = /[a-zA-Z_](\w|')*/
const QUOTED_IDENTIFIER = {
scope: 'variable',
begin: /``/,
end: /``/,
}
// 'a or ^a where a can be a ``quoted identifier``
const BEGIN_GENERIC_TYPE_SYMBOL_RE = /\B('|\^)/
const GENERIC_TYPE_SYMBOL = {
scope: 'symbol',
variants: [
// the type name is a quoted identifier:
{ match: concat(BEGIN_GENERIC_TYPE_SYMBOL_RE, /``.*?``/) },
// the type name is a normal identifier (we don't use IDENTIFIER_RE because there cannot be another apostrophe here):
{
match: concat(
BEGIN_GENERIC_TYPE_SYMBOL_RE,
hljs.UNDERSCORE_IDENT_RE
),
},
],
relevance: 0,
}
const makeOperatorMode = function ({ includeEqual }) {
// List or symbolic operator characters from the FSharp Spec 4.1, minus the dot, and with `?` added, used for nullable operators.
let allOperatorChars
if (includeEqual) allOperatorChars = '!%&*+-/<=>@^|~?{}[]'
else allOperatorChars = '!%&*+-/<>@^|~?{}[]'
const OPERATOR_CHARS = Array.from(allOperatorChars)
const OPERATOR_CHAR_RE = concat('[', ...OPERATOR_CHARS.map(escape), ']')
// The lone dot operator is special. It cannot be redefined, and we don't want to highlight it. It can be used as part of a multi-chars operator though.
const OPERATOR_CHAR_OR_DOT_RE = either(OPERATOR_CHAR_RE, /\./)
// When a dot is present, it must be followed by another operator char:
const OPERATOR_FIRST_CHAR_OF_MULTIPLE_RE = concat(
OPERATOR_CHAR_OR_DOT_RE,
lookahead(OPERATOR_CHAR_OR_DOT_RE)
)
const SYMBOLIC_OPERATOR_RE = either(
concat(
OPERATOR_FIRST_CHAR_OF_MULTIPLE_RE,
OPERATOR_CHAR_OR_DOT_RE,
'*'
), // Matches at least 2 chars operators
concat(OPERATOR_CHAR_RE, '+') // Matches at least one char operators
)
return {
scope: 'operator',
match: either(
// symbolic operators:
SYMBOLIC_OPERATOR_RE,
// other symbolic keywords:
// Type casting and conversion operators:
/:\?>/,
/:\?/,
/:>/,
/:=/, // Reference cell assignment
/::?/, // : or ::
/\$/
), // A single $ can be used as an operator
relevance: 0,
}
}
const OPERATOR = makeOperatorMode({ includeEqual: true })
// This variant is used when matching '=' should end a parent mode:
const OPERATOR_WITHOUT_EQUAL = makeOperatorMode({ includeEqual: false })
const makeTypeAnnotationMode = function (prefix, prefixScope) {
return {
begin: concat(
// a type annotation is a
prefix, // should be a colon or the 'of' keyword
lookahead(
// that has to be followed by
concat(
/\s*/, // optional space
either(
// then either of:
/\w/, // word
/'/, // generic type name
/\^/, // generic type name
/#/, // flexible type name
/``/, // quoted type name
/\(/, // parens type expression
/{\|/ // anonymous type annotation
)
)
)
),
beginScope: prefixScope,
// BUG: because ending with \n is necessary for some cases, multi-line type annotations are not properly supported.
// Examples where \n is required at the end:
// - abstract member definitions in classes: abstract Property : int * string
// - return type annotations: let f f' = f' () : returnTypeAnnotation
// - record fields definitions: { A : int \n B : string }
end: lookahead(either(/\n/, /=/)),
relevance: 0,
// we need the known types, and we need the type constraint keywords and literals. e.g.: when 'a : null
keywords: hljs.inherit(ALL_KEYWORDS, { type: KNOWN_TYPES }),
contains: [
COMMENT,
GENERIC_TYPE_SYMBOL,
hljs.inherit(QUOTED_IDENTIFIER, { scope: null }), // match to avoid strange patterns inside that may break the parsing
OPERATOR_WITHOUT_EQUAL,
],
}
}
const TYPE_ANNOTATION = makeTypeAnnotationMode(/:/, 'operator')
const DISCRIMINATED_UNION_TYPE_ANNOTATION = makeTypeAnnotationMode(
/\bof\b/,
'keyword'
)
// type MyType<'a> = ...
const TYPE_DECLARATION = {
begin: [
/(^|\s+)/, // prevents matching the following: `match s.stype with`
/type/,
/\s+/,
IDENTIFIER_RE,
],
beginScope: {
2: 'keyword',
4: 'title.class',
},
end: lookahead(/\(|=|$/),
keywords: ALL_KEYWORDS, // match keywords in type constraints. e.g.: when 'a : null
contains: [
COMMENT,
hljs.inherit(QUOTED_IDENTIFIER, { scope: null }), // match to avoid strange patterns inside that may break the parsing
GENERIC_TYPE_SYMBOL,
{
// For visual consistency, highlight type brackets as operators.
scope: 'operator',
match: /<|>/,
},
TYPE_ANNOTATION, // generic types can have constraints, which are type annotations. e.g. type MyType<'T when 'T : delegate<obj * string>> =
],
}
const COMPUTATION_EXPRESSION = {
// computation expressions:
scope: 'computation-expression',
// BUG: might conflict with record deconstruction. e.g. let f { Name = name } = name // will highlight f
match: /\b[_a-z]\w*(?=\s*\{)/,
}
const PREPROCESSOR = {
// preprocessor directives and fsi commands:
begin: [/^\s*/, concat(/#/, either(...PREPROCESSOR_KEYWORDS)), /\b/],
beginScope: { 2: 'meta' },
end: lookahead(/\s|$/),
}
// TODO: this definition is missing support for type suffixes and octal notation.
// BUG: range operator without any space is wrongly interpreted as a single number (e.g. 1..10 )
const NUMBER = {
variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE],
}
// All the following string definitions are potentially multi-line.
// BUG: these definitions are missing support for byte strings (suffixed with B)
// "..."
const QUOTED_STRING = {
scope: 'string',
begin: /"/,
end: /"/,
contains: [hljs.BACKSLASH_ESCAPE],
}
// @"..."
const VERBATIM_STRING = {
scope: 'string',
begin: /@"/,
end: /"/,
contains: [
{
match: /""/, // escaped "
},
hljs.BACKSLASH_ESCAPE,
],
}
// """..."""
const TRIPLE_QUOTED_STRING = {
scope: 'string',
begin: /"""/,
end: /"""/,
relevance: 2,
}
const SUBST = {
scope: 'subst',
begin: /\{/,
end: /\}/,
keywords: ALL_KEYWORDS,
}
// $"...{1+1}..."
const INTERPOLATED_STRING = {
scope: 'string',
begin: /\$"/,
end: /"/,
contains: [
{
match: /\{\{/, // escaped {
},
{
match: /\}\}/, // escaped }
},
hljs.BACKSLASH_ESCAPE,
SUBST,
],
}
// $@"...{1+1}..."
const INTERPOLATED_VERBATIM_STRING = {
scope: 'string',
begin: /(\$@|@\$)"/,
end: /"/,
contains: [
{
match: /\{\{/, // escaped {
},
{
match: /\}\}/, // escaped }
},
{
match: /""/,
},
hljs.BACKSLASH_ESCAPE,
SUBST,
],
}
// $"""...{1+1}..."""
const INTERPOLATED_TRIPLE_QUOTED_STRING = {
scope: 'string',
begin: /\$"""/,
end: /"""/,
contains: [
{
match: /\{\{/, // escaped {
},
{
match: /\}\}/, // escaped }
},
SUBST,
],
relevance: 2,
}
// '.'
const CHAR_LITERAL = {
scope: 'string',
match: concat(
/'/,
either(
/[^\\']/, // either a single non escaped char...
/\\(?:.|\d{3}|x[a-fA-F\d]{2}|u[a-fA-F\d]{4}|U[a-fA-F\d]{8})/ // ...or an escape sequence
),
/'/
),
}
// F# allows a lot of things inside string placeholders.
// Things that don't currently seem allowed by the compiler: types definition, attributes usage.
// (Strictly speaking, some of the followings are only allowed inside triple quoted interpolated strings...)
SUBST.contains = [
INTERPOLATED_VERBATIM_STRING,
INTERPOLATED_STRING,
VERBATIM_STRING,
QUOTED_STRING,
CHAR_LITERAL,
BANG_KEYWORD_MODE,
COMMENT,
QUOTED_IDENTIFIER,
TYPE_ANNOTATION,
COMPUTATION_EXPRESSION,
PREPROCESSOR,
NUMBER,
GENERIC_TYPE_SYMBOL,
OPERATOR,
]
const STRING = {
variants: [
INTERPOLATED_TRIPLE_QUOTED_STRING,
INTERPOLATED_VERBATIM_STRING,
INTERPOLATED_STRING,
TRIPLE_QUOTED_STRING,
VERBATIM_STRING,
QUOTED_STRING,
CHAR_LITERAL,
],
}
return {
name: 'F#',
aliases: ['fs', 'f#'],
keywords: ALL_KEYWORDS,
illegal: /\/\*/,
classNameAliases: {
'computation-expression': 'keyword',
},
contains: [
BANG_KEYWORD_MODE,
STRING,
COMMENT,
QUOTED_IDENTIFIER,
TYPE_DECLARATION,
{
// e.g. [<Attributes("")>] or [<``module``: MyCustomAttributeThatWorksOnModules>]
// or [<Sealed; NoEquality; NoComparison; CompiledName("FSharpAsync`1")>]
scope: 'meta',
begin: /\[</,
end: />\]/,
relevance: 2,
contains: [
QUOTED_IDENTIFIER,
// can contain any constant value
TRIPLE_QUOTED_STRING,
VERBATIM_STRING,
QUOTED_STRING,
CHAR_LITERAL,
NUMBER,
],
},
DISCRIMINATED_UNION_TYPE_ANNOTATION,
TYPE_ANNOTATION,
COMPUTATION_EXPRESSION,
PREPROCESSOR,
NUMBER,
GENERIC_TYPE_SYMBOL,
OPERATOR,
],
}
}