Debian Codegraph @

codemirror-legacy-modes/mode/powershell.js

raw
1 function buildRegexp(patterns, options) {
2 options = options || {};
3 var prefix = options.prefix !== undefined ? options.prefix : '^';
4 var suffix = options.suffix !== undefined ? options.suffix : '\\b';
5
6 for (var i = 0; i < patterns.length; i++) {
7 if (patterns[i] instanceof RegExp) {
8 patterns[i] = patterns[i].source;
9 }
10 else {
11 patterns[i] = patterns[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
12 }
13 }
14
15 return new RegExp(prefix + '(' + patterns.join('|') + ')' + suffix, 'i');
16 }
17
18 var notCharacterOrDash = '(?=[^A-Za-z\\d\\-_]|$)';
19 var varNames = /[\w\-:]/
20 var keywords = buildRegexp([
21 /begin|break|catch|continue|data|default|do|dynamicparam/,
22 /else|elseif|end|exit|filter|finally|for|foreach|from|function|if|in/,
23 /param|process|return|switch|throw|trap|try|until|where|while/
24 ], { suffix: notCharacterOrDash });
25
26 var punctuation = /[\[\]{},;`\\\.]|@[({]/;
27 var wordOperators = buildRegexp([
28 'f',
29 /b?not/,
30 /[ic]?split/, 'join',
31 /is(not)?/, 'as',
32 /[ic]?(eq|ne|[gl][te])/,
33 /[ic]?(not)?(like|match|contains)/,
34 /[ic]?replace/,
35 /b?(and|or|xor)/
36 ], { prefix: '-' });
37 var symbolOperators = /[+\-*\/%]=|\+\+|--|\.\.|[+\-*&^%:=!|\/]|<(?!#)|(?!#)>/;
38 var operators = buildRegexp([wordOperators, symbolOperators], { suffix: '' });
39
40 var numbers = /^((0x[\da-f]+)|((\d+\.\d+|\d\.|\.\d+|\d+)(e[\+\-]?\d+)?))[ld]?([kmgtp]b)?/i;
41
42 var identifiers = /^[A-Za-z\_][A-Za-z\-\_\d]*\b/;
43
44 var symbolBuiltins = /[A-Z]:|%|\?/i;
45 var namedBuiltins = buildRegexp([
46 /Add-(Computer|Content|History|Member|PSSnapin|Type)/,
47 /Checkpoint-Computer/,
48 /Clear-(Content|EventLog|History|Host|Item(Property)?|Variable)/,
49 /Compare-Object/,
50 /Complete-Transaction/,
51 /Connect-PSSession/,
52 /ConvertFrom-(Csv|Json|SecureString|StringData)/,
53 /Convert-Path/,
54 /ConvertTo-(Csv|Html|Json|SecureString|Xml)/,
55 /Copy-Item(Property)?/,
56 /Debug-Process/,
57 /Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,
58 /Disconnect-PSSession/,
59 /Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/,
60 /(Enter|Exit)-PSSession/,
61 /Export-(Alias|Clixml|Console|Counter|Csv|FormatData|ModuleMember|PSSession)/,
62 /ForEach-Object/,
63 /Format-(Custom|List|Table|Wide)/,
64 new RegExp('Get-(Acl|Alias|AuthenticodeSignature|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Counter|Credential'
65 + '|Culture|Date|Event|EventLog|EventSubscriber|ExecutionPolicy|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job'
66 + '|Location|Member|Module|PfxCertificate|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration'
67 + '|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|Verb|WinEvent|WmiObject)'),
68 /Group-Object/,
69 /Import-(Alias|Clixml|Counter|Csv|LocalizedData|Module|PSSession)/,
70 /ImportSystemModules/,
71 /Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)/,
72 /Join-Path/,
73 /Limit-EventLog/,
74 /Measure-(Command|Object)/,
75 /Move-Item(Property)?/,
76 new RegExp('New-(Alias|Event|EventLog|Item(Property)?|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile'
77 + '|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy|WinEvent)'),
78 /Out-(Default|File|GridView|Host|Null|Printer|String)/,
79 /Pause/,
80 /(Pop|Push)-Location/,
81 /Read-Host/,
82 /Receive-(Job|PSSession)/,
83 /Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)/,
84 /Remove-(Computer|Event|EventLog|Item(Property)?|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)/,
85 /Rename-(Computer|Item(Property)?)/,
86 /Reset-ComputerMachinePassword/,
87 /Resolve-Path/,
88 /Restart-(Computer|Service)/,
89 /Restore-Computer/,
90 /Resume-(Job|Service)/,
91 /Save-Help/,
92 /Select-(Object|String|Xml)/,
93 /Send-MailMessage/,
94 new RegExp('Set-(Acl|Alias|AuthenticodeSignature|Content|Date|ExecutionPolicy|Item(Property)?|Location|PSBreakpoint|PSDebug' +
95 '|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)'),
96 /Show-(Command|ControlPanelItem|EventLog)/,
97 /Sort-Object/,
98 /Split-Path/,
99 /Start-(Job|Process|Service|Sleep|Transaction|Transcript)/,
100 /Stop-(Computer|Job|Process|Service|Transcript)/,
101 /Suspend-(Job|Service)/,
102 /TabExpansion2/,
103 /Tee-Object/,
104 /Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)/,
105 /Trace-Command/,
106 /Unblock-File/,
107 /Undo-Transaction/,
108 /Unregister-(Event|PSSessionConfiguration)/,
109 /Update-(FormatData|Help|List|TypeData)/,
110 /Use-Transaction/,
111 /Wait-(Event|Job|Process)/,
112 /Where-Object/,
113 /Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning)/,
114 /cd|help|mkdir|more|oss|prompt/,
115 /ac|asnp|cat|cd|chdir|clc|clear|clhy|cli|clp|cls|clv|cnsn|compare|copy|cp|cpi|cpp|cvpa|dbp|del|diff|dir|dnsn|ebp/,
116 /echo|epal|epcsv|epsn|erase|etsn|exsn|fc|fl|foreach|ft|fw|gal|gbp|gc|gci|gcm|gcs|gdr|ghy|gi|gjb|gl|gm|gmo|gp|gps/,
117 /group|gsn|gsnp|gsv|gu|gv|gwmi|h|history|icm|iex|ihy|ii|ipal|ipcsv|ipmo|ipsn|irm|ise|iwmi|iwr|kill|lp|ls|man|md/,
118 /measure|mi|mount|move|mp|mv|nal|ndr|ni|nmo|npssc|nsn|nv|ogv|oh|popd|ps|pushd|pwd|r|rbp|rcjb|rcsn|rd|rdr|ren|ri/,
119 /rjb|rm|rmdir|rmo|rni|rnp|rp|rsn|rsnp|rujb|rv|rvpa|rwmi|sajb|sal|saps|sasv|sbp|sc|select|set|shcm|si|sl|sleep|sls/,
120 /sort|sp|spjb|spps|spsv|start|sujb|sv|swmi|tee|trcm|type|where|wjb|write/
121 ], { prefix: '', suffix: '' });
122 var variableBuiltins = buildRegexp([
123 /[$?^_]|Args|ConfirmPreference|ConsoleFileName|DebugPreference|Error|ErrorActionPreference|ErrorView|ExecutionContext/,
124 /FormatEnumerationLimit|Home|Host|Input|MaximumAliasCount|MaximumDriveCount|MaximumErrorCount|MaximumFunctionCount/,
125 /MaximumHistoryCount|MaximumVariableCount|MyInvocation|NestedPromptLevel|OutputEncoding|Pid|Profile|ProgressPreference/,
126 /PSBoundParameters|PSCommandPath|PSCulture|PSDefaultParameterValues|PSEmailServer|PSHome|PSScriptRoot|PSSessionApplicationName/,
127 /PSSessionConfigurationName|PSSessionOption|PSUICulture|PSVersionTable|Pwd|ShellId|StackTrace|VerbosePreference/,
128 /WarningPreference|WhatIfPreference/,
129
130 /Event|EventArgs|EventSubscriber|Sender/,
131 /Matches|Ofs|ForEach|LastExitCode|PSCmdlet|PSItem|PSSenderInfo|This/,
132 /true|false|null/
133 ], { prefix: '\\$', suffix: '' });
134
135 var builtins = buildRegexp([symbolBuiltins, namedBuiltins, variableBuiltins], { suffix: notCharacterOrDash });
136
137 var grammar = {
138 keyword: keywords,
139 number: numbers,
140 operator: operators,
141 builtin: builtins,
142 punctuation: punctuation,
143 variable: identifiers
144 };
145
146 // tokenizers
147 function tokenBase(stream, state) {
148 // Handle Comments
149 //var ch = stream.peek();
150
151 var parent = state.returnStack[state.returnStack.length - 1];
152 if (parent && parent.shouldReturnFrom(state)) {
153 state.tokenize = parent.tokenize;
154 state.returnStack.pop();
155 return state.tokenize(stream, state);
156 }
157
158 if (stream.eatSpace()) {
159 return null;
160 }
161
162 if (stream.eat('(')) {
163 state.bracketNesting += 1;
164 return 'punctuation';
165 }
166
167 if (stream.eat(')')) {
168 state.bracketNesting -= 1;
169 return 'punctuation';
170 }
171
172 for (var key in grammar) {
173 if (stream.match(grammar[key])) {
174 return key;
175 }
176 }
177
178 var ch = stream.next();
179
180 // single-quote string
181 if (ch === "'") {
182 return tokenSingleQuoteString(stream, state);
183 }
184
185 if (ch === '$') {
186 return tokenVariable(stream, state);
187 }
188
189 // double-quote string
190 if (ch === '"') {
191 return tokenDoubleQuoteString(stream, state);
192 }
193
194 if (ch === '<' && stream.eat('#')) {
195 state.tokenize = tokenComment;
196 return tokenComment(stream, state);
197 }
198
199 if (ch === '#') {
200 stream.skipToEnd();
201 return 'comment';
202 }
203
204 if (ch === '@') {
205 var quoteMatch = stream.eat(/["']/);
206 if (quoteMatch && stream.eol()) {
207 state.tokenize = tokenMultiString;
208 state.startQuote = quoteMatch[0];
209 return tokenMultiString(stream, state);
210 } else if (stream.eol()) {
211 return 'error';
212 } else if (stream.peek().match(/[({]/)) {
213 return 'punctuation';
214 } else if (stream.peek().match(varNames)) {
215 // splatted variable
216 return tokenVariable(stream, state);
217 }
218 }
219 return 'error';
220 }
221
222 function tokenSingleQuoteString(stream, state) {
223 var ch;
224 while ((ch = stream.peek()) != null) {
225 stream.next();
226
227 if (ch === "'" && !stream.eat("'")) {
228 state.tokenize = tokenBase;
229 return 'string';
230 }
231 }
232
233 return 'error';
234 }
235
236 function tokenDoubleQuoteString(stream, state) {
237 var ch;
238 while ((ch = stream.peek()) != null) {
239 if (ch === '$') {
240 state.tokenize = tokenStringInterpolation;
241 return 'string';
242 }
243
244 stream.next();
245 if (ch === '`') {
246 stream.next();
247 continue;
248 }
249
250 if (ch === '"' && !stream.eat('"')) {
251 state.tokenize = tokenBase;
252 return 'string';
253 }
254 }
255
256 return 'error';
257 }
258
259 function tokenStringInterpolation(stream, state) {
260 return tokenInterpolation(stream, state, tokenDoubleQuoteString);
261 }
262
263 function tokenMultiStringReturn(stream, state) {
264 state.tokenize = tokenMultiString;
265 state.startQuote = '"'
266 return tokenMultiString(stream, state);
267 }
268
269 function tokenHereStringInterpolation(stream, state) {
270 return tokenInterpolation(stream, state, tokenMultiStringReturn);
271 }
272
273 function tokenInterpolation(stream, state, parentTokenize) {
274 if (stream.match('$(')) {
275 var savedBracketNesting = state.bracketNesting;
276 state.returnStack.push({
277 /*jshint loopfunc:true */
278 shouldReturnFrom: function(state) {
279 return state.bracketNesting === savedBracketNesting;
280 },
281 tokenize: parentTokenize
282 });
283 state.tokenize = tokenBase;
284 state.bracketNesting += 1;
285 return 'punctuation';
286 } else {
287 stream.next();
288 state.returnStack.push({
289 shouldReturnFrom: function() { return true; },
290 tokenize: parentTokenize
291 });
292 state.tokenize = tokenVariable;
293 return state.tokenize(stream, state);
294 }
295 }
296
297 function tokenComment(stream, state) {
298 var maybeEnd = false, ch;
299 while ((ch = stream.next()) != null) {
300 if (maybeEnd && ch == '>') {
301 state.tokenize = tokenBase;
302 break;
303 }
304 maybeEnd = (ch === '#');
305 }
306 return 'comment';
307 }
308
309 function tokenVariable(stream, state) {
310 var ch = stream.peek();
311 if (stream.eat('{')) {
312 state.tokenize = tokenVariableWithBraces;
313 return tokenVariableWithBraces(stream, state);
314 } else if (ch != undefined && ch.match(varNames)) {
315 stream.eatWhile(varNames);
316 state.tokenize = tokenBase;
317 return 'variable';
318 } else {
319 state.tokenize = tokenBase;
320 return 'error';
321 }
322 }
323
324 function tokenVariableWithBraces(stream, state) {
325 var ch;
326 while ((ch = stream.next()) != null) {
327 if (ch === '}') {
328 state.tokenize = tokenBase;
329 break;
330 }
331 }
332 return 'variable';
333 }
334
335 function tokenMultiString(stream, state) {
336 var quote = state.startQuote;
337 if (stream.sol() && stream.match(new RegExp(quote + '@'))) {
338 state.tokenize = tokenBase;
339 }
340 else if (quote === '"') {
341 while (!stream.eol()) {
342 var ch = stream.peek();
343 if (ch === '$') {
344 state.tokenize = tokenHereStringInterpolation;
345 return 'string';
346 }
347
348 stream.next();
349 if (ch === '`') {
350 stream.next();
351 }
352 }
353 }
354 else {
355 stream.skipToEnd();
356 }
357
358 return 'string';
359 }
360
361 export const powerShell = {
362 name: "powershell",
363
364 startState: function() {
365 return {
366 returnStack: [],
367 bracketNesting: 0,
368 tokenize: tokenBase
369 };
370 },
371
372 token: function(stream, state) {
373 return state.tokenize(stream, state);
374 },
375
376 languageData: {
377 commentTokens: {line: "#", block: {open: "<#", close: "#>"}}
378 }
379 };