-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathmonaco.ts
263 lines (225 loc) · 8.99 KB
/
monaco.ts
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
/// <reference path="../localtypings/monaco.d.ts" />
/// <reference path="../built/pxtlib.d.ts"/>
export interface BlockDefiniton {
commentAttr: pxtc.CommentAttrs;
fns?: pxt.Map<string>;
}
export interface MethodDef {
sig: string;
snippet: string;
comment?: string;
metaData?: pxtc.CommentAttrs;
snippetOnly?: boolean;
}
export interface NameDefiniton {
fns: { [fn: string]: MethodDef };
vars?: { [index: string]: string }
metaData?: pxtc.CommentAttrs;
builtin?: boolean;
}
export type DefinitionMap = { [ns: string]: NameDefiniton };
export function syncModels(mainPkg: pxt.MainPackage, libs: { [path: string]: monaco.IDisposable }, currFile: string, readOnly: boolean) {
if (readOnly) return;
let extraLibs = (monaco.languages.typescript.typescriptDefaults as any).getExtraLibs();
let modelMap: pxt.Map<string> = {}
mainPkg.sortedDeps().forEach(pkg => {
pkg.getFiles().forEach(f => {
let fp = pkg.id + "/" + f;
let proto = "pkg:" + fp;
if (/\.(ts)$/.test(f) && fp != currFile) {
if (!(monaco.languages.typescript.typescriptDefaults as any).getExtraLibs()[fp]) {
// inserting a space creates syntax errors in Python
let content = pkg.readFile(f) || "\n";
libs[fp] = monaco.languages.typescript.typescriptDefaults.addExtraLib(content, fp);
}
modelMap[fp] = "1";
}
});
});
// dispose of any extra libraries, the typescript worker will be killed as a result of this
Object.keys(extraLibs)
.filter(lib => /\.(ts)$/.test(lib) && !modelMap[lib])
.forEach(lib => {
libs[lib].dispose();
});
}
export function initMonacoAsync(element: HTMLElement): Promise<monaco.editor.IStandaloneCodeEditor> {
return new Promise<monaco.editor.IStandaloneCodeEditor>((resolve, reject) => {
if (typeof ((window as any).monaco) === 'object') {
// monaco is already loaded
resolve(createEditor(element));
return;
}
let monacoPaths: pxt.Map<string> = (window as any).MonacoPaths
let onGotAmdLoader = () => {
let req = (window as any).require
req.config({ paths: monacoPaths });
// Load monaco
req(['vs/editor/editor.main'], () => {
setupMonaco();
resolve(createEditor(element));
});
};
// Load AMD loader if necessary
if (!(<any>window).require) {
let loaderScript = document.createElement('script');
loaderScript.type = 'text/javascript';
loaderScript.src = monacoPaths['vs/loader'];
loaderScript.addEventListener('load', onGotAmdLoader);
document.body.appendChild(loaderScript);
} else {
onGotAmdLoader();
}
})
}
function setupMonaco() {
initAsmMonarchLanguage();
initTypeScriptLanguageDefinition();
}
export function createEditor(element: HTMLElement): monaco.editor.IStandaloneCodeEditor {
const inverted = pxt.appTarget.appTheme.invertedMonaco;
const hasFieldEditors = !!(pxt.appTarget.appTheme.monacoFieldEditors && pxt.appTarget.appTheme.monacoFieldEditors.length);
let editor = monaco.editor.create(element, {
model: null,
ariaLabel: pxt.Util.lf("JavaScript editor"),
fontFamily: "'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', 'monospace'",
scrollBeyondLastLine: true,
language: "typescript",
mouseWheelZoom: false,
wordBasedSuggestions: true,
lineNumbersMinChars: 3,
formatOnPaste: true,
folding: hasFieldEditors,
glyphMargin: hasFieldEditors || pxt.appTarget.appTheme.debugger,
minimap: {
enabled: false
},
fixedOverflowWidgets: true,
autoIndent: "full",
useTabStops: true,
dragAndDrop: true,
matchBrackets: "always",
occurrencesHighlight: false,
quickSuggestionsDelay: 200,
theme: inverted ? 'vs-dark' : 'vs',
renderIndentGuides: true,
accessibilityHelpUrl: "", //TODO: Add help url explaining how to use the editor with a screen reader
quickSuggestions: {
"other": true,
"comments": true,
"strings": true
},
acceptSuggestionOnCommitCharacter: true,
acceptSuggestionOnEnter: "on",
accessibilitySupport: "on"
});
editor.layout();
return editor;
}
function initAsmMonarchLanguage(): void {
monaco.languages.register({ id: 'asm', extensions: ['.asm'] });
monaco.languages.setMonarchTokensProvider('asm', <monaco.languages.IMonarchLanguage>{
// Set defaultToken to invalid to see what you do not tokenize yet
// defaultToken: 'invalid',
tokenPostfix: '',
//Extracted from http://infocenter.arm.com/help/topic/com.arm.doc.qrc0006e/QRC0006_UAL16.pdf
//Should be a superset of the instructions emitted
keywords: [
'movs', 'mov', 'adds', 'add', 'adcs', 'adr', 'subs', 'sbcs', 'sub', 'rsbs',
'muls', 'cmp', 'cmn', 'ands', 'eors', 'orrs', 'bics', 'mvns', 'tst', 'lsls',
'lsrs', 'asrs', 'rors', 'ldr', 'ldrh', 'ldrb', 'ldrsh', 'ldrsb', 'ldm',
'str', 'strh', 'strb', 'stm', 'push', 'pop', 'cbz', 'cbnz', 'b', 'bl', 'bx', 'blx',
'sxth', 'sxtb', 'uxth', 'uxtb', 'rev', 'rev16', 'revsh', 'svc', 'cpsid', 'cpsie',
'setend', 'bkpt', 'nop', 'sev', 'wfe', 'wfi', 'yield',
'beq', 'bne', 'bcs', 'bhs', 'bcc', 'blo', 'bmi', 'bpl', 'bvs', 'bvc', 'bhi', 'bls',
'bge', 'blt', 'bgt', 'ble', 'bal',
//Registers
'r0', 'r1', 'r2', 'r3', 'r4', 'r5', 'r6', 'r7', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15',
'pc', 'sp', 'lr'
],
typeKeywords: [
'.startaddr', '.hex', '.short', '.space', '.section', '.string', '.byte'
],
operators: [],
// Not all of these are valid in ARM Assembly
symbols: /[:\*]+/,
// C# style strings
escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
// The main tokenizer for our languages
tokenizer: {
root: [
// identifiers and keywords
[/(\.)?[a-z_$\.][\w$]*/, {
cases: {
'@typeKeywords': 'keyword',
'@keywords': 'keyword',
'@default': 'identifier'
}
}],
// whitespace
{ include: '@whitespace' },
// delimiters and operators
[/[{}()\[\]]/, '@brackets'],
[/[<>](?!@symbols)/, '@brackets'],
[/@symbols/, {
cases: {
'@operators': 'operator',
'@default': ''
}
}],
// @ annotations.
[/@\s*[a-zA-Z_\$][\w\$]*/, { token: 'annotation' }],
// numbers
//[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/(#|(0[xX]))?[0-9a-fA-F]+/, 'number'],
// delimiter: after number because of .\d floats
[/[;,.]/, 'delimiter'],
// strings
[/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string
[/"/, { token: 'string.quote', bracket: '@open', next: '@string' }],
// characters
[/'[^\\']'/, 'string'],
[/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
[/'/, 'string.invalid']
],
comment: [],
string: [
[/[^\\"]+/, 'string'],
[/@escapes/, 'string.escape'],
[/\\./, 'string.escape.invalid'],
[/"/, { token: 'string.quote', bracket: '@close', next: '@pop' }]
],
whitespace: [
[/[ \t\r\n]+/, 'white'],
[/\/\*/, 'comment', '@comment'],
[/;.*$/, 'comment'],
],
}
});
}
function initTypeScriptLanguageDefinition() {
if (!monaco.languages.typescript) {
return;
}
// validation settings
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSyntaxValidation: true,
noSemanticValidation: true
});
// Register our worker
monaco.languages.typescript.typescriptDefaults.setWorkerOptions({
customWorkerPath: pxt.webConfig.typeScriptWorkerJs
});
// compiler options
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
allowUnreachableCode: true,
noImplicitAny: true,
allowJs: false,
allowUnusedLabels: true,
target: monaco.languages.typescript.ScriptTarget.ES5,
outDir: "built",
rootDir: ".",
noLib: true,
mouseWheelZoom: false
});
}