-
Notifications
You must be signed in to change notification settings - Fork 4
/
cpp.js
382 lines (325 loc) · 13.6 KB
/
cpp.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
/**
* @copyright 2015, Robin Dietrich
* @license MIT
*/
define(function(require, exports, module) {
main.consumes = [
"Plugin", "language", "ext", "tabManager", "c9", "save",
"settings", "preferences", "ui", "collab", "collab.connect",
"error_handler", "dialog.error", "installer"
];
main.provides = ["cpp"];
return main;
// returns true if file is handled by us (by extension)
function is_c_cpp(filename) {
// handled extensions, last used by capnproto ('-.-)
var _extensions = ["c", "h", "cc", "cpp", "hpp", "cxx", "hxx", "h++", "c++"];
// get extension
var _extension = filename.split(".");
if (_extension.length < 2)
return false;
_extension = _extension[_extension.length - 1];
return (_extensions.indexOf(_extension) >= 0);
}
function main(options, imports, register) {
// imports
var _ = require("lodash");
var async = require("async");
var language = imports.language;
var ext = imports.ext;
var Plugin = imports.Plugin;
var plugin = new Plugin("Robin Dietrich", main.consumes);
var tabManager = imports.tabManager;
var c9 = imports.c9;
var save = imports.save;
var settings = imports.settings;
var prefs = imports.preferences;
var ui = imports.ui;
var collab = imports.collab;
var collabConnect = imports["collab.connect"];
var useCollab = collab.connected;
var errorHandler = imports.error_handler;
var showError = imports["dialog.error"].show;
var installer = imports.installer;
var emit = plugin.getEmitter();
// constants and services used in the plugin
var basedir = c9.workspaceDir; // Use this to get the full file path for clang_tool
var clang_tool = null; // Service side clang_tool component
var worker = null; // Language worker
// for call throttling
var pendingServerCall = null;
var lastServerCall = Date.now();
var callInterval = 1000;
// make sure all deps are installed
installer.createSession("c9.ide.language.cpp", require("./install"));
// Make sure file contents stay in sync with the server
function syncChanges(cb) {
var value = tabManager.focussedTab.document.value;
var path = tabManager.focussedTab.path;
if (useCollab) {
var revNum = -1;
var collabDoc = collab.getDocument(path);
if (collabDoc) {
revNum = collabDoc.latestRevNum + (collabDoc.pendingUpdates ? 1 : 0);
collabDoc.sendNow();
}
callRemoteLimited("indexTouchUnsavedCollab", [basedir+path, path, revNum, cb]);
} else {
callRemoteLimited("indexTouchUnsaved", [basedir+path, value, cb]);
}
}
// Calls a clang_remote function, uses rate limitting
function callRemoteLimited(fcn, params) {
var tries = 0;
setupServerFcn();
// Initiates a server call
function setupServerFcn() {
var waiting = lastServerCall + callInterval - Date.now();
if (waiting > 0) {
// only set pending on first try
if (tries == 0)
pendingServerCall = setupServerFcn;
setTimeout(setupServerFcn, waiting, ++tries);
} else {
//
if (pendingServerCall !== setupServerFcn && pendingServerCall != null) {
} else {
pendingServerCall = null; // reset our own fcn
lastServerCall = Date.now();
plugin.once("initServer", invokeServerFcn);
}
}
}
// Invokes the actual server function
function invokeServerFcn() {
if (clang_tool)
clang_tool[fcn].apply(clang_tool, params);
}
}
// Callback when a new document is opened
// - Adds new files to the index to enable faster completion
function onDocumentOpened(data) {
if (!is_c_cpp(data.path))
return;
if (clang_tool)
clang_tool.indexTouch(basedir+data.path);
}
// Callback when a document is closed
// - Removed translation unit from the index
function onDocumentClosed(data) {
if (!is_c_cpp(data.path))
return;
if (clang_tool)
clang_tool.indexClear(basedir+data.path);
}
// Callback when a document is saved
function onDocumentSave(data) {
if (!is_c_cpp(data.path))
return;
// add / update on index
if (clang_tool)
clang_tool.indexTouch(basedir+data.path);
}
// Code completion
function workerCompletion(data) {
var path = basedir+tabManager.focussedTab.path;
if (!clang_tool)
return worker.emit("_completionResult", {data: {id: data.id, results: []}});
// add temporary data to index and do code completion
syncChanges(function () {
clang_tool.cursorCandidatesAt(path, data.pos.row+1, data.pos.column+1, function(err, res) {
worker.emit("_completionResult", {data: {id: data.id, results: res}});
})
});
}
// Code diagnosics
function workerAnalysis(data) {
var path = basedir+tabManager.focussedTab.path;
if (!clang_tool)
return worker.emit("_diagnoseResult", {data: {id: data.id, results: []}});
callRemoteLimited("fileDiagnose", [path, function(err, res) {
res = _.filter(res, function(r) {
return r.file == path;
});
worker.emit("_diagnoseResult", {data: {id: data.id, results: res, path: path}});
}]);
}
// AST to outline conversion
function workerOutline(data) {
var path = basedir+tabManager.focussedTab.path;
if (!clang_tool)
return worker.emit("_outlineResult", {data: {id: data.id, ast: []}});
// generate outline
clang_tool.fileAst(path, function(err, res) {
worker.emit("_outlineResult", {data: {id: data.id, ast: res.children}});
});
}
// Jump to definition/declaration
function workerJumpToDefinition(data) {
var path = basedir+tabManager.focussedTab.path;
if (!clang_tool)
return worker.emit("_jumpToDefResult", {data: {id: data.id, pos: {}}});
var row = data.pos.row+1;
var col = data.pos.column+1;
// get definition/declaration
clang_tool.cursorDefinitionAt(path, row, col, function(err, res) {
if (!res.file) {
// no definition found, try declaration instead
clang_tool.cursorDeclarationAt(path, row, col, function(err, res) {
if (res.file) res.file = "/"+res.file;
worker.emit("_jumpToDefResult", {data: {id: data.id, pos: res}});
});
} else {
res.file = "/"+res.file;
worker.emit("_jumpToDefResult", {data: {id: data.id, pos: res}});
}
});
}
// Register our language handler
var path = options.packagePath;
path = path.substr(0, path.lastIndexOf("/") + 1) + "cpp_worker";
language.registerLanguageHandler(path, function(err, worker_) {
if (err) {
errorHandler.reportError(err);
return showError("Could not load cpp language worker: " + (err.message | err));
}
// Set worker object and register callback's
worker = worker_;
worker.on("documentOpened", onDocumentOpened);
worker.on("documentClosed", onDocumentClosed);
save.on("afterSave", onDocumentSave);
//
// Important:
// Do not run indexTouch or indexTouchUnsaved for each and every worker action.
// Certain actions may be interleaved, creating a indexTouch <-> indexTouchUnsaved chain
// that takes forever to resolve.
//
// + Call indexTouchUnsaved in all worker functions that handle temp data
// + Call indexTouch only on save events
//
worker.on("_completion", workerCompletion);
worker.on("_diagnose", workerAnalysis);
worker.on("_outline", workerOutline);
worker.on("_jumpToDefinition", workerJumpToDefinition);
});
// Called on c9.connect
function onOnline() {
// Refresh collab state after 10 seconds
setTimeout(function() {
useCollab = collab.connected;
}, 10000);
// Load plugin an connect collab
async.series([
function extendVFS(next) {
ext.loadRemotePlugin("clang_tool", {
code: require("text!./cpp_server.js"),
redefine: !clang_tool
}, function(err, plugin) {
clang_tool = plugin;
next(err);
});
},
function loadClang(next) {
clang_tool.load(function (err) {
clang_tool.setArgs(settings.get("project/c_cpp/@compilerArguments").split(/\s+/));
next(err);
});
},
function waitForCollab(next) {
if (installer.isInstalled("c9.ide.collab") && !useCollab) {
setTimeout(function() {
useCollab = collab.connected;
next();
}, 10000);
} else {
return next();
}
},
function connectCollab(next) {
if (!useCollab) {
console.log("[c9.ide.langauge.cpp] Info: Not using collab");
return next();
}
var wait = setTimeout(function() {
done(new Error("Collab never gets to available state"));
}, 20000);
collabConnect.once("available", function() {
console.log("[c9.ide.langauge.cpp] Info: Using collab");
clearTimeout(wait);
next();
});
},
], done);
function done(err) {
if (err) {
errorHandler.reportError(err);
showError("[c9.ide.language.cpp] Error initializing server: " + err.message);
clang_tool = null;
return false;
}
emit.sticky("initServer");
}
}
// Called on c9.disconnect
function onOffline() {
if (clang_tool) {
clang_tool.indexClear(function() {
clang_tool = null;
});
}
}
c9.on("connect", onOnline);
c9.on("disconnect", onOffline);
// Initialize the plugin
plugin.on("load", function() {
// Add project specific preferences
prefs.add({
"Project" : {
"C / C++" : {
position: 1000,
"Compiler Arguments" : {
type: "textarea",
width: 400,
height: 130,
rowheight: 155,
path: "project/c_cpp/@compilerArguments",
position: 5000
}
}
}
}, plugin);
// Set default values
settings.on("read", function(e) {
settings.setDefaults("project/c_cpp", [
["compilerArguments", "-Wall -Wextra -std=c++11 -I/usr/include -I/usr/local/include"]
]);
}, plugin);
// Listen to updates
settings.on("project/c_cpp/@compilerArguments", function(value) {
if (clang_tool)
clang_tool.setArgs(value.split(/\s+/));
}, plugin);
// Add css
ui.insertCss(require("text!./icons.css"), false, plugin);
// Initialize plugin
onOnline();
});
// Make sure the plugin is unloaded correctly so that cached translation units get purged
plugin.on("unload", function(){
if (clang_tool) {
clang_tool.unload();
clang_tool = null;
worker = null;
pendingServerCall = null;
lastServerCall = 0;
}
});
// Public api for the cpp plugin
// - Allow different cpp extensions to be added
// - Cache handling with indexStatus and indexClear
// - Recursive file ast parsing for tokenizers
plugin.freezePublicAPI({});
// Registers our plugin with C9
register(null, { cpp: plugin });
}
});