Debian Codegraph @

codemirror-legacy-modes/mode/clike.js

raw
1 function Context(indented, column, type, info, align, prev) {
2 this.indented = indented;
3 this.column = column;
4 this.type = type;
5 this.info = info;
6 this.align = align;
7 this.prev = prev;
8 }
9 function pushContext(state, col, type, info) {
10 var indent = state.indented;
11 if (state.context && state.context.type == "statement" && type != "statement")
12 indent = state.context.indented;
13 return state.context = new Context(indent, col, type, info, null, state.context);
14 }
15 function popContext(state) {
16 var t = state.context.type;
17 if (t == ")" || t == "]" || t == "}")
18 state.indented = state.context.indented;
19 return state.context = state.context.prev;
20 }
21
22 function typeBefore(stream, state, pos) {
23 if (state.prevToken == "variable" || state.prevToken == "type") return true;
24 if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true;
25 if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;
26 }
27
28 function isTopScope(context) {
29 for (;;) {
30 if (!context || context.type == "top") return true;
31 if (context.type == "}" && context.prev.info != "namespace") return false;
32 context = context.prev;
33 }
34 }
35
36 export function clike(parserConfig) {
37 var statementIndentUnit = parserConfig.statementIndentUnit,
38 dontAlignCalls = parserConfig.dontAlignCalls,
39 keywords = parserConfig.keywords || {},
40 types = parserConfig.types || {},
41 builtin = parserConfig.builtin || {},
42 blockKeywords = parserConfig.blockKeywords || {},
43 defKeywords = parserConfig.defKeywords || {},
44 atoms = parserConfig.atoms || {},
45 hooks = parserConfig.hooks || {},
46 multiLineStrings = parserConfig.multiLineStrings,
47 indentStatements = parserConfig.indentStatements !== false,
48 indentSwitch = parserConfig.indentSwitch !== false,
49 namespaceSeparator = parserConfig.namespaceSeparator,
50 isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/,
51 numberStart = parserConfig.numberStart || /[\d\.]/,
52 number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,
53 isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/,
54 isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/,
55 // An optional function that takes a {string} token and returns true if it
56 // should be treated as a builtin.
57 isReservedIdentifier = parserConfig.isReservedIdentifier || false;
58
59 var curPunc, isDefKeyword;
60
61 function tokenBase(stream, state) {
62 var ch = stream.next();
63 if (hooks[ch]) {
64 var result = hooks[ch](stream, state);
65 if (result !== false) return result;
66 }
67 if (ch == '"' || ch == "'") {
68 state.tokenize = tokenString(ch);
69 return state.tokenize(stream, state);
70 }
71 if (numberStart.test(ch)) {
72 stream.backUp(1)
73 if (stream.match(number)) return "number"
74 stream.next()
75 }
76 if (isPunctuationChar.test(ch)) {
77 curPunc = ch;
78 return null;
79 }
80 if (ch == "/") {
81 if (stream.eat("*")) {
82 state.tokenize = tokenComment;
83 return tokenComment(stream, state);
84 }
85 if (stream.eat("/")) {
86 stream.skipToEnd();
87 return "comment";
88 }
89 }
90 if (isOperatorChar.test(ch)) {
91 while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {}
92 return "operator";
93 }
94 stream.eatWhile(isIdentifierChar);
95 if (namespaceSeparator) while (stream.match(namespaceSeparator))
96 stream.eatWhile(isIdentifierChar);
97
98 var cur = stream.current();
99 if (contains(keywords, cur)) {
100 if (contains(blockKeywords, cur)) curPunc = "newstatement";
101 if (contains(defKeywords, cur)) isDefKeyword = true;
102 return "keyword";
103 }
104 if (contains(types, cur)) return "type";
105 if (contains(builtin, cur)
106 || (isReservedIdentifier && isReservedIdentifier(cur))) {
107 if (contains(blockKeywords, cur)) curPunc = "newstatement";
108 return "builtin";
109 }
110 if (contains(atoms, cur)) return "atom";
111 return "variable";
112 }
113
114 function tokenString(quote) {
115 return function(stream, state) {
116 var escaped = false, next, end = false;
117 while ((next = stream.next()) != null) {
118 if (next == quote && !escaped) {end = true; break;}
119 escaped = !escaped && next == "\\";
120 }
121 if (end || !(escaped || multiLineStrings))
122 state.tokenize = null;
123 return "string";
124 };
125 }
126
127 function tokenComment(stream, state) {
128 var maybeEnd = false, ch;
129 while (ch = stream.next()) {
130 if (ch == "/" && maybeEnd) {
131 state.tokenize = null;
132 break;
133 }
134 maybeEnd = (ch == "*");
135 }
136 return "comment";
137 }
138
139 function maybeEOL(stream, state) {
140 if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))
141 state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)
142 }
143
144 // Interface
145
146 return {
147 name: parserConfig.name,
148 startState: function(indentUnit) {
149 return {
150 tokenize: null,
151 context: new Context(-indentUnit, 0, "top", null, false),
152 indented: 0,
153 startOfLine: true,
154 prevToken: null
155 };
156 },
157
158 token: function(stream, state) {
159 var ctx = state.context;
160 if (stream.sol()) {
161 if (ctx.align == null) ctx.align = false;
162 state.indented = stream.indentation();
163 state.startOfLine = true;
164 }
165 if (stream.eatSpace()) { maybeEOL(stream, state); return null; }
166 curPunc = isDefKeyword = null;
167 var style = (state.tokenize || tokenBase)(stream, state);
168 if (style == "comment" || style == "meta") return style;
169 if (ctx.align == null) ctx.align = true;
170
171 if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false)))
172 while (state.context.type == "statement") popContext(state);
173 else if (curPunc == "{") pushContext(state, stream.column(), "}");
174 else if (curPunc == "[") pushContext(state, stream.column(), "]");
175 else if (curPunc == "(") pushContext(state, stream.column(), ")");
176 else if (curPunc == "}") {
177 while (ctx.type == "statement") ctx = popContext(state);
178 if (ctx.type == "}") ctx = popContext(state);
179 while (ctx.type == "statement") ctx = popContext(state);
180 }
181 else if (curPunc == ctx.type) popContext(state);
182 else if (indentStatements &&
183 (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
184 (ctx.type == "statement" && curPunc == "newstatement"))) {
185 pushContext(state, stream.column(), "statement", stream.current());
186 }
187
188 if (style == "variable" &&
189 ((state.prevToken == "def" ||
190 (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&
191 isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
192 style = "def";
193
194 if (hooks.token) {
195 var result = hooks.token(stream, state, style);
196 if (result !== undefined) style = result;
197 }
198
199 if (style == "def" && parserConfig.styleDefs === false) style = "variable";
200
201 state.startOfLine = false;
202 state.prevToken = isDefKeyword ? "def" : style || curPunc;
203 maybeEOL(stream, state);
204 return style;
205 },
206
207 indent: function(state, textAfter, context) {
208 if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine && isTopScope(state.context))
209 return null;
210 var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
211 var closing = firstChar == ctx.type;
212 if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
213 if (parserConfig.dontIndentStatements)
214 while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info))
215 ctx = ctx.prev
216 if (hooks.indent) {
217 var hook = hooks.indent(state, ctx, textAfter, context.unit);
218 if (typeof hook == "number") return hook
219 }
220 var switchBlock = ctx.prev && ctx.prev.info == "switch";
221 if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {
222 while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev
223 return ctx.indented
224 }
225 if (ctx.type == "statement")
226 return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit || context.unit);
227 if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
228 return ctx.column + (closing ? 0 : 1);
229 if (ctx.type == ")" && !closing)
230 return ctx.indented + (statementIndentUnit || context.unit);
231
232 return ctx.indented + (closing ? 0 : context.unit) +
233 (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? context.unit : 0);
234 },
235
236 languageData: {
237 indentOnInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
238 commentTokens: {line: "//", block: {open: "/*", close: "*/"}},
239 autocomplete: Object.keys(keywords).concat(Object.keys(types)).concat(Object.keys(builtin)).concat(Object.keys(atoms)),
240 ...parserConfig.languageData
241 }
242 };
243 };
244
245 function words(str) {
246 var obj = {}, words = str.split(" ");
247 for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
248 return obj;
249 }
250 function contains(words, word) {
251 if (typeof words === "function") {
252 return words(word);
253 } else {
254 return words.propertyIsEnumerable(word);
255 }
256 }
257 var cKeywords = "auto if break case register continue return default do sizeof " +
258 "static else struct switch extern typedef union for goto while enum const " +
259 "volatile inline restrict asm fortran";
260
261 // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20.
262 var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch " +
263 "class compl concept constexpr const_cast decltype delete dynamic_cast " +
264 "explicit export final friend import module mutable namespace new noexcept " +
265 "not not_eq operator or or_eq override private protected public " +
266 "reinterpret_cast requires static_assert static_cast template this " +
267 "thread_local throw try typeid typename using virtual xor xor_eq";
268
269 var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy " +
270 "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " +
271 "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " +
272 "@public @package @private @protected @required @optional @try @catch @finally @import " +
273 "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available";
274
275 var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION " +
276 " NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER " +
277 "NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION " +
278 "NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT"
279
280 // Do not use this. Use the cTypes function below. This is global just to avoid
281 // excessive calls when cTypes is being called multiple times during a parse.
282 var basicCTypes = words("int long char short double float unsigned signed " +
283 "void bool");
284
285 // Do not use this. Use the objCTypes function below. This is global just to avoid
286 // excessive calls when objCTypes is being called multiple times during a parse.
287 var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL");
288
289 // Returns true if identifier is a "C" type.
290 // C type is defined as those that are reserved by the compiler (basicTypes),
291 // and those that end in _t (Reserved by POSIX for types)
292 // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html
293 function cTypes(identifier) {
294 return contains(basicCTypes, identifier) || /.+_t$/.test(identifier);
295 }
296
297 // Returns true if identifier is a "Objective C" type.
298 function objCTypes(identifier) {
299 return cTypes(identifier) || contains(basicObjCTypes, identifier);
300 }
301
302 var cBlockKeywords = "case do else for if switch while struct enum union";
303 var cDefKeywords = "struct enum union";
304
305 function cppHook(stream, state) {
306 if (!state.startOfLine) return false
307 for (var ch, next = null; ch = stream.peek();) {
308 if (ch == "\\" && stream.match(/^.$/)) {
309 next = cppHook
310 break
311 } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) {
312 break
313 }
314 stream.next()
315 }
316 state.tokenize = next
317 return "meta"
318 }
319
320 function pointerHook(_stream, state) {
321 if (state.prevToken == "type") return "type";
322 return false;
323 }
324
325 // For C and C++ (and ObjC): identifiers starting with __
326 // or _ followed by a capital letter are reserved for the compiler.
327 function cIsReservedIdentifier(token) {
328 if (!token || token.length < 2) return false;
329 if (token[0] != '_') return false;
330 return (token[1] == '_') || (token[1] !== token[1].toLowerCase());
331 }
332
333 function cpp14Literal(stream) {
334 stream.eatWhile(/[\w\.']/);
335 return "number";
336 }
337
338 function cpp11StringHook(stream, state) {
339 stream.backUp(1);
340 // Raw strings.
341 if (stream.match(/^(?:R|u8R|uR|UR|LR)/)) {
342 var match = stream.match(/^"([^\s\\()]{0,16})\(/);
343 if (!match) {
344 return false;
345 }
346 state.cpp11RawStringDelim = match[1];
347 state.tokenize = tokenRawString;
348 return tokenRawString(stream, state);
349 }
350 // Unicode strings/chars.
351 if (stream.match(/^(?:u8|u|U|L)/)) {
352 if (stream.match(/^["']/, /* eat */ false)) {
353 return "string";
354 }
355 return false;
356 }
357 // Ignore this hook.
358 stream.next();
359 return false;
360 }
361
362 function cppLooksLikeConstructor(word) {
363 var lastTwo = /(\w+)::~?(\w+)$/.exec(word);
364 return lastTwo && lastTwo[1] == lastTwo[2];
365 }
366
367 // C#-style strings where "" escapes a quote.
368 function tokenAtString(stream, state) {
369 var next;
370 while ((next = stream.next()) != null) {
371 if (next == '"' && !stream.eat('"')) {
372 state.tokenize = null;
373 break;
374 }
375 }
376 return "string";
377 }
378
379 // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
380 // <delim> can be a string up to 16 characters long.
381 function tokenRawString(stream, state) {
382 // Escape characters that have special regex meanings.
383 var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
384 var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
385 if (match)
386 state.tokenize = null;
387 else
388 stream.skipToEnd();
389 return "string";
390 }
391
392 export const c = clike({
393 name: "c",
394 keywords: words(cKeywords),
395 types: cTypes,
396 blockKeywords: words(cBlockKeywords),
397 defKeywords: words(cDefKeywords),
398 typeFirstDefinitions: true,
399 atoms: words("NULL true false"),
400 isReservedIdentifier: cIsReservedIdentifier,
401 hooks: {
402 "#": cppHook,
403 "*": pointerHook,
404 }
405 })
406
407 export const cpp = clike({
408 name: "cpp",
409 keywords: words(cKeywords + " " + cppKeywords),
410 types: cTypes,
411 blockKeywords: words(cBlockKeywords + " class try catch"),
412 defKeywords: words(cDefKeywords + " class namespace"),
413 typeFirstDefinitions: true,
414 atoms: words("true false NULL nullptr"),
415 dontIndentStatements: /^template$/,
416 isIdentifierChar: /[\w\$_~\xa1-\uffff]/,
417 isReservedIdentifier: cIsReservedIdentifier,
418 hooks: {
419 "#": cppHook,
420 "*": pointerHook,
421 "u": cpp11StringHook,
422 "U": cpp11StringHook,
423 "L": cpp11StringHook,
424 "R": cpp11StringHook,
425 "0": cpp14Literal,
426 "1": cpp14Literal,
427 "2": cpp14Literal,
428 "3": cpp14Literal,
429 "4": cpp14Literal,
430 "5": cpp14Literal,
431 "6": cpp14Literal,
432 "7": cpp14Literal,
433 "8": cpp14Literal,
434 "9": cpp14Literal,
435 token: function(stream, state, style) {
436 if (style == "variable" && stream.peek() == "(" &&
437 (state.prevToken == ";" || state.prevToken == null ||
438 state.prevToken == "}") &&
439 cppLooksLikeConstructor(stream.current()))
440 return "def";
441 }
442 },
443 namespaceSeparator: "::"
444 });
445
446 export const java = clike({
447 name: "java",
448 keywords: words("abstract assert break case catch class const continue default " +
449 "do else enum extends final finally for goto if implements import " +
450 "instanceof interface native new package private protected public " +
451 "return static strictfp super switch synchronized this throw throws transient " +
452 "try volatile while @interface"),
453 types: words("var byte short int long float double boolean char void Boolean Byte Character Double Float " +
454 "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
455 blockKeywords: words("catch class do else finally for if switch try while"),
456 defKeywords: words("class interface enum @interface"),
457 typeFirstDefinitions: true,
458 atoms: words("true false null"),
459 number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
460 hooks: {
461 "@": function(stream) {
462 // Don't match the @interface keyword.
463 if (stream.match('interface', false)) return false;
464
465 stream.eatWhile(/[\w\$_]/);
466 return "meta";
467 },
468 '"': function(stream, state) {
469 if (!stream.match(/""$/)) return false;
470 state.tokenize = tokenTripleString;
471 return state.tokenize(stream, state);
472 }
473 }
474 })
475
476 export const csharp = clike({
477 name: "csharp",
478 keywords: words("abstract as async await base break case catch checked class const continue" +
479 " default delegate do else enum event explicit extern finally fixed for" +
480 " foreach goto if implicit in init interface internal is lock namespace new" +
481 " operator out override params private protected public readonly record ref required return sealed" +
482 " sizeof stackalloc static struct switch this throw try typeof unchecked" +
483 " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
484 " global group into join let orderby partial remove select set value var yield"),
485 types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
486 " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
487 " UInt64 bool byte char decimal double short int long object" +
488 " sbyte float string ushort uint ulong"),
489 blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
490 defKeywords: words("class interface namespace record struct var"),
491 typeFirstDefinitions: true,
492 atoms: words("true false null"),
493 hooks: {
494 "@": function(stream, state) {
495 if (stream.eat('"')) {
496 state.tokenize = tokenAtString;
497 return tokenAtString(stream, state);
498 }
499 stream.eatWhile(/[\w\$_]/);
500 return "meta";
501 }
502 }
503 });
504
505 function tokenTripleString(stream, state) {
506 var escaped = false;
507 while (!stream.eol()) {
508 if (!escaped && stream.match('"""')) {
509 state.tokenize = null;
510 break;
511 }
512 escaped = stream.next() == "\\" && !escaped;
513 }
514 return "string";
515 }
516
517 function tokenNestedComment(depth) {
518 return function (stream, state) {
519 var ch
520 while (ch = stream.next()) {
521 if (ch == "*" && stream.eat("/")) {
522 if (depth == 1) {
523 state.tokenize = null
524 break
525 } else {
526 state.tokenize = tokenNestedComment(depth - 1)
527 return state.tokenize(stream, state)
528 }
529 } else if (ch == "/" && stream.eat("*")) {
530 state.tokenize = tokenNestedComment(depth + 1)
531 return state.tokenize(stream, state)
532 }
533 }
534 return "comment"
535 }
536 }
537
538 export const scala = clike({
539 name: "scala",
540 keywords: words(
541 /* scala */
542 "abstract case catch class def do else extends final finally for forSome if " +
543 "implicit import lazy match new null object override package private protected return " +
544 "sealed super this throw trait try type val var while with yield _ " +
545
546 /* package scala */
547 "assert assume require print println printf readLine readBoolean readByte readShort " +
548 "readChar readInt readLong readFloat readDouble"
549 ),
550 types: words(
551 "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
552 "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " +
553 "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
554 "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
555 "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
556
557 /* package java.lang */
558 "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
559 "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
560 "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
561 "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
562 ),
563 multiLineStrings: true,
564 blockKeywords: words("catch class enum do else finally for forSome if match switch try while"),
565 defKeywords: words("class enum def object package trait type val var"),
566 atoms: words("true false null"),
567 indentStatements: false,
568 indentSwitch: false,
569 isOperatorChar: /[+\-*&%=<>!?|\/#:@]/,
570 hooks: {
571 "@": function(stream) {
572 stream.eatWhile(/[\w\$_]/);
573 return "meta";
574 },
575 '"': function(stream, state) {
576 if (!stream.match('""')) return false;
577 state.tokenize = tokenTripleString;
578 return state.tokenize(stream, state);
579 },
580 "'": function(stream) {
581 if (stream.match(/^(\\[^'\s]+|[^\\'])'/)) return "character"
582 stream.eatWhile(/[\w\$_\xa1-\uffff]/);
583 return "atom";
584 },
585 "=": function(stream, state) {
586 var cx = state.context
587 if (cx.type == "}" && cx.align && stream.eat(">")) {
588 state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)
589 return "operator"
590 } else {
591 return false
592 }
593 },
594
595 "/": function(stream, state) {
596 if (!stream.eat("*")) return false
597 state.tokenize = tokenNestedComment(1)
598 return state.tokenize(stream, state)
599 }
600 },
601 languageData: {
602 closeBrackets: {brackets: ["(", "[", "{", "'", '"', '"""']}
603 }
604 });
605
606 function tokenKotlinString(tripleString){
607 return function (stream, state) {
608 var escaped = false, next, end = false;
609 while (!stream.eol()) {
610 if (!tripleString && !escaped && stream.match('"') ) {end = true; break;}
611 if (tripleString && stream.match('"""')) {end = true; break;}
612 next = stream.next();
613 if(!escaped && next == "$" && stream.match('{'))
614 stream.skipTo("}");
615 escaped = !escaped && next == "\\" && !tripleString;
616 }
617 if (end || !tripleString)
618 state.tokenize = null;
619 return "string";
620 }
621 }
622
623 export const kotlin = clike({
624 name: "kotlin",
625 keywords: words(
626 /*keywords*/
627 "package as typealias class interface this super val operator " +
628 "var fun for is in This throw return annotation " +
629 "break continue object if else while do try when !in !is as? " +
630
631 /*soft keywords*/
632 "file import where by get set abstract enum open inner override private public internal " +
633 "protected catch finally out final vararg reified dynamic companion constructor init " +
634 "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
635 "external annotation crossinline const operator infix suspend actual expect setparam"
636 ),
637 types: words(
638 /* package java.lang */
639 "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
640 "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
641 "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
642 "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " +
643 "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " +
644 "LazyThreadSafetyMode LongArray Nothing ShortArray Unit"
645 ),
646 intendSwitch: false,
647 indentStatements: false,
648 multiLineStrings: true,
649 number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
650 blockKeywords: words("catch class do else finally for if where try while enum"),
651 defKeywords: words("class val var object interface fun"),
652 atoms: words("true false null this"),
653 hooks: {
654 "@": function(stream) {
655 stream.eatWhile(/[\w\$_]/);
656 return "meta";
657 },
658 '*': function(_stream, state) {
659 return state.prevToken == '.' ? 'variable' : 'operator';
660 },
661 '"': function(stream, state) {
662 state.tokenize = tokenKotlinString(stream.match('""'));
663 return state.tokenize(stream, state);
664 },
665 "/": function(stream, state) {
666 if (!stream.eat("*")) return false;
667 state.tokenize = tokenNestedComment(1);
668 return state.tokenize(stream, state)
669 },
670 indent: function(state, ctx, textAfter, indentUnit) {
671 var firstChar = textAfter && textAfter.charAt(0);
672 if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "")
673 return state.indented;
674 if ((state.prevToken == "operator" && textAfter != "}" && state.context.type != "}") ||
675 state.prevToken == "variable" && firstChar == "." ||
676 (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".")
677 return indentUnit * 2 + ctx.indented;
678 if (ctx.align && ctx.type == "}")
679 return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit);
680 }
681 },
682 languageData: {
683 closeBrackets: {brackets: ["(", "[", "{", "'", '"', '"""']}
684 }
685 });
686
687 export const shader = clike({
688 name: "shader",
689 keywords: words("sampler1D sampler2D sampler3D samplerCube " +
690 "sampler1DShadow sampler2DShadow " +
691 "const attribute uniform varying " +
692 "break continue discard return " +
693 "for while do if else struct " +
694 "in out inout"),
695 types: words("float int bool void " +
696 "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
697 "mat2 mat3 mat4"),
698 blockKeywords: words("for while do if else struct"),
699 builtin: words("radians degrees sin cos tan asin acos atan " +
700 "pow exp log exp2 sqrt inversesqrt " +
701 "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
702 "length distance dot cross normalize ftransform faceforward " +
703 "reflect refract matrixCompMult " +
704 "lessThan lessThanEqual greaterThan greaterThanEqual " +
705 "equal notEqual any all not " +
706 "texture1D texture1DProj texture1DLod texture1DProjLod " +
707 "texture2D texture2DProj texture2DLod texture2DProjLod " +
708 "texture3D texture3DProj texture3DLod texture3DProjLod " +
709 "textureCube textureCubeLod " +
710 "shadow1D shadow2D shadow1DProj shadow2DProj " +
711 "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
712 "dFdx dFdy fwidth " +
713 "noise1 noise2 noise3 noise4"),
714 atoms: words("true false " +
715 "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
716 "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
717 "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
718 "gl_FogCoord gl_PointCoord " +
719 "gl_Position gl_PointSize gl_ClipVertex " +
720 "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
721 "gl_TexCoord gl_FogFragCoord " +
722 "gl_FragCoord gl_FrontFacing " +
723 "gl_FragData gl_FragDepth " +
724 "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
725 "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
726 "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
727 "gl_TextureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
728 "gl_ProjectionMatrixInverseTranspose " +
729 "gl_ModelViewProjectionMatrixInverseTranspose " +
730 "gl_TextureMatrixInverseTranspose " +
731 "gl_NormalScale gl_DepthRange gl_ClipPlane " +
732 "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
733 "gl_FrontLightModelProduct gl_BackLightModelProduct " +
734 "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
735 "gl_FogParameters " +
736 "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
737 "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
738 "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
739 "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
740 "gl_MaxDrawBuffers"),
741 indentSwitch: false,
742 hooks: {"#": cppHook}
743 })
744
745 export const nesC = clike({
746 name: "nesc",
747 keywords: words(cKeywords + " as atomic async call command component components configuration event generic " +
748 "implementation includes interface module new norace nx_struct nx_union post provides " +
749 "signal task uses abstract extends"),
750 types: cTypes,
751 blockKeywords: words(cBlockKeywords),
752 atoms: words("null true false"),
753 hooks: {"#": cppHook}
754 })
755
756 export const objectiveC = clike({
757 name: "objectivec",
758 keywords: words(cKeywords + " " + objCKeywords),
759 types: objCTypes,
760 builtin: words(objCBuiltins),
761 blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"),
762 defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"),
763 dontIndentStatements: /^@.*$/,
764 typeFirstDefinitions: true,
765 atoms: words("YES NO NULL Nil nil true false nullptr"),
766 isReservedIdentifier: cIsReservedIdentifier,
767 hooks: {
768 "#": cppHook,
769 "*": pointerHook,
770 }
771 })
772
773 export const objectiveCpp = clike({
774 name: "objectivecpp",
775 keywords: words(cKeywords + " " + objCKeywords + " " + cppKeywords),
776 types: objCTypes,
777 builtin: words(objCBuiltins),
778 blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"),
779 defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class class namespace"),
780 dontIndentStatements: /^@.*$|^template$/,
781 typeFirstDefinitions: true,
782 atoms: words("YES NO NULL Nil nil true false nullptr"),
783 isReservedIdentifier: cIsReservedIdentifier,
784 hooks: {
785 "#": cppHook,
786 "*": pointerHook,
787 "u": cpp11StringHook,
788 "U": cpp11StringHook,
789 "L": cpp11StringHook,
790 "R": cpp11StringHook,
791 "0": cpp14Literal,
792 "1": cpp14Literal,
793 "2": cpp14Literal,
794 "3": cpp14Literal,
795 "4": cpp14Literal,
796 "5": cpp14Literal,
797 "6": cpp14Literal,
798 "7": cpp14Literal,
799 "8": cpp14Literal,
800 "9": cpp14Literal,
801 token: function(stream, state, style) {
802 if (style == "variable" && stream.peek() == "(" &&
803 (state.prevToken == ";" || state.prevToken == null ||
804 state.prevToken == "}") &&
805 cppLooksLikeConstructor(stream.current()))
806 return "def";
807 }
808 },
809 namespaceSeparator: "::"
810 })
811
812 export const squirrel = clike({
813 name: "squirrel",
814 keywords: words("base break clone continue const default delete enum extends function in class" +
815 " foreach local resume return this throw typeof yield constructor instanceof static"),
816 types: cTypes,
817 blockKeywords: words("case catch class else for foreach if switch try while"),
818 defKeywords: words("function local class"),
819 typeFirstDefinitions: true,
820 atoms: words("true false null"),
821 hooks: {"#": cppHook}
822 })
823
824 // Ceylon Strings need to deal with interpolation
825 var stringTokenizer = null;
826 function tokenCeylonString(type) {
827 return function(stream, state) {
828 var escaped = false, next, end = false;
829 while (!stream.eol()) {
830 if (!escaped && stream.match('"') &&
831 (type == "single" || stream.match('""'))) {
832 end = true;
833 break;
834 }
835 if (!escaped && stream.match('``')) {
836 stringTokenizer = tokenCeylonString(type);
837 end = true;
838 break;
839 }
840 next = stream.next();
841 escaped = type == "single" && !escaped && next == "\\";
842 }
843 if (end)
844 state.tokenize = null;
845 return "string";
846 }
847 }
848
849 export const ceylon = clike({
850 name: "ceylon",
851 keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" +
852 " exists extends finally for function given if import in interface is let module new" +
853 " nonempty object of out outer package return satisfies super switch then this throw" +
854 " try value void while"),
855 types: function(word) {
856 // In Ceylon all identifiers that start with an uppercase are types
857 var first = word.charAt(0);
858 return (first === first.toUpperCase() && first !== first.toLowerCase());
859 },
860 blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"),
861 defKeywords: words("class dynamic function interface module object package value"),
862 builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" +
863 " native optional sealed see serializable shared suppressWarnings tagged throws variable"),
864 isPunctuationChar: /[\[\]{}\(\),;\:\.`]/,
865 isOperatorChar: /[+\-*&%=<>!?|^~:\/]/,
866 numberStart: /[\d#$]/,
867 number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,
868 multiLineStrings: true,
869 typeFirstDefinitions: true,
870 atoms: words("true false null larger smaller equal empty finished"),
871 indentSwitch: false,
872 styleDefs: false,
873 hooks: {
874 "@": function(stream) {
875 stream.eatWhile(/[\w\$_]/);
876 return "meta";
877 },
878 '"': function(stream, state) {
879 state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single");
880 return state.tokenize(stream, state);
881 },
882 '`': function(stream, state) {
883 if (!stringTokenizer || !stream.match('`')) return false;
884 state.tokenize = stringTokenizer;
885 stringTokenizer = null;
886 return state.tokenize(stream, state);
887 },
888 "'": function(stream) {
889 if (stream.match(/^(\\[^'\s]+|[^\\'])'/)) return "string.special"
890 stream.eatWhile(/[\w\$_\xa1-\uffff]/);
891 return "atom";
892 },
893 token: function(_stream, state, style) {
894 if ((style == "variable" || style == "type") &&
895 state.prevToken == ".") {
896 return "variableName.special";
897 }
898 }
899 },
900 languageData: {
901 closeBrackets: {brackets: ["(", "[", "{", "'", '"', '"""']}
902 }
903 })
904
905 function pushInterpolationStack(state) {
906 (state.interpolationStack || (state.interpolationStack = [])).push(state.tokenize);
907 }
908
909 function popInterpolationStack(state) {
910 return (state.interpolationStack || (state.interpolationStack = [])).pop();
911 }
912
913 function sizeInterpolationStack(state) {
914 return state.interpolationStack ? state.interpolationStack.length : 0;
915 }
916
917 function tokenDartString(quote, stream, state, raw) {
918 var tripleQuoted = false;
919 if (stream.eat(quote)) {
920 if (stream.eat(quote)) tripleQuoted = true;
921 else return "string"; //empty string
922 }
923 function tokenStringHelper(stream, state) {
924 var escaped = false;
925 while (!stream.eol()) {
926 if (!raw && !escaped && stream.peek() == "$") {
927 pushInterpolationStack(state);
928 state.tokenize = tokenInterpolation;
929 return "string";
930 }
931 var next = stream.next();
932 if (next == quote && !escaped && (!tripleQuoted || stream.match(quote + quote))) {
933 state.tokenize = null;
934 break;
935 }
936 escaped = !raw && !escaped && next == "\\";
937 }
938 return "string";
939 }
940 state.tokenize = tokenStringHelper;
941 return tokenStringHelper(stream, state);
942 }
943
944 function tokenInterpolation(stream, state) {
945 stream.eat("$");
946 if (stream.eat("{")) {
947 // let clike handle the content of ${...},
948 // we take over again when "}" appears (see hooks).
949 state.tokenize = null;
950 } else {
951 state.tokenize = tokenInterpolationIdentifier;
952 }
953 return null;
954 }
955
956 function tokenInterpolationIdentifier(stream, state) {
957 stream.eatWhile(/[\w_]/);
958 state.tokenize = popInterpolationStack(state);
959 return "variable";
960 }
961
962 export const dart = clike({
963 name: "dart",
964 keywords: words("this super static final const abstract class extends external factory " +
965 "implements mixin get native set typedef with enum throw rethrow assert break case " +
966 "continue default in return new deferred async await covariant try catch finally " +
967 "do else for if switch while import library export part of show hide is as extension " +
968 "on yield late required sealed base interface when inline"),
969 blockKeywords: words("try catch finally do else for if switch while"),
970 builtin: words("void bool num int double dynamic var String Null Never"),
971 atoms: words("true false null"),
972 // clike numbers without the suffixes, and with '_' separators.
973 number: /^(?:0x[a-f\d_]+|(?:[\d_]+\.?[\d_]*|\.[\d_]+)(?:e[-+]?[\d_]+)?)/i,
974 hooks: {
975 "@": function(stream) {
976 stream.eatWhile(/[\w\$_\.]/);
977 return "meta";
978 },
979
980 // custom string handling to deal with triple-quoted strings and string interpolation
981 "'": function(stream, state) {
982 return tokenDartString("'", stream, state, false);
983 },
984 "\"": function(stream, state) {
985 return tokenDartString("\"", stream, state, false);
986 },
987 "r": function(stream, state) {
988 var peek = stream.peek();
989 if (peek == "'" || peek == "\"") {
990 return tokenDartString(stream.next(), stream, state, true);
991 }
992 return false;
993 },
994
995 "}": function(_stream, state) {
996 // "}" is end of interpolation, if interpolation stack is non-empty
997 if (sizeInterpolationStack(state) > 0) {
998 state.tokenize = popInterpolationStack(state);
999 return null;
1000 }
1001 return false;
1002 },
1003
1004 "/": function(stream, state) {
1005 if (!stream.eat("*")) return false
1006 state.tokenize = tokenNestedComment(1)
1007 return state.tokenize(stream, state)
1008 },
1009 token: function(stream, _, style) {
1010 if (style == "variable") {
1011 // Assume uppercase symbols are classes
1012 var isUpper = RegExp('^[_$]*[A-Z][a-zA-Z0-9_$]*$','g');
1013 if (isUpper.test(stream.current())) {
1014 return 'type';
1015 }
1016 }
1017 }
1018 }
1019 })