diff --git a/.bowerrc b/.bowerrc
deleted file mode 100644
index a41a3219a..000000000
--- a/.bowerrc
+++ /dev/null
@@ -1 +0,0 @@
-{ "directory": "static/ext" }
diff --git a/.gitignore b/.gitignore
index 04bee72b8..c8c269bc7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,7 +2,6 @@
/node_modules
newrelic_agent.log
/.npm-updated
-/.bower-updated
*.vscode
/out
*.heapsnapshot
@@ -10,3 +9,7 @@ etc/config/*.local.properties
.travis-compilers
/nbproject
/package-lock.json
+*.bundle*.js
+*.map
+static/dist
+static/vs
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e331bf6f9..6bf3cf17a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -5,7 +5,8 @@ Before we go too far, an apology: Compiler Explorer grew out of a bit of hacky J
well-used project pretty quickly. Not all the code was originally well-written or well-tested. Please be forgiving of that,
and be ready to help in improving that.
-Note that Compiler Explorer targets the latest Node.js LTS, so it's better if you do so as well when testing your changes locally. (But it will run in everything post-Node.js 8)
+Note that Compiler Explorer targets the latest Node.js LTS, so it's better if you do so as well when testing your changes locally.
+(But it *should* run in everything post-Node.js 8)
## In brief
* Make your changes, trying to stick to the style and code format where possible. We use default IntelliJ settings,
@@ -22,8 +23,8 @@ every commit, ensuring that they pass before commiting your changes. _You can di
## Basic code layout
-Code is separated into server-side code and client-side code. Server packages are installed via `package.json` and client-side via
-`bower.json`. Server code is in `app.js` and in the `lib` directory. Client code is all in the `static` directory.
+Code is separated into server-side code and client-side code. All dependencies (server and client side) are installed via `package.json`.
+Server code is in `app.js` and in the `lib` directory. Client code is all in the `static` directory.
In the server code, the `app.js` sets up a basic `express` middleware-driven web server, delegating to the various compiler
backends in `lib/compilers`. Most inherit (loosely) from `lib/base-compiler.js` which does most of the work of running
diff --git a/Makefile b/Makefile
index 7e72b2629..e04462c17 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,8 @@
NODE_DIR?=/opt/compiler-explorer/node
-NPM:= $(shell env PATH="$(NODE_DIR)/bin:$$PATH" which npm)
-NODE:= $(shell env PATH="$(NODE_DIR)/bin:$$PATH" which node || env PATH="$(NODE_DIR)/bin:$$PATH" which nodejs)
+YARN_DIR?=/opt/compiler-explorer/yarn
+YARN_EXE:=$(shell env PATH="$(NODE_DIR)/bin:$(YARN_DIR)/bin:$(PATH)" which yarn)
+NODE:=$(shell env PATH="$(NODE_DIR)/bin:$(PATH)" which node || env PATH="$(NODE_DIR)/bin:$(PATH)" which nodejs)
+YARN:=$(NODE) $(YARN_EXE).js
default: run
NODE_VERSION_USED:=8
@@ -21,9 +23,8 @@ endif
endif
.PHONY: clean run test run-amazon c-preload optional-haskell-support optional-d-support optional-rust-support
-.PHONY: dist lint prereqs node_modules bower_modules travis-dist
-prereqs: optional-haskell-support optional-d-support optional-rust-support node_modules c-preload bower_modules
-
+.PHONY: dist lint prereqs node_modules travis-dist
+prereqs: optional-haskell-support optional-d-support optional-rust-support node_modules webpack c-preload
GDC?=gdc
DMD?=dmd
LDC?=ldc2
@@ -56,24 +57,18 @@ endif
NODE_MODULES=.npm-updated
$(NODE_MODULES): package.json
- $(NPM) install
+ $(YARN) install
@touch $@
-BOWER_MODULES=.bower-updated
-$(BOWER_MODULES): bower.json $(NODE_MODULES)
- if ! test -f "${BOWER_MODULES}"; then rm -rf static/ext; fi
- $(NODE) ./node_modules/bower/bin/bower install
- @touch $@
- # Workaround for lack of versioned monaco-editor in bower
- rm -rf static/ext/monaco-editor
- cp -r node_modules/monaco-editor static/ext/
+webpack:
+ $(NODE) node_modules/webpack/bin/webpack.js ${WEBPACK_ARGS}
lint: $(NODE_MODULES)
- $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.server app.js $(shell find lib test -name '*.js')
- $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.client $(shell find static -name '*.js' -not -path 'static/ext/*' -not -path static/analytics.js)
+ $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.server app.js $(shell find lib -name '*.js')
+ $(NODE) ./node_modules/.bin/jshint --config etc/jshintrc.client $(shell find static -name '*.js' -not -path 'static/dist/*' -not -path static/analytics.js -not -path 'static/vs/*' -not -path 'static/ext/*')
node_modules: $(NODE_MODULES)
-bower_modules: $(BOWER_MODULES)
+webpack: $(WEBPACK)
test: $(NODE_MODULES) lint
$(MAKE) -C c-preload test
@@ -83,37 +78,31 @@ check: $(NODE_MODULES) lint
$(NODE) ./node_modules/.bin/mocha --recursive
clean:
- rm -rf bower_modules node_modules .npm-updated .bower-updated out static/ext
+ rm -rf node_modules .npm-updated out static/dist static/vs
$(MAKE) -C d clean
$(MAKE) -C c-preload clean
+run: export NODE_ENV=LOCAL WEBPACK_ARGS="-p"
run: prereqs
$(NODE) ./node_modules/.bin/supervisor -w app.js,lib,etc/config -e 'js|node|properties' --exec $(NODE) $(NODE_ARGS) -- ./app.js $(EXTRA_ARGS)
+dev: export NODE_ENV=DEV
+dev: prereqs
+ $(NODE) ./node_modules/.bin/supervisor -w app.js,lib,etc/config -e 'js|node|properties' --exec $(NODE) $(NODE_ARGS) -- ./app.js $(EXTRA_ARGS)
+
+
+
HASH := $(shell git rev-parse HEAD)
+dist: export WEBPACK_ARGS=-p
dist: prereqs
- rm -rf out/dist
- $(NODE) ./node_modules/requirejs/bin/r.js -o app.build.js
- # Move all assets to a versioned directory
- echo $(HASH) > out/dist/git_hash
- mkdir -p out/dist/v/$(HASH)
- mv out/dist/main.js* out/dist/v/$(HASH)/
- mv out/dist/explorer.css out/dist/v/$(HASH)/
- mv out/dist/assets/ out/dist/v/$(HASH)/
- mv out/dist/themes/ out/dist/v/$(HASH)/
- # copy any external references into the directory too
- cp -r $(shell pwd)/out/dist/ext out/dist/v/$(HASH)/ext
- # uglify requirejs itself
- $(NODE) ./node_modules/.bin/uglifyjs out/dist/v/$(HASH)/ext/requirejs/require.js \
- -c \
- --output out/dist/v/$(HASH)/ext/requirejs/require.js \
- --source-map out/dist/v/$(HASH)/ext/requirejs/require.js.map \
- --source-map-url require.js.map \
- --source-map-root //v/$(HASH)/ext/requirejs \
- --prefix 6
+ rm -rf out/dist/
+ mkdir -p out/dist
+ mkdir -p out/dist/vs
+ cp -r static/dist/ out/dist/
+ cp -r static/vs/ out/dist/
travis-dist: dist
- tar --exclude './.travis-compilers' --exclude './.git' --exclude './static' --exclude './out/dist/ext' -Jcf /tmp/ce-build.tar.xz .
+ tar --exclude './.travis-compilers' --exclude './.git' --exclude './static' -Jcf /tmp/ce-build.tar.xz .
rm -rf out/dist-bin
mkdir -p out/dist-bin
mv /tmp/ce-build.tar.xz out/dist-bin/${TRAVIS_BUILD_NUMBER}.tar.xz
diff --git a/README.md b/README.md
index f6590097c..4770b1897 100644
--- a/README.md
+++ b/README.md
@@ -26,10 +26,10 @@ Compiler Explorer is written in node.js.
Assuming you have a compatible version of `node` installed, simply running `make` ought to get you up and running with an Explorer
running on port 10240 on your local machine: http://localhost:10240/. Currently Compiler Explorer requires `node` v8 installed, either on the path or at `NODE_PATH` (an environment variable or `make` parameter).
-Running with `make EXTRA_ARGS='--language LANG'` will allow you to load `LANG` exclusively, where `LANG` is one for the language ids/aliases defined in `lib/languages.js`
-The `Makefile` will automatically install all the third party libraries needed to run; using `npm` to install server-side
-components and `bower` to install all the client-facing libraries.
+Running with `make EXTRA_ARGS='--language LANG'` will allow you to load `LANG` exclusively, where `LANG` is one for the language ids/aliases defined in `lib/languages.js`
+The `Makefile` will automatically install all the third party libraries needed to run; using `yarn` to install server-side and client side components
+
If you want to point it at your own GCC or similar binaries, either edit the `etc/config/compiler-explorer.defaults.properties` or else make a new one with the name
`compiler-explorer.local.properties`. `*.local.properties` files have the highest priority when loading properties.
diff --git a/app.js b/app.js
index 2fecc6912..c0f17c9e8 100755
--- a/app.js
+++ b/app.js
@@ -36,8 +36,10 @@ const nopt = require('nopt'),
url = require('url'),
_ = require('underscore-node'),
express = require('express'),
+ Raven = require('raven'),
logger = require('./lib/logger').logger,
- Raven = require('raven');
+ webpackDevMiddleware = require("webpack-dev-middleware");
+
// Parse arguments from command line 'node ./app.js args...'
const opts = nopt({
@@ -86,19 +88,30 @@ const port = opts.port || 10240;
const staticDir = opts.static || 'static';
const archivedVersions = opts.archivedVersions;
let gitReleaseName = "";
-let versionedRootPrefix = "";
const wantedLanguage = opts.language || null;
+
+
+
+const webpackConfig = require('./webpack.config.js')[1],
+ webpackCompiler = require('webpack')(webpackConfig),
+ manifestName = 'manifest.json',
+ staticManifestPath = path.join(__dirname, staticDir, webpackConfig.output.publicPath),
+ assetManifestPath = path.join(staticManifestPath, 'assets'),
+ staticManifest = require(path.join(staticManifestPath, manifestName)),
+ assetManifest = require(path.join(assetManifestPath, manifestName));
+
// Use the canned git_hash if provided
if (opts.static && fs.existsSync(opts.static + "/git_hash")) {
gitReleaseName = fs.readFileSync(opts.static + "/git_hash").toString().trim();
} else if (fs.existsSync('.git/')) { // Just if we have been cloned and not downloaded (Thanks David!)
gitReleaseName = child_process.execSync('git rev-parse HEAD').toString().trim();
}
-if (opts.static && fs.existsSync(opts.static + '/v/' + gitReleaseName))
- versionedRootPrefix = "v/" + gitReleaseName + "/";
+
// Don't treat @ in paths as remote adresses
const fetchCompilersFromRemote = !opts.noRemoteFetch;
+const isDevMode = () => process.env.NODE_ENV === "DEV";
+
const propHierarchy = _.flatten([
'defaults',
env,
@@ -559,14 +572,25 @@ Promise.all([findCompilers(), aws.initConfig(awsProps)])
logger.info("=======================================");
logger.info(`Listening on http://${hostname || 'localhost'}:${port}/`);
- logger.info(` serving static files from '${staticDir}'`);
if (gitReleaseName) logger.info(` git release ${gitReleaseName}`);
function renderConfig(extra) {
const options = _.extend(extra, clientOptionsHandler.get());
options.compilerExplorerOptions = JSON.stringify(options);
- options.root = versionedRootPrefix;
options.extraBodyClass = extraBodyClass;
+ options.require = function (path) {
+ if (isDevMode()) {
+ //this will break assets in dev mode for now
+ return '/dist/' + path;
+ }
+ if(staticManifest.hasOwnProperty(path)) {
+ return "dist/" + staticManifest[path];
+ }
+ if(assetManifest.hasOwnProperty(path)) {
+ return "dist/assets/" + assetManifest[path];
+ }
+ logger.warn("Requested an asset I don't know about");
+ };
return options;
}
@@ -575,8 +599,26 @@ Promise.all([findCompilers(), aws.initConfig(awsProps)])
contentPolicyHeader(res);
res.render('embed', renderConfig({embedded: true}));
};
- const router = express.Router();
- router
+ const healthCheck = require('./lib/handlers/health-check');
+
+ if (isDevMode()) {
+ webServer.use(webpackDevMiddleware(webpackCompiler, {
+ publicPath: webpackConfig.output.publicPath
+ }));
+ webServer.use(express.static(staticDir));
+ } else {
+ //assume that anything not dev is just production this gives sane defaults for anyone who isn't messing with this
+ logger.info(" serving static files from '" + staticDir + "'");
+ webServer.use(express.static(staticDir, {maxAge: staticMaxAgeSecs * 1000}));
+ }
+
+ webServer
+ .use(Raven.requestHandler())
+ .set('trust proxy', true)
+ .set('view engine', 'pug')
+ .use('/healthcheck', new healthCheck.HealthCheckHandler().handle) // before morgan so healthchecks aren't logged
+ .use(morgan('combined', {stream: logger.stream}))
+ .use(compression())
.get('/', (req, res) => {
staticHeaders(res);
contentPolicyHeader(res);
@@ -598,39 +640,18 @@ Promise.all([findCompilers(), aws.initConfig(awsProps)])
res.set('Content-Type', 'application/xml');
res.render('sitemap');
})
- .use(sFavicon(`${staticDir}/favicon.ico`))
- .use('/v', express.static(`${staticDir}/v`, {maxAge: Infinity, index: false}))
- .use(express.static(staticDir, {maxAge: staticMaxAgeSecs * 1000}));
- if (archivedVersions) {
- // The archived versions directory is used to serve "old" versioned data during updates. It's expected
- // to contain all the SHA-hashed directories from previous versions of Compiler Explorer.
- logger.info(" serving archived versions from", archivedVersions);
- router.use('/v', express.static(archivedVersions, {maxAge: Infinity, index: false}));
- }
- router
+ .use(sFavicon(path.join(staticDir, webpackConfig.output.publicPath, 'favicon.ico')));
+
+ webServer
.use(bodyParser.json({limit: ceProps('bodyParserLimit', maxUploadSize)}))
.use(bodyParser.text({limit: ceProps('bodyParserLimit', maxUploadSize), type: () => true}))
.use(restreamer())
.use('/source', sourceHandler.handle.bind(sourceHandler))
.use('/api', apiHandler.handle)
.use('/g', shortUrlHandler);
-
- const healthCheck = require('./lib/handlers/health-check');
- webServer
- .use(Raven.requestHandler())
- .set('trust proxy', true)
- .set('view engine', 'pug')
- .use('/healthcheck', new healthCheck.HealthCheckHandler().handle) // before morgan so healthchecks aren't logged
- .use(morgan('combined', {stream: logger.stream}))
- .use(compression())
- .use(router)
- .use(Raven.errorHandler())
- .on('error', err => logger.error('Caught error:', err, "(in web error handler; continuing)"));
-
- const webAlias = ceProps("web-alias", "");
- if (webAlias) webServer.use(webAlias, router);
- _.each(env, e => webServer.use(`/${e}`, router));
logger.info("=======================================");
+ webServer.use(Raven.errorHandler());
+ webServer.on('error', err => logger.error('Caught error:', err, "(in web error handler; continuing)"));
webServer.listen(port, hostname);
})
.catch(err => {
diff --git a/bower.json b/bower.json
deleted file mode 100644
index 5a63ac404..000000000
--- a/bower.json
+++ /dev/null
@@ -1,36 +0,0 @@
-{
- "name": "compiler-explorer",
- "description": "Interactively investigate compiler output",
- "main": "./app.js",
- "authors": [
- "Matt Godbolt"
- ],
- "license": "BSD-2-Clause",
- "homepage": "https://github.com/mattgodbolt/compiler-explorer",
- "private": true,
- "ignore": [
- "**/.*",
- "node_modules",
- "bower_components",
- "test",
- "tests"
- ],
- "dependencies": {
- "requirejs": "^2.3.2",
- "underscore": "^1.8.3",
- "golden-layout": "^1.5.9",
- "jquery": "^3.1.1",
- "bootstrap": "^3.3.7",
- "selectize": "RabsRincon/selectize.js#master",
- "eventEmitter": "^5.1.0",
- "lz-string": "^1.4.4",
- "clipboard": "^1.5.12",
- "raven-js": "^3.10.0",
- "es6-promise": "^4.0.5",
- "lru-cache": "2.7.3",
- "seiyria-bootstrap-slider": "9.7.x",
- "big-integer": "https://github.com/peterolson/BigInteger.js.git#^1.6.22",
- "file-saver": "filesaver#^1.3.3",
- "vis": "4.20.1"
- }
-}
diff --git a/etc/jshintrc.client b/etc/jshintrc.client
index ae815b3f0..7d776cc03 100644
--- a/etc/jshintrc.client
+++ b/etc/jshintrc.client
@@ -2,6 +2,7 @@
"strict": true,
"undef": true,
"browser": true,
- "globals": {"define": false},
+ "node": true,
+ "globals": {"define": false, "monaco": true, "__webpack_public_path__": true},
"esversion": 5
}
diff --git a/etc/scripts/pre-commit b/etc/scripts/pre-commit
index 96b4f6834..f97124941 100755
--- a/etc/scripts/pre-commit
+++ b/etc/scripts/pre-commit
@@ -1,5 +1,5 @@
#!/bin/bash
-FORBIDDEN='console.log'
+FORBIDDEN='console.(log|warn)'
FILES_PATTERN='\.(js)(\..+)?$'
printf "\033[0;32mRunning tests...\033[0m\n"
diff --git a/lib/compilation-env.js b/lib/compilation-env.js
index bdb7bb179..d7937c547 100644
--- a/lib/compilation-env.js
+++ b/lib/compilation-env.js
@@ -101,9 +101,9 @@ CompilationEnvironment.prototype.enqueue = function (job) {
try {
return job();
} catch (e) {
- Raven.captureException(e);
- logger.error("Caught promise exception " + e);
if (e.stack) logger.info(e.stack);
+ logger.error("Caught promise exception " + e);
+ Raven.captureException(e);
return Promise.resolve(null);
}
};
diff --git a/package.json b/package.json
index b0e0021e2..3c264719a 100644
--- a/package.json
+++ b/package.json
@@ -17,41 +17,66 @@
"main": "./app.js",
"dependencies": {
"aws-sdk": "^2.177.0",
+ "big-integer": "^1.6.25",
"body-parser": "^1.18.2",
+ "bootstrap": "^3.3.7",
+ "bootstrap-slider": "^9.9.0",
+ "clipboard": "^1.7.1",
"compiler-opt-info": "0.0.4",
"compression": "^1.7.1",
"denodeify": "^1.2.1",
+ "es6-promise": "^4.1.1",
"express": "4.16.x",
+ "file-saver": "^1.3.3",
"fs-extra": "0.26.x",
+ "golden-layout": "^1.5.9",
+ "html-loader": "^0.5.5",
"http-proxy": "^1.16.2",
+ "jquery": "^3.2.1",
"lru-cache": "4.1.1",
+ "lz-string": "^1.4.4",
"monaco-editor": "0.10.1",
"morgan": "^1.9.0",
"nopt": "3.0.x",
"promise-queue": "2.2.3",
"pug": "^2.0.0-beta11",
"raven": "^2.2.1",
+ "raven-js": "^3.19.1",
+ "selectize": "^0.12.4",
"serve-favicon": "^2.4.5",
"shell-quote": "1.6.x",
"temp": "0.8.x",
"tree-kill": "^1.2.0",
+ "uglifyjs-webpack-plugin": "^1.1.8",
+ "underscore": "^1.8.3",
"underscore-node": "*",
- "winston": "^2.4.0"
+ "vis": "4.20.1",
+ "winston": "^2.4.0",
+ "wolfy87-eventemitter": "^5.2.3"
},
"devDependencies": {
"aws-sdk-mock": "^1.7.0",
- "bower": "*",
"chai": "3.5.x",
"chai-as-promised": "^7.1.1",
"chai-http": "^3.0.0",
"codecov": "^3.0.0",
+ "copy-webpack-plugin": "^4.1.1",
+ "css-loader": "^0.28.7",
+ "extract-text-webpack-plugin": "^3.0.1",
+ "file-loader": "^1.1.5",
"istanbul": "^0.4.5",
"jshint": "^2.9.5",
"mocha": "^3.3.0",
"nock": "^9.1.4",
"requirejs": "*",
+ "style-loader": "^0.19.0",
"supervisor": "*",
- "uglify-js": "*"
+ "uglify-js": "*",
+ "url-loader": "^0.6.2",
+ "webpack": "^3.6.0",
+ "webpack-dev-middleware": "^1.12.0",
+ "webpack-dev-server": "^2.9.4",
+ "webpack-manifest-plugin": "^1.3.2"
},
"scripts": {
"test": "mocha --recursive && make test",
diff --git a/static/alert.js b/static/alert.js
index fbd55c2ca..e67ea78bb 100644
--- a/static/alert.js
+++ b/static/alert.js
@@ -22,79 +22,77 @@
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
+"use strict";
-define(function (require) {
- "use strict";
- var _ = require('underscore');
- var $ = require('jquery');
+var _ = require('underscore');
+var $ = require('jquery');
- function Alert() {
- this.yesHandler = null;
- this.noHandler = null;
- var yesNo = $('#yes-no');
- yesNo.find('button.yes').click(_.bind(function () {
- if (this.yesHandler) this.yesHandler();
- }, this));
- yesNo.find('button.no').click(_.bind(function () {
- if (this.noHandler) this.noHandler();
- }, this));
+function Alert() {
+ this.yesHandler = null;
+ this.noHandler = null;
+ var yesNo = $('#yes-no');
+ yesNo.find('button.yes').click(_.bind(function () {
+ if (this.yesHandler) this.yesHandler();
+ }, this));
+ yesNo.find('button.no').click(_.bind(function () {
+ if (this.noHandler) this.noHandler();
+ }, this));
+}
+
+Alert.prototype.alert = function (title, body, onClose) {
+ var modal = $('#alert');
+ modal.find('.modal-title').html(title);
+ modal.find('.modal-body').html(body);
+ modal.modal();
+ if (onClose) {
+ modal.off('hidden.bs.modal');
+ modal.on('hidden.bs.modal', onClose);
}
+};
- Alert.prototype.alert = function (title, body, onClose) {
- var modal = $('#alert');
- modal.find('.modal-title').html(title);
- modal.find('.modal-body').html(body);
- modal.modal();
- if (onClose) {
- modal.off('hidden.bs.modal');
- modal.on('hidden.bs.modal', onClose);
- }
- };
+Alert.prototype.ask = function (title, question, handlers) {
+ var modal = $('#yes-no');
+ this.yesHandler = handlers.yes;
+ this.noHandler = handlers.no;
+ modal.find('.modal-title').html(title);
+ modal.find('.modal-body').html(question);
+ modal.modal();
+};
- Alert.prototype.ask = function (title, question, handlers) {
- var modal = $('#yes-no');
- this.yesHandler = handlers.yes;
- this.noHandler = handlers.no;
- modal.find('.modal-title').html(title);
- modal.find('.modal-body').html(question);
- modal.modal();
- };
+/* Options parameter:
+ * group: What group this notification is from. Sets data-group's value. Default: none
+ * collapseSimilar: If set to true, other notifications with the same group will be removed before sending this. (Note that this only has any effect if group is set). Default: true
+ * alertClass: Space separated classes to give to the notification div element. Default: none
+ * autoDismiss: If set to true, the notification will fade out and be removed automatically. Default: true
+ * dismissTime: If allowed by autoDismiss, controls how long the notification will be visible before being automatically removed. Default: 5000ms. Min: 1000ms
+ */
+Alert.prototype.notify = function (body, options) {
+ var container = $('#notifications');
+ if (!container) return;
+ var newElement = $('
' + body + '
');
+ if (!options) options = {};
+ // Set defaults
+ options.collapseSimilar = ("collapseSimilar" in options) ? options.collapseSimilar : true; // Collapse similars by default
+ options.autoDismiss = ("autoDismiss" in options) ? options.autoDismiss : true; // autoDismiss by default
+ options.dismissTime = options.dismissTime ? Math.max(1000, options.dismissTime) : 5000; // Dismiss this after 5000ms by default
+ if (options.group) {
+ if (options.collapseSimilar) {
+ // Only collapsing if a group has been specified
+ container.find('[data-group="' + options.group + '"]').remove();
+ }
+ newElement.attr('data-group', options.group); // Add the group to the data-group
+ }
+ if (options.alertClass) { // If we want a custom class, apply it
+ newElement.addClass(options.alertClass);
+ }
+ if (options.autoDismiss) { // Dismiss this after dismissTime
+ setTimeout(function () {
+ newElement.fadeOut('slow', function () {
+ newElement.remove();
+ });
+ }, options.dismissTime);
+ }
+ container.append(newElement); // Add the new notification to the container
+};
- /* Options parameter:
- * group: What group this notification is from. Sets data-group's value. Default: none
- * collapseSimilar: If set to true, other notifications with the same group will be removed before sending this. (Note that this only has any effect if group is set). Default: true
- * alertClass: Space separated classes to give to the notification div element. Default: none
- * autoDismiss: If set to true, the notification will fade out and be removed automatically. Default: true
- * dismissTime: If allowed by autoDismiss, controls how long the notification will be visible before being automatically removed. Default: 5000ms. Min: 1000ms
- */
- Alert.prototype.notify = function (body, options) {
- var container = $('#notifications');
- if (!container) return;
- var newElement = $('
' + body + '
');
- if (!options) options = {};
- // Set defaults
- options.collapseSimilar = ("collapseSimilar" in options) ? options.collapseSimilar : true; // Collapse similars by default
- options.autoDismiss = ("autoDismiss" in options) ? options.autoDismiss : true; // autoDismiss by default
- options.dismissTime = options.dismissTime ? Math.max(1000, options.dismissTime) : 5000; // Dismiss this after 5000ms by default
- if (options.group) {
- if (options.collapseSimilar) {
- // Only collapsing if a group has been specified
- container.find('[data-group="' + options.group + '"]').remove();
- }
- newElement.attr('data-group', options.group); // Add the group to the data-group
- }
- if (options.alertClass) { // If we want a custom class, apply it
- newElement.addClass(options.alertClass);
- }
- if (options.autoDismiss) { // Dismiss this after dismissTime
- setTimeout(function () {
- newElement.fadeOut('slow', function () {
- newElement.remove();
- });
- }, options.dismissTime);
- }
- container.append(newElement); // Add the new notification to the container
- };
-
- return Alert;
-});
\ No newline at end of file
+module.exports = Alert;
diff --git a/static/analytics.js b/static/analytics.js
index bafe12f3f..9961db151 100644
--- a/static/analytics.js
+++ b/static/analytics.js
@@ -23,109 +23,107 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- "use strict";
- var options = require('options');
- var Raven = require('raven-js');
- var $ = require('jquery');
+"use strict";
+var options = require('options');
+var Raven = require('raven-js');
+var $ = require('jquery');
- if (options.raven) {
- Raven.config(options.raven, {
- release: options.release,
- environment: options.environment.join("/")
- }).install();
- }
+if (options.raven) {
+ Raven.config(options.raven, {
+ release: options.release,
+ environment: options.environment.join("/")
+ }).install();
+}
- var gaProxy;
- if (options.googleAnalyticsEnabled) {
- (function (i, s, o, g, r, a, m) {
- i.GoogleAnalyticsObject = r;
- i[r] = i[r] || function () {
- (i[r].q = i[r].q || []).push(arguments);
- };
- i[r].l = 1 * new Date();
- a = s.createElement(o);
- m = s.getElementsByTagName(o)[0];
- a.async = 1;
- a.src = g;
- m.parentNode.insertBefore(a, m);
- })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
- ga('create', options.googleAnalyticsAccount, 'auto');
- ga('send', 'pageview');
- gaProxy = function () {
- window.ga.apply(window.ga, arguments);
+var gaProxy;
+if (options.googleAnalyticsEnabled) {
+ (function (i, s, o, g, r, a, m) {
+ i.GoogleAnalyticsObject = r;
+ i[r] = i[r] || function () {
+ (i[r].q = i[r].q || []).push(arguments);
};
- // fullstory stuff:
- window['_fs_debug'] = false;
- window['_fs_host'] = 'www.fullstory.com';
- window['_fs_org'] = '2F4NV';
- window['_fs_namespace'] = 'FS';
- (function (m, n, e, t, l, o, g, y) {
- if (e in m && m.console && m.console.log) {
- m.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].');
- return;
- }
- g = m[e] = function (a, b) {
- g.q ? g.q.push([a, b]) : g._api(a, b);
- };
- g.q = [];
- o = n.createElement(t);
- o.async = 1;
- o.src = 'https://' + _fs_host + '/s/fs.js';
- y = n.getElementsByTagName(t)[0];
- y.parentNode.insertBefore(o, y);
- g.identify = function (i, v) {
- g(l, {uid: i});
- if (v) g(l, v)
- };
- g.setUserVars = function (v) {
- g(l, v)
- };
- g.identifyAccount = function (i, v) {
- o = 'account';
- v = v || {};
- v.acctId = i;
- g(o, v)
- };
- g.clearUserCookie = function (c, d, i) {
- if (!c || document.cookie.match('fs_uid=[`;`]*`[`;`]*`[`;`]*`')) {
- d = n.domain;
- while (1) {
- n.cookie = 'fs_uid=;domain=' + d +
- ';path=/;expires=' + new Date(0).toUTCString();
- i = d.indexOf('.');
- if (i < 0) break;
- d = d.slice(i + 1)
- }
- }
- };
- })(window, document, window['_fs_namespace'], 'script', 'user');
- } else {
- gaProxy = function () {
- };
- }
-
- function initialise() {
- if (options.embedded) return;
- $(function () {
- function create_script_element(id, url) {
- var el = document.createElement('script');
- el.type = 'text/javascript';
- el.async = true;
- el.id = id;
- el.src = url;
- var s = document.getElementsByTagName('script')[0];
- s.parentNode.insertBefore(el, s);
- }
-
- if (options.sharingEnabled) {
- create_script_element('twitter-wjs', 'https://platform.twitter.com/widgets.js');
- }
- });
- }
-
- return {
- ga: gaProxy,
- initialise: initialise
+ i[r].l = 1 * new Date();
+ a = s.createElement(o);
+ m = s.getElementsByTagName(o)[0];
+ a.async = 1;
+ a.src = g;
+ m.parentNode.insertBefore(a, m);
+ })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
+ ga('create', options.googleAnalyticsAccount, 'auto');
+ ga('send', 'pageview');
+ gaProxy = function () {
+ window.ga.apply(window.ga, arguments);
};
-});
+ // fullstory stuff:
+ window['_fs_debug'] = false;
+ window['_fs_host'] = 'www.fullstory.com';
+ window['_fs_org'] = '2F4NV';
+ window['_fs_namespace'] = 'FS';
+ (function (m, n, e, t, l, o, g, y) {
+ if (e in m && m.console && m.console.log) {
+ m.console.log('FullStory namespace conflict. Please set window["_fs_namespace"].');
+ return;
+ }
+ g = m[e] = function (a, b) {
+ g.q ? g.q.push([a, b]) : g._api(a, b);
+ };
+ g.q = [];
+ o = n.createElement(t);
+ o.async = 1;
+ o.src = 'https://' + _fs_host + '/s/fs.js';
+ y = n.getElementsByTagName(t)[0];
+ y.parentNode.insertBefore(o, y);
+ g.identify = function (i, v) {
+ g(l, {uid: i});
+ if (v) g(l, v)
+ };
+ g.setUserVars = function (v) {
+ g(l, v)
+ };
+ g.identifyAccount = function (i, v) {
+ o = 'account';
+ v = v || {};
+ v.acctId = i;
+ g(o, v)
+ };
+ g.clearUserCookie = function (c, d, i) {
+ if (!c || document.cookie.match('fs_uid=[`;`]*`[`;`]*`[`;`]*`')) {
+ d = n.domain;
+ while (1) {
+ n.cookie = 'fs_uid=;domain=' + d +
+ ';path=/;expires=' + new Date(0).toUTCString();
+ i = d.indexOf('.');
+ if (i < 0) break;
+ d = d.slice(i + 1)
+ }
+ }
+ };
+ })(window, document, window['_fs_namespace'], 'script', 'user');
+} else {
+ gaProxy = function () {
+ };
+}
+
+function initialise() {
+ if (options.embedded) return;
+ $(function () {
+ function create_script_element(id, url) {
+ var el = document.createElement('script');
+ el.type = 'text/javascript';
+ el.async = true;
+ el.id = id;
+ el.src = url;
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(el, s);
+ }
+
+ if (options.sharingEnabled) {
+ create_script_element('twitter-wjs', 'https://platform.twitter.com/widgets.js');
+ }
+ });
+}
+
+module.exports = {
+ ga: gaProxy,
+ initialise: initialise
+};
diff --git a/static/asm-mode.js b/static/asm-mode.js
index 87f45cca1..3a230c651 100644
--- a/static/asm-mode.js
+++ b/static/asm-mode.js
@@ -22,103 +22,100 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- "use strict";
- var monaco = require('monaco');
+"use strict";
- function definition() {
- return {
- // Set defaultToken to invalid to see what you do not tokenize yet
- defaultToken: 'invalid',
+function definition() {
+ return {
+ // Set defaultToken to invalid to see what you do not tokenize yet
+ defaultToken: 'invalid',
- // C# style strings
- escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
+ // C# style strings
+ escapes: /\\(?:[abfnrtv\\"']|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/,
- registers: /%?\b(r[0-9]+[dbw]?|([er]?([abcd][xhl]|cs|fs|ds|ss|sp|bp|ip|sil?|dil?))|[xyz]mm[0-9]+|sp|fp|lr)\b/,
+ registers: /%?\b(r[0-9]+[dbw]?|([er]?([abcd][xhl]|cs|fs|ds|ss|sp|bp|ip|sil?|dil?))|[xyz]mm[0-9]+|sp|fp|lr)\b/,
- intelOperators: /PTR|(D|Q|[XYZ]MM)?WORD/,
+ intelOperators: /PTR|(D|Q|[XYZ]MM)?WORD/,
- tokenizer: {
- root: [
- // Error document
- [/^<.*>$/, {token: 'annotation'}],
- // Label definition
- [/^[.a-zA-Z0-9_$?@].*:/, {token: 'type.identifier', next: '@rest'}],
- // Label definition (ARM style)
- [/^\s*[|][^|]*[|]/, {token: 'type.identifier', next: '@rest'}],
- // Label definition (CL style)
- [/^\s*[.a-zA-Z0-9_$|]*\s*(PROC|ENDP|DB|DD)/, {token: 'type.identifier', next: '@rest'}],
- // Constant definition
- [/^[.a-zA-Z0-9_$?@][^=]*=/, {token: 'type.identifier', next: '@rest'}],
- // opcode
- [/[.a-zA-Z_][.a-zA-Z_0-9]*/, {token: 'keyword', next: '@rest'}],
+ tokenizer: {
+ root: [
+ // Error document
+ [/^<.*>$/, {token: 'annotation'}],
+ // Label definition
+ [/^[.a-zA-Z0-9_$?@].*:/, {token: 'type.identifier', next: '@rest'}],
+ // Label definition (ARM style)
+ [/^\s*[|][^|]*[|]/, {token: 'type.identifier', next: '@rest'}],
+ // Label definition (CL style)
+ [/^\s*[.a-zA-Z0-9_$|]*\s*(PROC|ENDP|DB|DD)/, {token: 'type.identifier', next: '@rest'}],
+ // Constant definition
+ [/^[.a-zA-Z0-9_$?@][^=]*=/, {token: 'type.identifier', next: '@rest'}],
+ // opcode
+ [/[.a-zA-Z_][.a-zA-Z_0-9]*/, {token: 'keyword', next: '@rest'}],
- // whitespace
- {include: '@whitespace'}
- ],
+ // whitespace
+ {include: '@whitespace'}
+ ],
- rest: [
- // pop at the beginning of the next line and rematch
- [/^.*$/, {token: '@rematch', next: '@pop'}],
+ rest: [
+ // pop at the beginning of the next line and rematch
+ [/^.*$/, {token: '@rematch', next: '@pop'}],
- [/@registers/, 'variable.predefined'],
- [/@intelOperators/, 'annotation'],
- // brackets
- [/[{}<>()\[\]]/, '@brackets'],
+ [/@registers/, 'variable.predefined'],
+ [/@intelOperators/, 'annotation'],
+ // brackets
+ [/[{}<>()\[\]]/, '@brackets'],
- // ARM-style label reference
- [/[|][^|]*[|]*/, 'type.identifier'],
+ // ARM-style label reference
+ [/[|][^|]*[|]*/, 'type.identifier'],
- // numbers
- [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
- [/([$]|0[xX])[0-9a-fA-F]+/, 'number.hex'],
- [/\d+/, 'number'],
- // ARM-style immediate numbers (which otherwise look like comments)
- [/#-?\d+/, 'number'],
+ // numbers
+ [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
+ [/([$]|0[xX])[0-9a-fA-F]+/, 'number.hex'],
+ [/\d+/, 'number'],
+ // ARM-style immediate numbers (which otherwise look like comments)
+ [/#-?\d+/, 'number'],
- // operators
- [/[-+,*\/!:&]/, 'operator'],
+ // operators
+ [/[-+,*\/!:&]/, 'operator'],
- // strings
- [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-terminated string
- [/"/, {token: 'string.quote', bracket: '@open', next: '@string'}],
+ // strings
+ [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-terminated string
+ [/"/, {token: 'string.quote', bracket: '@open', next: '@string'}],
- // characters
- [/'[^\\']'/, 'string'],
- [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
- [/'/, 'string.invalid'],
+ // characters
+ [/'[^\\']'/, 'string'],
+ [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
+ [/'/, 'string.invalid'],
- // Assume anything else is a label reference
- [/%?[.?_$a-zA-Z@][.?_$a-zA-Z0-9@]*/, 'type.identifier'],
+ // Assume anything else is a label reference
+ [/%?[.?_$a-zA-Z@][.?_$a-zA-Z0-9@]*/, 'type.identifier'],
- // whitespace
- {include: '@whitespace'}
- ],
+ // whitespace
+ {include: '@whitespace'}
+ ],
- comment: [
- [/[^\/*]+/, 'comment'],
- [/\/\*/, 'comment', '@push'], // nested comment
- ["\\*/", 'comment', '@pop'],
- [/[\/*]/, 'comment']
- ],
+ comment: [
+ [/[^\/*]+/, 'comment'],
+ [/\/\*/, 'comment', '@push'], // nested comment
+ ["\\*/", 'comment', '@pop'],
+ [/[\/*]/, 'comment']
+ ],
- string: [
- [/[^\\"]+/, 'string'],
- [/@escapes/, 'string.escape'],
- [/\\./, 'string.escape.invalid'],
- [/"/, {token: 'string.quote', bracket: '@close', next: '@pop'}]
- ],
+ string: [
+ [/[^\\"]+/, 'string'],
+ [/@escapes/, 'string.escape'],
+ [/\\./, 'string.escape.invalid'],
+ [/"/, {token: 'string.quote', bracket: '@close', next: '@pop'}]
+ ],
- whitespace: [
- [/[ \t\r\n]+/, 'white'],
- [/\/\*/, 'comment', '@comment'],
- [/\/\/.*$/, 'comment'],
- [/[#;\\@].*$/, 'comment']
- ]
- }
- };
- }
+ whitespace: [
+ [/[ \t\r\n]+/, 'white'],
+ [/\/\*/, 'comment', '@comment'],
+ [/\/\/.*$/, 'comment'],
+ [/[#;\\@].*$/, 'comment']
+ ]
+ }
+ };
+}
- monaco.languages.register({id: 'asm'});
- monaco.languages.setMonarchTokensProvider('asm', definition());
-});
+monaco.languages.register({id: 'asm'});
+monaco.languages.setMonarchTokensProvider('asm', definition());
diff --git a/static/ast-view.js b/static/ast-view.js
index c3f43962a..fc8ff6481 100644
--- a/static/ast-view.js
+++ b/static/ast-view.js
@@ -22,131 +22,138 @@
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
+"use strict";
-define(function (require) {
- "use strict";
+var FontScale = require('fontscale');
+var monaco = require('monaco');
+var _ = require('underscore');
+var $ = require('jquery');
- var FontScale = require('fontscale');
- var monaco = require('monaco');
- var _ = require('underscore');
- var $ = require('jquery');
+function Ast(hub, container, state) {
+ this.container = container;
+ this.eventHub = hub.createEventHub();
+ this.domRoot = container.getElement();
+ this.domRoot.html($('#ast').html());
+ this._currentDecorations = [];
+ this.astEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], {
+ value: "",
+ scrollBeyondLastLine: false,
+ language: 'cppp', //we only support cpp for now
+ readOnly: true,
+ glyphMargin: true,
+ fontFamily: 'monospace',
+ quickSuggestions: false,
+ fixedOverflowWidgets: true,
+ minimap: {
+ maxColumn: 80
+ },
+ lineNumbersMinChars: 3
+ });
- function Ast(hub, container, state) {
- this.container = container;
- this.eventHub = hub.createEventHub();
- this.domRoot = container.getElement();
- this.domRoot.html($('#ast').html());
- this._currentDecorations = [];
- this.astEditor = monaco.editor.create(this.domRoot.find(".monaco-placeholder")[0], {
- value: "",
- scrollBeyondLastLine: false,
- language: 'cppp', //we only support cpp for now
- readOnly: true,
- glyphMargin: true,
- fontFamily: 'monospace',
- quickSuggestions: false,
- fixedOverflowWidgets: true,
- minimap: {
- maxColumn: 80
- },
- lineNumbersMinChars: 3
- });
+ this._compilerid = state.id;
+ this._compilerName = state.compilerName;
+ this._editorid = state.editorid;
+ this.fontScale = new FontScale(this.domRoot, state, this.astEditor);
+ this.fontScale.on('change', _.bind(this.updateState, this));
- this._compilerid = state.id;
- this._compilerName = state.compilerName;
- this._editorid = state.editorid;
- this.fontScale = new FontScale(this.domRoot, state, this.astEditor);
- this.fontScale.on('change', _.bind(this.updateState, this));
+ this.container.on('destroy', this.close, this);
- this.container.on('destroy', this.close, this);
+ this.eventHub.on('compileResult', this.onCompileResult, this);
+ this.eventHub.on('compiler', this.onCompiler, this);
+ this.eventHub.on('compilerClose', this.onCompilerClose, this);
+ this.eventHub.on('editorChange', this.onEditorChange, this);
+ this.eventHub.on('settingsChange', this.onSettingsChange, this);
+ this.eventHub.emit('astViewOpened', this._compilerid);
+ this.eventHub.emit('requestSettings');
- this.eventHub.on('compileResult', this.onCompileResult, this);
- this.eventHub.on('compiler', this.onCompiler, this);
- this.eventHub.on('compilerClose', this.onCompilerClose, this);
- this.eventHub.on('editorChange', this.onEditorChange, this);
- this.eventHub.on('settingsChange', this.onSettingsChange, this);
- this.eventHub.emit('astViewOpened', this._compilerid);
- this.eventHub.emit('requestSettings');
+ container.on('resize', this.resize, this);
+ container.on('shown', this.resize, this);
+ if (state && state.astOutput) {
+ this.showAstResults(state.astOutput);
+ }
+ this.setTitle();
+}
- container.on('resize', this.resize, this);
- container.on('shown', this.resize, this);
- if (state && state.astOutput) {
- this.showAstResults(state.astOutput);
+// TODO: de-dupe with compiler etc
+Ast.prototype.resize = function () {
+ var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true);
+ this.astEditor.layout({
+ width: this.domRoot.width(),
+ height: this.domRoot.height() - topBarHeight
+ });
+};
+
+Ast.prototype.onEditorChange = function (id, source) {
+};
+
+Ast.prototype.onCompileResult = function (id, compiler, result) {
+ if (this._compilerid == id) {
+ if (result.hasAstOutput) {
+ this.showAstResults(result.astOutput);
}
+ else {
+ this.showAstResults("");
+ }
+ }
+};
+Ast.prototype.setTitle = function () {
+ this.container.setTitle(this._compilerName + " Ast Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")");
+};
+
+Ast.prototype.getDisplayableAst = function (astResult) {
+ return "**" + astResult.astType + "** - " + astResult.displayString;
+};
+
+Ast.prototype.showAstResults = function (results) {
+ this.astEditor.setValue(results);
+};
+
+Ast.prototype.onCompiler = function (id, compiler, options, editorid) {
+ if (id == this._compilerid) {
+ this._compilerName = compiler ? compiler.name : '';
+ this._editorid = editorid;
this.setTitle();
}
+};
- // TODO: de-dupe with compiler etc
- Ast.prototype.resize = function () {
- var topBarHeight = this.domRoot.find(".top-bar").outerHeight(true);
- this.astEditor.layout({
- width: this.domRoot.width(),
- height: this.domRoot.height() - topBarHeight
- });
- };
+Ast.prototype.onCompilerClose = function (id) {
+ if (id === this._compilerid) {
+ // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
+ // the hierarchy. We can't modify while it's being iterated over.
+ _.defer(function (self) {
+ self.container.close();
+ }, this);
+ }
+};
- Ast.prototype.onEditorChange = function (id, source) {
- };
+Ast.prototype.updateState = function () {
+};
- Ast.prototype.onCompileResult = function (id, compiler, result) {
- if (this._compilerid == id) {
- if (result.hasAstOutput) {
- this.showAstResults(result.astOutput);
- }
- else {
- this.showAstResults("");
- }
+Ast.prototype.onCompilerClose = function (id) {
+ if (id === this._compilerid) {
+ // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
+ // the hierarchy. We can't modify while it's being iterated over.
+ this.close();
+ _.defer(function (self) {
+ self.container.close();
+ }, this);
+ }
+};
+
+Ast.prototype.onSettingsChange = function (newSettings) {
+ this.astEditor.updateOptions({
+ minimap: {
+ enabled: newSettings.showMinimap
}
- };
- Ast.prototype.setTitle = function () {
- this.container.setTitle(this._compilerName + " Ast Viewer (Editor #" + this._editorid + ", Compiler #" + this._compilerid + ")");
- };
+ });
+};
- Ast.prototype.getDisplayableAst = function (astResult) {
- return "**" + astResult.astType + "** - " + astResult.displayString;
- };
+Ast.prototype.close = function () {
+ this.eventHub.unsubscribe();
+ this.eventHub.emit("astViewClosed", this._compilerid);
+ this.astEditor.dispose();
+};
- Ast.prototype.showAstResults = function (results) {
- this.astEditor.setValue(results);
- };
-
- Ast.prototype.onCompiler = function (id, compiler, options, editorid) {
- if (id == this._compilerid) {
- this._compilerName = compiler ? compiler.name : '';
- this._editorid = editorid;
- this.setTitle();
- }
- };
-
- Ast.prototype.onCompilerClose = function (id) {
- if (id === this._compilerid) {
- // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
- // the hierarchy. We can't modify while it's being iterated over.
- this.close();
- _.defer(function (self) {
- self.container.close();
- }, this);
- }
- };
-
- Ast.prototype.updateState = function () {
- };
-
- Ast.prototype.onSettingsChange = function (newSettings) {
- this.astEditor.updateOptions({
- minimap: {
- enabled: newSettings.showMinimap
- }
- });
- };
-
- Ast.prototype.close = function () {
- this.eventHub.unsubscribe();
- this.eventHub.emit("astViewClosed", this._compilerid);
- this.astEditor.dispose();
- };
-
- return {
- Ast: Ast
- };
-});
+module.exports = {
+ Ast: Ast
+};
diff --git a/static/cfg-view.js b/static/cfg-view.js
index 5b2b4cadb..0b60ea2f7 100644
--- a/static/cfg-view.js
+++ b/static/cfg-view.js
@@ -23,154 +23,146 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- 'use strict';
+'use strict';
- var $ = require('jquery');
- var vis = require('vis');
- var _ = require('underscore');
- require('selectize');
+var $ = require('jquery');
+var vis = require('vis');
+var _ = require('underscore');
- function Cfg(hub, container, state) {
- this.container = container;
- this.eventHub = hub.createEventHub();
- this.domRoot = container.getElement();
- this.domRoot.html($('#cfg').html());
- this.defaultCfgOutput = {nodes: [{id: 0, shape: 'box', label: 'No Output'}], edges: []};
- this.binaryModeSupport = {
- nodes: [{
- id: 0,
- shape: 'box',
- label: 'Cfg mode cannot be used when the binary filter is set'
- }], edges: []
- };
- // Note that this might be outdated if no functions were present when creating the link, but that's handled
- // by selectize
- this.currentFunc = state.selectedFn || '';
- this.functions = [];
- this.networkOpts = {
- autoResize: true,
- locale: 'en',
- edges: {
- arrows: {to: {enabled: true}},
- smooth: {enabled: true},
- physics: false
- },
- nodes: {
- font: {face: 'monospace', align: 'left'}
- },
- layout: {
- improvedLayout: true,
- hierarchical: {
- enabled: true,
- sortMethod: 'directed',
- direction: 'UD',
- nodeSpacing: 100,
- levelSeparation: 150
- }
- },
- physics: {
- hierarchicalRepulsion: {
- nodeDistance: 125
- }
- },
- interaction: {
- navigationButtons: false,
- keyboard: {
- enabled: true,
- speed: {x: 10, y: 10, zoom: 0.03},
- bindToWindow: false
- }
+require('selectize');
+require("vis/dist/vis.css");
+
+function Cfg(hub, container, state) {
+ this.container = container;
+ this.eventHub = hub.createEventHub();
+ this.domRoot = container.getElement();
+ this.domRoot.html($('#cfg').html());
+ this.defaultCfgOutput = {nodes: [{id: 0, shape: 'box', label: 'No Output'}], edges: []};
+ this.binaryModeSupport = {
+ nodes: [{
+ id: 0,
+ shape: 'box',
+ label: 'Cfg mode cannot be used when the binary filter is set'
+ }], edges: []
+ };
+ // Note that this might be outdated if no functions were present when creating the link, but that's handled
+ // by selectize
+ this.currentFunc = state.selectedFn || '';
+ this.functions = [];
+ this.networkOpts = {
+ autoResize: true,
+ locale: 'en',
+ edges: {
+ arrows: {to: {enabled: true}},
+ smooth: {enabled: true},
+ physics: false
+ },
+ nodes: {
+ font: {face: 'monospace', align: 'left'}
+ },
+ layout: {
+ improvedLayout: true,
+ hierarchical: {
+ enabled: true,
+ sortMethod: 'directed',
+ direction: 'UD',
+ nodeSpacing: 100,
+ levelSeparation: 150
}
- };
-
- this.cfgVisualiser = new vis.Network(this.domRoot.find('.graph-placeholder')[0],
- this.defaultCfgOutput, this.networkOpts);
- this.domRoot.find('.show-hide-btn').on('click', _.bind(function () {
- this.networkOpts.interaction.navigationButtons = !this.networkOpts.interaction.navigationButtons;
- this.cfgVisualiser.setOptions(this.networkOpts);
- }, this));
-
- this.compilerId = state.id;
- this._editorid = state.editorid;
- this._binaryFilter = false;
-
- this.functionPicker = $(this.domRoot).find('.function-picker').selectize({
- sortField: 'name',
- valueField: 'name',
- labelField: 'name',
- searchField: ['name']
- }).on('change', _.bind(function (e) {
- var selectedFn = this.functions[e.target.value];
- if (selectedFn) {
- this.currentFunc = e.target.value;
- this.showCfgResults({
- nodes: selectedFn.nodes,
- edges: selectedFn.edges
- });
- this.cfgVisualiser.selectNodes([selectedFn.nodes[0].id]);
- this.saveState();
+ },
+ physics: {
+ hierarchicalRepulsion: {
+ nodeDistance: 125
}
- }, this));
-
- this.eventHub.on('compilerClose', this.onCompilerClose, this);
- this.eventHub.on('compileResult', this.onCompileResult, this);
- this.eventHub.on('compiler', this.onCompiler, this);
- this.eventHub.on('filtersChange', this.onFiltersChange, this);
-
- this.container.on('destroy', this.close, this);
- this.container.on('resize', this.resize, this);
- this.container.on('shown', this.resize, this);
- this.eventHub.emit('cfgViewOpened', this.compilerId);
- this.eventHub.emit('requestFilters', this.compilerId);
- this.eventHub.emit('requestCompiler', this.compilerId);
-
- this.adaptStructure = function (names) {
- return _.map(names, function (name) {return {name: name};});
- };
-
- this.setTitle();
- }
-
- Cfg.prototype.onCompileResult = function (id, compiler, result) {
- if (this.compilerId === id) {
- var functionNames = [];
- if (this.supportsCfg && !$.isEmptyObject(result.cfg)) {
- this.functions = result.cfg;
- functionNames = Object.keys(this.functions);
- if (functionNames.indexOf(this.currentFunc) === -1) {
- this.currentFunc = functionNames[0];
- }
- this.showCfgResults({
- nodes: this.functions[this.currentFunc].nodes,
- edges: this.functions[this.currentFunc].edges
- });
- this.cfgVisualiser.selectNodes([this.functions[this.currentFunc].nodes[0].id]);
- } else {
- // We don't reset the current function here as we would lose the saved one if this happened at the begining
- // (Hint: It *does* happen)
- this.showCfgResults(this._binaryFilter ? this.binaryModeSupport : this.defaultCfgOutput);
+ },
+ interaction: {
+ navigationButtons: false,
+ keyboard: {
+ enabled: true,
+ speed: {x: 10, y: 10, zoom: 0.03},
+ bindToWindow: false
}
-
- this.functionPicker[0].selectize.clearOptions();
- this.functionPicker[0].selectize.addOption(functionNames.length ? this.adaptStructure(functionNames) : {name: 'The input does not contain functions'});
- this.functionPicker[0].selectize.refreshOptions(false);
-
- this.functionPicker[0].selectize.clear();
- this.functionPicker[0].selectize.addItem(functionNames.length ? this.currentFunc : 'The input does not contain functions', true);
- this.saveState();
}
};
- Cfg.prototype.setTitle = function () {
- this.container.setTitle((this._compilerName || '') + ' Graph Viewer (Editor #' + this._editorid + ', Compiler #' + this.compilerId + ')');
+ this.cfgVisualiser = new vis.Network(this.domRoot.find('.graph-placeholder')[0],
+ this.defaultCfgOutput, this.networkOpts);
+ this.domRoot.find('.show-hide-btn').on('click', _.bind(function () {
+ this.networkOpts.interaction.navigationButtons = !this.networkOpts.interaction.navigationButtons;
+ this.cfgVisualiser.setOptions(this.networkOpts);
+ }, this));
+
+ this.compilerId = state.id;
+ this._editorid = state.editorid;
+ this._binaryFilter = false;
+
+ this.functionPicker = $(this.domRoot).find('.function-picker').selectize({
+ sortField: 'name',
+ valueField: 'name',
+ labelField: 'name',
+ searchField: ['name']
+ }).on('change', _.bind(function (e) {
+ var selectedFn = this.functions[e.target.value];
+ if (selectedFn) {
+ this.currentFunc = e.target.value;
+ this.showCfgResults({
+ nodes: selectedFn.nodes,
+ edges: selectedFn.edges
+ });
+ this.cfgVisualiser.selectNodes([selectedFn.nodes[0].id]);
+ this.saveState();
+ }
+ }, this));
+
+ this.eventHub.on('compilerClose', this.onCompilerClose, this);
+ this.eventHub.on('compileResult', this.onCompileResult, this);
+ this.eventHub.on('compiler', this.onCompiler, this);
+ this.eventHub.on('filtersChange', this.onFiltersChange, this);
+
+ this.container.on('destroy', this.close, this);
+ this.container.on('resize', this.resize, this);
+ this.container.on('shown', this.resize, this);
+ this.eventHub.emit('cfgViewOpened', this.compilerId);
+ this.eventHub.emit('requestFilters', this.compilerId);
+ this.eventHub.emit('requestCompiler', this.compilerId);
+
+ this.adaptStructure = function (names) {
+ return _.map(names, function (name) {return {name: name};});
};
- Cfg.prototype.showCfgResults = function (data) {
- this.cfgVisualiser.setData(data);
- };
+ this.setTitle();
+}
- Cfg.prototype.onCompiler = function (id, compiler) {
+Cfg.prototype.onCompileResult = function (id, compiler, result) {
+ if (this._compilerid === id) {
+ var functionNames = [];
+ if (result.supportsCfg && !$.isEmptyObject(result.cfg)) {
+ this.functions = result.cfg;
+ functionNames = Object.keys(this.functions);
+ if (functionNames.indexOf(this.currentFunc) === -1) {
+ this.currentFunc = functionNames[0];
+ }
+ this.showCfgResults({
+ nodes: this.functions[this.currentFunc].nodes,
+ edges: this.functions[this.currentFunc].edges
+ });
+ this.cfgVisualiser.selectNodes([this.functions[this.currentFunc].nodes[0].id]);
+ } else {
+ // We don't reset the current function here as we would lose the saved one if this happened at the begining
+ // (Hint: It *does* happen)
+ this.showCfgResults(this._binaryFilter ? this.binaryModeSupport : this.defaultCfgOutput);
+ }
+
+ this.functionPicker[0].selectize.clearOptions();
+ this.functionPicker[0].selectize.addOption(functionNames.length ? this.adaptStructure(functionNames) : {name: 'The input does not contain functions'});
+ this.functionPicker[0].selectize.refreshOptions(false);
+
+ this.functionPicker[0].selectize.clear();
+ this.functionPicker[0].selectize.addItem(functionNames.length ? this.currentFunc : 'The input does not contain any function', true);
+ this.saveState();
+ }
+};
+Cfg.prototype.onCompiler = function (id, compiler) {
if (id === this.compilerId) {
this._compilerName = compiler ? compiler.name : '';
this.supportsCfg = compiler.supportsCfg;
@@ -178,51 +170,62 @@ define(function (require) {
}
};
- Cfg.prototype.onFiltersChange = function (id, filters) {
- if (this.compilerId === id) {
- this._binaryFilter = filters.binary;
- }
- };
+Cfg.prototype.onFiltersChange = function (id, filters) {
+ if (this.compilerId === id) {
+ this._binaryFilter = filters.binary;
+ }
+};
- Cfg.prototype.resize = function () {
- if (this.cfgVisualiser.canvas) {
- var height = this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true);
- this.cfgVisualiser.setSize('100%', height.toString());
- this.cfgVisualiser.redraw();
- }
- };
+Cfg.prototype.resize = function () {
+ if (this.cfgVisualiser.canvas) {
+ var height = this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true);
+ this.cfgVisualiser.setSize('100%', height.toString());
+ this.cfgVisualiser.redraw();
+ }
+};
- Cfg.prototype.saveState = function () {
- this.container.setState(this.currentState());
- };
+Cfg.prototype.setTitle = function () {
+ this.container.setTitle(this._compilerName + ' Graph Viewer (Editor #' + this._editorid + ', Compiler #' + this._compilerid + ')');
+};
- Cfg.prototype.currentState = function () {
- return {
- id: this.compilerId,
- editorid: this._editorid,
- selectedFn: this.currentFunc
- };
- };
+Cfg.prototype.showCfgResults = function (data) {
+ this.cfgVisualiser.setData(data);
+};
- Cfg.prototype.onCompilerClose = function (compilerId) {
- if (this.compilerId === compilerId) {
- // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
- // the hierarchy. We can't modify while it's being iterated over.
- this.close();
- _.defer(function (self) {
- self.container.close();
- }, this);
- }
- };
- Cfg.prototype.close = function () {
- this.eventHub.unsubscribe();
- this.eventHub.emit('cfgViewClosed', this.compilerId);
- this.cfgVisualiser.destroy();
- };
+Cfg.prototype.onCompilerClose = function (compilerId) {
+ if (this.compilerId === compilerId) {
+ // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
+ // the hierarchy. We can't modify while it's being iterated over.
+ this.close();
+ _.defer(function (self) {
+ self.container.close();
+ }, this);
+ }
+};
+Cfg.prototype.close = function () {
+ this.eventHub.unsubscribe();
+ this.eventHub.emit('cfgViewClosed', this.compilerId);
+ this.cfgVisualiser.destroy();
+};
+
+
+
+Cfg.prototype.saveState = function () {
+ this.container.setState(this.currentState());
+};
+
+Cfg.prototype.currentState = function () {
return {
- Cfg: Cfg
+ id: this.compilerId,
+ editorid: this._editorid,
+ selectedFn: this.currentFunc
};
-});
+};
+
+
+module.exports = {
+ Cfg: Cfg
+};
diff --git a/static/colour.js b/static/colour.js
index 174a55a3a..1749d3888 100644
--- a/static/colour.js
+++ b/static/colour.js
@@ -22,42 +22,38 @@
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
+"use strict";
-define(function (require) {
- "use strict";
+var _ = require('underscore');
- var _ = require('underscore');
- var monaco = require('monaco');
+// themes is an array so one scheme can be used in multiple places. If you want to use it everywhere, ['all'] should suffice
+var schemes = [
+ {name: 'rainbow', desc: 'Rainbow 1', count: 12, themes: ['default']},
+ {name: 'rainbow2', desc: 'Rainbow 2', count: 12, themes: ['default']},
+ {name: 'earth', desc: 'Earth tones (colourblind safe)', count: 9, themes: ['default']},
+ {name: 'green-blue', desc: 'Greens and blues (colourblind safe)', count: 4, themes: ['default']},
+ {name: 'gray-shade', desc: 'Gray shades', count: 4, themes: ['dark']}
+];
- // themes is an array so one scheme can be used in multiple places. If you want to use it everywhere, ['all'] should suffice
- var schemes = [
- {name: 'rainbow', desc: 'Rainbow 1', count: 12, themes: ['default']},
- {name: 'rainbow2', desc: 'Rainbow 2', count: 12, themes: ['default']},
- {name: 'earth', desc: 'Earth tones (colourblind safe)', count: 9, themes: ['default']},
- {name: 'green-blue', desc: 'Greens and blues (colourblind safe)', count: 4, themes: ['default']},
- {name: 'gray-shade', desc: 'Gray shades', count: 4, themes: ['dark']}
- ];
-
- function applyColours(editor, colours, schemeName, prevDecorations) {
- var scheme = _.findWhere(schemes, {name: schemeName});
- if (!scheme) {
- scheme = schemes[0];
- }
- var newDecorations = _.map(colours, function (ordinal, line) {
- line = parseInt(line) + 1;
- return {
- range: new monaco.Range(line, 1, line, 1),
- options: {
- isWholeLine: true,
- className: scheme.name + "-" + (ordinal % scheme.count)
- }
- };
- });
- return editor.deltaDecorations(prevDecorations, newDecorations);
+function applyColours(editor, colours, schemeName, prevDecorations) {
+ var scheme = _.findWhere(schemes, {name: schemeName});
+ if (!scheme) {
+ scheme = schemes[0];
}
+ var newDecorations = _.map(colours, function (ordinal, line) {
+ line = parseInt(line) + 1;
+ return {
+ range: new monaco.Range(line, 1, line, 1),
+ options: {
+ isWholeLine: true,
+ className: scheme.name + "-" + (ordinal % scheme.count)
+ }
+ };
+ });
+ return editor.deltaDecorations(prevDecorations, newDecorations);
+}
- return {
- applyColours: applyColours,
- schemes: schemes
- };
-});
+module.exports = {
+ applyColours: applyColours,
+ schemes: schemes
+};
diff --git a/static/compiler-service.js b/static/compiler-service.js
index 538c08214..66b94ba59 100644
--- a/static/compiler-service.js
+++ b/static/compiler-service.js
@@ -23,122 +23,120 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- "use strict";
- var $ = require('jquery');
- var _ = require('underscore');
- var LruCache = require('lru-cache');
- var options = require('options');
- var Promise = require('es6-promise').Promise;
+"use strict";
+var $ = require('jquery');
+var _ = require('underscore');
+var LruCache = require('lru-cache');
+var options = require('options');
+var Promise = require('es6-promise').Promise;
- function CompilerService() {
- this.cache = new LruCache({
- max: 200 * 1024,
- length: function (n) {
- return JSON.stringify(n).length;
- }
- });
- this.compilersByLang = {};
- _.each(options.compilers, function (compiler) {
- if (!this.compilersByLang[compiler.lang]) this.compilersByLang[compiler.lang] = {};
- this.compilersByLang[compiler.lang][compiler.id] = compiler;
- if (compiler.alias) {
- this.compilersByLang[compiler.lang][compiler.alias] = compiler;
- }
- }, this);
+function CompilerService() {
+ this.cache = new LruCache({
+ max: 200 * 1024,
+ length: function (n) {
+ return JSON.stringify(n).length;
+ }
+ });
+ this.compilersByLang = {};
+ _.each(options.compilers, function (compiler) {
+ if (!this.compilersByLang[compiler.lang]) this.compilersByLang[compiler.lang] = {};
+ this.compilersByLang[compiler.lang][compiler.id] = compiler;
+ if (compiler.alias) {
+ this.compilersByLang[compiler.lang][compiler.alias] = compiler;
+ }
+ }, this);
+}
+
+CompilerService.prototype.getCompilersForLang = function (langId) {
+ return this.compilersByLang[langId] || {};
+};
+
+CompilerService.prototype.findCompiler = function (langId, compilerId) {
+ if (!compilerId) return null;
+ var compilers = this.getCompilersForLang(langId);
+ if (compilers && compilers[compilerId]) {
+ return compilers[compilerId];
}
+ return _.find(compilers, function (compiler) {
+ return compiler.alias === compilerId;
+ });
+};
- CompilerService.prototype.getCompilersForLang = function (langId) {
- return this.compilersByLang[langId] || {};
- };
-
- CompilerService.prototype.findCompiler = function (langId, compilerId) {
- if (!compilerId) return null;
- var compilers = this.getCompilersForLang(langId);
- if (compilers && compilers[compilerId]) {
- return compilers[compilerId];
- }
- return _.find(compilers, function (compiler) {
- return compiler.alias === compilerId;
+CompilerService.prototype.submit = function (request) {
+ var jsonRequest = JSON.stringify(request);
+ var cachedResult = this.cache.get(jsonRequest);
+ if (cachedResult) {
+ return Promise.resolve({
+ request: request,
+ result: cachedResult,
+ localCacheHit: true
});
- };
-
- CompilerService.prototype.submit = function (request) {
- var jsonRequest = JSON.stringify(request);
- var cachedResult = this.cache.get(jsonRequest);
- if (cachedResult) {
- return Promise.resolve({
- request: request,
- result: cachedResult,
- localCacheHit: true
- });
- }
- return new Promise(_.bind(function (resolve, reject) {
- $.ajax({
- type: 'POST',
- url: 'api/compiler/' + encodeURIComponent(request.compiler) + '/compile',
- dataType: 'json',
- contentType: 'application/json',
- data: jsonRequest,
- success: _.bind(function (result) {
- if (result && result.okToCache) {
- this.cache.set(jsonRequest, result);
- }
- resolve({
- request: request,
- result: result,
- localCacheHit: false
- });
- }, this),
- error: function (xhr, textStatus, errorThrown) {
- var error = errorThrown;
- if (!error) {
- switch (textStatus) {
- case "timeout":
- error = "Request timed out";
- break;
- case "abort":
- error = "Request was aborted";
- break;
- default:
- error = "Error sending request";
- break;
- }
- }
- reject({
- request: request,
- error: error
- });
+ }
+ return new Promise(_.bind(function (resolve, reject) {
+ $.ajax({
+ type: 'POST',
+ url: 'api/compiler/' + encodeURIComponent(request.compiler) + '/compile',
+ dataType: 'json',
+ contentType: 'application/json',
+ data: jsonRequest,
+ success: _.bind(function (result) {
+ if (result && result.okToCache) {
+ this.cache.set(jsonRequest, result);
}
- });
- }, this));
- };
-
- CompilerService.prototype.expand = function (source) {
- var includeFind = /^\s*#include\s*["<](https?:\/\/[^>"]+)[>"]/;
- var lines = source.split("\n");
- var promises = [];
- _.each(lines, function (line, lineNumZeroBased) {
- var match = line.match(includeFind);
- if (match) {
- promises.push(new Promise(function (resolve, reject) {
- var req = $.get(match[1], function (data) {
- data = '#line 1 "' + match[1] + '"\n' + data + '\n\n#line ' +
- (lineNumZeroBased + 1) + ' ""\n';
-
- lines[lineNumZeroBased] = data;
- resolve();
- });
- req.fail(function () {
- resolve();
- });
- }));
+ resolve({
+ request: request,
+ result: result,
+ localCacheHit: false
+ });
+ }, this),
+ error: function (xhr, textStatus, errorThrown) {
+ var error = errorThrown;
+ if (!error) {
+ switch (textStatus) {
+ case "timeout":
+ error = "Request timed out";
+ break;
+ case "abort":
+ error = "Request was aborted";
+ break;
+ default:
+ error = "Error sending request";
+ break;
+ }
+ }
+ reject({
+ request: request,
+ error: error
+ });
}
});
- return Promise.all(promises).then(function () {
- return lines.join("\n");
- });
- };
+ }, this));
+};
- return CompilerService;
-});
+CompilerService.prototype.expand = function (source) {
+ var includeFind = /^\s*#include\s*["<](https?:\/\/[^>"]+)[>"]/;
+ var lines = source.split("\n");
+ var promises = [];
+ _.each(lines, function (line, lineNumZeroBased) {
+ var match = line.match(includeFind);
+ if (match) {
+ promises.push(new Promise(function (resolve, reject) {
+ var req = $.get(match[1], function (data) {
+ data = '#line 1 "' + match[1] + '"\n' + data + '\n\n#line ' +
+ (lineNumZeroBased + 1) + ' ""\n';
+
+ lines[lineNumZeroBased] = data;
+ resolve();
+ });
+ req.fail(function () {
+ resolve();
+ });
+ }));
+ }
+ });
+ return Promise.all(promises).then(function () {
+ return lines.join("\n");
+ });
+};
+
+module.exports = CompilerService;
diff --git a/static/compiler.js b/static/compiler.js
index 7ccf20b56..23ee5a645 100644
--- a/static/compiler.js
+++ b/static/compiler.js
@@ -23,1244 +23,1243 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- 'use strict';
- var $ = require('jquery');
- var _ = require('underscore');
- var ga = require('analytics').ga;
- var colour = require('colour');
- var Toggles = require('toggles');
- var FontScale = require('fontscale');
- var Promise = require('es6-promise').Promise;
- var Components = require('components');
- var LruCache = require('lru-cache');
- var options = require('options');
- var monaco = require('monaco');
- var Alert = require('alert');
- var bigInt = require('big-integer');
- var local = require('./local');
- var Raven = require('raven-js');
- require('asm-mode');
+'use strict';
+var $ = require('jquery');
+var _ = require('underscore');
+var ga = require('analytics').ga;
+var colour = require('colour');
+var Toggles = require('toggles');
+var FontScale = require('fontscale');
+var Promise = require('es6-promise').Promise;
+var Components = require('components');
+var LruCache = require('lru-cache');
+var options = require('options');
+var monaco = require('monaco');
+var Alert = require('alert');
+var bigInt = require('big-integer');
+var local = require('./local');
+var Raven = require('raven-js');
+require('asm-mode');
- require('selectize');
+require('selectize');
- var OpcodeCache = new LruCache({
- max: 64 * 1024,
- length: function (n) {
- return JSON.stringify(n).length;
+var OpcodeCache = new LruCache({
+ max: 64 * 1024,
+ length: function (n) {
+ return JSON.stringify(n).length;
+ }
+});
+
+function patchOldFilters(filters) {
+ if (filters === undefined) return undefined;
+ // Filters are of the form {filter: true|false¸ ...}. In older versions, we used
+ // to suppress the {filter:false} form. This means we can't distinguish between
+ // "filter not on" and "filter not present". In the latter case we want to default
+ // the filter. In the former case we want the filter off. Filters now don't suppress
+ // but there are plenty of permanlinks out there with no filters set at all. Here
+ // we manually set any missing filters to 'false' to recover the old behaviour of
+ // "if it's not here, it's off".
+ _.each(['binary', 'labels', 'directives', 'commentOnly', 'trim', 'intel'], function (oldFilter) {
+ if (filters[oldFilter] === undefined) filters[oldFilter] = false;
+ });
+ return filters;
+}
+
+var languages = options.languages;
+
+function Compiler(hub, container, state) {
+ this.container = container;
+ this.eventHub = hub.createEventHub();
+ this.compilerService = hub.compilerService;
+ this.domRoot = container.getElement();
+ this.domRoot.html($('#compiler').html());
+ this.id = state.id || hub.nextCompilerId();
+ this.sourceEditorId = state.source || 1;
+ this.settings = JSON.parse(local.get('settings', '{}'));
+ // If we don't have a language, but a compiler, find the corresponding language.
+ this.currentLangId = state.lang;
+ if (!this.currentLangId && state.compiler) {
+ this.currentLangId = this.langOfCompiler(state.compiler);
+ }
+ if (!this.currentLangId && languages[this.settings.defaultLanguage]) {
+ this.currentLangId = languages[this.settings.defaultLanguage].id;
+ }
+ if (!this.currentLangId) {
+ this.currentLangId = _.keys(languages)[0];
+ }
+ this.originalCompilerId = state.compiler;
+ if (state.compiler)
+ this.compiler = this.findCompiler(this.currentLangId, state.compiler);
+ else
+ this.compiler = this.findCompiler(this.currentLangId, options.defaultCompiler[this.currentLangId]);
+ if (!this.compiler) {
+ var compilers = this.compilerService.compilersByLang[this.currentLangId];
+ if (compilers) this.compiler = _.values(compilers)[0];
+ }
+ this.infoByLang = {};
+ this.deferCompiles = hub.deferred;
+ this.needsCompile = false;
+ this.options = state.options || options.compileOptions[this.currentLangId];
+ this.filters = new Toggles(this.domRoot.find('.filters'), patchOldFilters(state.filters));
+ this.source = '';
+ this.assembly = [];
+ this.colours = [];
+ this.lastResult = {};
+ this.pendingRequestSentAt = 0;
+ this.nextRequest = null;
+ this.optViewOpen = false;
+ this.cfgViewOpen = false;
+ this.wantOptInfo = state.wantOptInfo;
+ this.decorations = {};
+ this.prevDecorations = [];
+ this.optButton = this.domRoot.find('.btn.view-optimization');
+ this.astButton = this.domRoot.find('.btn.view-ast');
+ this.gccDumpButton = this.domRoot.find('.btn.view-gccdump');
+ this.cfgButton = this.domRoot.find('.btn.view-cfg');
+ this.libsButton = this.domRoot.find('.btn.show-libs');
+ this.compileTimeLabel = this.domRoot.find('.compile-time');
+ this.compileClearCache = this.domRoot.find('.clear-cache');
+
+ this.availableLibs = {};
+ this.updateAvailableLibs = function () {
+ if (!this.availableLibs[this.currentLangId]) {
+ this.availableLibs[this.currentLangId] = $.extend(true, {}, options.libs[this.currentLangId]);
}
+ };
+ this.updateAvailableLibs();
+ _.each(state.libs, _.bind(function (lib) {
+ if (this.availableLibs[this.currentLangId][lib.name] &&
+ this.availableLibs[this.currentLangId][lib.name].versions &&
+ this.availableLibs[this.currentLangId][lib.name].versions[lib.ver]) {
+ this.availableLibs[this.currentLangId][lib.name].versions[lib.ver].used = true;
+ }
+ }, this));
+
+ this.linkedFadeTimeoutId = -1;
+ this.getGroupsInUse = function () {
+ var currentLangCompilers = _.map(this.getCurrentLangCompilers(), _.identity, this);
+ return _.map(_.uniq(currentLangCompilers, false, function (compiler) {
+ return compiler.group;
+ }), function (compiler) {
+ return {value: compiler.group, label: compiler.groupName || compiler.group};
+ });
+ };
+
+ this.domRoot.find('.compiler-picker').selectize({
+ sortField: 'name',
+ valueField: 'id',
+ labelField: 'name',
+ searchField: ['name'],
+ optgroupField: 'group',
+ optgroups: this.getGroupsInUse(),
+ options: _.map(this.getCurrentLangCompilers(), _.identity, this),
+ items: this.compiler ? [this.compiler.id] : []
+ }).on('change', _.bind(function (e) {
+ var val = $(e.target).val();
+ if (val) {
+ ga('send', {
+ hitType: 'event',
+ eventCategory: 'SelectCompiler',
+ eventAction: val
+ });
+ this.onCompilerChange(val);
+ }
+ }, this));
+ var optionsChange = _.debounce(_.bind(function (e) {
+ this.onOptionsChange($(e.target).val());
+ }, this), 800);
+ this.optionsField = this.domRoot.find('.options');
+ this.optionsField
+ .val(this.options)
+ .on('change', optionsChange)
+ .on('keyup', optionsChange);
+
+ this.domRoot.find("[data-bind='execute']").toggle(options.supportsExecute);
+
+ this.outputEditor = monaco.editor.create(this.domRoot.find('.monaco-placeholder')[0], {
+ scrollBeyondLastLine: false,
+ readOnly: true,
+ language: 'asm',
+ fontFamily: '"Fira Mono", monospace',
+ glyphMargin: !options.embedded,
+ fixedOverflowWidgets: true,
+ minimap: {
+ maxColumn: 80
+ },
+ lineNumbersMinChars: options.embedded ? 1 : 5
+ });
+ this.outputEditor.addAction({
+ id: 'viewsource',
+ label: 'Scroll to source',
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10],
+ keybindingContext: null,
+ contextMenuGroupId: 'navigation',
+ contextMenuOrder: 1.5,
+ run: _.bind(function (ed) {
+ var desiredLine = ed.getPosition().lineNumber - 1;
+ var source = this.assembly[desiredLine].source;
+ if (source.file === null) {
+ // a null file means it was the user's source
+ this.eventHub.emit('editorSetDecoration', this.sourceEditorId, source.line, true);
+ } else {
+ // TODO: some indication this asm statement came from elsewhere
+ this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false);
+ }
+ }, this)
});
- function patchOldFilters(filters) {
- if (filters === undefined) return undefined;
- // Filters are of the form {filter: true|false¸ ...}. In older versions, we used
- // to suppress the {filter:false} form. This means we can't distinguish between
- // "filter not on" and "filter not present". In the latter case we want to default
- // the filter. In the former case we want the filter off. Filters now don't suppress
- // but there are plenty of permanlinks out there with no filters set at all. Here
- // we manually set any missing filters to 'false' to recover the old behaviour of
- // "if it's not here, it's off".
- _.each(['binary', 'labels', 'directives', 'commentOnly', 'trim', 'intel'], function (oldFilter) {
- if (filters[oldFilter] === undefined) filters[oldFilter] = false;
- });
- return filters;
- }
+ this.outputEditor.addAction({
+ id: 'viewasmdoc',
+ label: 'View asm doc',
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F8],
+ keybindingContext: null,
+ contextMenuGroupId: 'help',
+ contextMenuOrder: 1.5,
+ run: _.bind(this.onAsmToolTip, this)
+ });
- var languages = options.languages;
-
- function Compiler(hub, container, state) {
- this.container = container;
- this.eventHub = hub.createEventHub();
- this.compilerService = hub.compilerService;
- this.domRoot = container.getElement();
- this.domRoot.html($('#compiler').html());
- this.id = state.id || hub.nextCompilerId();
- this.sourceEditorId = state.source || 1;
- this.settings = JSON.parse(local.get('settings', '{}'));
- // If we don't have a language, but a compiler, find the corresponding language.
- this.currentLangId = state.lang;
- if (!this.currentLangId && state.compiler) {
- this.currentLangId = this.langOfCompiler(state.compiler);
- }
- if (!this.currentLangId && languages[this.settings.defaultLanguage]) {
- this.currentLangId = languages[this.settings.defaultLanguage].id;
- }
- if (!this.currentLangId) {
- this.currentLangId = _.keys(languages)[0];
- }
- this.originalCompilerId = state.compiler;
- if (state.compiler)
- this.compiler = this.findCompiler(this.currentLangId, state.compiler);
- else
- this.compiler = this.findCompiler(this.currentLangId, options.defaultCompiler[this.currentLangId]);
- if (!this.compiler) {
- var compilers = this.compilerService.compilersByLang[this.currentLangId];
- if (compilers) this.compiler = _.values(compilers)[0];
- }
- this.infoByLang = {};
- this.deferCompiles = hub.deferred;
- this.needsCompile = false;
- this.options = state.options || options.compileOptions[this.currentLangId];
- this.filters = new Toggles(this.domRoot.find('.filters'), patchOldFilters(state.filters));
- this.source = '';
- this.assembly = [];
- this.colours = [];
- this.lastResult = {};
- this.pendingRequestSentAt = 0;
- this.nextRequest = null;
- this.optViewOpen = false;
- this.cfgViewOpen = false;
- this.wantOptInfo = state.wantOptInfo;
- this.decorations = {};
- this.prevDecorations = [];
- this.optButton = this.domRoot.find('.btn.view-optimization');
- this.astButton = this.domRoot.find('.btn.view-ast');
- this.gccDumpButton = this.domRoot.find('.btn.view-gccdump');
- this.cfgButton = this.domRoot.find('.btn.view-cfg');
- this.libsButton = this.domRoot.find('.btn.show-libs');
- this.compileTimeLabel = this.domRoot.find('.compile-time');
- this.compileClearCache = this.domRoot.find('.clear-cache');
-
- this.availableLibs = {};
- this.updateAvailableLibs = function () {
- if (!this.availableLibs[this.currentLangId]) {
- this.availableLibs[this.currentLangId] = $.extend(true, {}, options.libs[this.currentLangId]);
- }
- };
- this.updateAvailableLibs();
- _.each(state.libs, _.bind(function (lib) {
- if (this.availableLibs[this.currentLangId][lib.name] &&
- this.availableLibs[this.currentLangId][lib.name].versions &&
- this.availableLibs[this.currentLangId][lib.name].versions[lib.ver]) {
- this.availableLibs[this.currentLangId][lib.name].versions[lib.ver].used = true;
- }
- }, this));
-
- this.linkedFadeTimeoutId = -1;
- this.getGroupsInUse = function () {
- var currentLangCompilers = _.map(this.getCurrentLangCompilers(), _.identity, this);
- return _.map(_.uniq(currentLangCompilers, false, function (compiler) {
- return compiler.group;
- }), function (compiler) {
- return {value: compiler.group, label: compiler.groupName || compiler.group};
+ this.outputEditor.addAction({
+ id: 'toggleColourisation',
+ label: 'Toggle colourisation',
+ keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F1],
+ keybindingContext: null,
+ run: _.bind(function () {
+ this.eventHub.emit('modifySettings', {
+ colouriseAsm: !this.settings.colouriseAsm
});
+ }, this)
+ });
+
+ var clearEditorsLinkedLines = _.bind(function () {
+ this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false);
+ }, this);
+
+ this.outputEditor.onMouseMove(_.bind(function (e) {
+ this.mouseMoveThrottledFunction(e);
+ if (this.linkedFadeTimeoutId !== -1) {
+ clearTimeout(this.linkedFadeTimeoutId);
+ this.linkedFadeTimeoutId = -1;
+ }
+ }, this));
+
+ this.mouseMoveThrottledFunction = _.throttle(_.bind(this.onMouseMove, this), 250);
+
+ this.outputEditor.onMouseLeave(_.bind(function () {
+ this.linkedFadeTimeoutId = setTimeout(_.bind(function () {
+ clearEditorsLinkedLines();
+ this.linkedFadeTimeoutId = -1;
+ }, this), 5000);
+ }, this));
+
+ this.fontScale = new FontScale(this.domRoot, state, this.outputEditor);
+ this.fontScale.on('change', _.bind(function () {
+ this.saveState();
+ this.updateFontScale();
+ }, this));
+
+ this.filters.on('change', _.bind(this.onFilterChange, this));
+
+ container.on('destroy', this.close, this);
+ container.on('resize', this.resize, this);
+ container.on('shown', this.resize, this);
+ container.on('open', function () {
+ this.eventHub.emit('compilerOpen', this.id, this.sourceEditorId);
+ this.updateFontScale();
+ }, this);
+ this.eventHub.on('editorChange', this.onEditorChange, this);
+ this.eventHub.on('editorClose', this.onEditorClose, this);
+ this.eventHub.on('colours', this.onColours, this);
+ this.eventHub.on('resendCompilation', this.onResendCompilation, this);
+ this.eventHub.on('findCompilers', this.sendCompiler, this);
+ this.eventHub.on('compilerSetDecorations', this.onCompilerSetDecorations, this);
+ this.eventHub.on('settingsChange', this.onSettingsChange, this);
+
+ this.eventHub.on('optViewOpened', this.onOptViewOpened, this);
+ this.eventHub.on('optViewClosed', this.onOptViewClosed, this);
+ this.eventHub.on('astViewOpened', this.onAstViewOpened, this);
+ this.eventHub.on('astViewClosed', this.onAstViewClosed, this);
+
+ this.eventHub.on('gccDumpPassSelected', this.onGccDumpPassSelected, this);
+ this.eventHub.on('gccDumpFiltersChanged', this.onGccDumpFiltersChanged, this);
+ this.eventHub.on('gccDumpViewOpened', this.onGccDumpViewOpened, this);
+ this.eventHub.on('gccDumpViewClosed', this.onGccDumpViewClosed, this);
+ this.eventHub.on('gccDumpUIInit', this.onGccDumpUIInit, this);
+
+ this.eventHub.on('cfgViewOpened', this.onCfgViewOpened, this);
+ this.eventHub.on('cfgViewClosed', this.onCfgViewClosed, this);
+ this.eventHub.on('resize', this.resize, this);
+ this.eventHub.on('requestFilters', function (id) {
+ if (id === this.id) {
+ this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters());
+ }
+ }, this);
+ this.eventHub.on('requestCompiler', function (id) {
+ if (id === this.id) {
+ this.sendCompiler();
+ }
+ }, this);
+ this.eventHub.on('languageChange', this.onLanguageChange, this);
+ this.onSettingsChange(this.settings);
+ this.sendCompiler();
+ this.updateCompilerName();
+ this.updateButtons();
+
+ var outputConfig = _.bind(function () {
+ return Components.getOutput(this.id, this.sourceEditorId);
+ }, this);
+
+ this.container.layoutManager.createDragSource(this.domRoot.find('.status').parent(), outputConfig);
+ this.domRoot.find('.status').parent().click(_.bind(function () {
+ var insertPoint = hub.findParentRowOrColumn(this.container) ||
+ this.container.layoutManager.root.contentItems[0];
+ insertPoint.addChild(outputConfig);
+ }, this));
+
+ var cloneComponent = _.bind(function () {
+ return {
+ type: 'component',
+ componentName: 'compiler',
+ componentState: this.currentState()
};
+ }, this);
- this.domRoot.find('.compiler-picker').selectize({
- sortField: 'name',
- valueField: 'id',
- labelField: 'name',
- searchField: ['name'],
- optgroupField: 'group',
- optgroups: this.getGroupsInUse(),
- options: _.map(this.getCurrentLangCompilers(), _.identity, this),
- items: this.compiler ? [this.compiler.id] : []
- }).on('change', _.bind(function (e) {
- var val = $(e.target).val();
- if (val) {
- ga('send', {
- hitType: 'event',
- eventCategory: 'SelectCompiler',
- eventAction: val
- });
- this.onCompilerChange(val);
- }
- }, this));
- var optionsChange = _.debounce(_.bind(function (e) {
- this.onOptionsChange($(e.target).val());
- }, this), 800);
- this.optionsField = this.domRoot.find('.options');
- this.optionsField
- .val(this.options)
- .on('change', optionsChange)
- .on('keyup', optionsChange);
+ var createOptView = _.bind(function () {
+ return Components.getOptViewWith(this.id, this.source, this.lastResult.optOutput, this.getCompilerName(), this.sourceEditorId);
+ }, this);
- this.domRoot.find("[data-bind='execute']").toggle(options.supportsExecute);
+ var createAstView = _.bind(function () {
+ return Components.getAstViewWith(this.id, this.source, this.lastResult.astOutput, this.getCompilerName(), this.sourceEditorId);
+ }, this);
- this.outputEditor = monaco.editor.create(this.domRoot.find('.monaco-placeholder')[0], {
- scrollBeyondLastLine: false,
- readOnly: true,
- language: 'asm',
- fontFamily: '"Fira Mono", monospace',
- glyphMargin: !options.embedded,
- fixedOverflowWidgets: true,
- minimap: {
- maxColumn: 80
+ var createGccDumpView = _.bind(function () {
+ return Components.getGccDumpViewWith(this.id, this.getCompilerName(), this.sourceEditorId, this.lastResult.gccDumpOutput);
+ }, this);
+
+ var createCfgView = _.bind(function () {
+ return Components.getCfgViewWith(this.id, this.sourceEditorId);
+ }, this);
+
+ var panerDropdown = this.domRoot.find('.pane-dropdown');
+ var togglePannerAdder = function () {
+ panerDropdown.dropdown('toggle');
+ };
+
+ this.container.layoutManager
+ .createDragSource(this.domRoot.find('.btn.add-compiler'), cloneComponent)
+ ._dragListener.on('dragStart', togglePannerAdder);
+
+ this.domRoot.find('.btn.add-compiler').click(_.bind(function () {
+ var insertPoint = hub.findParentRowOrColumn(this.container) ||
+ this.container.layoutManager.root.contentItems[0];
+ insertPoint.addChild(cloneComponent);
+ }, this));
+
+ this.container.layoutManager
+ .createDragSource(this.optButton, createOptView)
+ ._dragListener.on('dragStart', togglePannerAdder);
+
+ this.optButton.click(_.bind(function () {
+ var insertPoint = hub.findParentRowOrColumn(this.container) ||
+ this.container.layoutManager.root.contentItems[0];
+ insertPoint.addChild(createOptView);
+ }, this));
+
+ this.container.layoutManager
+ .createDragSource(this.astButton, createAstView)
+ ._dragListener.on('dragStart', togglePannerAdder);
+
+ this.astButton.click(_.bind(function () {
+ var insertPoint = hub.findParentRowOrColumn(this.container) ||
+ this.container.layoutManager.root.contentItems[0];
+ insertPoint.addChild(createAstView);
+ }, this));
+
+ this.container.layoutManager
+ .createDragSource(this.gccDumpButton, createGccDumpView)
+ ._dragListener.on('dragStart', togglePannerAdder);
+
+ this.gccDumpButton.click(_.bind(function () {
+ var insertPoint = hub.findParentRowOrColumn(this.container) ||
+ this.container.layoutManager.root.contentItems[0];
+ insertPoint.addChild(createGccDumpView);
+ }, this));
+
+ this.container.layoutManager
+ .createDragSource(this.cfgButton, createCfgView)
+ ._dragListener.on('dragStart', togglePannerAdder);
+
+ this.cfgButton.click(_.bind(function () {
+ var insertPoint = hub.findParentRowOrColumn(this.container) ||
+ this.container.layoutManager.root.contentItems[0];
+ insertPoint.addChild(createCfgView);
+ }, this));
+
+ this.updateLibsDropdown();
+
+ this.compileClearCache.on('click', _.bind(function () {
+ this.compilerService.cache.reset();
+ this.compile();
+ }, this));
+
+ // Dismiss the popover on escape.
+ $(document).on('keyup.editable', _.bind(function (e) {
+ if (e.which === 27) {
+ this.libsButton.popover('hide');
+ }
+ }, this));
+
+ // Dismiss on any click that isn't either in the opening element, inside
+ // the popover or on any alert
+ $(document).on('click', _.bind(function (e) {
+ var elem = this.libsButton;
+ var target = $(e.target);
+ if (!target.is(elem) && elem.has(target).length === 0 && target.closest('.popover').length === 0) {
+ elem.popover('hide');
+ }
+ }, this));
+
+ this.onSettingsChange(this.settings);
+ this.eventHub.on('initialised', this.undefer, this);
+
+ this.saveState();
+}
+
+Compiler.prototype.close = function () {
+ this.eventHub.unsubscribe();
+ this.eventHub.emit('compilerClose', this.id);
+ this.outputEditor.dispose();
+};
+
+Compiler.prototype.undefer = function () {
+ this.deferCompiles = false;
+ if (this.needsCompile) this.compile();
+};
+
+// TODO: need to call resize if either .top-bar or .bottom-bar resizes, which needs some work.
+// Issue manifests if you make a window where one compiler is small enough that the buttons spill onto two lines:
+// reload the page and the bottom-bar is off the bottom until you scroll a tiny bit.
+Compiler.prototype.resize = function () {
+ var topBarHeight = this.domRoot.find('.top-bar').outerHeight(true);
+ var bottomBarHeight = this.domRoot.find('.bottom-bar').outerHeight(true);
+ this.outputEditor.layout({
+ width: this.domRoot.width(),
+ height: this.domRoot.height() - topBarHeight - bottomBarHeight
+ });
+};
+
+// Gets the filters that will actually be used (accounting for issues with binary
+// mode etc).
+Compiler.prototype.getEffectiveFilters = function () {
+ if (!this.compiler) return {};
+ var filters = this.filters.get();
+ if (filters.binary && !this.compiler.supportsBinary) {
+ delete filters.binary;
+ }
+ if (filters.execute && !this.compiler.supportsExecute) {
+ delete filters.execute;
+ }
+ return filters;
+};
+
+Compiler.prototype.compile = function () {
+ if (this.deferCompiles) {
+ this.needsCompile = true;
+ return;
+ }
+ this.needsCompile = false;
+ var options = {
+ userArguments: this.options,
+ compilerOptions: {
+ produceAst: this.astViewOpen,
+ produceGccDump: {
+ opened: this.gccDumpViewOpen,
+ pass: this.gccDumpPassSelected,
+ treeDump: this.treeDumpEnabled,
+ rtlDump: this.rtlDumpEnabled
},
- lineNumbersMinChars: options.embedded ? 1 : 5
- });
- this.outputEditor.addAction({
- id: 'viewsource',
- label: 'Scroll to source',
- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F10],
- keybindingContext: null,
- contextMenuGroupId: 'navigation',
- contextMenuOrder: 1.5,
- run: _.bind(function (ed) {
- var desiredLine = ed.getPosition().lineNumber - 1;
- var source = this.assembly[desiredLine].source;
- if (source.file === null) {
- // a null file means it was the user's source
- this.eventHub.emit('editorSetDecoration', this.sourceEditorId, source.line, true);
- } else {
- // TODO: some indication this asm statement came from elsewhere
- this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false);
- }
- }, this)
- });
-
- this.outputEditor.addAction({
- id: 'viewasmdoc',
- label: 'View asm doc',
- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F8],
- keybindingContext: null,
- contextMenuGroupId: 'help',
- contextMenuOrder: 1.5,
- run: _.bind(this.onAsmToolTip, this)
- });
-
- this.outputEditor.addAction({
- id: 'toggleColourisation',
- label: 'Toggle colourisation',
- keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.F1],
- keybindingContext: null,
- run: _.bind(function () {
- this.eventHub.emit('modifySettings', {
- colouriseAsm: !this.settings.colouriseAsm
+ produceOptInfo: this.wantOptInfo,
+ produceCfg: this.cfgViewOpen
+ },
+ filters: this.getEffectiveFilters()
+ };
+ _.each(this.availableLibs[this.currentLangId], function (lib) {
+ _.each(lib.versions, function (version) {
+ if (version.used) {
+ _.each(version.path, function (path) {
+ options.userArguments += ' -I' + path;
});
- }, this)
+ }
});
-
- var clearEditorsLinkedLines = _.bind(function () {
- this.eventHub.emit('editorSetDecoration', this.sourceEditorId, -1, false);
- }, this);
-
- this.outputEditor.onMouseMove(_.bind(function (e) {
- this.mouseMoveThrottledFunction(e);
- if (this.linkedFadeTimeoutId !== -1) {
- clearTimeout(this.linkedFadeTimeoutId);
- this.linkedFadeTimeoutId = -1;
- }
- }, this));
-
- this.mouseMoveThrottledFunction = _.throttle(_.bind(this.onMouseMove, this), 250);
-
- this.outputEditor.onMouseLeave(_.bind(function () {
- this.linkedFadeTimeoutId = setTimeout(_.bind(function () {
- clearEditorsLinkedLines();
- this.linkedFadeTimeoutId = -1;
- }, this), 5000);
- }, this));
-
- this.fontScale = new FontScale(this.domRoot, state, this.outputEditor);
- this.fontScale.on('change', _.bind(function () {
- this.saveState();
- this.updateFontScale();
- }, this));
-
- this.filters.on('change', _.bind(this.onFilterChange, this));
-
- container.on('destroy', this.close, this);
- container.on('resize', this.resize, this);
- container.on('shown', this.resize, this);
- container.on('open', function () {
- this.eventHub.emit('compilerOpen', this.id, this.sourceEditorId);
- this.updateFontScale();
- }, this);
- this.eventHub.on('editorChange', this.onEditorChange, this);
- this.eventHub.on('editorClose', this.onEditorClose, this);
- this.eventHub.on('colours', this.onColours, this);
- this.eventHub.on('resendCompilation', this.onResendCompilation, this);
- this.eventHub.on('findCompilers', this.sendCompiler, this);
- this.eventHub.on('compilerSetDecorations', this.onCompilerSetDecorations, this);
- this.eventHub.on('settingsChange', this.onSettingsChange, this);
-
- this.eventHub.on('optViewOpened', this.onOptViewOpened, this);
- this.eventHub.on('optViewClosed', this.onOptViewClosed, this);
- this.eventHub.on('astViewOpened', this.onAstViewOpened, this);
- this.eventHub.on('astViewClosed', this.onAstViewClosed, this);
-
- this.eventHub.on('gccDumpPassSelected', this.onGccDumpPassSelected, this);
- this.eventHub.on('gccDumpFiltersChanged', this.onGccDumpFiltersChanged, this);
- this.eventHub.on('gccDumpViewOpened', this.onGccDumpViewOpened, this);
- this.eventHub.on('gccDumpViewClosed', this.onGccDumpViewClosed, this);
- this.eventHub.on('gccDumpUIInit', this.onGccDumpUIInit, this);
-
- this.eventHub.on('cfgViewOpened', this.onCfgViewOpened, this);
- this.eventHub.on('cfgViewClosed', this.onCfgViewClosed, this);
- this.eventHub.on('resize', this.resize, this);
- this.eventHub.on('requestFilters', function (id) {
- if (id === this.id) {
- this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters());
- }
- }, this);
- this.eventHub.on('requestCompiler', function (id) {
- if (id === this.id) {
- this.sendCompiler();
- }
- }, this);
- this.eventHub.on('languageChange', this.onLanguageChange, this);
- this.onSettingsChange(this.settings);
- this.sendCompiler();
- this.updateCompilerName();
- this.updateButtons();
-
- var outputConfig = _.bind(function () {
- return Components.getOutput(this.id, this.sourceEditorId);
- }, this);
-
- this.container.layoutManager.createDragSource(this.domRoot.find('.status').parent(), outputConfig);
- this.domRoot.find('.status').parent().click(_.bind(function () {
- var insertPoint = hub.findParentRowOrColumn(this.container) ||
- this.container.layoutManager.root.contentItems[0];
- insertPoint.addChild(outputConfig);
- }, this));
-
- var cloneComponent = _.bind(function () {
- return {
- type: 'component',
- componentName: 'compiler',
- componentState: this.currentState()
- };
- }, this);
-
- var createOptView = _.bind(function () {
- return Components.getOptViewWith(this.id, this.source, this.lastResult.optOutput, this.getCompilerName(), this.sourceEditorId);
- }, this);
-
- var createAstView = _.bind(function () {
- return Components.getAstViewWith(this.id, this.source, this.lastResult.astOutput, this.getCompilerName(), this.sourceEditorId);
- }, this);
-
- var createGccDumpView = _.bind(function () {
- return Components.getGccDumpViewWith(this.id, this.getCompilerName(), this.sourceEditorId, this.lastResult.gccDumpOutput);
- }, this);
-
- var createCfgView = _.bind(function () {
- return Components.getCfgViewWith(this.id, this.sourceEditorId);
- }, this);
-
- var panerDropdown = this.domRoot.find('.pane-dropdown');
- var togglePannerAdder = function () {
- panerDropdown.dropdown('toggle');
- };
-
- this.container.layoutManager
- .createDragSource(this.domRoot.find('.btn.add-compiler'), cloneComponent)
- ._dragListener.on('dragStart', togglePannerAdder);
-
- this.domRoot.find('.btn.add-compiler').click(_.bind(function () {
- var insertPoint = hub.findParentRowOrColumn(this.container) ||
- this.container.layoutManager.root.contentItems[0];
- insertPoint.addChild(cloneComponent);
- }, this));
-
- this.container.layoutManager
- .createDragSource(this.optButton, createOptView)
- ._dragListener.on('dragStart', togglePannerAdder);
-
- this.optButton.click(_.bind(function () {
- var insertPoint = hub.findParentRowOrColumn(this.container) ||
- this.container.layoutManager.root.contentItems[0];
- insertPoint.addChild(createOptView);
- }, this));
-
- this.container.layoutManager
- .createDragSource(this.astButton, createAstView)
- ._dragListener.on('dragStart', togglePannerAdder);
-
- this.astButton.click(_.bind(function () {
- var insertPoint = hub.findParentRowOrColumn(this.container) ||
- this.container.layoutManager.root.contentItems[0];
- insertPoint.addChild(createAstView);
- }, this));
-
- this.container.layoutManager
- .createDragSource(this.gccDumpButton, createGccDumpView)
- ._dragListener.on('dragStart', togglePannerAdder);
-
- this.gccDumpButton.click(_.bind(function () {
- var insertPoint = hub.findParentRowOrColumn(this.container) ||
- this.container.layoutManager.root.contentItems[0];
- insertPoint.addChild(createGccDumpView);
- }, this));
-
- this.container.layoutManager
- .createDragSource(this.cfgButton, createCfgView)
- ._dragListener.on('dragStart', togglePannerAdder);
-
- this.cfgButton.click(_.bind(function () {
- var insertPoint = hub.findParentRowOrColumn(this.container) ||
- this.container.layoutManager.root.contentItems[0];
- insertPoint.addChild(createCfgView);
- }, this));
-
- this.updateLibsDropdown();
-
- this.compileClearCache.on('click', _.bind(function () {
- this.compilerService.cache.reset();
- this.compile();
- }, this));
-
- // Dismiss the popover on escape.
- $(document).on('keyup.editable', _.bind(function (e) {
- if (e.which === 27) {
- this.libsButton.popover('hide');
- }
- }, this));
-
- // Dismiss on any click that isn't either in the opening element, inside
- // the popover or on any alert
- $(document).on('click', _.bind(function (e) {
- var elem = this.libsButton;
- var target = $(e.target);
- if (!target.is(elem) && elem.has(target).length === 0 && target.closest('.popover').length === 0) {
- elem.popover('hide');
- }
- }, this));
-
- this.onSettingsChange(this.settings);
- this.eventHub.on('initialised', this.undefer, this);
-
- this.saveState();
- }
-
- Compiler.prototype.close = function () {
- this.eventHub.unsubscribe();
- this.eventHub.emit('compilerClose', this.id);
- this.outputEditor.dispose();
- };
-
- Compiler.prototype.undefer = function () {
- this.deferCompiles = false;
- if (this.needsCompile) this.compile();
- };
-
- // TODO: need to call resize if either .top-bar or .bottom-bar resizes, which needs some work.
- // Issue manifests if you make a window where one compiler is small enough that the buttons spill onto two lines:
- // reload the page and the bottom-bar is off the bottom until you scroll a tiny bit.
- Compiler.prototype.resize = function () {
- var topBarHeight = this.domRoot.find('.top-bar').outerHeight(true);
- var bottomBarHeight = this.domRoot.find('.bottom-bar').outerHeight(true);
- this.outputEditor.layout({
- width: this.domRoot.width(),
- height: this.domRoot.height() - topBarHeight - bottomBarHeight
- });
- };
-
- // Gets the filters that will actually be used (accounting for issues with binary
- // mode etc).
- Compiler.prototype.getEffectiveFilters = function () {
- if (!this.compiler) return {};
- var filters = this.filters.get();
- if (filters.binary && !this.compiler.supportsBinary) {
- delete filters.binary;
- }
- if (filters.execute && !this.compiler.supportsExecute) {
- delete filters.execute;
- }
- return filters;
- };
-
- Compiler.prototype.compile = function () {
- if (this.deferCompiles) {
- this.needsCompile = true;
- return;
- }
- this.needsCompile = false;
- var options = {
- userArguments: this.options,
- compilerOptions: {
- produceAst: this.astViewOpen,
- produceGccDump: {
- opened: this.gccDumpViewOpen,
- pass: this.gccDumpPassSelected,
- treeDump: this.treeDumpEnabled,
- rtlDump: this.rtlDumpEnabled
- },
- produceOptInfo: this.wantOptInfo,
- produceCfg: this.cfgViewOpen
- },
- filters: this.getEffectiveFilters()
- };
- _.each(this.availableLibs[this.currentLangId], function (lib) {
- _.each(lib.versions, function (version) {
- if (version.used) {
- _.each(version.path, function (path) {
- options.userArguments += ' -I' + path;
- });
- }
- });
- });
- this.compilerService.expand(this.source).then(_.bind(function (expanded) {
- var request = {
- source: expanded || '',
- compiler: this.compiler ? this.compiler.id : '',
- options: options,
- lang: this.currentLangId
- };
- if (!this.compiler) {
- this.onCompileResponse(request, errorResult(''), false);
- } else {
- this.sendCompile(request);
- }
- }, this));
- };
-
- Compiler.prototype.sendCompile = function (request) {
- var onCompilerResponse = _.bind(this.onCompileResponse, this);
-
- if (this.pendingRequestSentAt) {
- // If we have a request pending, then just store this request to do once the
- // previous request completes.
- this.nextRequest = request;
- return;
- }
- this.eventHub.emit('compiling', this.id, this.compiler);
- this.pendingRequestSentAt = Date.now();
- // After a short delay, give the user some indication that we're working on their
- // compilation.
- var progress = setTimeout(_.bind(function () {
- this.setAssembly(fakeAsm(''));
- }, this), 500);
- this.compilerService.submit(request)
- .then(function (x) {
- clearTimeout(progress);
- onCompilerResponse(request, x.result, x.localCacheHit);
- })
- .catch(function (x) {
- clearTimeout(progress);
- onCompilerResponse(request, errorResult(''), false);
- });
- };
-
- Compiler.prototype.getBinaryForLine = function (line) {
- var obj = this.assembly[line - 1];
- if (!obj) return '
????
????
';
- var address = obj.address ? obj.address.toString(16) : '';
- var opcodes = '
';
- _.each(obj.opcodes, function (op) {
- opcodes += ('' + op + '');
- });
- return '
' + address + '
' + opcodes + '
';
- };
-
- // TODO: use ContentWidgets? OverlayWidgets?
- // Use highlight providers? hover providers? highlight providers?
- Compiler.prototype.setAssembly = function (assembly) {
- this.assembly = assembly;
- if (this.outputEditor.getModel()) {
- this.outputEditor.getModel().setValue(_.pluck(assembly, 'text').join('\n'));
- var addrToAddrDiv = {};
- var decorations = [];
- _.each(this.assembly, _.bind(function (obj, line) {
- var address = obj.address ? obj.address.toString(16) : '';
- // var div = $("
" + address + "
");
- addrToAddrDiv[address] = {div: 'moo', line: line};
- }, this));
-
- _.each(this.assembly, _.bind(function (obj, line) {
- if (obj.links) {
- _.each(obj.links, _.bind(function (link) {
- var address = link.to.toString(16);
- // var thing = $("" + address + "");
- // this.outputEditor.markText(
- // from, to, {replacedWith: thing[0], handleMouseEvents: false});
- var dest = addrToAddrDiv[address];
- if (dest) {
- decorations.push({
- range: new monaco.Range(line, link.offset, line, link.offset + link.length),
- options: {}
- });
- // var editor = this.outputEditor;
- // thing.hover(function (e) {
- // var entered = e.type == "mouseenter";
- // dest.div.toggleClass("highlighted", entered);
- // thing.toggleClass("highlighted", entered);
- // });
- // thing.on('click', function (e) {
- // editor.scrollIntoView({line: dest.line, ch: 0}, 30);
- // dest.div.toggleClass("highlighted", false);
- // thing.toggleClass("highlighted", false);
- // e.preventDefault();
- // });
- }
- }, this));
- }
- }, this));
- }
- };
-
- function errorResult(text) {
- return {asm: fakeAsm(text), code: -1, stdout: '', stderr: ''};
- }
-
- function fakeAsm(text) {
- return [{text: text, source: null, fake: true}];
- }
-
- Compiler.prototype.onCompileResponse = function (request, result, cached) {
- // Delete trailing empty lines
- if ($.isArray(result.asm)) {
- var cutCount = 0;
- for (var i = result.asm.length - 1; i >= 0; i--) {
- if (result.asm[i].text) {
- break;
- }
- cutCount++;
- }
- result.asm.splice(result.asm.length - cutCount, cutCount);
- }
- this.lastResult = result;
- var timeTaken = Math.max(0, Date.now() - this.pendingRequestSentAt);
- var wasRealReply = this.pendingRequestSentAt > 0;
- this.pendingRequestSentAt = 0;
- ga('send', {
- hitType: 'event',
- eventCategory: 'Compile',
- eventAction: request.compiler,
- eventLabel: request.options.userArguments,
- eventValue: cached ? 1 : 0
- });
- ga('send', {
- hitType: 'timing',
- timingCategory: 'Compile',
- timingVar: request.compiler,
- timingValue: timeTaken
- });
- this.setAssembly(result.asm || fakeAsm(''));
- if (request.options.filters.binary) {
- this.outputEditor.updateOptions({
- lineNumbers: _.bind(this.getBinaryForLine, this),
- // Until something comes out of Microsoft/monaco-editor/issues/515, this gets clamped to ten
- lineNumbersMinChars: 25,
- glyphMargin: false
- });
- } else {
- this.outputEditor.updateOptions({
- lineNumbers: true,
- lineNumbersMinChars: options.embedded ? 1 : 5,
- glyphMargin: true
- });
- }
- var status = this.domRoot.find('.status');
- var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join('\n');
- var failed = result.code !== 0;
- var warns = !failed && !!allText;
- status.toggleClass('error', failed);
- status.toggleClass('warning', warns);
- status.parent().attr('title', allText);
- if (cached) {
- this.compileTimeLabel.text(' - cached');
- } else if (wasRealReply) {
- this.compileTimeLabel.text(' - ' + timeTaken + 'ms');
- } else {
- this.compileTimeLabel.text('');
- }
- this.eventHub.emit('compileResult', this.id, this.compiler, result);
- this.updateButtons();
-
- if (this.nextRequest) {
- var next = this.nextRequest;
- this.nextRequest = null;
- this.sendCompile(next);
- }
- };
-
- Compiler.prototype.onEditorChange = function (editor, source, langId, compilerId) {
- if (editor === this.sourceEditorId && langId === this.currentLangId && (compilerId === undefined || compilerId === this.id)) {
- this.source = source;
- this.compile();
- }
- };
-
- Compiler.prototype.onOptViewClosed = function (id) {
- if (this.id == id) {
- this.wantOptInfo = false;
- this.optViewOpen = false;
- this.optButton.prop('disabled', this.optViewOpen);
- }
- };
-
- Compiler.prototype.onAstViewOpened = function (id) {
- if (this.id == id) {
- this.astButton.prop('disabled', true);
- this.astViewOpen = true;
- this.compile();
- }
- };
-
- Compiler.prototype.onAstViewClosed = function (id) {
- if (this.id === id) {
- this.astButton.prop('disabled', false);
- this.astViewOpen = false;
- }
- };
-
- Compiler.prototype.onGccDumpUIInit = function (id) {
- if (this.id === id) {
- this.compile();
- }
- };
-
- Compiler.prototype.onGccDumpFiltersChanged = function (id, filters, reqCompile) {
- if (this.id === id) {
- this.treeDumpEnabled = (filters.treeDump !== false);
- this.rtlDumpEnabled = (filters.rtlDump !== false);
-
- if (reqCompile) {
- this.compile();
- }
- }
- };
-
- Compiler.prototype.onGccDumpPassSelected = function (id, passId, reqCompile) {
- if (this.id === id) {
- this.gccDumpPassSelected = passId;
-
- if (reqCompile && passId !== '') {
- this.compile();
- }
- }
- };
-
- Compiler.prototype.onGccDumpViewOpened = function (id) {
- if (this.id === id) {
- this.gccDumpButton.prop('disabled', true);
- this.gccDumpViewOpen = true;
- }
- };
-
- Compiler.prototype.onGccDumpViewClosed = function (id) {
- if (this.id === id) {
- this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump);
- this.gccDumpViewOpen = false;
-
- delete this.gccDumpPassSelected;
- delete this.treeDumpEnabled;
- delete this.rtlDumpEnabled;
- }
- };
-
- Compiler.prototype.onOptViewOpened = function (id) {
- if (this.id === id) {
- this.optViewOpen = true;
- this.wantOptInfo = true;
- this.optButton.prop('disabled', this.optViewOpen);
- this.compile();
- }
- };
-
- Compiler.prototype.onCfgViewOpened = function (id) {
- if (this.id == id) {
- this.cfgButton.prop('disabled', true);
- this.cfgViewOpen = true;
- this.compile();
- }
- };
-
- Compiler.prototype.onCfgViewClosed = function (id) {
- if (this.id === id) {
- this.cfgViewOpen = false;
- this.cfgButton.prop('disabled', this.getEffectiveFilters().binary);
- }
- };
-
-
- Compiler.prototype.updateButtons = function () {
- if (!this.compiler) return;
- var filters = this.getEffectiveFilters();
- // We can support intel output if the compiler supports it, or if we're compiling
- // to binary (as we can disassemble it however we like).
- var intelAsm = this.compiler.supportsIntel || filters.binary;
- this.domRoot.find("[data-bind='intel']").prop('disabled', !intelAsm);
- // Disable binary support on compilers that don't work with it.
- this.domRoot.find("[data-bind='binary']").prop('disabled', !this.compiler.supportsBinary);
- this.domRoot.find("[data-bind='execute']").prop('disabled', !this.compiler.supportsExecute);
- // Disable demangle for compilers where we can't access it
- this.domRoot.find("[data-bind='demangle']").prop('disabled', !this.compiler.demangler);
- // Disable any of the options which don't make sense in binary mode.
- var filtersDisabled = !!filters.binary && !this.compiler.supportsFiltersInBinary;
- this.domRoot.find('.nonbinary').prop('disabled', filtersDisabled);
- // If its already open, we should turn the it off.
- // The pane will update with error text
- // Other wise we just disable the button.
- if (!this.optViewOpen) {
- this.optButton.prop('disabled', !this.compiler.supportsOptOutput);
- } else {
- this.optButton.prop('disabled', true);
- }
-
- if (!this.cfgViewOpen) {
- this.cfgButton.prop('disabled', !this.compiler.supportsCfg);
- } else {
- this.cfgButton.prop('disabled', true);
- }
-
- if (!this.gccDumpViewOpen) {
- this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump);
- } else {
- this.gccDumpButton.prop('disabled', true);
- }
- };
-
- Compiler.prototype.onOptionsChange = function (options) {
- this.options = options;
- this.saveState();
- this.compile();
- this.updateButtons();
- this.sendCompiler();
- };
-
- Compiler.prototype.onCompilerChange = function (value) {
- this.compiler = this.compilerService.findCompiler(this.currentLangId, value);
- this.saveState();
- this.compile();
- this.updateButtons();
- this.updateCompilerName();
- this.sendCompiler();
- };
-
- Compiler.prototype.sendCompiler = function () {
- this.eventHub.emit('compiler', this.id, this.compiler, this.options, this.sourceEditorId);
- };
-
- Compiler.prototype.onEditorClose = function (editor) {
- if (editor === this.sourceEditorId) {
- // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
- // the hierarchy. We can't modify while it's being iterated over.
- this.close();
- _.defer(function (self) {
- self.container.close();
- }, this);
- }
- };
-
- Compiler.prototype.onFilterChange = function () {
- this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters());
- this.saveState();
- this.compile();
- this.updateButtons();
- };
-
- Compiler.prototype.currentState = function () {
- var libs = [];
- _.each(this.availableLibs[this.currentLangId], function (library, name) {
- _.each(library.versions, function (version, ver) {
- if (library.versions[ver].used) {
- libs.push({name: name, ver: ver});
- }
- });
- });
- var state = {
+ });
+ this.compilerService.expand(this.source).then(_.bind(function (expanded) {
+ var request = {
+ source: expanded || '',
compiler: this.compiler ? this.compiler.id : '',
- source: this.sourceEditorId,
- options: this.options,
- // NB must *not* be effective filters
- filters: this.filters.get(),
- wantOptInfo: this.wantOptInfo,
- libs: libs,
+ options: options,
lang: this.currentLangId
};
- this.fontScale.addState(state);
- return state;
- };
-
- Compiler.prototype.saveState = function () {
- this.container.setState(this.currentState());
- };
-
- Compiler.prototype.updateFontScale = function () {
- this.eventHub.emit('compilerFontScale', this.id, this.fontScale.scale);
- };
-
- Compiler.prototype.onColours = function (editor, colours, scheme) {
- if (editor == this.sourceEditorId) {
- var asmColours = {};
- _.each(this.assembly, function (x, index) {
- if (x.source && x.source.file === null) {
- asmColours[index] = colours[x.source.line - 1];
- }
- });
- this.colours = colour.applyColours(this.outputEditor, asmColours, scheme, this.colours);
+ if (!this.compiler) {
+ this.onCompileResponse(request, errorResult(''), false);
+ } else {
+ this.sendCompile(request);
}
- };
+ }, this));
+};
- Compiler.prototype.getCompilerName = function () {
- return this.compiler ? this.compiler.name : 'no compiler set';
- };
+Compiler.prototype.sendCompile = function (request) {
+ var onCompilerResponse = _.bind(this.onCompileResponse, this);
- Compiler.prototype.updateCompilerName = function () {
- var langName = options.languages[this.currentLangId].name;
- var compilerName = this.getCompilerName();
- var compilerVersion = this.compiler ? this.compiler.version : '';
- this.container.setTitle(compilerName + ' (Editor #' + this.sourceEditorId + ', Compiler #' + this.id + ') ' + langName);
- this.domRoot.find('.full-compiler-name').text(compilerVersion);
- };
-
- Compiler.prototype.onResendCompilation = function (id) {
- if (id === this.id && !$.isEmptyObject(this.lastResult)) {
- this.eventHub.emit('compileResult', this.id, this.compiler, this.lastResult);
- }
- };
-
- Compiler.prototype.updateDecorations = function () {
- this.prevDecorations = this.outputEditor.deltaDecorations(
- this.prevDecorations, _.flatten(_.values(this.decorations), true));
- };
-
- Compiler.prototype.onCompilerSetDecorations = function (id, lineNums, revealLine) {
- if (id == this.id) {
- if (revealLine && lineNums[0])
- this.outputEditor.revealLineInCenter(lineNums[0]);
- this.decorations.linkedCode = _.map(lineNums, function (line) {
- return {
- range: new monaco.Range(line, 1, line, 1),
- options: {
- isWholeLine: true,
- linesDecorationsClassName: 'linked-code-decoration-margin',
- inlineClassName: 'linked-code-decoration-inline'
- }
- };
- });
- this.updateDecorations();
- }
- };
-
- Compiler.prototype.onSettingsChange = function (newSettings) {
- var before = this.settings;
- this.settings = _.clone(newSettings);
- if (!before.lastHoverShowSource && this.settings.hoverShowSource) {
- this.onCompilerSetDecorations(this.id, []);
- }
- this.outputEditor.updateOptions({
- contextmenu: this.settings.useCustomContextMenu,
- minimap: {
- enabled: this.settings.showMinimap && !options.embedded
- }
- });
- };
-
- var hexLike = /^(#?[$]|0x)([0-9a-fA-F]+)$/;
- var hexLike2 = /^(#?)([0-9a-fA-F]+)H$/;
- var decimalLike = /^(#?)(-?[0-9]+)$/;
-
- function getNumericToolTip(value) {
- var match = hexLike.exec(value) || hexLike2.exec(value);
- if (match) {
- return value + ' = ' + bigInt(match[2], 16).toString(10);
- }
- match = decimalLike.exec(value);
- if (match) {
- var asBig = bigInt(match[2]);
- if (asBig.isNegative()) {
- asBig = bigInt('ffffffffffffffff', 16).and(asBig);
- }
- return value + ' = 0x' + asBig.toString(16).toUpperCase();
- }
-
- return null;
+ if (this.pendingRequestSentAt) {
+ // If we have a request pending, then just store this request to do once the
+ // previous request completes.
+ this.nextRequest = request;
+ return;
}
-
-
- var getAsmInfo = function (opcode) {
- var cacheName = 'asm/' + opcode;
- var cached = OpcodeCache.get(cacheName);
- if (cached) {
- return Promise.resolve(cached.found ? cached.result : null);
- }
- return new Promise(function (resolve, reject) {
- $.ajax({
- type: 'GET',
- url: 'api/asm/' + opcode,
- dataType: 'json', // Expected,
- contentType: 'text/plain', // Sent
- success: function (result) {
- OpcodeCache.set(cacheName, result);
- resolve(result.found ? result.result : null);
- },
- error: function (result) {
- reject(result);
- },
- cache: true
- });
+ this.eventHub.emit('compiling', this.id, this.compiler);
+ this.pendingRequestSentAt = Date.now();
+ // After a short delay, give the user some indication that we're working on their
+ // compilation.
+ var progress = setTimeout(_.bind(function () {
+ this.setAssembly(fakeAsm(''));
+ }, this), 500);
+ this.compilerService.submit(request)
+ .then(function (x) {
+ clearTimeout(progress);
+ onCompilerResponse(request, x.result, x.localCacheHit);
+ })
+ .catch(function (x) {
+ clearTimeout(progress);
+ onCompilerResponse(request, errorResult(''), false);
});
- };
+};
- Compiler.prototype.onMouseMove = function (e) {
- if (e === null || e.target === null || e.target.position === null) return;
- if (this.settings.hoverShowSource === true && this.assembly) {
- var hoverAsm = this.assembly[e.target.position.lineNumber - 1];
- if (hoverAsm) {
- // We check that we actually have something to show at this point!
- this.eventHub.emit('editorSetDecoration', this.sourceEditorId, hoverAsm.source && !hoverAsm.source.file ? hoverAsm.source.line : -1, false);
- }
- }
- var currentWord = this.outputEditor.getModel().getWordAtPosition(e.target.position);
- if (currentWord && currentWord.word) {
- var word = currentWord.word;
- currentWord.range = new monaco.Range(e.target.position.lineNumber, currentWord.startColumn, e.target.position.lineNumber, currentWord.endColumn);
- // Avoid throwing an exception if somehow (How?) we have a non existent lineNumber. c.f. https://sentry.io/matt-godbolt/compiler-explorer/issues/285270358/
- if (e.target.position.lineNumber < this.outputEditor.getModel().getLineCount()) {
- // Hacky workaround to check for negative numbers. c.f. https://github.com/mattgodbolt/compiler-explorer/issues/434
- var lineContent = this.outputEditor.getModel().getLineContent(e.target.position.lineNumber);
- if (lineContent[currentWord.startColumn - 2] === '-') {
- word = '-' + word;
- currentWord.range.startColumn -= 1;
- }
- }
- var numericToolTip = getNumericToolTip(word);
- if (numericToolTip) {
- this.decorations.numericToolTip = {
- range: currentWord.range,
- options: {isWholeLine: false, hoverMessage: ['`' + numericToolTip + '`']}
- };
- this.updateDecorations();
- }
+Compiler.prototype.getBinaryForLine = function (line) {
+ var obj = this.assembly[line - 1];
+ if (!obj) return '
????
????
';
+ var address = obj.address ? obj.address.toString(16) : '';
+ var opcodes = '
';
+ _.each(obj.opcodes, function (op) {
+ opcodes += ('' + op + '');
+ });
+ return '
' + address + '
' + opcodes + '
';
+};
- var getTokensForLine = function (model, line) {
- //Force line's state to be accurate
- if (line > model.getLineCount()) return [];
- model.getLineTokens(line, /*inaccurateTokensAcceptable*/false);
- // Get the tokenization state at the beginning of this line
- var state = model._lines[line - 1].getState();
- if (!state) return [];
- var freshState = model._lines[line - 1].getState().clone();
- // Get the human readable tokens on this line
- return model._tokenizationSupport.tokenize(model.getLineContent(line), freshState, 0).tokens;
- };
+// TODO: use ContentWidgets? OverlayWidgets?
+// Use highlight providers? hover providers? highlight providers?
+Compiler.prototype.setAssembly = function (assembly) {
+ this.assembly = assembly;
+ if (this.outputEditor.getModel()) {
+ this.outputEditor.getModel().setValue(_.pluck(assembly, 'text').join('\n'));
+ var addrToAddrDiv = {};
+ var decorations = [];
+ _.each(this.assembly, _.bind(function (obj, line) {
+ var address = obj.address ? obj.address.toString(16) : '';
+ // var div = $("
" + address + "
");
+ addrToAddrDiv[address] = {div: 'moo', line: line};
+ }, this));
- if (this.settings.hoverShowAsmDoc === true &&
- _.some(getTokensForLine(this.outputEditor.getModel(), currentWord.range.startLineNumber), function (t) {
- return t.offset + 1 === currentWord.startColumn && t.type === 'keyword.asm';
- })) {
- getAsmInfo(currentWord.word).then(_.bind(function (response) {
- if (response) {
- this.decorations.asmToolTip = {
- range: currentWord.range,
- options: {
- isWholeLine: false,
- hoverMessage: [response.tooltip + '\n\nMore information available in the context menu.']
- }
- };
- this.updateDecorations();
+ _.each(this.assembly, _.bind(function (obj, line) {
+ if (obj.links) {
+ _.each(obj.links, _.bind(function (link) {
+ var address = link.to.toString(16);
+ // var thing = $("" + address + "");
+ // this.outputEditor.markText(
+ // from, to, {replacedWith: thing[0], handleMouseEvents: false});
+ var dest = addrToAddrDiv[address];
+ if (dest) {
+ decorations.push({
+ range: new monaco.Range(line, link.offset, line, link.offset + link.length),
+ options: {}
+ });
+ // var editor = this.outputEditor;
+ // thing.hover(function (e) {
+ // var entered = e.type == "mouseenter";
+ // dest.div.toggleClass("highlighted", entered);
+ // thing.toggleClass("highlighted", entered);
+ // });
+ // thing.on('click', function (e) {
+ // editor.scrollIntoView({line: dest.line, ch: 0}, 30);
+ // dest.div.toggleClass("highlighted", false);
+ // thing.toggleClass("highlighted", false);
+ // e.preventDefault();
+ // });
}
}, this));
}
- }
- };
+ }, this));
+ }
+};
- Compiler.prototype.onAsmToolTip = function (ed) {
- var pos = ed.getPosition();
- var word = ed.getModel().getWordAtPosition(pos);
- if (!word || !word.word) return;
- var opcode = word.word.toUpperCase();
- getAsmInfo(word.word).then(
- _.bind(function (asmHelp) {
- if (asmHelp) {
- new Alert().alert(opcode + ' help', asmHelp.html +
- '
For more information, visit the ' +
- opcode + ' documentation .',
- function () {
- ed.focus();
- ed.setPosition(pos);
- }
- );
- } else {
- new Alert().notify('This token was not found in the documentation. Only mostIntel x86 opcodes supported for now.', {
- group: 'notokenindocs',
- alertClass: 'notification-error',
- dismissTime: 3000
- });
+function errorResult(text) {
+ return {asm: fakeAsm(text), code: -1, stdout: '', stderr: ''};
+}
+
+function fakeAsm(text) {
+ return [{text: text, source: null, fake: true}];
+}
+
+Compiler.prototype.onCompileResponse = function (request, result, cached) {
+ // Delete trailing empty lines
+ if ($.isArray(result.asm)) {
+ var cutCount = 0;
+ for (var i = result.asm.length - 1; i >= 0; i--) {
+ if (result.asm[i].text) {
+ break;
+ }
+ cutCount++;
+ }
+ result.asm.splice(result.asm.length - cutCount, cutCount);
+ }
+ this.lastResult = result;
+ var timeTaken = Math.max(0, Date.now() - this.pendingRequestSentAt);
+ var wasRealReply = this.pendingRequestSentAt > 0;
+ this.pendingRequestSentAt = 0;
+ ga('send', {
+ hitType: 'event',
+ eventCategory: 'Compile',
+ eventAction: request.compiler,
+ eventLabel: request.options.userArguments,
+ eventValue: cached ? 1 : 0
+ });
+ ga('send', {
+ hitType: 'timing',
+ timingCategory: 'Compile',
+ timingVar: request.compiler,
+ timingValue: timeTaken
+ });
+ this.setAssembly(result.asm || fakeAsm(''));
+ if (request.options.filters.binary) {
+ this.outputEditor.updateOptions({
+ lineNumbers: _.bind(this.getBinaryForLine, this),
+ // Until something comes out of Microsoft/monaco-editor/issues/515, this gets clamped to ten
+ lineNumbersMinChars: 25,
+ glyphMargin: false
+ });
+ } else {
+ this.outputEditor.updateOptions({
+ lineNumbers: true,
+ lineNumbersMinChars: options.embedded ? 1 : 5,
+ glyphMargin: true
+ });
+ }
+ var status = this.domRoot.find('.status');
+ var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join('\n');
+ var failed = result.code !== 0;
+ var warns = !failed && !!allText;
+ status.toggleClass('error', failed);
+ status.toggleClass('warning', warns);
+ status.parent().attr('title', allText);
+ if (cached) {
+ this.compileTimeLabel.text(' - cached');
+ } else if (wasRealReply) {
+ this.compileTimeLabel.text(' - ' + timeTaken + 'ms');
+ } else {
+ this.compileTimeLabel.text('');
+ }
+ this.eventHub.emit('compileResult', this.id, this.compiler, result);
+ this.updateButtons();
+
+ if (this.nextRequest) {
+ var next = this.nextRequest;
+ this.nextRequest = null;
+ this.sendCompile(next);
+ }
+};
+
+Compiler.prototype.onEditorChange = function (editor, source, langId, compilerId) {
+ if (editor === this.sourceEditorId && langId === this.currentLangId && (compilerId === undefined || compilerId === this.id)) {
+ this.source = source;
+ this.compile();
+ }
+};
+
+Compiler.prototype.onOptViewClosed = function (id) {
+ if (this.id == id) {
+ this.wantOptInfo = false;
+ this.optViewOpen = false;
+ this.optButton.prop('disabled', this.optViewOpen);
+ }
+};
+
+Compiler.prototype.onAstViewOpened = function (id) {
+ if (this.id == id) {
+ this.astButton.prop('disabled', true);
+ this.astViewOpen = true;
+ this.compile();
+ }
+};
+
+Compiler.prototype.onAstViewClosed = function (id) {
+ if (this.id === id) {
+ this.astButton.prop('disabled', false);
+ this.astViewOpen = false;
+ }
+};
+
+Compiler.prototype.onGccDumpUIInit = function (id) {
+ if (this.id === id) {
+ this.compile();
+ }
+};
+
+Compiler.prototype.onGccDumpFiltersChanged = function (id, filters, reqCompile) {
+ if (this.id === id) {
+ this.treeDumpEnabled = (filters.treeDump !== false);
+ this.rtlDumpEnabled = (filters.rtlDump !== false);
+
+ if (reqCompile) {
+ this.compile();
+ }
+ }
+};
+
+Compiler.prototype.onGccDumpPassSelected = function (id, passId, reqCompile) {
+ if (this.id === id) {
+ this.gccDumpPassSelected = passId;
+
+ if (reqCompile && passId !== '') {
+ this.compile();
+ }
+ }
+};
+
+Compiler.prototype.onGccDumpViewOpened = function (id) {
+ if (this.id === id) {
+ this.gccDumpButton.prop('disabled', true);
+ this.gccDumpViewOpen = true;
+ }
+};
+
+Compiler.prototype.onGccDumpViewClosed = function (id) {
+ if (this.id === id) {
+ this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump);
+ this.gccDumpViewOpen = false;
+
+ delete this.gccDumpPassSelected;
+ delete this.treeDumpEnabled;
+ delete this.rtlDumpEnabled;
+ }
+};
+
+Compiler.prototype.onOptViewOpened = function (id) {
+ if (this.id === id) {
+ this.optViewOpen = true;
+ this.wantOptInfo = true;
+ this.optButton.prop('disabled', this.optViewOpen);
+ this.compile();
+ }
+};
+
+Compiler.prototype.onCfgViewOpened = function (id) {
+ if (this.id == id) {
+ this.cfgButton.prop('disabled', true);
+ this.cfgViewOpen = true;
+ this.compile();
+ }
+};
+
+Compiler.prototype.onCfgViewClosed = function (id) {
+ if (this.id === id) {
+ this.cfgViewOpen = false;
+ this.cfgButton.prop('disabled', this.getEffectiveFilters().binary);
+ }
+};
+
+
+Compiler.prototype.updateButtons = function () {
+ if (!this.compiler) return;
+ var filters = this.getEffectiveFilters();
+ // We can support intel output if the compiler supports it, or if we're compiling
+ // to binary (as we can disassemble it however we like).
+ var intelAsm = this.compiler.supportsIntel || filters.binary;
+ this.domRoot.find("[data-bind='intel']").prop('disabled', !intelAsm);
+ // Disable binary support on compilers that don't work with it.
+ this.domRoot.find("[data-bind='binary']").prop('disabled', !this.compiler.supportsBinary);
+ this.domRoot.find("[data-bind='execute']").prop('disabled', !this.compiler.supportsExecute);
+ // Disable demangle for compilers where we can't access it
+ this.domRoot.find("[data-bind='demangle']").prop('disabled', !this.compiler.demangler);
+ // Disable any of the options which don't make sense in binary mode.
+ var filtersDisabled = !!filters.binary && !this.compiler.supportsFiltersInBinary;
+ this.domRoot.find('.nonbinary').prop('disabled', filtersDisabled);
+ // If its already open, we should turn the it off.
+ // The pane will update with error text
+ // Other wise we just disable the button.
+ if (!this.optViewOpen) {
+ this.optButton.prop('disabled', !this.compiler.supportsOptOutput);
+ } else {
+ this.optButton.prop('disabled', true);
+ }
+
+ if (!this.cfgViewOpen) {
+ this.cfgButton.prop('disabled', !this.compiler.supportsCfg);
+ } else {
+ this.cfgButton.prop('disabled', true);
+ }
+
+ if (!this.gccDumpViewOpen) {
+ this.gccDumpButton.prop('disabled', !this.compiler.supportsGccDump);
+ } else {
+ this.gccDumpButton.prop('disabled', true);
+ }
+};
+
+Compiler.prototype.onOptionsChange = function (options) {
+ this.options = options;
+ this.saveState();
+ this.compile();
+ this.updateButtons();
+ this.sendCompiler();
+};
+
+Compiler.prototype.onCompilerChange = function (value) {
+ this.compiler = this.compilerService.findCompiler(this.currentLangId, value);
+ this.saveState();
+ this.compile();
+ this.updateButtons();
+ this.updateCompilerName();
+ this.sendCompiler();
+};
+
+Compiler.prototype.sendCompiler = function () {
+ this.eventHub.emit('compiler', this.id, this.compiler, this.options, this.sourceEditorId);
+};
+
+Compiler.prototype.onEditorClose = function (editor) {
+ if (editor === this.sourceEditorId) {
+ // We can't immediately close as an outer loop somewhere in GoldenLayout is iterating over
+ // the hierarchy. We can't modify while it's being iterated over.
+ this.close();
+ _.defer(function (self) {
+ self.container.close();
+ }, this);
+ }
+};
+
+Compiler.prototype.onFilterChange = function () {
+ this.eventHub.emit('filtersChange', this.id, this.getEffectiveFilters());
+ this.saveState();
+ this.compile();
+ this.updateButtons();
+};
+
+Compiler.prototype.currentState = function () {
+ var libs = [];
+ _.each(this.availableLibs[this.currentLangId], function (library, name) {
+ _.each(library.versions, function (version, ver) {
+ if (library.versions[ver].used) {
+ libs.push({name: name, ver: ver});
+ }
+ });
+ });
+ var state = {
+ compiler: this.compiler ? this.compiler.id : '',
+ source: this.sourceEditorId,
+ options: this.options,
+ // NB must *not* be effective filters
+ filters: this.filters.get(),
+ wantOptInfo: this.wantOptInfo,
+ libs: libs,
+ lang: this.currentLangId
+ };
+ this.fontScale.addState(state);
+ return state;
+};
+
+Compiler.prototype.saveState = function () {
+ this.container.setState(this.currentState());
+};
+
+Compiler.prototype.updateFontScale = function () {
+ this.eventHub.emit('compilerFontScale', this.id, this.fontScale.scale);
+};
+
+Compiler.prototype.onColours = function (editor, colours, scheme) {
+ if (editor == this.sourceEditorId) {
+ var asmColours = {};
+ _.each(this.assembly, function (x, index) {
+ if (x.source && x.source.file === null) {
+ asmColours[index] = colours[x.source.line - 1];
+ }
+ });
+ this.colours = colour.applyColours(this.outputEditor, asmColours, scheme, this.colours);
+ }
+};
+
+Compiler.prototype.getCompilerName = function () {
+ return this.compiler ? this.compiler.name : 'no compiler set';
+};
+
+Compiler.prototype.updateCompilerName = function () {
+ var langName = options.languages[this.currentLangId].name;
+ var compilerName = this.getCompilerName();
+ var compilerVersion = this.compiler ? this.compiler.version : '';
+ this.container.setTitle(compilerName + ' (Editor #' + this.sourceEditorId + ', Compiler #' + this.id + ') ' + langName);
+ this.domRoot.find('.full-compiler-name').text(compilerVersion);
+};
+
+Compiler.prototype.onResendCompilation = function (id) {
+ if (id === this.id && !$.isEmptyObject(this.lastResult)) {
+ this.eventHub.emit('compileResult', this.id, this.compiler, this.lastResult);
+ }
+};
+
+Compiler.prototype.updateDecorations = function () {
+ this.prevDecorations = this.outputEditor.deltaDecorations(
+ this.prevDecorations, _.flatten(_.values(this.decorations), true));
+};
+
+Compiler.prototype.onCompilerSetDecorations = function (id, lineNums, revealLine) {
+ if (id == this.id) {
+ if (revealLine && lineNums[0])
+ this.outputEditor.revealLineInCenter(lineNums[0]);
+ this.decorations.linkedCode = _.map(lineNums, function (line) {
+ return {
+ range: new monaco.Range(line, 1, line, 1),
+ options: {
+ isWholeLine: true,
+ linesDecorationsClassName: 'linked-code-decoration-margin',
+ inlineClassName: 'linked-code-decoration-inline'
}
- }), function (rejection) {
- new Alert().notify('There was an error fetching the documentation for this opcode (' + rejection + ').', {
+ };
+ });
+ this.updateDecorations();
+ }
+};
+
+Compiler.prototype.onSettingsChange = function (newSettings) {
+ var before = this.settings;
+ this.settings = _.clone(newSettings);
+ if (!before.lastHoverShowSource && this.settings.hoverShowSource) {
+ this.onCompilerSetDecorations(this.id, []);
+ }
+ this.outputEditor.updateOptions({
+ contextmenu: this.settings.useCustomContextMenu,
+ minimap: {
+ enabled: this.settings.showMinimap && !options.embedded
+ }
+ });
+};
+
+var hexLike = /^(#?[$]|0x)([0-9a-fA-F]+)$/;
+var hexLike2 = /^(#?)([0-9a-fA-F]+)H$/;
+var decimalLike = /^(#?)(-?[0-9]+)$/;
+
+function getNumericToolTip(value) {
+ var match = hexLike.exec(value) || hexLike2.exec(value);
+ if (match) {
+ return value + ' = ' + bigInt(match[2], 16).toString(10);
+ }
+ match = decimalLike.exec(value);
+ if (match) {
+ var asBig = bigInt(match[2]);
+ if (asBig.isNegative()) {
+ asBig = bigInt('ffffffffffffffff', 16).and(asBig);
+ }
+ return value + ' = 0x' + asBig.toString(16).toUpperCase();
+ }
+
+ return null;
+}
+
+
+var getAsmInfo = function (opcode) {
+ var cacheName = 'asm/' + opcode;
+ var cached = OpcodeCache.get(cacheName);
+ if (cached) {
+ return Promise.resolve(cached.found ? cached.result : null);
+ }
+ return new Promise(function (resolve, reject) {
+ $.ajax({
+ type: 'GET',
+ url: 'api/asm/' + opcode,
+ dataType: 'json', // Expected,
+ contentType: 'text/plain', // Sent
+ success: function (result) {
+ OpcodeCache.set(cacheName, result);
+ resolve(result.found ? result.result : null);
+ },
+ error: function (result) {
+ reject(result);
+ },
+ cache: true
+ });
+ });
+};
+
+Compiler.prototype.onMouseMove = function (e) {
+ if (e === null || e.target === null || e.target.position === null) return;
+ if (this.settings.hoverShowSource === true && this.assembly) {
+ var hoverAsm = this.assembly[e.target.position.lineNumber - 1];
+ if (hoverAsm) {
+ // We check that we actually have something to show at this point!
+ this.eventHub.emit('editorSetDecoration', this.sourceEditorId, hoverAsm.source && !hoverAsm.source.file ? hoverAsm.source.line : -1, false);
+ }
+ }
+ var currentWord = this.outputEditor.getModel().getWordAtPosition(e.target.position);
+ if (currentWord && currentWord.word) {
+ var word = currentWord.word;
+ currentWord.range = new monaco.Range(e.target.position.lineNumber, currentWord.startColumn, e.target.position.lineNumber, currentWord.endColumn);
+ // Avoid throwing an exception if somehow (How?) we have a non existent lineNumber. c.f. https://sentry.io/matt-godbolt/compiler-explorer/issues/285270358/
+ if (e.target.position.lineNumber < this.outputEditor.getModel().getLineCount()) {
+ // Hacky workaround to check for negative numbers. c.f. https://github.com/mattgodbolt/compiler-explorer/issues/434
+ var lineContent = this.outputEditor.getModel().getLineContent(e.target.position.lineNumber);
+ if (lineContent[currentWord.startColumn - 2] === '-') {
+ word = '-' + word;
+ currentWord.range.startColumn -= 1;
+ }
+ }
+ var numericToolTip = getNumericToolTip(word);
+ if (numericToolTip) {
+ this.decorations.numericToolTip = {
+ range: currentWord.range,
+ options: {isWholeLine: false, hoverMessage: ['`' + numericToolTip + '`']}
+ };
+ this.updateDecorations();
+ }
+
+ var getTokensForLine = function (model, line) {
+ //Force line's state to be accurate
+ if (line > model.getLineCount()) return [];
+ model.getLineTokens(line, /*inaccurateTokensAcceptable*/false);
+ // Get the tokenization state at the beginning of this line
+ var state = model._lines[line - 1].getState();
+ if (!state) return [];
+ var freshState = model._lines[line - 1].getState().clone();
+ // Get the human readable tokens on this line
+ return model._tokenizationSupport.tokenize(model.getLineContent(line), freshState, 0).tokens;
+ };
+
+ if (this.settings.hoverShowAsmDoc === true &&
+ _.some(getTokensForLine(this.outputEditor.getModel(), currentWord.range.startLineNumber), function (t) {
+ return t.offset + 1 === currentWord.startColumn && t.type === 'keyword.asm';
+ })) {
+ getAsmInfo(currentWord.word).then(_.bind(function (response) {
+ if (response) {
+ this.decorations.asmToolTip = {
+ range: currentWord.range,
+ options: {
+ isWholeLine: false,
+ hoverMessage: [response.tooltip + '\n\nMore information available in the context menu.']
+ }
+ };
+ this.updateDecorations();
+ }
+ }, this));
+ }
+ }
+};
+
+Compiler.prototype.onAsmToolTip = function (ed) {
+ var pos = ed.getPosition();
+ var word = ed.getModel().getWordAtPosition(pos);
+ if (!word || !word.word) return;
+ var opcode = word.word.toUpperCase();
+ getAsmInfo(word.word).then(
+ _.bind(function (asmHelp) {
+ if (asmHelp) {
+ new Alert().alert(opcode + ' help', asmHelp.html +
+ '
For more information, visit the ' +
+ opcode + ' documentation .',
+ function () {
+ ed.focus();
+ ed.setPosition(pos);
+ }
+ );
+ } else {
+ new Alert().notify('This token was not found in the documentation. Only mostIntel x86 opcodes supported for now.', {
group: 'notokenindocs',
alertClass: 'notification-error',
dismissTime: 3000
});
}
- );
- };
+ }), function (rejection) {
+ new Alert().notify('There was an error fetching the documentation for this opcode (' + rejection + ').', {
+ group: 'notokenindocs',
+ alertClass: 'notification-error',
+ dismissTime: 3000
+ });
+ }
+ );
+};
- Compiler.prototype.updateLibsDropdown = function () {
- this.updateAvailableLibs();
- this.libsButton.popover({
- container: 'body',
- content: _.bind(function () {
- var libsCount = _.keys(this.availableLibs[this.currentLangId]).length;
- if (libsCount === 0) {
- return $('')
- .text('No libs configured for ' + options.languages[this.currentLangId].name + ' yet. ')
- .append($('')
- .attr('target', '_blank')
- .attr('rel', 'noopener noreferrer')
- .attr('href', 'https://github.com/mattgodbolt/compiler-explorer/issues/new')
- .text('You can suggest us one at any time ')
- .append($('')
- .addClass('glyphicon glyphicon-new-window')
- .width('16px')
- .height('16px')
- .attr('title', 'Opens in a new window')
- )
- );
- }
- var columnCount = Math.ceil(libsCount / 5);
- var currentLibIndex = -1;
+Compiler.prototype.updateLibsDropdown = function () {
+ this.updateAvailableLibs();
+ this.libsButton.popover({
+ container: 'body',
+ content: _.bind(function () {
+ var libsCount = _.keys(this.availableLibs[this.currentLangId]).length;
+ if (libsCount === 0) {
+ return $('')
+ .text('No libs configured for ' + options.languages[this.currentLangId].name + ' yet. ')
+ .append($('')
+ .attr('target', '_blank')
+ .attr('rel', 'noopener noreferrer')
+ .attr('href', 'https://github.com/mattgodbolt/compiler-explorer/issues/new')
+ .text('You can suggest us one at any time ')
+ .append($('')
+ .addClass('glyphicon glyphicon-new-window')
+ .width('16px')
+ .height('16px')
+ .attr('title', 'Opens in a new window')
+ )
+ );
+ }
+ var columnCount = Math.ceil(libsCount / 5);
+ var currentLibIndex = -1;
- var libLists = [];
- for (var i = 0; i < columnCount; i++) {
- libLists.push($('
').addClass('lib-list'));
- }
+ var libLists = [];
+ for (var i = 0; i < columnCount; i++) {
+ libLists.push($('
').addClass('lib-list'));
+ }
- // Utility function so we can iterate indefinetly over our lists
- var getNextList = function () {
- currentLibIndex = (currentLibIndex + 1) % columnCount;
- return libLists[currentLibIndex];
- };
-
- var onChecked = _.bind(function (e) {
- var elem = $(e.target);
- // Uncheck every lib checkbox with the same name if we're checking the target
- if (elem.prop('checked')) {
- var others = $.find('input[name=\'' + elem.prop('name') + '\']');
- _.each(others, function (other) {
- $(other).prop('checked', false);
- });
- // Recheck the targeted one
- elem.prop('checked', true);
- }
- // And now do the same with the availableLibs object
- _.each(this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions, function (version) {
- version.used = false;
- });
- this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions[elem.prop('data-version')].used = elem.prop('checked');
- this.saveState();
- this.compile();
- }, this);
-
- _.each(this.availableLibs[this.currentLangId], function (lib, libKey) {
- var libsList = getNextList();
- var libHeader = $('')
- .text(lib.name + ' ')
- .addClass('lib-header');
- if (lib.url && lib.url.length >= 1) {
- libHeader.append($('')
- .prop('href', lib.url)
- .prop('target', '_blank')
- .prop('rel', 'noopener noreferrer')
- .append($('')
- .addClass('glyphicon glyphicon-new-window')
- )
- );
- }
- var libCat = $('')
- .append(libHeader)
- .addClass('lib-item');
-
- var libGroup = $('');
-
- if (libsList.children().length > 0)
- libsList.append($('').addClass('lib-separator'));
-
- _.each(lib.versions, function (version, vKey) {
- libGroup.append($('')
- .append($('')
- .addClass('lib-checkbox')
- .prop('data-lib', libKey)
- .prop('data-version', vKey)
- .prop('checked', version.used)
- .prop('name', libKey)
- .on('change', onChecked)
- ).append($('')
- .addClass('lib-label')
- .text(lib.name + ' ' + version.version)
- .on('click', function () {
- $(this).parent().find('.lib-checkbox').trigger('click');
- })
- )
- );
- });
- libGroup.appendTo(libCat);
- libCat.appendTo(libsList);
- });
- return $('').addClass('libs-container').append(libLists);
- }, this),
- html: true,
- placement: 'bottom',
- trigger: 'manual'
- }).click(_.bind(function () {
- this.libsButton.popover('show');
- }, this)).on('show.bs.popover', function () {
- $(this).data('bs.popover').tip().css('max-width', '100%').css('width', 'auto');
- });
- };
-
- Compiler.prototype.onLanguageChange = function (editorId, newLangId) {
- if (this.sourceEditorId === editorId) {
- var oldLangId = this.currentLangId;
- this.currentLangId = newLangId;
- // Store the current selected stuff to come back to it later in the same session (Not state stored!)
- this.infoByLang[oldLangId] = {
- compiler: this.compiler && this.compiler.id ? this.compiler.id : options.defaultCompiler[oldLangId],
- options: this.options
+ // Utility function so we can iterate indefinetly over our lists
+ var getNextList = function () {
+ currentLibIndex = (currentLibIndex + 1) % columnCount;
+ return libLists[currentLibIndex];
};
- this.updateLibsDropdown();
- this.updateCompilersSelector();
- this.updateCompilerName();
- this.saveState();
- }
- };
- Compiler.prototype.getCurrentLangCompilers = function () {
- return this.compilerService.getCompilersForLang(this.currentLangId);
- };
+ var onChecked = _.bind(function (e) {
+ var elem = $(e.target);
+ // Uncheck every lib checkbox with the same name if we're checking the target
+ if (elem.prop('checked')) {
+ var others = $.find('input[name=\'' + elem.prop('name') + '\']');
+ _.each(others, function (other) {
+ $(other).prop('checked', false);
+ });
+ // Recheck the targeted one
+ elem.prop('checked', true);
+ }
+ // And now do the same with the availableLibs object
+ _.each(this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions, function (version) {
+ version.used = false;
+ });
+ this.availableLibs[this.currentLangId][elem.prop('data-lib')].versions[elem.prop('data-version')].used = elem.prop('checked');
+ this.saveState();
+ this.compile();
+ }, this);
- Compiler.prototype.updateCompilersSelector = function () {
- var selector = this.domRoot.find('.compiler-picker')[0].selectize;
- selector.clearOptions(true);
- selector.clearOptionGroups();
- _.each(this.getGroupsInUse(), function (group) {
- selector.addOptionGroup(group.value, {label: group.label});
- }, this);
- selector.load(_.bind(function (callback) {
- callback(_.map(this.getCurrentLangCompilers(), _.identity, this));
+ _.each(this.availableLibs[this.currentLangId], function (lib, libKey) {
+ var libsList = getNextList();
+ var libHeader = $('')
+ .text(lib.name + ' ')
+ .addClass('lib-header');
+ if (lib.url && lib.url.length >= 1) {
+ libHeader.append($('')
+ .prop('href', lib.url)
+ .prop('target', '_blank')
+ .prop('rel', 'noopener noreferrer')
+ .append($('')
+ .addClass('glyphicon glyphicon-new-window')
+ )
+ );
+ }
+ var libCat = $('')
+ .append(libHeader)
+ .addClass('lib-item');
+
+ var libGroup = $('');
+
+ if (libsList.children().length > 0)
+ libsList.append($('').addClass('lib-separator'));
+
+ _.each(lib.versions, function (version, vKey) {
+ libGroup.append($('')
+ .append($('')
+ .addClass('lib-checkbox')
+ .prop('data-lib', libKey)
+ .prop('data-version', vKey)
+ .prop('checked', version.used)
+ .prop('name', libKey)
+ .on('change', onChecked)
+ ).append($('')
+ .addClass('lib-label')
+ .text(lib.name + ' ' + version.version)
+ .on('click', function () {
+ $(this).parent().find('.lib-checkbox').trigger('click');
+ })
+ )
+ );
+ });
+ libGroup.appendTo(libCat);
+ libCat.appendTo(libsList);
+ });
+ return $('').addClass('libs-container').append(libLists);
+ }, this),
+ html: true,
+ placement: 'bottom',
+ trigger: 'manual'
+ }).click(_.bind(function () {
+ this.libsButton.popover('show');
+ }, this)).on('show.bs.popover', function () {
+ $(this).data('bs.popover').tip().css('max-width', '100%').css('width', 'auto');
+ });
+};
+
+Compiler.prototype.onLanguageChange = function (editorId, newLangId) {
+ if (this.sourceEditorId === editorId) {
+ var oldLangId = this.currentLangId;
+ this.currentLangId = newLangId;
+ // Store the current selected stuff to come back to it later in the same session (Not state stored!)
+ this.infoByLang[oldLangId] = {
+ compiler: this.compiler && this.compiler.id ? this.compiler.id : options.defaultCompiler[oldLangId],
+ options: this.options
+ };
+ this.updateLibsDropdown();
+ this.updateCompilersSelector();
+ this.updateCompilerName();
+ this.saveState();
+ }
+};
+
+Compiler.prototype.getCurrentLangCompilers = function () {
+ return this.compilerService.getCompilersForLang(this.currentLangId);
+};
+
+Compiler.prototype.updateCompilersSelector = function () {
+ var selector = this.domRoot.find('.compiler-picker')[0].selectize;
+ selector.clearOptions(true);
+ selector.clearOptionGroups();
+ _.each(this.getGroupsInUse(), function (group) {
+ selector.addOptionGroup(group.value, {label: group.label});
+ }, this);
+ selector.load(_.bind(function (callback) {
+ callback(_.map(this.getCurrentLangCompilers(), _.identity, this));
+ }, this));
+ var defaultOrFirst = _.bind(function defaultOrFirst() {
+ // If the default is a valid compiler, return it
+ var defaultCompiler = options.defaultCompiler[this.currentLangId];
+ if (defaultCompiler) return defaultCompiler;
+ // Else try to find the first one for this language
+ var value = _.find(options.compilers, _.bind(function (compiler) {
+ return compiler.lang === this.currentLangId;
}, this));
- var defaultOrFirst = _.bind(function defaultOrFirst() {
- // If the default is a valid compiler, return it
- var defaultCompiler = options.defaultCompiler[this.currentLangId];
- if (defaultCompiler) return defaultCompiler;
- // Else try to find the first one for this language
- var value = _.find(options.compilers, _.bind(function (compiler) {
- return compiler.lang === this.currentLangId;
- }, this));
- // Return the first, or an empty string if none found (Should prob report this one...)
- return value && value.id ? value.id : "";
- }, this);
- var info = this.infoByLang[this.currentLangId] || {};
- this.compiler = this.findCompiler(this.currentLangId, info.compiler || defaultOrFirst());
- if (this.compiler) selector.setValue([this.compiler.id], true);
- this.options = info.options || "";
- this.optionsField.val(this.options);
- };
+ // Return the first, or an empty string if none found (Should prob report this one...)
+ return value && value.id ? value.id : "";
+ }, this);
+ var info = this.infoByLang[this.currentLangId] || {};
+ this.compiler = this.findCompiler(this.currentLangId, info.compiler || defaultOrFirst());
+ if (this.compiler) selector.setValue([this.compiler.id], true);
+ this.options = info.options || "";
+ this.optionsField.val(this.options);
+};
- Compiler.prototype.findCompiler = function (langId, compilerId) {
- return this.compilerService.findCompiler(langId, compilerId);
- };
+Compiler.prototype.findCompiler = function (langId, compilerId) {
+ return this.compilerService.findCompiler(langId, compilerId);
+};
- Compiler.prototype.langOfCompiler = function (compilerId) {
- var compiler = _.find(options.compilers, function (compiler) {
- return compiler.id === compilerId || compiler.alias === compilerId;
- });
- if (!compiler) {
- Raven.captureMessage('Unable to find compiler id "' + compilerId + '"');
- compiler = options.compilers[0];
- }
- return compiler.lang;
- };
+Compiler.prototype.langOfCompiler = function (compilerId) {
+ var compiler = _.find(options.compilers, function (compiler) {
+ return compiler.id === compilerId || compiler.alias === compilerId;
+ });
+ if (!compiler) {
+ Raven.captureMessage('Unable to find compiler id "' + compilerId + '"');
+ compiler = options.compilers[0];
+ }
+ return compiler.lang;
+};
+
+module.exports = {
+ Compiler: Compiler
+};
- return {
- Compiler: Compiler
- };
-});
diff --git a/static/conformance-view.js b/static/conformance-view.js
index 7a1e4b8ab..d97e63f5d 100644
--- a/static/conformance-view.js
+++ b/static/conformance-view.js
@@ -23,291 +23,300 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- "use strict";
+"use strict";
- var options = require('options');
- var _ = require('underscore');
- var $ = require('jquery');
+var options = require('options');
+var _ = require('underscore');
+var $ = require('jquery');
- require('selectize');
+require('selectize');
- function Conformance(hub, container, state) {
- this.container = container;
- this.eventHub = hub.createEventHub();
- this.compilerService = hub.compilerService;
- this.domRoot = container.getElement();
- this.domRoot.html($('#conformance').html());
- this.selectorList = this.domRoot.find('.compiler-list');
- this.addCompilerButton = this.domRoot.find('.add-compiler');
- this.selectorTemplate = $('#compiler-selector .compiler-row');
- this.editorId = state.editorid;
- this.nextSelectorId = 0;
- this.maxCompilations = options.cvCompilerCountMax || 6;
- this.langId = state.langId || _.keys(options.languages)[0];
- this.source = state.source || "";
+function Conformance(hub, container, state) {
+ this.container = container;
+ this.eventHub = hub.createEventHub();
+ this.compilerService = hub.compilerService;
+ this.domRoot = container.getElement();
+ this.domRoot.html($('#conformance').html());
+ this.selectorList = this.domRoot.find('.compiler-list');
+ this.addCompilerButton = this.domRoot.find('.add-compiler');
+ this.selectorTemplate = $('#compiler-selector .compiler-row');
+ this.editorId = state.editorid;
+ this.nextSelectorId = 0;
+ this.maxCompilations = options.cvCompilerCountMax || 6;
+ this.langId = state.langId || _.keys(options.languages)[0];
+ this.source = state.source || "";
- this.status = {
- allowCompile: false,
- allowAdd: true
- };
- this.stateByLang = {};
-
- this.container.on('destroy', this.close, this);
-
- this.container.on('open', function () {
- this.eventHub.emit("conformanceViewOpen", this.editorId);
- }, this);
-
- this.eventHub.on('resize', this.resize, this);
- this.container.on('resize', this.resize, this);
-
- this.container.on('shown', this.resize, this);
-
- this.eventHub.on('editorChange', this.onEditorChange, this);
- this.eventHub.on('editorClose', this.onEditorClose, this);
- this.eventHub.on('languageChange', this.onLanguageChange, this);
-
- this.addCompilerButton.on('click', _.bind(function () {
- this.addCompilerSelector();
- this.saveState();
- }, this));
-
- this.initFromState(state);
- this.handleToolbarUI();
- }
-
- Conformance.prototype.setTitle = function (compilerCount) {
- this.container.setTitle(options.languages[this.langId].name + " Conformance viewer (Editor #" + this.editorId + ") " + (
- compilerCount !== 0 ? (compilerCount + "/" + this.maxCompilations) : ""
- ));
+ this.status = {
+ allowCompile: false,
+ allowAdd: true
};
+ this.stateByLang = {};
- Conformance.prototype.addCompilerSelector = function (config) {
- if (!config) {
- config = {
- // Code we have
- cv: this.nextSelectorId,
- // Compiler id which is being used
- compilerId: "",
- // Options which are in use
- options: "",
- };
- this.nextSelectorId++;
- }
-
- config.cv = Number(config.cv);
-
- var newEntry = this.selectorTemplate.clone();
-
- newEntry.attr("data-cv", config.cv);
-
- var onOptionsChange = _.debounce(_.bind(function () {
- this.saveState();
- this.compileAll();
- }, this), 800);
-
- newEntry.find('.options')
- .attr("data-cv", config.cv)
- .val(config.options)
- .on("click", onOptionsChange)
- .on("keyup", onOptionsChange);
-
- newEntry.find('.close')
- .attr("data-cv", config.cv)
- .on("click", _.bind(function () {
- this.removeCompilerSelector(config.cv);
- }, this));
-
- this.selectorList.append(newEntry);
-
- var status = newEntry.find('.status').attr("data-cv", config.cv);
- var langId = this.langId;
- var isVisible = function (compiler) {
- return compiler.lang === langId;
- };
-
- newEntry.find('.compiler-picker')
- .attr("data-cv", config.cv)
- .selectize({
- sortField: 'name',
- valueField: 'id',
- labelField: 'name',
- searchField: ['name'],
- options: _.filter(options.compilers, isVisible),
- items: config.compilerId ? [config.compilerId] : []
- })
- .on('change', _.bind(function () {
- // Hide the results button when a new compiler is selected
- this.handleStatusIcon(status, {code: 0, text: ""});
- // We could narrow the compilation to only this compiler!
- this.compileAll();
- // We're not saving state here. It's done after compiling
- }, this));
- this.handleStatusIcon(status, {code: 0, text: ""});
- this.handleToolbarUI();
- this.saveState();
- };
-
- Conformance.prototype.removeCompilerSelector = function (cv) {
- _.each(this.selectorList.children(), function (row) {
- var child = $(row);
- if (child.attr("data-cv") == cv) {
- child.remove();
- }
- }, this);
- this.handleToolbarUI();
- this.saveState();
- };
-
- Conformance.prototype.onEditorChange = function (editorId, newSource, langId) {
- if (editorId == this.editorId) {
- this.langId = langId;
- this.source = newSource;
- this.compileAll();
- }
- };
-
- Conformance.prototype.onEditorClose = function (editorId) {
- if (editorId === this.editorId) {
- this.close();
- _.defer(function (self) {
- self.container.close();
- }, this);
- }
- };
-
- Conformance.prototype.onCompileResponse = function (cv, result) {
- var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join("\n");
- var failed = result.code !== 0;
- var warns = !failed && !!allText;
- var status = {
- text: allText.replace(/\x1b\\[[0-9;]*m/, ''),
- code: failed ? 3 : (warns ? 2 : 1)
- };
- this.handleStatusIcon(this.selectorList.find('[data-cv="' + cv + '"] .status'), status);
- this.saveState();
- };
-
- Conformance.prototype.compileAll = function () {
- if (!this.source) return;
- // Hide previous status icons
- this.selectorList.find('.status').css("visibility", "hidden");
- this.compilerService.expand(this.source).then(_.bind(function (expanded) {
- var compileCount = 0;
- _.each(this.selectorList.children(), _.bind(function (child) {
- var picker = $(child).find('.compiler-picker');
- // We make sure we are not over our limit
- if (picker && compileCount < this.maxCompilations) {
- compileCount++;
- if (picker.val()) {
- var cv = Number(picker.attr("data-cv"));
- var request = {
- source: expanded || "",
- compiler: picker.val(),
- options: {
- userArguments: $(child).find(".options[data-cv='" + cv + "']").val(),
- filters: {},
- compilerOptions: {produceAst: false, produceOptInfo: false}
- }
- };
- // This error function ensures that the user will know we had a problem (As we don't save asm)
- this.compilerService.submit(request)
- .then(_.bind(function (x) {
- this.onCompileResponse(cv, x.result);
- }, this))
- .catch(_.bind(function (x) {
- this.onCompileResponse(cv, {
- asm: "",
- code: -1,
- stdout: "",
- stderr: x.error
- });
- }, this));
- }
- }
- }, this));
- }, this));
- };
-
- Conformance.prototype.handleToolbarUI = function () {
- var compilerCount = this.selectorList.children().length;
-
- // Only allow new compilers if we allow for more
- this.addCompilerButton.attr("disabled", compilerCount >= this.maxCompilations);
-
- this.setTitle(compilerCount);
- };
-
- Conformance.prototype.handleStatusIcon = function (element, status) {
- if (!element) return;
- element.attr("class", "status glyphicon glyphicon-" + (status.code === 3 ? "remove-sign" : (status.code === 2 ? "info-sign" : "ok-sign")))
- .css("visibility", status.code === 0 ? "hidden" : "visible")
- .css("color", status.code === 3 ? "red" : (status.code === 2 ? "yellow" : "green"))
- .attr("title", status.text)
- .attr("aria-label", status.code === 3 ? "Compilation failed!" : (status.code === 2 ? "Compiled with warnings" : "Compiled without warnings"))
- .attr("data-status", status.code);
- };
-
- Conformance.prototype.currentState = function () {
- var state = {
- editorid: this.editorId,
- langId: this.langId,
- compilers: []
- };
- _.each(this.selectorList.children(), _.bind(function (child) {
- state.compilers.push({
- // Code we have
- cv: $(child).attr("data-cv"),
- // Compiler which is being used
- compilerId: $(child).find('.compiler-picker').val(),
- // Options which are in use
- options: $(child).find(".options").val(),
- });
- }, this));
- return state;
- };
-
- Conformance.prototype.saveState = function () {
- this.container.setState(this.currentState());
- };
-
- Conformance.prototype.resize = function () {
- this.selectorList.css("height", this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true));
- };
-
- Conformance.prototype.onLanguageChange = function (editorId, newLangId) {
- if (editorId === this.editorId && this.langId !== newLangId) {
- var oldLangId = this.langId;
- this.stateByLang[oldLangId] = this.currentState();
-
- this.langId = newLangId;
- this.selectorList.children().remove();
- this.nextSelectorId = 0;
- if (this.stateByLang[newLangId]) {
- this.initFromState(this.stateByLang[newLangId]);
- }
- this.handleToolbarUI();
- this.saveState();
- }
- };
-
- Conformance.prototype.initFromState = function (state) {
- if (state.compilers) {
- _.each(state.compilers, _.bind(function (config) {
- config.cv = this.nextSelectorId;
- this.nextSelectorId++;
- this.addCompilerSelector(config);
- }, this));
- }
- };
-
- Conformance.prototype.close = function () {
+ this.container.on('destroy', function () {
this.eventHub.unsubscribe();
this.eventHub.emit("conformanceViewClose", this.editorId);
+ }, this);
+
+ this.container.on('destroy', this.close, this);
+ this.container.on('open', function () {
+ this.eventHub.emit("conformanceViewOpen", this.editorId);
+ }, this);
+
+ this.eventHub.on('resize', this.resize, this);
+ this.container.on('resize', this.resize, this);
+ this.eventHub.on('editorChange', this.onEditorChange, this);
+ this.eventHub.on('editorClose', this.onEditorClose, this);
+ this.eventHub.on('languageChange', this.onLanguageChange, this);
+ this.container.on('shown', this.resize, this);
+
+ this.eventHub.on('editorChange', this.onEditorChange, this);
+ this.eventHub.on('editorClose', this.onEditorClose, this);
+
+ this.addCompilerButton.on('click', _.bind(function () {
+ this.addCompilerSelector();
+ this.saveState();
+ }, this));
+
+ if (state.compilers) {
+ _.each(state.compilers, _.bind(function (config) {
+ config.cv = this.nextSelectorId;
+ this.nextSelectorId++;
+ this.addCompilerSelector(config);
+ }, this));
+ }
+
+ this.handleToolbarUI();
+}
+
+Conformance.prototype.setTitle = function (compilerCount) {
+ this.container.setTitle("Conformance viewer (Editor #" + this.editorId + ") " + (
+ compilerCount !== 0 ? (compilerCount + "/" + this.maxCompilations) : ""
+ ));
+};
+
+
+Conformance.prototype.addCompilerSelector = function (config) {
+ if (!config) {
+ config = {
+ // Code we have
+ cv: this.nextSelectorId,
+ // Compiler id which is being used
+ compilerId: "",
+ // Options which are in use
+ options: "",
+ };
+ this.nextSelectorId++;
+ }
+
+ config.cv = Number(config.cv);
+
+ var newEntry = this.selectorTemplate.clone();
+
+ newEntry.attr("data-cv", config.cv);
+
+ var onOptionsChange = _.debounce(_.bind(function () {
+ this.saveState();
+ this.compileAll();
+ }, this), 800);
+
+ newEntry.find('.options')
+ .attr("data-cv", config.cv)
+ .val(config.options)
+ .on("click", onOptionsChange)
+ .on("keyup", onOptionsChange);
+
+ newEntry.find('.close')
+ .attr("data-cv", config.cv)
+ .on("click", _.bind(function () {
+ this.removeCompilerSelector(config.cv);
+ }, this));
+
+ this.selectorList.append(newEntry);
+
+ var status = newEntry.find('.status').attr("data-cv", config.cv);
+ var langId = this.langId;
+ var isVisible = function (compiler) {
+ return compiler.lang === langId;
};
- return {
- Conformance: Conformance
+ newEntry.find('.compiler-picker')
+ .attr("data-cv", config.cv)
+ .selectize({
+ sortField: 'name',
+ valueField: 'id',
+ labelField: 'name',
+ searchField: ['name'],
+ options: _.filter(options.compilers, isVisible),
+ items: config.compilerId ? [config.compilerId] : []
+ })
+ .on('change', _.bind(function () {
+ // Hide the results button when a new compiler is selected
+ this.handleStatusIcon(status, {code: 0, text: ""});
+ // We could narrow the compilation to only this compiler!
+ this.compileAll();
+ // We're not saving state here. It's done after compiling
+ }, this));
+ this.handleStatusIcon(status, {code: 0, text: ""});
+ this.handleToolbarUI();
+ this.saveState();
+};
+Conformance.prototype.removeCompilerSelector = function (cv) {
+ _.each(this.selectorList.children(), function (row) {
+ var child = $(row);
+ if (child.attr("data-cv") == cv) {
+ child.remove();
+ }
+ }, this);
+ this.handleToolbarUI();
+ this.saveState();
+};
+
+Conformance.prototype.onEditorChange = function (editorId, newSource, langId) {
+ if (editorId == this.editorId) {
+ this.langId = langId;
+ this.source = newSource;
+ this.compileAll();
+ }
+};
+
+Conformance.prototype.onEditorClose = function (editorId) {
+ if (editorId == this.editorId) {
+ this.close();
+ _.defer(function (self) {
+ self.container.close();
+ }, this);
+ }
+};
+
+Conformance.prototype.onCompileResponse = function (cv, result) {
+ var allText = _.pluck((result.stdout || []).concat(result.stderr || []), 'text').join("\n");
+ var failed = result.code !== 0;
+ var warns = !failed && !!allText;
+ var status = {
+ text: allText.replace(/\x1b\\[[0-9;]*m/, ''),
+ code: failed ? 3 : (warns ? 2 : 1)
};
-});
+ this.handleStatusIcon(this.selectorList.find('[data-cv="' + cv + '"] .status'), status);
+ this.saveState();
+};
+
+Conformance.prototype.compileAll = function () {
+ if (!this.source) return;
+ // Hide previous status icons
+ this.selectorList.find('.status').css("visibility", "hidden");
+ this.compilerService.expand(this.source).then(_.bind(function (expanded) {
+ var compileCount = 0;
+ _.each(this.selectorList.children(), _.bind(function (child) {
+ var picker = $(child).find('.compiler-picker');
+ // We make sure we are not over our limit
+ if (picker && compileCount < this.maxCompilations) {
+ compileCount++;
+ if (picker.val()) {
+ var cv = Number(picker.attr("data-cv"));
+ var request = {
+ source: expanded || "",
+ compiler: picker.val(),
+ options: {
+ userArguments: $(child).find(".options[data-cv='" + cv + "']").val(),
+ filters: {},
+ compilerOptions: {produceAst: false, produceOptInfo: false}
+ }
+ };
+ // This error function ensures that the user will know we had a problem (As we don't save asm)
+ this.compilerService.submit(request)
+ .then(_.bind(function (x) {
+ this.onCompileResponse(cv, x.result);
+ }, this))
+ .catch(_.bind(function (x) {
+ this.onCompileResponse(cv, {
+ asm: "",
+ code: -1,
+ stdout: "",
+ stderr: x.error
+ });
+ }, this));
+ }
+ }
+ }, this));
+ }, this));
+};
+
+Conformance.prototype.handleToolbarUI = function () {
+ var compilerCount = this.selectorList.children().length;
+
+ // Only allow new compilers if we allow for more
+ this.addCompilerButton.attr("disabled", compilerCount >= this.maxCompilations);
+
+ this.setTitle(compilerCount);
+};
+
+Conformance.prototype.handleStatusIcon = function (element, status) {
+ if (!element) return;
+ element.attr("class", "status glyphicon glyphicon-" + (status.code === 3 ? "remove-sign" : (status.code === 2 ? "info-sign" : "ok-sign")))
+ .css("visibility", status.code === 0 ? "hidden" : "visible")
+ .css("color", status.code === 3 ? "red" : (status.code === 2 ? "yellow" : "green"))
+ .attr("title", status.text)
+ .attr("aria-label", status.code === 3 ? "Compilation failed!" : (status.code === 2 ? "Compiled with warnings" : "Compiled without warnings"))
+ .attr("data-status", status.code);
+};
+
+Conformance.prototype.currentState = function () {
+ var state = {
+ editorid: this.editorId,
+ langId: this.langId,
+ compilers: []
+ };
+ _.each(this.selectorList.children(), _.bind(function (child) {
+ state.compilers.push({
+ // Code we have
+ cv: $(child).attr("data-cv"),
+ // Compiler which is being used
+ compilerId: $(child).find('.compiler-picker').val(),
+ // Options which are in use
+ options: $(child).find(".options").val(),
+ });
+ }, this));
+ return state;
+};
+
+Conformance.prototype.saveState = function () {
+ this.container.setState(this.currentState());
+};
+
+Conformance.prototype.resize = function () {
+ this.selectorList.css("height", this.domRoot.height() - this.domRoot.find('.top-bar').outerHeight(true));
+};
+
+Conformance.prototype.onLanguageChange = function (editorId, newLangId) {
+ if (editorId === this.editorId && this.langId !== newLangId) {
+ var oldLangId = this.langId;
+ this.stateByLang[oldLangId] = this.currentState();
+
+ this.langId = newLangId;
+ this.selectorList.children().remove();
+ this.nextSelectorId = 0;
+ if (this.stateByLang[newLangId]) {
+ this.initFromState(this.stateByLang[newLangId]);
+ }
+ this.handleToolbarUI();
+ this.saveState();
+ }
+};
+
+Conformance.prototype.close = function () {
+ this.eventHub.unsubscribe();
+ this.eventHub.emit("conformanceViewClose", this.editorId);
+};
+
+Conformance.prototype.initFromState = function (state) {
+ if (state.compilers) {
+ _.each(state.compilers, _.bind(function (config) {
+ config.cv = this.nextSelectorId;
+ this.nextSelectorId++;
+ this.addCompilerSelector(config);
+ }, this));
+ }
+};
+module.exports = {
+ Conformance: Conformance
+};
diff --git a/static/cppp-mode.js b/static/cppp-mode.js
index deaeb07f1..8d36db6d2 100644
--- a/static/cppp-mode.js
+++ b/static/cppp-mode.js
@@ -1,48 +1,45 @@
-define(function (require) {
- 'use strict';
- var $ = require('jquery');
- var monaco = require('monaco');
- var cpp = require('vs/basic-languages/src/cpp');
+'use strict';
+var $ = require('jquery');
+var cpp = require('vs/basic-languages/src/cpp');
- // We need to create a new definition for cpp so we can remove invalid keywords
+// We need to create a new definition for cpp so we can remove invalid keywords
- function definition() {
- var cppp = $.extend(true, {}, cpp.language); // deep copy
+function definition() {
+ var cppp = $.extend(true, {}, cpp.language); // deep copy
- function removeKeyword(keyword) {
- var index = cppp.keywords.indexOf(keyword);
- if (index > -1) {
- cppp.keywords.splice(index, 1);
- }
+ function removeKeyword(keyword) {
+ var index = cppp.keywords.indexOf(keyword);
+ if (index > -1) {
+ cppp.keywords.splice(index, 1);
}
-
- function removeKeywords(keywords) {
- for (var i = 0; i < keywords.length; ++i) {
- removeKeyword(keywords[i]);
- }
- }
-
- function addKeywords(keywords) {
- // (Ruben) Done one by one as if you just push them all, Monaco complains that they're not strings, but as
- // far as I can tell, they indeed are all strings. This somehow fixes it. If you know how to fix it, plz go
- for (var i = 0; i < keywords.length; ++i) {
- cppp.keywords.push(keywords[i]);
- }
- }
-
- // We remove everything that's not an identifier, underscore reserved name and not an official C++ keyword...
- // Regarding #617, final is a identifier with special meaning, not a fully qualified keyword
- removeKeywords(["abstract", "amp", "array", "cpu", "delegate", "each", "event", "finally", "gcnew",
- "generic", "in", "initonly", "interface", "interior_ptr", "internal", "literal", "partial", "pascal",
- "pin_ptr", "property", "ref", "restrict", "safe_cast", "sealed", "title_static", "where"]);
-
- addKeywords(["alignas", "alignof", "and", "and_eq", "asm", "bitand", "bitor", "char16_t", "char32_t", "compl",
- "not", "not_eq", "or", "or_eq", "xor", "xor_eq"]);
-
- return cppp;
}
- monaco.languages.register({id: 'cppp'});
- monaco.languages.setLanguageConfiguration('cppp', cpp.conf);
- monaco.languages.setMonarchTokensProvider('cppp', definition());
-});
+ function removeKeywords(keywords) {
+ for (var i = 0; i < keywords.length; ++i) {
+ removeKeyword(keywords[i]);
+ }
+ }
+
+ function addKeywords(keywords) {
+ // (Ruben) Done one by one as if you just push them all, Monaco complains that they're not strings, but as
+ // far as I can tell, they indeed are all strings. This somehow fixes it. If you know how to fix it, plz go
+ for (var i = 0; i < keywords.length; ++i) {
+ cppp.keywords.push(keywords[i]);
+ }
+ }
+
+ // We remove everything that's not an identifier, underscore reserved name and not an official C++ keyword...
+ // Regarding #617, final is a identifier with special meaning, not a fully qualified keyword
+ removeKeywords(["abstract", "amp", "array", "cpu", "delegate", "each", "event", "finally", "gcnew",
+ "generic", "in", "initonly", "interface", "interior_ptr", "internal", "literal", "partial", "pascal",
+ "pin_ptr", "property", "ref", "restrict", "safe_cast", "sealed", "title_static", "where"]);
+
+ addKeywords(["alignas", "alignof", "and", "and_eq", "asm", "bitand", "bitor", "char16_t", "char32_t", "compl",
+ "not", "not_eq", "or", "or_eq", "xor", "xor_eq"]);
+
+ return cppp;
+}
+
+monaco.languages.register({id: 'cppp'});
+monaco.languages.setLanguageConfiguration('cppp', cpp.conf);
+monaco.languages.setMonarchTokensProvider('cppp', definition());
diff --git a/static/d-mode.js b/static/d-mode.js
index 476719f03..a22c6838b 100644
--- a/static/d-mode.js
+++ b/static/d-mode.js
@@ -21,263 +21,259 @@
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
+"use strict";
-define(function (require) {
- "use strict";
- var monaco = require('monaco');
+function definition() {
+ return {
+ defaultToken: 'invalid',
- function definition() {
- return {
- defaultToken: 'invalid',
+ keywords: [
+ 'abstract',
+ 'alias',
+ 'align',
+ 'asm',
+ 'assert',
+ 'auto',
+ 'body',
+ 'bool',
+ 'break',
+ 'byte',
+ 'case',
+ 'cast',
+ 'catch',
+ 'cdouble',
+ 'cent',
+ 'cfloat',
+ 'char',
+ 'class',
+ 'const',
+ 'continue',
+ 'creal',
+ 'dchar',
+ 'debug',
+ 'default',
+ 'delegate',
+ 'delete ',
+ 'deprecated',
+ 'do',
+ 'double',
+ 'else',
+ 'enum',
+ 'export',
+ 'extern',
+ 'false',
+ 'final',
+ 'finally',
+ 'float',
+ 'for',
+ 'foreach',
+ 'foreach_reverse',
+ 'function',
+ 'goto',
+ 'idouble',
+ 'if',
+ 'ifloat',
+ 'immutable',
+ 'import',
+ 'in',
+ 'inout',
+ 'int',
+ 'interface',
+ 'invariant',
+ 'ireal',
+ 'is',
+ 'lazy',
+ 'long',
+ 'macro',
+ 'mixin',
+ 'module',
+ 'new',
+ 'nothrow',
+ 'null',
+ 'out',
+ 'override',
+ 'package',
+ 'pragma',
+ 'private',
+ 'protected',
+ 'public',
+ 'pure',
+ 'real',
+ 'ref',
+ 'return',
+ 'scope',
+ 'shared',
+ 'short',
+ 'static',
+ 'struct',
+ 'super',
+ 'switch',
+ 'synchronized',
+ 'template',
+ 'this',
+ 'throw',
+ 'true',
+ 'try',
+ 'typedef',
+ 'typeid',
+ 'typeof',
+ 'ubyte',
+ 'ucent',
+ 'uint',
+ 'ulong',
+ 'union',
+ 'unittest',
+ 'ushort',
+ 'version',
+ 'void',
+ 'volatile',
+ 'wchar',
+ 'while',
+ 'with',
+ '__FILE__',
+ '__FILE_FULL_PATH__',
+ '__MODULE__',
+ '__LINE__',
+ '__FUNCTION__',
+ '__PRETTY_FUNCTION__',
+ '__gshared',
+ '__traits',
+ '__vector',
+ '__parameters'],
- keywords: [
- 'abstract',
- 'alias',
- 'align',
- 'asm',
- 'assert',
- 'auto',
- 'body',
- 'bool',
- 'break',
- 'byte',
- 'case',
- 'cast',
- 'catch',
- 'cdouble',
- 'cent',
- 'cfloat',
- 'char',
- 'class',
- 'const',
- 'continue',
- 'creal',
- 'dchar',
- 'debug',
- 'default',
- 'delegate',
- 'delete ',
- 'deprecated',
- 'do',
- 'double',
- 'else',
- 'enum',
- 'export',
- 'extern',
- 'false',
- 'final',
- 'finally',
- 'float',
- 'for',
- 'foreach',
- 'foreach_reverse',
- 'function',
- 'goto',
- 'idouble',
- 'if',
- 'ifloat',
- 'immutable',
- 'import',
- 'in',
- 'inout',
- 'int',
- 'interface',
- 'invariant',
- 'ireal',
- 'is',
- 'lazy',
- 'long',
- 'macro',
- 'mixin',
- 'module',
- 'new',
- 'nothrow',
- 'null',
- 'out',
- 'override',
- 'package',
- 'pragma',
- 'private',
- 'protected',
- 'public',
- 'pure',
- 'real',
- 'ref',
- 'return',
- 'scope',
- 'shared',
- 'short',
- 'static',
- 'struct',
- 'super',
- 'switch',
- 'synchronized',
- 'template',
- 'this',
- 'throw',
- 'true',
- 'try',
- 'typedef',
- 'typeid',
- 'typeof',
- 'ubyte',
- 'ucent',
- 'uint',
- 'ulong',
- 'union',
- 'unittest',
- 'ushort',
- 'version',
- 'void',
- 'volatile',
- 'wchar',
- 'while',
- 'with',
- '__FILE__',
- '__FILE_FULL_PATH__',
- '__MODULE__',
- '__LINE__',
- '__FUNCTION__',
- '__PRETTY_FUNCTION__',
- '__gshared',
- '__traits',
- '__vector',
- '__parameters'],
+ typeKeywords: [
+ 'bool', 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'char', 'wchar', 'dchar',
+ 'float', 'double', 'real', 'ifloat', 'idouble', 'ireal', 'cfloat', 'cdouble', 'creal', 'void'
+ ],
- typeKeywords: [
- 'bool', 'byte', 'ubyte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'char', 'wchar', 'dchar',
- 'float', 'double', 'real', 'ifloat', 'idouble', 'ireal', 'cfloat', 'cdouble', 'creal', 'void'
+ operators: [
+ '=', '>', '<', '!', '~', '?', ':',
+ '==', '<=', '>=', '!=', '&&', '||', '++', '--',
+ '+', '-', '*', '/', '&', '|', '^', '%', '<<',
+ '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=',
+ '^=', '%=', '<<=', '>>=', '>>>='
+ ],
+
+ // we include these common regular expressions
+ symbols: /[=>](?!@symbols)/, '@brackets'],
+ [/@symbols/, {
+ cases: {
+ '@operators': 'operator',
+ '@default': ''
+ }
+ }],
+
+ // numbers
+ [/\d*\.\d+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'],
+ [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'],
+ [/0[0-7_]*[0-7][Ll]?/, 'number.octal'],
+ [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'],
+ [/\d+[lL]?/, 'number'],
+
+ // delimiter: after number because of .\d floats
+ [/[;,.]/, 'delimiter'],
+
+ // strings
+ [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string
+ [/"/, 'string', '@string'],
+ [/`/, 'string', '@rawstring'],
+
+ // characters
+ [/'[^\\']'/, 'string'],
+ [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
+ [/'/, 'string.invalid']
],
- operators: [
- '=', '>', '<', '!', '~', '?', ':',
- '==', '<=', '>=', '!=', '&&', '||', '++', '--',
- '+', '-', '*', '/', '&', '|', '^', '%', '<<',
- '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=',
- '^=', '%=', '<<=', '>>=', '>>>='
+ whitespace: [
+ [/[ \t\r\n]+/, 'white'],
+ [/\/\*/, 'comment', '@comment'],
+ [/\/\+/, 'comment', '@nestingcomment'],
+ [/\/\/.*$/, 'comment'],
],
- // we include these common regular expressions
- symbols: /[=>](?!@symbols)/, '@brackets'],
- [/@symbols/, {
- cases: {
- '@operators': 'operator',
- '@default': ''
- }
- }],
-
- // numbers
- [/\d*\.\d+([eE][\-+]?\d+)?[fFdD]?/, 'number.float'],
- [/0[xX][0-9a-fA-F_]*[0-9a-fA-F][Ll]?/, 'number.hex'],
- [/0[0-7_]*[0-7][Ll]?/, 'number.octal'],
- [/0[bB][0-1_]*[0-1][Ll]?/, 'number.binary'],
- [/\d+[lL]?/, 'number'],
-
- // delimiter: after number because of .\d floats
- [/[;,.]/, 'delimiter'],
-
- // strings
- [/"([^"\\]|\\.)*$/, 'string.invalid'], // non-teminated string
- [/"/, 'string', '@string'],
- [/`/, 'string', '@rawstring'],
-
- // characters
- [/'[^\\']'/, 'string'],
- [/(')(@escapes)(')/, ['string', 'string.escape', 'string']],
- [/'/, 'string.invalid']
- ],
-
- whitespace: [
- [/[ \t\r\n]+/, 'white'],
- [/\/\*/, 'comment', '@comment'],
- [/\/\+/, 'comment', '@nestingcomment'],
- [/\/\/.*$/, 'comment'],
- ],
-
- comment: [
- [/[^\/*]+/, 'comment'],
- [/\*\//, 'comment', '@pop'],
- [/[\/*]/, 'comment']
- ],
-
- nestingcomment: [
- [/[^\/+]+/, 'comment'],
- [/\/\+/, 'comment', '@push'],
- [/\/\+/, 'comment.invalid'],
- [/\+\//, 'comment', '@pop'],
- [/[\/+]/, 'comment']
- ],
-
- string: [
- [/[^\\"]+/, 'string'],
- [/@escapes/, 'string.escape'],
- [/\\./, 'string.escape.invalid'],
- [/"/, 'string', '@pop']
- ],
-
- rawstring: [
- [/[^\`]/, "string"],
- [/`/, "string", "@pop"]
- ],
- }
- };
- }
-
- function configuration() {
- return {
- comments: {
- lineComment: '//',
- blockComment: ['/*', '*/'],
- },
-
- brackets: [
- ['{', '}'],
- ['[', ']'],
- ['(', ')']
+ comment: [
+ [/[^\/*]+/, 'comment'],
+ [/\*\//, 'comment', '@pop'],
+ [/[\/*]/, 'comment']
],
- autoClosingPairs: [
- { open: '{', close: '}' },
- { open: '[', close: ']' },
- { open: '(', close: ')' },
- { open: '`', close: '`', notIn: ['string'] },
- { open: '"', close: '"', notIn: ['string'] },
- { open: '\'', close: '\'', notIn: ['string', 'comment'] },
+ nestingcomment: [
+ [/[^\/+]+/, 'comment'],
+ [/\/\+/, 'comment', '@push'],
+ [/\/\+/, 'comment.invalid'],
+ [/\+\//, 'comment', '@pop'],
+ [/[\/+]/, 'comment']
],
- surroundingPairs: [
- { open: '{', close: '}' },
- { open: '[', close: ']' },
- { open: '(', close: ')' },
- { open: '`', close: '`' },
- { open: '"', close: '"' },
- { open: '\'', close: '\'' },
- ]
- };
- }
+ string: [
+ [/[^\\"]+/, 'string'],
+ [/@escapes/, 'string.escape'],
+ [/\\./, 'string.escape.invalid'],
+ [/"/, 'string', '@pop']
+ ],
- monaco.languages.register({id: 'd'});
- monaco.languages.setMonarchTokensProvider('d', definition());
- monaco.languages.setLanguageConfiguration('d', configuration());
-});
\ No newline at end of file
+ rawstring: [
+ [/[^\`]/, "string"],
+ [/`/, "string", "@pop"]
+ ],
+ }
+ };
+}
+
+function configuration() {
+ return {
+ comments: {
+ lineComment: '//',
+ blockComment: ['/*', '*/'],
+ },
+
+ brackets: [
+ ['{', '}'],
+ ['[', ']'],
+ ['(', ')']
+ ],
+
+ autoClosingPairs: [
+ { open: '{', close: '}' },
+ { open: '[', close: ']' },
+ { open: '(', close: ')' },
+ { open: '`', close: '`', notIn: ['string'] },
+ { open: '"', close: '"', notIn: ['string'] },
+ { open: '\'', close: '\'', notIn: ['string', 'comment'] },
+ ],
+
+ surroundingPairs: [
+ { open: '{', close: '}' },
+ { open: '[', close: ']' },
+ { open: '(', close: ')' },
+ { open: '`', close: '`' },
+ { open: '"', close: '"' },
+ { open: '\'', close: '\'' },
+ ]
+ };
+}
+
+monaco.languages.register({id: 'd'});
+monaco.languages.setMonarchTokensProvider('d', definition());
+monaco.languages.setLanguageConfiguration('d', configuration());
diff --git a/static/diff.js b/static/diff.js
index ed86db5c7..ecb20ff46 100644
--- a/static/diff.js
+++ b/static/diff.js
@@ -23,209 +23,207 @@
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
-define(function (require) {
- "use strict";
+"use strict";
- var FontScale = require('fontscale');
- var monaco = require('monaco');
- var _ = require('underscore');
- var $ = require('jquery');
+var FontScale = require('fontscale');
+var monaco = require('monaco');
+var _ = require('underscore');
+var $ = require('jquery');
- require('asm-mode');
- require('selectize');
+require('asm-mode');
+require('selectize');
- function State(id, model) {
- this.id = id;
- this.model = model;
- this.compiler = null;
- this.result = null;
- }
+function State(id, model) {
+ this.id = id;
+ this.model = model;
+ this.compiler = null;
+ this.result = null;
+}
- State.prototype.update = function (id, compiler, result) {
- if (this.id !== id) return false;
- this.compiler = compiler;
- this.result = result;
- var asm = result.asm || [];
- this.model.setValue(_.pluck(asm, 'text').join("\n"));
- return true;
- };
+State.prototype.update = function (id, compiler, result) {
+ if (this.id !== id) return false;
+ this.compiler = compiler;
+ this.result = result;
+ var asm = result.asm || [];
+ this.model.setValue(_.pluck(asm, 'text').join("\n"));
+ return true;
+};
- function Diff(hub, container, state) {
- this.container = container;
- this.eventHub = hub.createEventHub();
- this.domRoot = container.getElement();
- this.domRoot.html($('#diff').html());
- this.compilers = {};
+function Diff(hub, container, state) {
+ this.container = container;
+ this.eventHub = hub.createEventHub();
+ this.domRoot = container.getElement();
+ this.domRoot.html($('#diff').html());
+ this.compilers = {};
- this.outputEditor = monaco.editor.createDiffEditor(this.domRoot.find(".monaco-placeholder")[0], {
- fontFamily: 'monospace',
- scrollBeyondLastLine: false,
- readOnly: true,
- language: 'asm'
- });
+ this.outputEditor = monaco.editor.createDiffEditor(this.domRoot.find(".monaco-placeholder")[0], {
+ fontFamily: 'monospace',
+ scrollBeyondLastLine: false,
+ readOnly: true,
+ language: 'asm'
+ });
- this.lhs = new State(state.lhs, monaco.editor.createModel('', 'asm'));
- this.rhs = new State(state.rhs, monaco.editor.createModel('', 'asm'));
- this.outputEditor.setModel({original: this.lhs.model, modified: this.rhs.model});
+ this.lhs = new State(state.lhs, monaco.editor.createModel('', 'asm'));
+ this.rhs = new State(state.rhs, monaco.editor.createModel('', 'asm'));
+ this.outputEditor.setModel({original: this.lhs.model, modified: this.rhs.model});
- var selectize = this.domRoot.find(".diff-picker").selectize({
- sortField: 'name',
- valueField: 'id',
- labelField: 'name',
- searchField: ['name'],
- options: [],
- items: [],
- render: {
- option: function (item, escape) {
- return '