From f2c1e0bd315fbce55582c440f2d3c8c922a5083a Mon Sep 17 00:00:00 2001 From: Matt Godbolt Date: Mon, 9 May 2022 23:13:50 -0500 Subject: [PATCH] The Grand Reformat (#3643) * The Grand Reformat - everything made prettier...literally - some tweaks to include a few more files, including documentation - minor changes to format style - some tiny `// prettier-ignore` changes to keep a few things the way we like them - a couple of super minor tweaks to embedded document types to ensure they format correctly --- .eslint-license-header.yml | 56 +- .eslintrc.yml | 10 +- .github/ISSUE_TEMPLATE/bug_report.yml | 9 +- .github/ISSUE_TEMPLATE/compiler_request.yml | 4 +- .github/ISSUE_TEMPLATE/feature_request.yml | 8 +- .github/ISSUE_TEMPLATE/library_request.yml | 8 +- .github/labeler.yml | 154 ++--- .github/workflows/browserslist.yml | 8 +- .github/workflows/codeql-analysis.yml | 58 +- .github/workflows/label.yml | 2 +- .github/workflows/test-and-deploy.yml | 4 +- .github/workflows/test-win.yml | 2 +- .idea/codeStyles/Project.xml | 3 + .prettierignore | 2 - .prettierrc.js | 3 +- AUTHORS.md | 6 +- CODE_OF_CONDUCT.md | 77 +-- CONTRIBUTING.md | 120 ++-- README.md | 131 ++-- SECURITY.md | 17 +- cypress/integration/frontend-testing.js | 2 +- docs/API.md | 133 ++-- docs/AboutLibraryPaths.md | 103 +-- docs/AddingACompiler.md | 165 ++--- docs/AddingAFormatter.md | 27 +- docs/AddingALanguage.md | 105 +-- docs/AddingALibrary.md | 186 +++--- docs/AddingATool.md | 36 +- docs/AddingAssemblyDocumentation.md | 37 +- docs/AddingCustomCompilersOverview.md | 43 +- docs/EWARM.md | 53 +- docs/EWAVR.md | 81 ++- docs/Privacy.md | 21 +- docs/README.md | 49 +- docs/Roadmap.md | 13 +- docs/Sponsors.md | 14 +- docs/SystemdSocketActivation.md | 6 +- docs/WindowsNative.md | 108 ++-- docs/WindowsSubsystemForLinux.md | 122 ++-- docs/internal/AddingLinkableLibrary.md | 71 +- docs/internal/BuildingAdHocCompilers.md | 15 +- docs/internal/FrontendTesting.md | 20 +- docs/internal/Preupdate-Checklist.md | 54 +- docs/internal/UpdatingAsmDocsx86.md | 10 +- docs/internal/library_builder_logging.md | 19 +- lib/asm-docs/_all.ts | 10 +- lib/asm-docs/amd64.ts | 8 +- lib/asm-docs/avr.ts | 8 +- lib/asm-docs/index.ts | 4 +- lib/asm-docs/java.ts | 8 +- lib/asm-docs/mos6502.ts | 8 +- lib/aws.js | 15 +- lib/buildenvsetup/_all.js | 4 +- lib/buildenvsetup/base.js | 17 +- lib/buildenvsetup/cliconan.js | 13 +- lib/buildenvsetup/index.js | 4 +- lib/cfg.js | 71 +- lib/clientstate.js | 22 +- lib/compilation-queue.js | 10 +- lib/compilers/_all.js | 128 ++-- lib/compilers/analysis-tool.js | 9 +- lib/compilers/assembly.js | 21 +- lib/compilers/cc65.js | 6 +- lib/compilers/circle.js | 6 +- lib/compilers/cproc.js | 2 +- lib/compilers/crystal.js | 10 +- lib/compilers/dart.js | 20 +- lib/compilers/default.js | 6 +- lib/compilers/dmd.js | 13 +- lib/compilers/ellcc.js | 6 +- lib/compilers/ewarm.js | 23 +- lib/compilers/ewavr.js | 21 +- lib/compilers/fake-for-test.js | 27 +- lib/compilers/fortran.js | 6 +- lib/compilers/gcc.js | 6 +- lib/compilers/gccrs.js | 6 +- lib/compilers/golang.js | 7 +- lib/compilers/index.js | 2 +- lib/compilers/ispc.js | 8 +- lib/compilers/kotlin.js | 13 +- lib/compilers/ldc.js | 16 +- lib/compilers/llc.js | 8 +- lib/compilers/llvm-mca.js | 12 +- lib/compilers/mrustc.js | 25 +- lib/compilers/nasm.js | 20 +- lib/compilers/nvcc.js | 10 +- lib/compilers/ocaml.js | 8 +- lib/compilers/opt.js | 8 +- lib/compilers/osaca.js | 14 +- lib/compilers/pascal-win.js | 51 +- lib/compilers/pascal.js | 20 +- lib/compilers/ppci.js | 16 +- lib/compilers/ptxas.js | 9 +- lib/compilers/python.js | 16 +- lib/compilers/ruby.js | 13 +- lib/compilers/rust.js | 15 +- lib/compilers/rustc-cg-gcc.js | 25 +- lib/compilers/scala.js | 15 +- lib/compilers/sdcc.js | 6 +- lib/compilers/spirv.js | 52 +- lib/compilers/swift.js | 8 +- lib/compilers/tendra.js | 6 +- lib/compilers/tinyc.js | 12 +- lib/compilers/typescript.js | 22 +- lib/compilers/win32-vc.js | 10 +- lib/compilers/win32-vc6.js | 10 +- lib/compilers/win32.js | 60 +- lib/compilers/wine-vc.js | 16 +- lib/compilers/wsl-vc.js | 14 +- lib/csp.js | 85 ++- lib/demangler/_all.js | 8 +- lib/demangler/cpp.js | 6 +- lib/demangler/default.js | 6 +- lib/demangler/index.js | 4 +- lib/demangler/pascal.js | 41 +- lib/demangler/prefix-tree.js | 18 +- lib/demangler/win32.js | 15 +- lib/formatters/_all.js | 8 +- lib/formatters/clang-format.js | 2 +- lib/formatters/dartformat.js | 4 +- lib/formatters/gofmt.js | 6 +- lib/formatters/index.js | 4 +- lib/formatters/rustfmt.js | 15 +- lib/handlers/compile.js | 82 ++- lib/handlers/formatting.js | 8 +- lib/handlers/health-check.js | 2 +- lib/handlers/noscript.js | 43 +- lib/handlers/route-api.js | 38 +- lib/handlers/source.js | 7 +- lib/instructionsets.js | 2 +- lib/keyed-type.js | 5 +- lib/languages.js | 2 +- lib/llvm-ir.js | 16 +- lib/mapfiles/map-file-delphi.js | 11 +- lib/mapfiles/map-file-vs.js | 7 +- lib/mapfiles/map-file.js | 58 +- lib/metrics-server.ts | 9 +- lib/objdumper/_all.js | 8 +- lib/objdumper/binutils.js | 6 +- lib/objdumper/default.js | 6 +- lib/objdumper/elftoolchain.js | 6 +- lib/objdumper/index.js | 4 +- lib/objdumper/llvm.js | 6 +- lib/packager.js | 54 +- lib/parsers/asm-parser-amdgpu.js | 2 +- lib/parsers/asm-parser-crystal.js | 2 +- lib/parsers/asm-parser-dart.js | 2 +- lib/parsers/asm-parser-dotnet.ts | 26 +- lib/parsers/asm-parser-ewavr.js | 51 +- lib/parsers/asm-parser-sass.js | 5 +- lib/parsers/asm-parser-vc.js | 40 +- lib/parsers/asm-parser-vc6.js | 46 +- lib/parsers/asm-parser.js | 40 +- lib/parsers/asm-raw.js | 14 +- lib/parsers/asmregex.js | 7 +- lib/pe32-support.js | 47 +- lib/properties.js | 8 +- lib/shortener/_all.js | 4 +- lib/shortener/base.js | 3 +- lib/shortener/default.js | 6 +- lib/shortener/index.js | 4 +- lib/shortener/tinyurl.js | 6 +- lib/sources/browser.ts | 2 +- lib/sources/builtin.ts | 2 +- lib/sources/index.ts | 9 +- lib/sponsors.js | 11 +- lib/storage/_all.js | 8 +- lib/storage/base.js | 8 +- lib/storage/index.js | 4 +- lib/storage/local.js | 8 +- lib/storage/null.js | 9 +- lib/storage/remote.js | 13 +- lib/storage/s3.js | 104 +-- lib/toolchain-utils.js | 4 +- lib/tooling/_all.js | 28 +- lib/tooling/base-tool.js | 30 +- lib/tooling/clang-format-tool.js | 8 +- lib/tooling/clang-query-tool.js | 8 +- lib/tooling/compiler-dropin-tool.js | 22 +- lib/tooling/index.js | 4 +- lib/tooling/llvm-mca-tool.js | 2 +- lib/tooling/microsoft-analysis-tool.js | 26 +- lib/tooling/osaca-tool.js | 19 +- lib/tooling/pahole-tool.js | 6 +- lib/tooling/readelf-tool.js | 11 +- lib/tooling/rustfmt-tool.js | 6 +- lib/tooling/strings-tool.js | 11 +- lib/tooling/testing-tool.js | 2 +- lib/tooling/x86to6502-tool.js | 14 +- package.json | 9 +- static/compiler-service.js | 232 +++---- static/explorer.scss | 53 +- static/noscript.scss | 4 +- static/panes/conformance-view.js | 257 +++++--- static/panes/device-view.js | 90 +-- static/panes/diff.js | 217 ++++--- static/rison.js | 1 + static/themes/dark-theme.scss | 49 +- static/themes/default-theme.scss | 39 +- test/_setup-log.js | 4 +- test/analysis-tests.js | 4 +- test/asm-tests.js | 22 +- test/aws-tests.js | 16 +- test/base-compiler-tests.js | 281 ++++---- test/base-formatter-tests.js | 2 +- test/cfg-tests.js | 2 +- test/checks.js | 9 +- test/compilation-env.js | 18 +- test/compiler-finder-tests.js | 3 +- test/compilers/argument-parsers-tests.js | 75 ++- test/compilers/clang-tests.js | 10 +- test/d-tests.js | 6 +- test/embedding.html | 32 +- test/filter-tests.js | 41 +- test/golang-tests.js | 6 +- test/google-tests.js | 30 +- test/handlers/api-tests.js | 47 +- test/handlers/asm-docs-tests.js | 89 ++- test/handlers/compile-tests.js | 605 ++++++++++-------- test/handlers/health-check-tests.js | 6 +- test/handlers/source-tests.js | 27 +- test/lang-tests.js | 8 +- test/llvm-ast-parser-tests.js | 6 +- test/llvm-ir-parser-tests.js | 108 ++-- test/llvm-ir-tests.js | 71 +- test/map-file-tests.js | 54 +- test/nim-tests.js | 4 +- test/options-handler.js | 89 +-- test/packager-tests.js | 12 +- test/pascal-tests.js | 116 ++-- test/pe32-tests.js | 2 +- test/pp-output-test.js | 5 +- test/ppci-tests.js | 16 +- test/properties-test.js | 15 +- test/sponsors-test.js | 18 +- test/statenormalisation-tests.js | 43 +- test/storage/storage-tests.js | 12 +- test/symbol-store-tests.js | 4 +- test/unfurl-tests.js | 21 +- test/utils-tests.js | 213 +++--- test/utils.js | 8 +- test/win-path-tests.js | 27 +- .../assembly-documentation.interfaces.ts | 2 +- types/languages.interfaces.ts | 8 +- 244 files changed, 4201 insertions(+), 3481 deletions(-) diff --git a/.eslint-license-header.yml b/.eslint-license-header.yml index 41db7dcd0..9d2ac71bd 100644 --- a/.eslint-license-header.yml +++ b/.eslint-license-header.yml @@ -1,32 +1,32 @@ --- plugins: -- eslint-plugin-header + - eslint-plugin-header rules: header/header: - - off - - line - - - pattern: "^ Copyright \\(c\\) \\d{4}, .*$" - template: " Copyright (c) 2021, Compiler Explorer Authors" - - " All rights reserved." - - "" - - " Redistribution and use in source and binary forms, with or without" - - " modification, are permitted provided that the following conditions are met:" - - "" - - " * Redistributions of source code must retain the above copyright notice," - - " this list of conditions and the following disclaimer." - - " * Redistributions in binary form must reproduce the above copyright" - - " notice, this list of conditions and the following disclaimer in the" - - " documentation and/or other materials provided with the distribution." - - "" - - " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" - - " AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE" - - " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE" - - " ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE" - - " LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" - - " CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" - - " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS" - - " INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" - - " 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." - - 2 + - off + - line + - - pattern: '^ Copyright \\(c\\) \\d{4}, .*$' + template: ' Copyright (c) 2021, Compiler Explorer Authors' + - ' All rights reserved.' + - '' + - ' Redistribution and use in source and binary forms, with or without' + - ' modification, are permitted provided that the following conditions are met:' + - '' + - ' * Redistributions of source code must retain the above copyright notice,' + - ' this list of conditions and the following disclaimer.' + - ' * Redistributions in binary form must reproduce the above copyright' + - ' notice, this list of conditions and the following disclaimer in the' + - ' documentation and/or other materials provided with the distribution.' + - '' + - ' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"' + - ' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE' + - ' IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE' + - ' ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE' + - ' LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR' + - ' CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF' + - ' SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS' + - ' INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN' + - ' 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.' + - 2 diff --git a/.eslintrc.yml b/.eslintrc.yml index deb38d4b2..cd5e073e4 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -45,7 +45,7 @@ rules: import/no-default-export: warn import/no-deprecated: warn import/no-mutable-exports: error - import/no-named-as-default-member: off # Far too many things (express, morgan, fs) trip this + import/no-named-as-default-member: off # Far too many things (express, morgan, fs) trip this import/no-self-import: error import/no-useless-path-segments: error import/no-webpack-loader-syntax: error @@ -147,7 +147,7 @@ rules: unicorn/prefer-spread: off unicorn/no-lonely-if: off unicorn/no-array-reduce: off - unicorn/prefer-array-flat: off # can't turn off yet without tests blowing up; lodash vs underscore? + unicorn/prefer-array-flat: off # can't turn off yet without tests blowing up; lodash vs underscore? unicorn/no-array-callback-reference: off unicorn/prefer-switch: off unicorn/no-static-only-class: off @@ -162,7 +162,7 @@ globals: BigInt: true settings: node: - tryExtensions: [ .js, .ts ] + tryExtensions: [.js, .ts] import/parsers: - "@typescript-eslint/parser": [ .ts, .tsx ] - import/resolver: "typescript" + '@typescript-eslint/parser': [.ts, .tsx] + import/resolver: 'typescript' diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 36295844e..85732bbed 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -1,7 +1,7 @@ name: Bug Report description: Create a report to help us improve -title: "[BUG]: " -labels: ["bug"] +title: '[BUG]: ' +labels: ['bug'] body: - type: textarea id: description @@ -50,12 +50,13 @@ body: required: false - type: markdown attributes: - value: "# System information" + value: '# System information' - type: input id: operating-system attributes: label: Operating System - description: If applicable (i.e, an issue with how the site behaves for you) the OS version this bug is happening in + description: + If applicable (i.e, an issue with how the site behaves for you) the OS version this bug is happening in placeholder: Ubuntu Linux 20.04 validations: required: false diff --git a/.github/ISSUE_TEMPLATE/compiler_request.yml b/.github/ISSUE_TEMPLATE/compiler_request.yml index ce01e603b..6c1bc3ed8 100644 --- a/.github/ISSUE_TEMPLATE/compiler_request.yml +++ b/.github/ISSUE_TEMPLATE/compiler_request.yml @@ -1,7 +1,7 @@ name: Compiler request description: Request a new compiler -title: "[COMPILER REQUEST]: " -labels: ["request", "new-compilers"] +title: '[COMPILER REQUEST]: ' +labels: ['request', 'new-compilers'] body: - type: input id: compiler-name diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml index ec458efc1..36da8b78d 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.yml +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -1,7 +1,7 @@ name: Feature request description: Suggest an idea for the project -title: "[REQUEST]: " -labels: ["request"] +title: '[REQUEST]: ' +labels: ['request'] body: - type: textarea id: introduction @@ -23,7 +23,9 @@ body: id: alternatives attributes: label: Describe alternatives you've considered - description: If applicable, please add a clear and concise description of any alternative solutions or features you've considered. + description: + If applicable, please add a clear and concise description of any alternative solutions or features you've + considered. placeholder: You can pass -E to the compiler flags, but I'd like to easily side-by-side compare validations: required: true diff --git a/.github/ISSUE_TEMPLATE/library_request.yml b/.github/ISSUE_TEMPLATE/library_request.yml index 6bd75b95c..0910d93cf 100644 --- a/.github/ISSUE_TEMPLATE/library_request.yml +++ b/.github/ISSUE_TEMPLATE/library_request.yml @@ -1,7 +1,7 @@ name: Library request description: Request a new library -title: "[LIB REQUEST]: " -labels: ["request", "new-libs"] +title: '[LIB REQUEST]: ' +labels: ['request', 'new-libs'] body: - type: input id: library-name @@ -15,7 +15,9 @@ body: id: library-description attributes: label: Library description - description: A sentence that describes what this library does. It helps us when filling some of the UI elements when adding the library + description: + A sentence that describes what this library does. It helps us when filling some of the UI elements when adding + the library placeholder: GoogleTest is a testing library for C++ validations: required: true diff --git a/.github/labeler.yml b/.github/labeler.yml index 81f99e2b7..e5afe1151 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -1,110 +1,110 @@ ui: - - static/**/* - - views/**/* + - static/**/* + - views/**/* lang-ada: - - lib/compilers/ada.js - - etc/config/ada.*.properties + - lib/compilers/ada.js + - etc/config/ada.*.properties lang-asm: - - lib/compilers/assembly.js - - lib/compilers/nasm.js - - lib/compilers/ptxas.js - - etc/config/assembly.*.properties + - lib/compilers/assembly.js + - lib/compilers/nasm.js + - lib/compilers/ptxas.js + - etc/config/assembly.*.properties lang-c: - - lib/compilers/cc65.js - - lib/compilers/ellcc.js - - lib/compilers/ewarm.js - - lib/compilers/awavr.js - - lib/compilers/ppci.js - - lib/compilers/sdcc.js - - lib/compilers/tendra.js - - etc/config/c.*.properties + - lib/compilers/cc65.js + - lib/compilers/ellcc.js + - lib/compilers/ewarm.js + - lib/compilers/awavr.js + - lib/compilers/ppci.js + - lib/compilers/sdcc.js + - lib/compilers/tendra.js + - etc/config/c.*.properties lang-c++: - - lib/compilers/ewarm.js - - lib/compilers/awavr.js - - etc/config/c++.*.properties + - lib/compilers/ewarm.js + - lib/compilers/awavr.js + - etc/config/c++.*.properties lang-c++-opencl: - - etc/config/cpp_for_opencl.*.properties + - etc/config/cpp_for_opencl.*.properties lang-circle: - - lib/compilers/circle.js - - etc/config/circle.*.properties + - lib/compilers/circle.js + - etc/config/circle.*.properties lang-clean: - - lib/compilers/clean.js - - etc/config/clean.*.properties + - lib/compilers/clean.js + - etc/config/clean.*.properties lang-cppx: - - etc/config/cppx?(_blue|_gold).*.properties + - etc/config/cppx?(_blue|_gold).*.properties lang-crystal: - - lib/compilers/crystal.js - - etc/config/crystal.*.properties + - lib/compilers/crystal.js + - etc/config/crystal.*.properties lang-cuda: - - lib/compilers/nvcc.js - - etc/config/cuda.*.properties + - lib/compilers/nvcc.js + - etc/config/cuda.*.properties lang-d: - - lib/compilers/dmd.js - - lib/compilers/ldc.js - - etc/config/d.*.properties + - lib/compilers/dmd.js + - lib/compilers/ldc.js + - etc/config/d.*.properties lang-dotnet: - - lib/compilers/dotnet.ts - - lib/asm-parser-dotnet.ts - - etc/config/csharp.*.properties - - etc/config/fsharp.*.properties - - etc/config/vb.*.properties + - lib/compilers/dotnet.ts + - lib/asm-parser-dotnet.ts + - etc/config/csharp.*.properties + - etc/config/fsharp.*.properties + - etc/config/vb.*.properties lang-dart: - - lib/compilers/dart.js - - etc/config/dart.*.properties + - lib/compilers/dart.js + - etc/config/dart.*.properties lang-fortran: - - lib/compilers/fortran.js - - etc/config/fortran.*.properties + - lib/compilers/fortran.js + - etc/config/fortran.*.properties lang-go: - - lib/compilers/golang.js - - etc/config/go.*.properties + - lib/compilers/golang.js + - etc/config/go.*.properties lang-haskell: - - lib/compilers/haskell.js - - etc/config/haskell.*.properties + - lib/compilers/haskell.js + - etc/config/haskell.*.properties lang-ispc: - - lib/compilers/ispc.js - - etc/config/ispc.*.properties + - lib/compilers/ispc.js + - etc/config/ispc.*.properties lang-java: - - lib/compilers/java.js - - etc/config/java.*.properties + - lib/compilers/java.js + - etc/config/java.*.properties lang-kotlin: - - lib/compilers/kotlin.js - - etc/config/kotlin.*.properties + - lib/compilers/kotlin.js + - etc/config/kotlin.*.properties lang-nim: - - lib/compilers/nim.js - - etc/config/nim.*.properties + - lib/compilers/nim.js + - etc/config/nim.*.properties lang-ocaml: - - lib/compilers/ocaml.js - - etc/config/ocaml.*.properties + - lib/compilers/ocaml.js + - etc/config/ocaml.*.properties lang-opencl-c: - - etc/config/openclc.*.properties + - etc/config/openclc.*.properties lang-pascal: - - lib/compilers/pascal.js - - etc/config/pascal.*.properties + - lib/compilers/pascal.js + - etc/config/pascal.*.properties lang-python: - - lib/compilers/python.js - - etc/config/python.*.properties + - lib/compilers/python.js + - etc/config/python.*.properties lang-ruby: - - lib/compilers/ruby.js - - etc/config/ruby.*.properties + - lib/compilers/ruby.js + - etc/config/ruby.*.properties lang-rust: - - lib/compilers/rust.js - - etc/config/rust.*.properties + - lib/compilers/rust.js + - etc/config/rust.*.properties lang-scala: - - lib/compilers/scala.js - - etc/config/scala.*.properties + - lib/compilers/scala.js + - etc/config/scala.*.properties lang-solidity: - - lib/compilers/solidity.js - - etc/config/solidity.*.properties + - lib/compilers/solidity.js + - etc/config/solidity.*.properties lang-swift: - - lib/compilers/swift.js - - etc/config/swift.*.properties + - lib/compilers/swift.js + - etc/config/swift.*.properties lang-typescript: - - lib/compilers/typescript.js - - etc/config/typescript.*.properties + - lib/compilers/typescript.js + - etc/config/typescript.*.properties lang-zig: - - lib/compilers/zig.js - - etc/config/zig.*.properties + - lib/compilers/zig.js + - etc/config/zig.*.properties documentation: - - docs/**/* - - README.md - - CONTRIBUTING.md + - docs/**/* + - README.md + - CONTRIBUTING.md diff --git a/.github/workflows/browserslist.yml b/.github/workflows/browserslist.yml index 0cc2c0041..b3bb9443d 100644 --- a/.github/workflows/browserslist.yml +++ b/.github/workflows/browserslist.yml @@ -19,8 +19,8 @@ jobs: - name: Create Pull Request uses: peter-evans/create-pull-request@v3 with: - title: "[bot] Update browsers list" + title: '[bot] Update browsers list' body: | - Automatic run of `npm run-update-browerslist` which needs to - be done periodically to keep in-date. - See [here](https://github.com/browserslist/browserslist#browsers-data-updating) for more details. + Automatic run of `npm run-update-browerslist` which needs to + be done periodically to keep in-date. + See [here](https://github.com/browserslist/browserslist#browsers-data-updating) for more details. diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index eeb493836..5364d6019 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -9,14 +9,14 @@ # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # -name: "CodeQL" +name: 'CodeQL' on: push: - branches: [ main, release ] + branches: [main, release] pull_request: # The branches below must be a subset of the branches above - branches: [ main ] + branches: [main] schedule: - cron: '22 19 * * 4' @@ -32,37 +32,37 @@ jobs: strategy: fail-fast: false matrix: - language: [ 'javascript', 'python' ] + language: ['javascript', 'python'] steps: - - name: Checkout repository - uses: actions/checkout@v2 + - name: Checkout repository + uses: actions/checkout@v2 - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v1 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v1 - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl - # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language - #- run: | - # make bootstrap - # make release + #- run: | + # make bootstrap + # make release - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/label.yml b/.github/workflows/label.yml index e5af1acc9..65390e194 100644 --- a/.github/workflows/label.yml +++ b/.github/workflows/label.yml @@ -13,4 +13,4 @@ jobs: steps: - uses: actions/labeler@v3 with: - repo-token: "${{ secrets.GITHUB_TOKEN }}" + repo-token: '${{ secrets.GITHUB_TOKEN }}' diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml index 1b06cc4a1..0f38de714 100644 --- a/.github/workflows/test-and-deploy.yml +++ b/.github/workflows/test-and-deploy.yml @@ -1,6 +1,6 @@ name: Compiler Explorer -on: [ push, pull_request ] +on: [push, pull_request] jobs: test: @@ -53,7 +53,7 @@ jobs: deploy: if: github.repository_owner == 'compiler-explorer' && github.event_name == 'push' - needs: [ test, build_dist ] + needs: [test, build_dist] runs-on: ubuntu-20.04 steps: diff --git a/.github/workflows/test-win.yml b/.github/workflows/test-win.yml index 9af5a4aba..8a039b6b2 100644 --- a/.github/workflows/test-win.yml +++ b/.github/workflows/test-win.yml @@ -1,6 +1,6 @@ name: Compiler Explorer on Windows -on: [ push ] +on: [push] jobs: build-and-test: diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 054d53a0d..3cc3fbdf7 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -62,5 +62,8 @@ + + \ No newline at end of file diff --git a/.prettierignore b/.prettierignore index 1af7cee3a..f4aa01431 100644 --- a/.prettierignore +++ b/.prettierignore @@ -33,11 +33,9 @@ newrelic_agent.log # From .eslintignore # Uninteresting folders (node_modules and dotfiles/dotfolders ignored by default) -docs etc examples out -views # Autogenerated files lib/asm-docs/generated/asm-docs-*.js diff --git a/.prettierrc.js b/.prettierrc.js index 11530bede..ce3f0a3a2 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -5,9 +5,10 @@ module.exports = { arrowParens: 'avoid', tabWidth: 4, bracketSpacing: false, + proseWrap: 'always', overrides: [ { - files: '*.{yml,json}', + files: '*.{yml,json,md}', options: { tabWidth: 2, }, diff --git a/AUTHORS.md b/AUTHORS.md index ff3f628e6..ddb5f154b 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -1,5 +1,6 @@ -Currently, the people referred to when the documentation or policies mention - the administration team of Compiler Explorer are: +Currently, the people referred to when the documentation or policies mention the administration team of Compiler +Explorer are: + - [Matt Godbolt](https://xania.org) - [Rubén Rincón](https://rinconblanco.es) - [Patrick Quist](https://github.com/partouf) @@ -8,6 +9,7 @@ Currently, the people referred to when the documentation or policies mention --- Additionally, these people have been immensely helpful in the development of Compiler Explorer: + - [Jared Wyles](https://github.com/jaredwy) - [Chedy Najjar](https://github.com/CppChedy) - [Simon Brand](https://blog.tartanllama.xyz/) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 160107325..80bd52f97 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -4,73 +4,60 @@ ## Our Pledge -In the interest of fostering an open and welcoming environment, we as - contributors and maintainers pledge to make participation in our project - and our community a harassment-free experience for everyone, regardless of age, - body size, disability, ethnicity, gender identity, and expression, - level of experience, nationality, personal appearance, race, religion, - or sexual identity and orientation. +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make +participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, +disability, ethnicity, gender identity, and expression, level of experience, nationality, personal appearance, race, +religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: -* Using welcoming and inclusive language. -* Being respectful of differing viewpoints and experiences. -* Gracefully accepting constructive criticism. -* Focusing on what is best for the community. -* Showing empathy towards other community members. +- Using welcoming and inclusive language. +- Being respectful of differing viewpoints and experiences. +- Gracefully accepting constructive criticism. +- Focusing on what is best for the community. +- Showing empathy towards other community members. Examples of **unacceptable** behavior by participants include: -* The use of sexualized language or imagery and unwelcome sexual attention or advances. -* Trolling, insulting/derogatory comments, and personal or political attacks. -* Public or private harassment. -* Publishing others' private information, such as a physical or electronic address, - without explicit permission. -* Other conduct which could reasonably be considered inappropriate in a - professional setting. +- The use of sexualized language or imagery and unwelcome sexual attention or advances. +- Trolling, insulting/derogatory comments, and personal or political attacks. +- Public or private harassment. +- Publishing others' private information, such as a physical or electronic address, without explicit permission. +- Other conduct which could reasonably be considered inappropriate in a professional setting. ## Our Responsibilities -Project maintainers are responsible for clarifying the standards of acceptable - behavior and are expected to take appropriate and fair corrective action in - response to any instances of unacceptable behavior. +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take +appropriate and fair corrective action in response to any instances of unacceptable behavior. -Project maintainers have the right and responsibility to remove, edit, or - reject comments, commits, code, wiki edits, issues, and other contributions - that are not aligned to this Code of Conduct, or to ban - temporarily or permanently any contributor for other behaviors that they deem - inappropriate, threatening, offensive, or harmful. +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, +issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope -This Code of Conduct applies both within project spaces and in public spaces - when an individual is representing the project or its community. Examples of - representing a project or community include using an official project e-mail - address, posting via an official social media account, or acting as - an appointed representative at an online or offline event. - Representation of a project may be further defined and clarified by the project - maintainers. +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the +project or its community. Examples of representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed representative at an online or offline +event. Representation of a project may be further defined and clarified by the project maintainers. ## Enforcement -Instances of abusive, harassing, or otherwise unacceptable behavior may be - reported by contacting the project owner at - [matt@godbolt.org](mailto:matt@godbolt.org). The project team will review - and investigate all complaints, and will respond in a way that it deems - appropriate to the circumstances. The project team is obligated to maintain - confidentiality concerning the reporter of an incident. Further details of - specific enforcement policies may be posted separately. +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project owner at +[matt@godbolt.org](mailto:matt@godbolt.org). The project team will review and investigate all complaints, and will +respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain +confidentiality concerning the reporter of an incident. Further details of specific enforcement policies may be posted +separately. -Project maintainers who do not follow or enforce the Code of Conduct in good - faith may face temporary or permanent repercussions as determined by other - members of the project's leadership. +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent +repercussions as determined by other members of the project's leadership. ## Attribution -This Code of Conduct is adapted from the [Contributor Covenant][homepage], - version 1.4, available at [contributor-covenant.org/version/1/4][version] +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at +[contributor-covenant.org/version/1/4][version] [homepage]: https://www.contributor-covenant.org/ [version]: https://www.contributor-covenant.org/version/1/4/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 46bb4f74f..b946d6db4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,94 +1,78 @@ # Contributing to Compiler Explorer -First off, if you're reading this: thank you! Even considering contributing to - **Compiler Explorer** is very much appreciated! -Before we go too far, an apology: **Compiler Explorer** grew out of a bit of - hacky JavaScript into a pretty large and well-used project pretty quickly. -Not all the code was originally well-written or well-tested. -Please be forgiving of that. +First off, if you're reading this: thank you! Even considering contributing to **Compiler Explorer** is very much +appreciated! Before we go too far, an apology: **Compiler Explorer** grew out of a bit of hacky JavaScript into a pretty +large and well-used project pretty quickly. Not all the code was originally well-written or well-tested. Please be +forgiving of that. -**Compiler Explorer** follows a [Code of Conduct](CODE_OF_CONDUCT.md) which - aims to foster an open and welcoming environment. +**Compiler Explorer** follows a [Code of Conduct](CODE_OF_CONDUCT.md) which aims to foster an open and welcoming +environment. # Where to start -We have labeled issues which should be easy to do that you can find [here](https://github.com/compiler-explorer/compiler-explorer/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) +We have labeled issues which should be easy to do that you can find +[here](https://github.com/compiler-explorer/compiler-explorer/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) If you have any questions, don't hesitate: [Contact us]. -If there is something you would like to do yourself, it might help to make an issue so people can weigh in and point you in the right direction. - +If there is something you would like to do yourself, it might help to make an issue so people can weigh in and point you +in the right direction. ## Node version -**Compiler Explorer** currently targets [Node.js](https://nodejs.org/) LTS version 16 - so it's better if you do so as well when testing your changes locally. + +**Compiler Explorer** currently targets [Node.js](https://nodejs.org/) LTS version 16 so it's better if you do so as +well when testing your changes locally. ## In brief -* Make your changes, trying to stick to the style and format where possible. - * We use [ESLint](https://eslint.org/) to ensure a consistent code base - and PRs won't pass unless it detects no errors. - * Running `make lint` will run the linter, which will auto-fix everything - it can and report back any errors and warnings. -* If you're adding a new server-side component, please do your best to add a test to - cover it. For client-side changes that's trickier. -* Tests should run automatically as a pre-commit step. - _You can disable this check with `git commit --no-verify` if needed_. -* You can run `make check` to run both the linter and the code tests -* Do a smoke test: - Run `make` and ensure the site works as you'd expect. Concentrate on the - areas you'd expect to have changed, but if you can, click about generally to - help check you haven't unintentionally broken something else -* Submit a Pull Request. + +- Make your changes, trying to stick to the style and format where possible. + - We use [ESLint](https://eslint.org/) to ensure a consistent code base and PRs won't pass unless it detects no + errors. + - Running `make lint` will run the linter, which will auto-fix everything it can and report back any errors and + warnings. +- If you're adding a new server-side component, please do your best to add a test to cover it. For client-side changes + that's trickier. +- Tests should run automatically as a pre-commit step. _You can disable this check with `git commit --no-verify` if + needed_. +- You can run `make check` to run both the linter and the code tests +- Do a smoke test: Run `make` and ensure the site works as you'd expect. Concentrate on the areas you'd expect to have + changed, but if you can, click about generally to help check you haven't unintentionally broken something else +- Submit a Pull Request. ## Basic code layout -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. +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/`. All of them inherit from `lib/base-compiler.js` which does - most of the work of running compilers, then parsing the output and forming a - JSON object to send to the client. Any assembly parsing is done in the - `lib/asm-parser.js`, and similar, files. +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/`. All of them inherit from `lib/base-compiler.js` which does most of the work of +running compilers, then parsing the output and forming a JSON object to send to the client. Any assembly parsing is done +in the `lib/asm-parser.js`, and similar, files. -In the client code, [GoldenLayout](https://www.golden-layout.com/) is used as - the container. If you look at some components like the - `static/compiler.js`, you'll see the general flow. - Any state stored makes it into the URL, so be careful not to stash - anything too big in there. +In the client code, [GoldenLayout](https://www.golden-layout.com/) is used as the container. If you look at some +components like the `static/compiler.js`, you'll see the general flow. Any state stored makes it into the URL, so be +careful not to stash anything too big in there. -The client code follows GoldenLayout's message-based system: - no component has a reference to any other and everything is done via messages. - This will allow us to use pop-out windows, if we ever need to, as the messages - are JSON-serializable between separate windows. +The client code follows GoldenLayout's message-based system: no component has a reference to any other and everything is +done via messages. This will allow us to use pop-out windows, if we ever need to, as the messages are JSON-serializable +between separate windows. ## Editing flow -The recommended way to work on **Compiler Explorer** is to just run `make dev` - and let the automatic reloading do its magic. -Any changes to the server code will cause the server to reload, and any changes - to the client code will be reflected upon a page reload. - This makes for a pretty quick turnaround. -Note that a current issue makes every project media asset to be locally - unavailable. We will hopefully fix this in the near future. +The recommended way to work on **Compiler Explorer** is to just run `make dev` and let the automatic reloading do its +magic. Any changes to the server code will cause the server to reload, and any changes to the client code will be +reflected upon a page reload. This makes for a pretty quick turnaround. Note that a current issue makes every project +media asset to be locally unavailable. We will hopefully fix this in the near future. ## Gotchas -* New client-side code should preferably be written in TypeScript, - but we will always accept js code too. Be aware that in that case, - you must stick to **ES5** (so no `let` or arrow operators) js code. - Sadly there are still enough users out there on old browsers. - Note that this restriction does not apply to the server side code, - in which you can use all the cool features you want. - In lieu of ES6 features, [Underscore.js](https://underscorejs.org/) is available - as a way to bridge the feature gap. The library is available both - in the client and server code. -* Be aware that **Compiler Explorer** runs on a cluster on the live site. - No local state is kept between invocations, and the user's next request will - likely hit a different node in the cluster, so don't rely on - any in-memory state. +- New client-side code should preferably be written in TypeScript, but we will always accept js code too. Be aware that + in that case, you must stick to **ES5** (so no `let` or arrow operators) js code. Sadly there are still enough users + out there on old browsers. Note that this restriction does not apply to the server side code, in which you can use all + the cool features you want. In lieu of ES6 features, [Underscore.js](https://underscorejs.org/) is available as a way + to bridge the feature gap. The library is available both in the client and server code. +- Be aware that **Compiler Explorer** runs on a cluster on the live site. No local state is kept between invocations, + and the user's next request will likely hit a different node in the cluster, so don't rely on any in-memory state. -[Contact us]: README.md#contact-us +[contact us]: README.md#contact-us diff --git a/README.md b/README.md index 0618d521d..618ff53dd 100644 --- a/README.md +++ b/README.md @@ -5,102 +5,98 @@ # Compiler Explorer -**Compiler Explorer** is an interactive compiler exploration website. Edit code in C, C++, C#, F#, Rust, Go, D, Haskell, Swift, Pascal, [ispc](https://ispc.github.io/), Python, Java - or in any of the other [30+ supported languages](https://godbolt.org/api/languages), and see how that code looks after being compiled in real time. - Multiple compilers are supported for each language, many different tools and visualisations are available, and the UI layout - is configurable (thanks to [GoldenLayout](https://www.golden-layout.com/)). +**Compiler Explorer** is an interactive compiler exploration website. Edit code in C, C++, C#, F#, Rust, Go, D, Haskell, +Swift, Pascal, [ispc](https://ispc.github.io/), Python, Java or in any of the other +[30+ supported languages](https://godbolt.org/api/languages), and see how that code looks after being compiled in real +time. Multiple compilers are supported for each language, many different tools and visualisations are available, and the +UI layout is configurable (thanks to [GoldenLayout](https://www.golden-layout.com/)). Try out at [godbolt.org](https://godbolt.org), or [run your own local instance](#running-a-local-instance). -**Compiler Explorer** follows a [Code of Conduct](CODE_OF_CONDUCT.md) which - aims to foster an open and welcoming environment. +**Compiler Explorer** follows a [Code of Conduct](CODE_OF_CONDUCT.md) which aims to foster an open and welcoming +environment. **Compiler Explorer** was started in 2012 to show how C++ constructs translated to assembly code. It started out as a - `tmux` session with `vi` running in one pane and `watch gcc -S foo.cc -o -` running in the other. +`tmux` session with `vi` running in one pane and `watch gcc -S foo.cc -o -` running in the other. -Since then, it has become a public website serving around [3,000,000 compilations per week](https://www.stathat.com/cards/Tk5csAWI0O7x). +Since then, it has become a public website serving around +[3,000,000 compilations per week](https://www.stathat.com/cards/Tk5csAWI0O7x). You can financially support [this project on Patreon](https://patreon.com/mattgodbolt), -[GitHub](https://github.com/sponsors/mattgodbolt/), [Paypal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=KQWQZ7GPY2GZ6&item_name=Compiler+Explorer+development¤cy_code=USD&source=url), or by -buying cool gear on the [Compiler Explorer store](https://shop.spreadshirt.com/compiler-explorer/). +[GitHub](https://github.com/sponsors/mattgodbolt/), +[Paypal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=KQWQZ7GPY2GZ6&item_name=Compiler+Explorer+development¤cy_code=USD&source=url), +or by buying cool gear on the [Compiler Explorer store](https://shop.spreadshirt.com/compiler-explorer/). ## Using Compiler Explorer ### FAQ -There is now a FAQ section [in the repository wiki](https://github.com/compiler-explorer/compiler-explorer/wiki/FAQ). - If your question is not present, please contact us as described below, so we can help you. - If you find that the FAQ is lacking some important point, please free to contribute to it and/or ask us to clarify it. +There is now a FAQ section [in the repository wiki](https://github.com/compiler-explorer/compiler-explorer/wiki/FAQ). If +your question is not present, please contact us as described below, so we can help you. If you find that the FAQ is +lacking some important point, please free to contribute to it and/or ask us to clarify it. ### Videos There are a number of videos that showcase some features of Compiler Explorer: -* [Presentation for CppCon 2019 about the project](https://www.youtube.com/watch?v=kIoZDUd5DKw) -* [Older 2 part series of videos](https://www.youtube.com/watch?v=4_HL3PH4wDg) which go into a bit more detail - into the more obscure features. -* [Just Enough Assembly for Compiler Explorer](https://youtu.be/QLolzolunJ4): Practical introduction to Assembly with a focus on usage on Compiler Explorer, from CppCon 2021. -* [Playlist: Compiler Explorer](https://www.youtube.com/playlist?list=PL2HVqYf7If8dNYVN6ayjB06FPyhHCcnhG): A collection of videos discussing Compiler Explorer; using it, installing it, what it's for, etc. +- [Presentation for CppCon 2019 about the project](https://www.youtube.com/watch?v=kIoZDUd5DKw) +- [Older 2 part series of videos](https://www.youtube.com/watch?v=4_HL3PH4wDg) which go into a bit more detail into the + more obscure features. +- [Just Enough Assembly for Compiler Explorer](https://youtu.be/QLolzolunJ4): Practical introduction to Assembly with a + focus on usage on Compiler Explorer, from CppCon 2021. +- [Playlist: Compiler Explorer](https://www.youtube.com/playlist?list=PL2HVqYf7If8dNYVN6ayjB06FPyhHCcnhG): A collection + of videos discussing Compiler Explorer; using it, installing it, what it's for, etc. -A [Road map](docs/Roadmap.md) is available which gives a little insight into -the future plans for **Compiler Explorer**. +A [Road map](docs/Roadmap.md) is available which gives a little insight into the future plans for **Compiler Explorer**. ## Developing **Compiler Explorer** is written in [Node.js](https://nodejs.org/). -Assuming you have a compatible version of `node` installed, on Linux simply running - `make` ought to get you up and running with an Explorer running on port 10240 - on your local machine: [http://localhost:10240/](http://localhost:10240/). If this doesn't work for you, please contact - us, as we consider it important you can quickly and easily get running. - Currently, **Compiler Explorer** - requires [`node` 16 _(LTS version)_](CONTRIBUTING.md#node-version) installed, either on the path or at `NODE_DIR` - (an environment variable or `make` parameter). +Assuming you have a compatible version of `node` installed, on Linux simply running `make` ought to get you up and +running with an Explorer running on port 10240 on your local machine: +[http://localhost:10240/](http://localhost:10240/). If this doesn't work for you, please contact us, as we consider it +important you can quickly and easily get running. Currently, **Compiler Explorer** requires +[`node` 16 _(LTS version)_](CONTRIBUTING.md#node-version) installed, either on the path or at `NODE_DIR` (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`. For example, to only run **Compiler Explorer** with C++ support, you'd run - `make EXTRA_ARGS='--language c++'`. The `Makefile` will automatically install all the - third party libraries needed to run; using `npm` to install server-side and - client side components. +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`. For example, to only run **Compiler Explorer** with C++ support, +you'd run `make EXTRA_ARGS='--language c++'`. The `Makefile` will automatically install all the third party libraries +needed to run; using `npm` to install server-side and client side components. -For development, we suggest using `make dev` to enable some useful features, - such as automatic reloading on file changes and shorter startup times. +For development, we suggest using `make dev` to enable some useful features, such as automatic reloading on file changes +and shorter startup times. You can also use `npm run dev` to run if `make dev` doesn't work on your machine. -Some languages need extra tools to demangle them, e.g. `rust`, `d`, or `haskell`. - Such tools are kept separately in the - [tools repo](https://github.com/compiler-explorer/compiler-explorer-tools). +Some languages need extra tools to demangle them, e.g. `rust`, `d`, or `haskell`. Such tools are kept separately in the +[tools repo](https://github.com/compiler-explorer/compiler-explorer-tools). -Configuring compiler explorer is achieved via configuration files in the `etc/config` directory. Values are - `key=value`. Options in a `{type}.local.properties` file (where `{type}` is `c++` or similar) override anything in the - `{type}.defaults.properties` file. There is a `.gitignore` file to ignore `*.local.*` files, so these won't be checked - into git, and you won't find yourself fighting with updated versions when you `git pull`. For more information see - [Adding a Compiler](docs/AddingACompiler.md). +Configuring compiler explorer is achieved via configuration files in the `etc/config` directory. Values are `key=value`. +Options in a `{type}.local.properties` file (where `{type}` is `c++` or similar) override anything in the +`{type}.defaults.properties` file. There is a `.gitignore` file to ignore `*.local.*` files, so these won't be checked +into git, and you won't find yourself fighting with updated versions when you `git pull`. For more information see +[Adding a Compiler](docs/AddingACompiler.md). -Check [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed information about how you can contribute to **Compiler Explorer**, - and the [docs](./docs) folder for specific details regarding various things you might want to do, - such as how to add new compilers or languages to the site. +Check [CONTRIBUTING.md](./CONTRIBUTING.md) for detailed information about how you can contribute to **Compiler +Explorer**, and the [docs](./docs) folder for specific details regarding various things you might want to do, such as +how to add new compilers or languages to the site. ### Running a local instance -If you want to point it at your own GCC or similar binaries, either edit the - `etc/config/LANG.defaults.properties` or else make a new one with - the name `LANG.local.properties`, substituting `LANG` as needed. - `*.local.properties` files have the highest priority when loading properties. +If you want to point it at your own GCC or similar binaries, either edit the `etc/config/LANG.defaults.properties` or +else make a new one with the name `LANG.local.properties`, substituting `LANG` as needed. `*.local.properties` files +have the highest priority when loading properties. -When running in a corporate setting the URL shortening service can be replaced - by an internal one if the default storage driver isn't appropriate for your - environment. To do this, add a new module in `lib/shortener/myservice.js` and - set the `urlShortenService` variable in configuration. This module should - export a single function, see the [tinyurl module](lib/shortener/tinyurl.js) - for an example. +When running in a corporate setting the URL shortening service can be replaced by an internal one if the default storage +driver isn't appropriate for your environment. To do this, add a new module in `lib/shortener/myservice.js` and set the +`urlShortenService` variable in configuration. This module should export a single function, see the +[tinyurl module](lib/shortener/tinyurl.js) for an example. ### RESTful API -There's a simple restful API that can be used to do compiles to asm and to - list compilers. +There's a simple restful API that can be used to do compiles to asm and to list compilers. You can find the API documentation [here](docs/API.md). @@ -108,7 +104,8 @@ You can find the API documentation [here](docs/API.md). We run a [Compiler Explorer Discord](https://discord.gg/B5WacA7), which is a place to discuss using or developing Compiler Explorer. We also have a presence on the [cpplang](https://cppalliance.org/slack/) Slack channel -`#compiler_explorer` and we have [a public mailing list](https://groups.google.com/forum/#!forum/compiler-explorer-discussion). +`#compiler_explorer` and we have +[a public mailing list](https://groups.google.com/forum/#!forum/compiler-explorer-discussion). There's a development channel on the discord, and also a [development mailing list](https://groups.google.com/forum/#!forum/compiler-explorer-development). @@ -118,20 +115,18 @@ Feel free to raise an issue on [github](https://github.com/compiler-explorer/com ## Credits -**Compiler Explorer** is maintained by the awesome people listed in the - [AUTHORS](AUTHORS.md) file. +**Compiler Explorer** is maintained by the awesome people listed in the [AUTHORS](AUTHORS.md) file. -We would like to thank the contributors listed in the - [CONTRIBUTORS](CONTRIBUTORS.md) file, who have helped shape **Compiler Explorer**. +We would like to thank the contributors listed in the [CONTRIBUTORS](CONTRIBUTORS.md) file, who have helped shape +**Compiler Explorer**. -We would also like to specially thank these people for their contributions to - **Compiler Explorer**: -- [Gabriel Devillers](https://github.com/voxelf) - (_while working for [Kalray](http://www.kalrayinc.com/)_) +We would also like to specially thank these people for their contributions to **Compiler Explorer**: + +- [Gabriel Devillers](https://github.com/voxelf) (_while working for [Kalray](http://www.kalrayinc.com/)_) - [Johan Engelen](https://github.com/JohanEngelen) - [Joshua Sheard](https://github.com/jsheard) - [Marc Poulhiès](https://github.com/dkm) - [Andrew Pardoe](https://github.com/AndrewPardoe) A number of [amazing sponsors](https://godbolt.org/#sponsors), both individuals and companies, have helped fund and - promote Compiler Explorer. +promote Compiler Explorer. diff --git a/SECURITY.md b/SECURITY.md index 6d7e18941..c9c96000d 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,16 +1,15 @@ # Security Policy -Compiler Explorer allows remote users to compile and, if configured, execute -code. We take security seriously, and encourage users to promptly report -security vulnerabilities they find. +Compiler Explorer allows remote users to compile and, if configured, execute code. We take security seriously, and +encourage users to promptly report security vulnerabilities they find. ## Reporting a Vulnerability -If the issue can be reported without revealing exploitable specifics, please -file [an issue](https://github.com/compiler-explorer/compiler-explorer/issues/new/choose) as a bug. +If the issue can be reported without revealing exploitable specifics, please file +[an issue](https://github.com/compiler-explorer/compiler-explorer/issues/new/choose) as a bug. -Please email matt@godbolt.org with specifics, or if the bug can't be reported publically -without leaving an obvious exploit in the public eye. +Please email matt@godbolt.org with specifics, or if the bug can't be reported publically without leaving an obvious +exploit in the public eye. -We expect to get back within a day or two. If you don't hear from us, please do ping us again, -or reach out to us on the [Discord](https://discord.gg/wFXUwDp). +We expect to get back within a day or two. If you don't hear from us, please do ping us again, or reach out to us on the +[Discord](https://discord.gg/wFXUwDp). diff --git a/cypress/integration/frontend-testing.js b/cypress/integration/frontend-testing.js index 4dcc06709..99e6a89a1 100644 --- a/cypress/integration/frontend-testing.js +++ b/cypress/integration/frontend-testing.js @@ -1,6 +1,6 @@ function runFrontendTest(name) { it(name, () => { - cy.window().then((win) => { + cy.window().then(win => { return win.compilerExplorerFrontendTesting.run(name); }); }); diff --git a/docs/API.md b/docs/API.md index faa764b83..de8919cd9 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,65 +1,59 @@ # RESTful API -There's a simple restful API that can be used to do compiles to asm and to - list compilers. In general all handlers live in `/api/*` endpoints, will - accept JSON or text in POSTs, and will return text or JSON responses depending - on the request's `Accept` header. +There's a simple restful API that can be used to do compiles to asm and to list compilers. In general all handlers live +in `/api/*` endpoints, will accept JSON or text in POSTs, and will return text or JSON responses depending on the +request's `Accept` header. -At a later date there may be some form of rate-limiting: - currently, requests will be queued and dealt with in the same way interactive - requests are done for the main site. Authentication might be required at some - point in the future (for the main **Compiler Explorer** site anyway). +At a later date there may be some form of rate-limiting: currently, requests will be queued and dealt with in the same +way interactive requests are done for the main site. Authentication might be required at some point in the future (for +the main **Compiler Explorer** site anyway). ## Endpoints ### `GET /api/languages` - return a list of languages -Returns a list of the currently supported languages, as pairs of languages IDs - and their names. +Returns a list of the currently supported languages, as pairs of languages IDs and their names. ### `GET /api/compilers` - return a list of compilers -Returns a list of compilers. In text form, there's a simple formatting of the - ID of the compiler, its description and its language ID. In JSON, all the - information is returned as an array of compilers, with the `id` key being the - primary identifier of each compiler. +Returns a list of compilers. In text form, there's a simple formatting of the ID of the compiler, its description and +its language ID. In JSON, all the information is returned as an array of compilers, with the `id` key being the primary +identifier of each compiler. -Due to the amount of compilers and information available through this api call, - by default you will only get these fields per compiler: - `['id', 'name', 'lang', 'compilerType', 'semver', 'extensions', 'monaco']` +Due to the amount of compilers and information available through this api call, by default you will only get these +fields per compiler: `['id', 'name', 'lang', 'compilerType', 'semver', 'extensions', 'monaco']` -If you require different fields, you can specify them by adding `?fields=field1,field2,field3` - to your query. +If you require different fields, you can specify them by adding `?fields=field1,field2,field3` to your query. To see all the available fields, you can use `?fields=all`. It is not recommended using this by default. ### `GET /api/compilers/` - return a list of compilers with matching language -Returns a list of compilers for the provided language id. In text form, - there's a simple formatting of the ID of the compiler, its description and its - language ID. In JSON, all the information is returned as an array of compilers, - with the `id` key being the primary identifier of each compiler. +Returns a list of compilers for the provided language id. In text form, there's a simple formatting of the ID of the +compiler, its description and its language ID. In JSON, all the information is returned as an array of compilers, with +the `id` key being the primary identifier of each compiler. The same field restrictions apply as with `GET /api/compilers` ### `GET /api/libraries/` - return a list of libraries available with for a language -Returns a list of libraries and library versions available for the provided language id. - This request only returns data in JSON. +Returns a list of libraries and library versions available for the provided language id. This request only returns data +in JSON. -You can use the given include paths to supply in the userArguments for compilation. *(deprecated)* +You can use the given include paths to supply in the userArguments for compilation. _(deprecated)_ -You will need the library id's, and the version id's to supply to **compile** if you want to include libraries during compilation. +You will need the library id's, and the version id's to supply to **compile** if you want to include libraries during +compilation. -### `GET /api/shortlinkinfo/` - return information about a given link +### `GET /api/shortlinkinfo/` - return information about a given link -Returns information like Sourcecode, Compiler settings and libraries for a given link id. - This request only returns data in JSON. +Returns information like Sourcecode, Compiler settings and libraries for a given link id. This request only returns data +in JSON. ### `POST /api/compiler//compile` - perform a compilation -To specify a compilation request as a JSON document, post it as the appropriate - type and send an object of the form: +To specify a compilation request as a JSON document, post it as the appropriate type and send an object of the form: + ```JSON { "source": "", @@ -94,6 +88,7 @@ To specify a compilation request as a JSON document, post it as the appropriate ``` Execution Only request example: + ```JSON { "source": "int main () { return 1; }", @@ -120,27 +115,26 @@ Execution Only request example: } ``` -The filters are a JSON object with `true`/`false` values. If not supplied, - defaults are used. If supplied, the provided filters override their default - values. The `compilerOptions` is used to pass extra arguments to the back end, - and is probably not useful for most REST users. +The filters are a JSON object with `true`/`false` values. If not supplied, defaults are used. If supplied, the provided +filters override their default values. The `compilerOptions` is used to pass extra arguments to the back end, and is +probably not useful for most REST users. To force a cache bypass, set `bypassCache` in the root of the request to `true`. -Filters include `binary`, `labels`, `intel`, `directives` and - `demangle`, which correspond to the UI buttons on the HTML version. +Filters include `binary`, `labels`, `intel`, `directives` and `demangle`, which correspond to the UI buttons on the HTML +version. -With the tools array you can ask CE to execute certain tools available for - the current compiler, and also supply arguments for this tool. +With the tools array you can ask CE to execute certain tools available for the current compiler, and also supply +arguments for this tool. -Libraries can be marked to have their directories available when including - their header files. The can be listed by supplying the library ids and versions in an array. - The id's to supply can be found with the `/api/libraries/` +Libraries can be marked to have their directories available when including their header files. The can be listed by +supplying the library ids and versions in an array. The id's to supply can be found with the +`/api/libraries/` ### `GET /api/formats` - return available code formatters -Returns a list of code formatters. The API returns an array of formatter objects - which have the following object structure: +Returns a list of code formatters. The API returns an array of formatter objects which have the following object +structure: ```JSON { @@ -178,8 +172,7 @@ The returned JSON body has the following object structure: } ``` -In cases of internal code formatter failure an additional field named `throw` - is also provided and set to true. +In cases of internal code formatter failure an additional field named `throw` is also provided and set to true. # Non-REST API's @@ -187,12 +180,10 @@ In cases of internal code formatter failure an additional field named `throw` This is same endpoint as for compilation using JSON. -A text compilation request has the source as the body of the post, and uses - query parameters to pass the options and filters. Filters are supplied as a - comma-separated string. Use the query parameter `filters=XX` to set the - filters directly, else `addFilters=XX` to add a filter to defaults, - or `removeFilters` to remove from defaults. - Compiler parameters should be passed as `options=-O2` and default to empty. +A text compilation request has the source as the body of the post, and uses query parameters to pass the options and +filters. Filters are supplied as a comma-separated string. Use the query parameter `filters=XX` to set the filters +directly, else `addFilters=XX` to add a filter to defaults, or `removeFilters` to remove from defaults. Compiler +parameters should be passed as `options=-O2` and default to empty. The text request is designed for simplicity for command-line clients like `curl` @@ -207,8 +198,7 @@ foo(): ret ``` -If JSON is present in the request's `Accept` header, the compilation results - are of the form: +If JSON is present in the request's `Accept` header, the compilation results are of the form: (_Optional values are marked with a `**`_) @@ -250,12 +240,14 @@ If JSON is present in the request's `Accept` header, the compilation results } ``` -### `POST /api/shortener` - saves given state *forever* to a shortlink and returns the unique id for the link +### `POST /api/shortener` - saves given state _forever_ to a shortlink and returns the unique id for the link -The body of this post should be in the format of a [ClientState](https://github.com/compiler-explorer/compiler-explorer/blob/main/lib/clientstate.js) -Be sure that the Content-Type of your post is application/json +The body of this post should be in the format of a +[ClientState](https://github.com/compiler-explorer/compiler-explorer/blob/main/lib/clientstate.js) Be sure that the +Content-Type of your post is application/json An example of one the easiest forms of a clientstate: + ```JSON { "sessions": [ @@ -286,6 +278,7 @@ An example of one the easiest forms of a clientstate: ``` Returns: + ```JSON { "url": "https://godbolt.org/z/Km_340" @@ -298,27 +291,27 @@ The storedId can be used in the api call /api/shortlinkinfo/ and to open in This call opens the website in a state that was previously saved using the built-in shortener. - ### `GET /z//code/` - Returns just the sourcecode from a shortlink This call returns plain/text for the code that was previously saved using the built-in shortener. -If there were multiple editors during the saved session, you can retrieve them by setting to 1, 2, 3, etcetera, otherwise can be set to 1. - +If there were multiple editors during the saved session, you can retrieve them by setting to 1, 2, 3, +etcetera, otherwise can be set to 1. ### `GET /clientstate/` - Opens the website in a given state This call is to open the website with a given state (without having to store the state first with /api/shortener) -Instead of sending the ClientState JSON in the post body, it will have to be encoded with base64 and attached directly onto the URL. - +Instead of sending the ClientState JSON in the post body, it will have to be encoded with base64 and attached directly +onto the URL. # Implementations Here are some examples of projects using the Compiler Explorer API: -* [Commandline CE by ethanhs](https://github.com/ethanhs/cce) (Rust) -* [VIM plugin by ldrumm](https://github.com/ldrumm/compiler-explorer.vim) -* [API in Delphi by partouf](https://github.com/partouf/compilerexplorer-api) (Delphi) -* [QTCreator Plugin by dobokirisame](https://github.com/dobokirisame/CompilerExplorer) (C++) -* [CLion plugin by ogrebenyuk](https://github.com/ogrebenyuk/compilerexplorer) (Java) -* [QCompilerExplorer - frontend in Qt](https://github.com/Waqar144/QCompilerExplorer) (C++) -* [Emacs client - compiler-explorer.el](https://github.com/mkcms/compiler-explorer.el) + +- [Commandline CE by ethanhs](https://github.com/ethanhs/cce) (Rust) +- [VIM plugin by ldrumm](https://github.com/ldrumm/compiler-explorer.vim) +- [API in Delphi by partouf](https://github.com/partouf/compilerexplorer-api) (Delphi) +- [QTCreator Plugin by dobokirisame](https://github.com/dobokirisame/CompilerExplorer) (C++) +- [CLion plugin by ogrebenyuk](https://github.com/ogrebenyuk/compilerexplorer) (Java) +- [QCompilerExplorer - frontend in Qt](https://github.com/Waqar144/QCompilerExplorer) (C++) +- [Emacs client - compiler-explorer.el](https://github.com/mkcms/compiler-explorer.el) diff --git a/docs/AboutLibraryPaths.md b/docs/AboutLibraryPaths.md index 5ce273cc3..825f09aaa 100644 --- a/docs/AboutLibraryPaths.md +++ b/docs/AboutLibraryPaths.md @@ -4,45 +4,53 @@ Libraries are hard. Libraries can be needed for user code, but also to run compilers. -For CE we use a lot of different compilers and environments that need to be separated from the OS's installation, and that makes things more complicated than just building with your standard OS's compiler. +For CE we use a lot of different compilers and environments that need to be separated from the OS's installation, and +that makes things more complicated than just building with your standard OS's compiler. Including header files or equivalent is usually the easy part. If there are binaries involved, things get complicated. -We have a couple of separate stages where we use and mix different techniques to be able to produce the right assembly or executables. - -* Compilation without linking - * The `LD_LIBRARY_PATH` environment variable is used here to enable the compiler to find the `.so` files that they need to run. - * If you're running a local installation, this is usually your own systems' `LD_LIBRARY_PATH` plus extra things that CE adds through properties. - * On godbolt.org we always start with an empty `LD_LIBRARY_PATH` and add what is set in the properties. -* Building an executable or binary - * We use `-Wl,-rpath=` (or equivalent `rpathFlag`) to force library paths into the executable so that they will always find the same `.so` files no matter where they are run. Usually this also includes lib64 and lib folders that the compiler offers for standard libraries that the toolchain offers. - * Library paths supplied through `-Wl,-rpath=` for shared libraries will be able to dynamically link to the right architecture's `.so` even if multiple paths are given that contain the same `.so` file. - * We use `-L` (or equivalent `libpathFlag`) to enable the compiler to find both static (`.a`) and shared (`.so`) libraries. - * We always add '.' as a path as well because that's where we put libraries that are downloaded from our Conan server. - * We use `-l` (or equivalent `linkFlag`) to say we want to statically or dynamically link to a named library binary (the compiler and linker decide if it's gonna be static or dynamic). -* Running the executable - * We use `LD_LIBRARY_PATH` just in case these are dependencies inherited from the compiler - and for the libraries that are used (also just in case). +We have a couple of separate stages where we use and mix different techniques to be able to produce the right assembly +or executables. +- Compilation without linking + - The `LD_LIBRARY_PATH` environment variable is used here to enable the compiler to find the `.so` files that they + need to run. + - If you're running a local installation, this is usually your own systems' `LD_LIBRARY_PATH` plus extra things that + CE adds through properties. + - On godbolt.org we always start with an empty `LD_LIBRARY_PATH` and add what is set in the properties. +- Building an executable or binary + - We use `-Wl,-rpath=` (or equivalent `rpathFlag`) to force library paths into the executable so that they will always + find the same `.so` files no matter where they are run. Usually this also includes lib64 and lib folders that the + compiler offers for standard libraries that the toolchain offers. + - Library paths supplied through `-Wl,-rpath=` for shared libraries will be able to dynamically link to the right + architecture's `.so` even if multiple paths are given that contain the same `.so` file. + - We use `-L` (or equivalent `libpathFlag`) to enable the compiler to find both static (`.a`) and shared (`.so`) + libraries. + - We always add '.' as a path as well because that's where we put libraries that are downloaded from our Conan server. + - We use `-l` (or equivalent `linkFlag`) to say we want to statically or dynamically link to a named library binary + (the compiler and linker decide if it's gonna be static or dynamic). +- Running the executable + - We use `LD_LIBRARY_PATH` just in case these are dependencies inherited from the compiler - and for the libraries + that are used (also just in case). ## Specific properties that are used in certain situations -* Compiler .ldPath - * is used for `LD_LIBRARY_PATH` to support running the compiler - * is used for linking (`-Wl,-rpath=` and/or `-L`) during building binaries - * is used for `LD_LIBRARY_PATH` to enable the users's executable to find `.so` files -* Compiler .libPath - * is used for linking (`-Wl,-rpath=` and/or `-L`) during building binaries - * is used for `LD_LIBRARY_PATH` to enable the users's executable to find `.so` files -* Library .libPath - * is used for linking (`-Wl,-rpath=` and/or `-L`) during building binaries - * is used for `LD_LIBRARY_PATH` to enable the users's executable to find `.so` files (just in case) - +- Compiler .ldPath + - is used for `LD_LIBRARY_PATH` to support running the compiler + - is used for linking (`-Wl,-rpath=` and/or `-L`) during building binaries + - is used for `LD_LIBRARY_PATH` to enable the users's executable to find `.so` files +- Compiler .libPath + - is used for linking (`-Wl,-rpath=` and/or `-L`) during building binaries + - is used for `LD_LIBRARY_PATH` to enable the users's executable to find `.so` files +- Library .libPath + - is used for linking (`-Wl,-rpath=` and/or `-L`) during building binaries + - is used for `LD_LIBRARY_PATH` to enable the users's executable to find `.so` files (just in case) ## Example Say we have the following things in a `c++.local.properties` file: -``` +```INI compilers=mycl compiler.mycl.exe=/home/ubuntu/mycl/bin compiler.mycl.ldPath=/home/ubuntu/mycl/lib/lib64 @@ -57,24 +65,25 @@ libs.mylib.libpath=/home/ubuntu/mylib/lib libs.mylib.staticliblink=mylib ``` -This will result in the following situations if we want to compile some code with both the mycl compiler and the mylib library: +This will result in the following situations if we want to compile some code with both the mycl compiler and the mylib +library: -* Compilation without linking - * `LD_LIBRARY_PATH` is set to `/home/ubuntu/mycl/lib/lib64` - * `-I/home/ubuntu/mylib/include` is added to the compilation arguments -* Building an executable or binary - * `LD_LIBRARY_PATH` is set to `/home/ubuntu/mycl/lib/lib64` - * The following are added to the compilation arguments - * `-I/home/ubuntu/mylib/include` (library include path) - * `-Wl,-rpath=/home/ubuntu/mycl/lib/lib64` (compiler library paths) - * `-Wl,-rpath=/home/ubuntu/mycl/lib/lib32` - * `-Wl,-rpath=.` (conan library path) - * `-L.` - * `-Wl,-rpath=/home/ubuntu/gcc10/lib/lib` (gcc toolchain library paths) - * `-Wl,-rpath=/home/ubuntu/gcc10/lib/lib32` - * `-Wl,-rpath=/home/ubuntu/gcc10/lib/lib64` - * `-Wl,-rpath=/home/ubuntu/mylib/lib` (mylib library path - just in case there are `.so` files used) - * `-L/home/ubuntu/mylib/lib` (mylib library path used to find `libmylib.a`) - * `-lmylib` (mylib library name) -* Running the executable - * `LD_LIBRARY_PATH` is set to `/home/ubuntu/mycl/lib/lib64:/home/ubuntu/mycl/lib/lib32:/home/ubuntu/mylib/lib` +- Compilation without linking + - `LD_LIBRARY_PATH` is set to `/home/ubuntu/mycl/lib/lib64` + - `-I/home/ubuntu/mylib/include` is added to the compilation arguments +- Building an executable or binary + - `LD_LIBRARY_PATH` is set to `/home/ubuntu/mycl/lib/lib64` + - The following are added to the compilation arguments + - `-I/home/ubuntu/mylib/include` (library include path) + - `-Wl,-rpath=/home/ubuntu/mycl/lib/lib64` (compiler library paths) + - `-Wl,-rpath=/home/ubuntu/mycl/lib/lib32` + - `-Wl,-rpath=.` (conan library path) + - `-L.` + - `-Wl,-rpath=/home/ubuntu/gcc10/lib/lib` (gcc toolchain library paths) + - `-Wl,-rpath=/home/ubuntu/gcc10/lib/lib32` + - `-Wl,-rpath=/home/ubuntu/gcc10/lib/lib64` + - `-Wl,-rpath=/home/ubuntu/mylib/lib` (mylib library path - just in case there are `.so` files used) + - `-L/home/ubuntu/mylib/lib` (mylib library path used to find `libmylib.a`) + - `-lmylib` (mylib library name) +- Running the executable + - `LD_LIBRARY_PATH` is set to `/home/ubuntu/mycl/lib/lib64:/home/ubuntu/mycl/lib/lib32:/home/ubuntu/mylib/lib` diff --git a/docs/AddingACompiler.md b/docs/AddingACompiler.md index d6f744699..18115cecd 100644 --- a/docs/AddingACompiler.md +++ b/docs/AddingACompiler.md @@ -1,51 +1,52 @@ # Adding a new compiler -This document explains how to add a new compiler to Compiler Explorer ("CE" from here on), first for a local instance, and -then how to submit PRs to get it into the main CE site. +This document explains how to add a new compiler to Compiler Explorer ("CE" from here on), first for a local instance, +and then how to submit PRs to get it into the main CE site. ## Configuration -Compiler configuration is done through the `etc/config/c++.*.properties` files -(for C++, other languages follow the obvious pattern, replace as needed for your case). +Compiler configuration is done through the `etc/config/c++.*.properties` files (for C++, other languages follow the +obvious pattern, replace as needed for your case). -The various named configuration files are used in different contexts: for example `etc/config/c++.local.properties` take priority over -`etc/config/c++.defaults.properties`. The `local` version is ignored by git, so you can make your own personalised changes there. -The live site uses the `etc/config/c++.amazon.properties` file. +The various named configuration files are used in different contexts: for example `etc/config/c++.local.properties` take +priority over `etc/config/c++.defaults.properties`. The `local` version is ignored by git, so you can make your own +personalised changes there. The live site uses the `etc/config/c++.amazon.properties` file. -Within the file, configuration is a set of key and value pairs, separated by an `=`. Whitespace is _not_ trimmed. -Lines starting with `#` are considered comments and not parsed. -The list of compilers is set by the `compilers` key and is a list of compiler identifiers or groups, separated by colons. Group names -have an `&` prepended. As a nod to backwards compatibility with very old configurations, a path to a compiler can also be put -in the list, but that doesn't let you configure many aspects of the compiler, nor does it allow paths with colons in them (since these -are used as separators). The identifier itself is not important, but must be unique to that compiler. +Within the file, configuration is a set of key and value pairs, separated by an `=`. Whitespace is _not_ trimmed. Lines +starting with `#` are considered comments and not parsed. The list of compilers is set by the `compilers` key and is a +list of compiler identifiers or groups, separated by colons. Group names have an `&` prepended. As a nod to backwards +compatibility with very old configurations, a path to a compiler can also be put in the list, but that doesn't let you +configure many aspects of the compiler, nor does it allow paths with colons in them (since these are used as +separators). The identifier itself is not important, but must be unique to that compiler. An example configuration: -``` +```INI compilers=gcc620:gcc720:&clang ``` -This says there are two compilers with identifiers `gcc620` and `gcc720`, and a group of compilers called `clang`. For the -compilers, CE will look for some keys named `compiler.ID.name` and `compiler.ID.exe` (and some others, detailed later). The `ID` -is the identifier of the compiler being looked up. The `name` value is used as the human-readable compiler name shown to users, -and the `exe` should be the path name of the compiler executable. +This says there are two compilers with identifiers `gcc620` and `gcc720`, and a group of compilers called `clang`. For +the compilers, CE will look for some keys named `compiler.ID.name` and `compiler.ID.exe` (and some others, detailed +later). The `ID` is the identifier of the compiler being looked up. The `name` value is used as the human-readable +compiler name shown to users, and the `exe` should be the path name of the compiler executable. For example: -``` +```INI compiler.gcc620.name=GCC 6.2.0 compiler.gcc620.exe=/usr/bin/gcc-6.2.0 compiler.gcc720.name=GCC 7.2.0 compiler.gcc720.exe=/usr/bin/gcc-7.2.0 ``` -In addition to the `name` and `exe` per-compiler configuration keys, there are also some other options. Most of them default -to sensible values for GCC-like compilers. +In addition to the `name` and `exe` per-compiler configuration keys, there are also some other options. Most of them +default to sensible values for GCC-like compilers. A group is defined similar to a list of compilers, and may contain other groups. Keys for groups start with `group.ID`. -Configuration keys applied to the group apply to all compilers in that group (unless overridden by the compiler itself). An example: +Configuration keys applied to the group apply to all compilers in that group (unless overridden by the compiler itself). +An example: -``` +```INI group.clang.compilers=clang4:clang5 group.clang.intelAsm=-mllvm -x86-asm-syntax=intel compiler.clang4.name=Clang 4 @@ -56,12 +57,13 @@ compiler.clang5.exe=/usr/bin/clang5 Note about configuration files hierarchy: -As mentioned previously, the live site uses `etc/config/c++.amazon.properties` to load its configuration from, -but for properties not defined in the `amazon` file, the values present in `etc/config/c++.defaults.properties` will be used. +As mentioned previously, the live site uses `etc/config/c++.amazon.properties` to load its configuration from, but for +properties not defined in the `amazon` file, the values present in `etc/config/c++.defaults.properties` will be used. -By design, this does not however work for groups (Nor any other nested property). -That is, if in `etc/config/c++.defaults.properties` you define the `intelAsm` property as: -``` +By design, this does not however work for groups (Nor any other nested property). That is, if in +`etc/config/c++.defaults.properties` you define the `intelAsm` property as: + +```INI versionFlag=--version compilers=&clang group.clang.intelAsm=-mllvm -x86-asm-syntax=intel @@ -70,88 +72,91 @@ group.clang.groupName=Clang ``` but `etc/config/c++.amazon.properties` only has: -``` + +```INI compilers=&clang group.clang.groupName=Clang ... ``` -once the site runs on the Amazon environment, the `&clang` group **will not** have the `intelAsm` property set, -but `versionFlag` will. + +once the site runs on the Amazon environment, the `&clang` group **will not** have the `intelAsm` property set, but +`versionFlag` will. ### Configuration keys -Key Name | Type | Description| ----------|-------|-----| -name | String | Human readable name of the compiler|| -exe | Path | Path to the executable| -alias | Identifier | Another identifier for this compiler (mostly deprecated, used for backwards compatibility with very old CE URLs) | -options | String | Additional compiler options passed to the compiler when running it | -intelAsm | String | Flags used to select intel assembly format (if not detected automatically)| -needsMulti | Boolean | Whether the compiler needs multi arch support (defaults to yes if the host has multiarch enabled)| -supportsBinary | Boolean | Whether this compiler supports compiling to binary| -supportsExecute | Boolean | Whether binary output from this compiler can be executed| -versionFlag | String | The flag to pass to the compiler to make it emit its version| -versionRe | RegExp | A regular expression used to capture the version from the version output| -compilerType | String | The name of the class handling this compiler| -interpreted | Boolean | Whether this is an interpreted language, and so the "compiler" is really an interpreter| -executionWrapper | Path | Path to script that can execute the compiler's output (e.g. could run under `qemu` or `mpi_run` or similar)| +| Key Name | Type | Description | +| ---------------- | ---------- | ---------------------------------------------------------------------------------------------------------------- | +| name | String | Human readable name of the compiler | +| exe | Path | Path to the executable | +| alias | Identifier | Another identifier for this compiler (mostly deprecated, used for backwards compatibility with very old CE URLs) | +| options | String | Additional compiler options passed to the compiler when running it | +| intelAsm | String | Flags used to select intel assembly format (if not detected automatically) | +| needsMulti | Boolean | Whether the compiler needs multi arch support (defaults to yes if the host has multiarch enabled) | +| supportsBinary | Boolean | Whether this compiler supports compiling to binary | +| supportsExecute | Boolean | Whether binary output from this compiler can be executed | +| versionFlag | String | The flag to pass to the compiler to make it emit its version | +| versionRe | RegExp | A regular expression used to capture the version from the version output | +| compilerType | String | The name of the class handling this compiler | +| interpreted | Boolean | Whether this is an interpreted language, and so the "compiler" is really an interpreter | +| executionWrapper | Path | Path to script that can execute the compiler's output (e.g. could run under `qemu` or `mpi_run` or similar) | -The `compilerType` option is special: it refers to the Javascript class in `lib/compilers/*.js` which handles running and handling -output for this compiler type. +The `compilerType` option is special: it refers to the Javascript class in `lib/compilers/*.js` which handles running +and handling output for this compiler type. ## Adding a new compiler locally -It should be pretty straightforward to add a compiler of your own. Create a `etc/config/c++.local.properties` file and override the -`compilers` list to include your own compiler, and its configuration. +It should be pretty straightforward to add a compiler of your own. Create a `etc/config/c++.local.properties` file and +override the `compilers` list to include your own compiler, and its configuration. -Once you've done that, running `make` should pick up the configuration and during startup you should see your compiler being run -and its version being extracted. If you don't, check for any errors, and try running with `make EXTRA_ARGS='--debug'` to see (a lot of) -debug output. +Once you've done that, running `make` should pick up the configuration and during startup you should see your compiler +being run and its version being extracted. If you don't, check for any errors, and try running with +`make EXTRA_ARGS='--debug'` to see (a lot of) debug output. -If you're looking to add other language compilers for another language, obviously create the `etc/config/LANG.local.properties` in -the above steps, and run with `make EXTRA_ARGS='--language LANG'` (e.g. `etc/config/rust.local.properties` and -`make EXTRA_ARGS='--language Rust'`). +If you're looking to add other language compilers for another language, obviously create the +`etc/config/LANG.local.properties` in the above steps, and run with `make EXTRA_ARGS='--language LANG'` (e.g. +`etc/config/rust.local.properties` and `make EXTRA_ARGS='--language Rust'`). -Test locally, and for many compilers that's probably all you need to do. Some compilers might need a few options tweaks (like -the intel asm setting, or the version flag). For a completely new compiler, you might need to define a whole new `compilerType`. -Doing so is beyond this document's scope at present, but take a look inside `lib/compilers/` to get some idea what might need -to be done. +Test locally, and for many compilers that's probably all you need to do. Some compilers might need a few options tweaks +(like the intel asm setting, or the version flag). For a completely new compiler, you might need to define a whole new +`compilerType`. Doing so is beyond this document's scope at present, but take a look inside `lib/compilers/` to get some +idea what might need to be done. ## Adding a new compiler running remotely to your locally built compiler explorer -If you would like to have both gcc and MSVC running in the "same" compiler explorer, one option would be running gcc on your local -Linux machine and add a proxy to the MSVC compiler, which is running on a remote Window host. To achieve this, you could +If you would like to have both gcc and MSVC running in the "same" compiler explorer, one option would be running gcc on +your local Linux machine and add a proxy to the MSVC compiler, which is running on a remote Window host. To achieve +this, you could -* Setup compiler explorer on your Linux host as usual -* Follow [this guide](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/WindowsNative.md) -to set up another compiler explorer instance on your Windows host -* Add your Windows compiler explorer as a proxy to your Linux compiler explorer. You can simply modify your -`etc/config/c++.local.properties` on your Linux host +- Setup compiler explorer on your Linux host as usual +- Follow [this guide](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/WindowsNative.md) to set up + another compiler explorer instance on your Windows host +- Add your Windows compiler explorer as a proxy to your Linux compiler explorer. You can simply modify your + `etc/config/c++.local.properties` on your Linux host ``` compilers=&gcc:&clang:myWindowsHost@10240 ``` -Yes it is the `@` symbol rather than the `:` before the port number. Restart the Linux compiler explorer, and you will be able to -see the MSVC compiler in the compiler list. +Yes it is the `@` symbol rather than the `:` before the port number. Restart the Linux compiler explorer, and you will +be able to see the MSVC compiler in the compiler list. ## Adding a new compiler to the live site -On the main CE website, compilers are installed into a `/opt/compiler-explorer/` directory by a set of scripts in the sister -GitHub repo: https://github.com/compiler-explorer/infra +On the main CE website, compilers are installed into a `/opt/compiler-explorer/` directory by a set of scripts in the +sister GitHub repo: https://github.com/compiler-explorer/infra -In the `update_compilers` directory in that repository are a set of scripts that download and install binaries and compilers. -If you wish to test locally, and can create a `/opt/compiler-explorer` directory on your machine which is readable and writable by your -current user, then you can run the scripts directly. The binaries and the free compilers can be installed - the commercial compilers -live in the `install_nonfree_compilers.sh` and won't work. +In the `update_compilers` directory in that repository are a set of scripts that download and install binaries and +compilers. If you wish to test locally, and can create a `/opt/compiler-explorer` directory on your machine which is +readable and writable by your current user, then you can run the scripts directly. The binaries and the free compilers +can be installed - the commercial compilers live in the `install_nonfree_compilers.sh` and won't work. -If your compiler fits nicely into the harness then it should be straightforward to add it there. Anything more complex: contact the CE -authors for more help. +If your compiler fits nicely into the harness then it should be straightforward to add it there. Anything more complex: +contact the CE authors for more help. ## Putting it all together -Hopefully that's enough to get an idea. The ideal case of a GCC-like compiler should be a pull request to add a couple of -lines to the `infra` repository to install the compiler, and a pull request to add a few lines to the `LANG.amazon.properties` -file in this repository. +Hopefully that's enough to get an idea. The ideal case of a GCC-like compiler should be a pull request to add a couple +of lines to the `infra` repository to install the compiler, and a pull request to add a few lines to the +`LANG.amazon.properties` file in this repository. If you feel like we could improve this document in any way, please contact us. We'd love to hear from you! diff --git a/docs/AddingAFormatter.md b/docs/AddingAFormatter.md index bda7ee10c..db7b0058f 100644 --- a/docs/AddingAFormatter.md +++ b/docs/AddingAFormatter.md @@ -1,25 +1,30 @@ # Adding a new formatter -* Add a `etc/config/compiler-explorer.local.properties` file +- Add a `etc/config/compiler-explorer.local.properties` file + - Add a new formatter under the `formatters` key - The new formatter can have the following keys: name, exe, styles, type, explicitVersion (to override version - parsing), version (argument to get version info), versionRe (regex to filter out the right version info) - - Add a `lib/formatters/.js` file using the template below, replacing `Type` and `type` as - appropriate + parsing), version (argument to get version info), versionRe (regex to filter out the right version info) + - Add a `lib/formatters/.js` file using the template below, replacing `Type` and `type` as appropriate + ```js - import { BaseFormatter } from '../base-formatter'; + import {BaseFormatter} from '../base-formatter'; export class TypeFormatter extends BaseFormatter { - static get key() { return 'type'; } + static get key() { + return 'type'; + } } ``` + - The value returned by `key` above corresponds to the `type` property you set in the compiler-explorer properties - configuration file. + configuration file. - Tweak `format(source, options)` and `isValidStyle(style)` as necessary. See the JSDoc for `format` and the - implementations for other formatters to get a further understanding of how to implement `format(source, options)`. -* Add your `TypeFormatter` to `lib/formatters/_all.js` in alphabetical order + implementations for other formatters to get a further understanding of how to implement `format(source, options)`. -* You can check the output of http://localhost:10240/api/formats to be sure your formatter is there. +- Add your `TypeFormatter` to `lib/formatters/_all.js` in alphabetical order -* Make an installer in the [infra](https://github.com/compiler-explorer/infra) repository. An example patch for adding +- You can check the output of http://localhost:10240/api/formats to be sure your formatter is there. + +- Make an installer in the [infra](https://github.com/compiler-explorer/infra) repository. An example patch for adding an installer can be found [here](https://github.com/compiler-explorer/infra/pull/560) diff --git a/docs/AddingALanguage.md b/docs/AddingALanguage.md index e23a77b5d..041e0b0f6 100644 --- a/docs/AddingALanguage.md +++ b/docs/AddingALanguage.md @@ -2,8 +2,10 @@ If you want to add a new language to the site, you should follow this steps: -* Add the new language to the exported `languages` variable in `lib/languages.js`: - - The syntax is as follows: +- Add the new language to the exported `languages` variable in `lib/languages.js`: + + - The syntax is as follows: + ```js 'language-key': { name: YOUR_LANGUAGE_DISPLAY_NAME, @@ -12,61 +14,68 @@ If you want to add a new language to the site, you should follow this steps: alias: [], // Leave empty unless needed } ``` - - If the language is supported by Monaco Editor (You can find the - list [here](https://github.com/microsoft/monaco-editor/tree/main/src/basic-languages)), you should add it to the list of - languages inside the `MonacoEditorWebpackPlugin` config in `webpack.config.js` - - If not, you should implement your own language mode; see `static/modes/asm-mode.js` as an example. Don't forget - to *require* your mode file in `static/modes/_all.ts`, in alphabetical order - - `language-key` is how your language will be referred internally by the code. In the rest of this document, - replace `{language-key}` by the corresponding value in the real files. -* Add a `lib/compilers/{language-key}.js` file using the template below: - ```js - import { BaseCompiler } from '../base-compiler'; + - If the language is supported by Monaco Editor (You can find the list + [here](https://github.com/microsoft/monaco-editor/tree/main/src/basic-languages)), you should add it to the list of + languages inside the `MonacoEditorWebpackPlugin` config in `webpack.config.js` + - If not, you should implement your own language mode; see `static/modes/asm-mode.js` as an example. Don't forget to + _require_ your mode file in `static/modes/_all.ts`, in alphabetical order + - `language-key` is how your language will be referred internally by the code. In the rest of this document, replace + `{language-key}` by the corresponding value in the real files. - export class LanguageCompiler extends BaseCompiler { - static get key() { return 'language'; } +- Add a `lib/compilers/{language-key}.js` file using the template below: + + ```js + import {BaseCompiler} from '../base-compiler'; + + export class LanguageCompiler extends BaseCompiler { + static get key() { + return 'language'; } - ``` - - The value returned by `key` above corresponds to the `compilerType` value - in `etc/config/{language-key}.defaults.properties` (Explained below). This is usually `{language-key}`, but you - can use whatever fits best - - Override the `OptionsForFilter` method from the base class - - Comment out the line saying `fs.remove(result.dirPath);` in base-compiler.js, so the latest CE compile attempt - remains on disk for you to review - - Remember to undo this change before opening a PR! - - For reference, the basic behaviour of BaseCompiler is: - - make a random temporary folder - - save example.extension to the new folder, the full path to this is the `inputFilename` - - the `outputFilename` is determined by the `getOutputFilename()` method - - execute the compiler.exe with the arguments from `OptionsForFilter()` and adding `inputFilename` - - be aware that the language class is only instanced once, so storing state is not possible - - If the compiler has problems with the defaults, you will have to override the `runCompiler()` method too. When - overriding it, here are some ideas - - set `execOptions.customCwd` parameter if the working directory needs to be somewhere else - - set `execOptions.env` parameter if the compiler requires special environment variables - - manipulate `options`, but make sure the user can still add their own arguments in CE + } + ``` -* Add your `LanguageCompiler` to `lib/compilers/_all.js`, in alphabetical order + - The value returned by `key` above corresponds to the `compilerType` value in + `etc/config/{language-key}.defaults.properties` (Explained below). This is usually `{language-key}`, but you can use + whatever fits best + - Override the `OptionsForFilter` method from the base class + - Comment out the line saying `fs.remove(result.dirPath);` in base-compiler.js, so the latest CE compile attempt + remains on disk for you to review + - Remember to undo this change before opening a PR! + - For reference, the basic behaviour of BaseCompiler is: + - make a random temporary folder + - save example.extension to the new folder, the full path to this is the `inputFilename` + - the `outputFilename` is determined by the `getOutputFilename()` method + - execute the compiler.exe with the arguments from `OptionsForFilter()` and adding `inputFilename` + - be aware that the language class is only instanced once, so storing state is not possible + - If the compiler has problems with the defaults, you will have to override the `runCompiler()` method too. When + overriding it, here are some ideas + - set `execOptions.customCwd` parameter if the working directory needs to be somewhere else + - set `execOptions.env` parameter if the compiler requires special environment variables + - manipulate `options`, but make sure the user can still add their own arguments in CE -* Add a `etc/config/{language-key}.local.properties` file: - - The syntax for its basic contents is documented in [AddingACompiler.md](AddingACompiler.md) - - This file is ignored by Git, so that you can test the config locally - - You should add 1 compiler for the language you want to test - - Test the command line options of the language compilers outside CE +- Add your `LanguageCompiler` to `lib/compilers/_all.js`, in alphabetical order -* Add a new file `etc/config/{language-key}.defaults.properties`. This is where a default configuration will live. - - Usually, this loads default compilers from their usual paths on a normal installation - (Check `etc/config/c++.defaults.properties` for an example) +- Add a `etc/config/{language-key}.local.properties` file: -* Of important note, for both files, is to properly define `compilerType` property in the newly added compilers. This + - The syntax for its basic contents is documented in [AddingACompiler.md](AddingACompiler.md) + - This file is ignored by Git, so that you can test the config locally + - You should add 1 compiler for the language you want to test + - Test the command line options of the language compilers outside CE + +- Add a new file `etc/config/{language-key}.defaults.properties`. This is where a default configuration will live. + + - Usually, this loads default compilers from their usual paths on a normal installation (Check + `etc/config/c++.defaults.properties` for an example) + +- Of important note, for both files, is to properly define `compilerType` property in the newly added compilers. This should equal the value returned by your `LanguageCompiler.key` function -* Running `make dev EXTRA_ARGS="--debug --language {language-key}"` to tell CE to only load your new language +- Running `make dev EXTRA_ARGS="--debug --language {language-key}"` to tell CE to only load your new language -* You can check http://127.0.0.1:10240/api/compilers to be sure your language and compilers are there +- You can check http://127.0.0.1:10240/api/compilers to be sure your language and compilers are there -* Make an installer in the [infra](https://github.com/compiler-explorer/infra) repository +- Make an installer in the [infra](https://github.com/compiler-explorer/infra) repository -* Add your language files (`{language-key}.*.properties` and `lib/compilers/{language-key}.js`) to the list - in `.github/labeler.yml` +- Add your language files (`{language-key}.*.properties` and `lib/compilers/{language-key}.js`) to the list in + `.github/labeler.yml` diff --git a/docs/AddingALibrary.md b/docs/AddingALibrary.md index 650cfaf96..d1040295f 100644 --- a/docs/AddingALibrary.md +++ b/docs/AddingALibrary.md @@ -1,42 +1,41 @@ # Adding a new library -This document explains how to add a new library to Compiler Explorer ("CE" from here on), first for a local instance, and -then how to submit PRs to get it into the main CE site. +This document explains how to add a new library to Compiler Explorer ("CE" from here on), first for a local instance, +and then how to submit PRs to get it into the main CE site. -Note that most libraries are Header-only. This is the easiest form of library to support. If the library needs to be built, -there are some caveats, best practices and good to knows. Consult the bottom of this page for details. +Note that most libraries are Header-only. This is the easiest form of library to support. If the library needs to be +built, there are some caveats, best practices and good to knows. Consult the bottom of this page for details. ## Configuration -Library configurations are part of the compiler's properties, which is done through the `etc/config/c++.*.properties` files -(for C++, other languages follow the obvious pattern). The various named configuration files are used in different contexts: - for example `etc/config/c++.local.properties` take priority over `etc/config/c++.defaults.properties`. -The `local` version is ignored by git, so you can make your own personalised changes there. -The live site uses the `etc/config/c++.amazon.properties` file. +Library configurations are part of the compiler's properties, which is done through the `etc/config/c++.*.properties` +files (for C++, other languages follow the obvious pattern). The various named configuration files are used in different +contexts: for example `etc/config/c++.local.properties` take priority over `etc/config/c++.defaults.properties`. The +`local` version is ignored by git, so you can make your own personalised changes there. The live site uses the +`etc/config/c++.amazon.properties` file. -Within the file, configuration is a set of key and value pairs, separated by an `=`. Whitespace is _not_ trimmed. -Lines starting with `#` are considered comments and not parsed. -The list of libraries is set by the `libs` key and is a list of library identifiers, separated by colons. -The identifier itself is not important, but must be unique to that library. +Within the file, configuration is a set of key and value pairs, separated by an `=`. Whitespace is _not_ trimmed. Lines +starting with `#` are considered comments and not parsed. The list of libraries is set by the `libs` key and is a list +of library identifiers, separated by colons. The identifier itself is not important, but must be unique to that library. An example configuration: -``` +```INI libs=kvasir:boost:rangesv3 ``` This says there are three libraries with identifiers `kvasir`, `boost` and `rangesv3`. CE will look for the key named -`libs.ID.versions`, `libs.ID.name` and the optionals `libs.ID.url` & `libs.ID.description`. The `ID` is the identifier (The one we just set) of the library being looked up. -The `name` key expects the human-readable name of the library (Note that you can use spaces here!). -The `versions` key expects another list, akin to the libs key itself. This time, you have to define the available versions -for each library. -The `url` key expects an unescaped url, where users can go to learn more about the library (This is usually the project's homepage, or in its -absence, the GitHub repo). -The `description` key should be use as an extremely short description of the library. Usually used to spell the library's full name in cases where the `name` key is an acronym. +`libs.ID.versions`, `libs.ID.name` and the optionals `libs.ID.url` & `libs.ID.description`. The `ID` is the identifier +(The one we just set) of the library being looked up. The `name` key expects the human-readable name of the library +(Note that you can use spaces here!). The `versions` key expects another list, akin to the libs key itself. This time, +you have to define the available versions for each library. The `url` key expects an unescaped url, where users can go +to learn more about the library (This is usually the project's homepage, or in its absence, the GitHub repo). The +`description` key should be use as an extremely short description of the library. Usually used to spell the library's +full name in cases where the `name` key is an acronym. For example: -``` +```INI libs.kvasir.name=Kvasir::mpl libs.kvasir.versions=trunk libs.kvasir.url=https://github.com/kvasir-io/Kvasir @@ -51,13 +50,14 @@ libs.rangesv3.versions=trunk:0110 libs.rangesv3.url=https://github.com/ericniebler/range-v3 ``` -Now, for each declared version, CE will look for a `version` key, a human-readable string representing the corresponding version, -and `path`, a list consisting of the paths separated by colon `:` (or semicolon `;` on Windows) to add to the inclusion path of the library. -Optionally, you can provide a `libpath`, a list consisting of paths to add to your linker path. +Now, for each declared version, CE will look for a `version` key, a human-readable string representing the corresponding +version, and `path`, a list consisting of the paths separated by colon `:` (or semicolon `;` on Windows) to add to the +inclusion path of the library. Optionally, you can provide a `libpath`, a list consisting of paths to add to your linker +path. This would leave us with: -``` +```INI libs.boost.name=Boost libs.boost.versions=175:176 libs.boost.url=http://www.boost.org/ @@ -90,106 +90,124 @@ libs.rangesv3.versions.0110.version=0.11.0 libs.rangesv3.versions.0110.path=/opt/compiler-explorer/libs/rangesv3/0.11.0/include ``` -If you're adding a new library and plan to submit a PR for it, please make sure that its identifier appears in alphabetical order - in the `libs` property. You should also put all its related configuration in that same order when defining it. - This helps us keep the config manageable until further automation can be implemented. Thank you! - +If you're adding a new library and plan to submit a PR for it, please make sure that its identifier appears in +alphabetical order in the `libs` property. You should also put all its related configuration in that same order when +defining it. This helps us keep the config manageable until further automation can be implemented. Thank you! ## Setting default libraries -The `defaultLibs` key specifies an array of libs/versions which will be enabled by default when the user visits the site. -The expected format is: -``` +The `defaultLibs` key specifies an array of libs/versions which will be enabled by default when the user visits the +site. The expected format is: + +```INI defaultLibs=libKeyA.version:libKeyB.version:libKeyC.version ``` -Where `libKey` is the key of the library to be enabled by default, and `version` is the version key to load. -Note that the site won't complain if invalid key/version pairs are set. Repeating a lib key more than once is supported. + +Where `libKey` is the key of the library to be enabled by default, and `version` is the version key to load. Note that +the site won't complain if invalid key/version pairs are set. Repeating a lib key more than once is supported. ## Adding a new library locally -It should be pretty straightforward to add a library of your own. Create a `etc/config/c++.local.properties` file and override the -`libs` list to include your own library, and its configuration. +It should be pretty straightforward to add a library of your own. Create a `etc/config/c++.local.properties` file and +override the `libs` list to include your own library, and its configuration. -Once you've done that, running `make` should pick up the configuration, and you should be able to use them from the library dropdown -on the compiler view (The book icon) +Once you've done that, running `make` should pick up the configuration, and you should be able to use them from the +library dropdown on the compiler view (The book icon) -If you're looking to add libraries for another language, obviously create the `etc/config/LANG.local.properties` in -the above steps, and run with `make EXTRA_ARGS='--language LANG` (e.g. `etc/config/rust.local.properties` and +If you're looking to add libraries for another language, obviously create the `etc/config/LANG.local.properties` in the +above steps, and run with `make EXTRA_ARGS='--language LANG` (e.g. `etc/config/rust.local.properties` and `make EXTRA_ARGS='--language Rust'`). -Test locally, and for many compilers that's probably all you need to do. Some compilers might need a few options tweaks (like -the intel asm setting, or the version flag). For a completely new compiler, you might need to define a whole new `compilerType`. -Doing so is beyond this document's scope at present, but take a look inside `lib/compilers/` to get some idea what might need -to be done. +Test locally, and for many compilers that's probably all you need to do. Some compilers might need a few options tweaks +(like the intel asm setting, or the version flag). For a completely new compiler, you might need to define a whole new +`compilerType`. Doing so is beyond this document's scope at present, but take a look inside `lib/compilers/` to get some +idea what might need to be done. ## Adding a new library to the live site -On the main CE website, libraries are installed into a `/opt/compiler-explorer/` directory by a set of scripts in the sister -GitHub repo: https://github.com/compiler-explorer/infra +On the main CE website, libraries are installed into a `/opt/compiler-explorer/` directory by a set of scripts in the +sister GitHub repo: https://github.com/compiler-explorer/infra -In the `bin/yaml` directory in that repository are a set of yaml files that configure the download, install and building of the libraries. -If you wish to test locally, and can create a `/opt/compiler-explorer` directory on your machine which is readable and writable by your -current user, then you can run the scripts directly. +In the `bin/yaml` directory in that repository are a set of yaml files that configure the download, install and building +of the libraries. If you wish to test locally, and can create a `/opt/compiler-explorer` directory on your machine which +is readable and writable by your current user, then you can run the scripts directly. Example of configuring a library that is header only: -``` - sol2: - type: github - method: clone_branch - repo: ThePhD/sol2 - check_file: include/sol/sol.hpp - build_type: none - targets: - - v3.2.1 + +```yaml +sol2: + type: github + method: clone_branch + repo: ThePhD/sol2 + check_file: include/sol/sol.hpp + build_type: none + targets: + - v3.2.1 ``` Example of configuring a library that is linked against: -``` - catch2: - type: github - repo: catchorg/Catch2 - build_type: cmake - make_targets: - - Catch2 - - Catch2WithMain - target_prefix: v - targets: - - 3.0.0-preview2 + +```yaml +catch2: + type: github + repo: catchorg/Catch2 + build_type: cmake + make_targets: + - Catch2 + - Catch2WithMain + target_prefix: v + targets: + - 3.0.0-preview2 ``` -If your library fits nicely into the harness then it should be straightforward to add it there. Anything more complex: contact the CE -authors for more help. +If your library fits nicely into the harness then it should be straightforward to add it there. Anything more complex: +contact the CE authors for more help. -Remember to also add the library dependencies following the same steps. It's on you if those should also appear in the UI. +Remember to also add the library dependencies following the same steps. It's on you if those should also appear in the +UI. ## Adding compilers with limited library support -If you have libraries that you don't want to be shown with a compiler, you can limit the libraries per compiler. By default, all libraries are visible for all compilers. +If you have libraries that you don't want to be shown with a compiler, you can limit the libraries per compiler. By +default, all libraries are visible for all compilers. For example if you only want all versions of fmt, and version 0.3.0 of Ranges, you can do the following: -``` + +```ini compiler.mycompiler.supportedLibraries=fmt:rangesv3.030 ``` ## Putting it all together -Hopefully that's enough to get an idea. The ideal case should be a pull request to add a couple of -lines to the `infra` repository to install the library, and a pull request to add a few lines to the `LANG.amazon.properties` -file in this repository. +Hopefully that's enough to get an idea. The ideal case should be a pull request to add a couple of lines to the `infra` +repository to install the library, and a pull request to add a few lines to the `LANG.amazon.properties` file in this +repository. If you feel like we could improve this document in any way, please contact us. We'd love to hear from you! - # Adding a library that needs to be compiled to .a or .so binaries Supporting library binaries are a complicated matter. -For "C" shared libraries is relatively easy, is mostly a "solved problem", and the most common way of connecting software and libraries together. OpenSSL has .so's to link against for x86-64 and x86. However, we currently do not offer any other platforms, and it gets a lot harder if we tried to support that. Not to mention we currently do not have hardware in the cloud for other platforms to actually execute your code. +For "C" shared libraries is relatively easy, is mostly a "solved problem", and the most common way of connecting +software and libraries together. OpenSSL has .so's to link against for x86-64 and x86. However, we currently do not +offer any other platforms, and it gets a lot harder if we tried to support that. Not to mention we currently do not have +hardware in the cloud for other platforms to actually execute your code. -For C++ libraries, static or shared, there is no standard or common way of building libraries. To be sure linking will work, we have to rebuild the libraries for every compiler we support. We try to support at least x86-64, x86 and if that's not possible - the default target of the compiler. For all llvm/clang based compilers, we also try to build the libraries for libc++, just to be sure that doesn't give any runtime issues. +For C++ libraries, static or shared, there is no standard or common way of building libraries. To be sure linking will +work, we have to rebuild the libraries for every compiler we support. We try to support at least x86-64, x86 and if +that's not possible - the default target of the compiler. For all llvm/clang based compilers, we also try to build the +libraries for libc++, just to be sure that doesn't give any runtime issues. -There are also some specific compiler flags that cause ABI incompatibility, but we're still looking for common cases; if you have any use-cases of flags that causes linking or runtime errors, please let us know. +There are also some specific compiler flags that cause ABI incompatibility, but we're still looking for common cases; if +you have any use-cases of flags that causes linking or runtime errors, please let us know. -For us to have the possibility of crosscompiling with multiple compilers, it's recommended to be able to build with CMake. CMake by default has support to provide different flags during compilation. Makefiles can provide ways for doing the same, but often they have variables and flags that cannot be changed. If you're a library developer, please take into account that we will need ways to set at least CC, CXX, CXXFLAGS. Be also aware that we will probably supply -Wl-rpath's and/or -L to ensure that the library knows where to find their dependencies. +For us to have the possibility of crosscompiling with multiple compilers, it's recommended to be able to build with +CMake. CMake by default has support to provide different flags during compilation. Makefiles can provide ways for doing +the same, but often they have variables and flags that cannot be changed. If you're a library developer, please take +into account that we will need ways to set at least CC, CXX, CXXFLAGS. Be also aware that we will probably supply +-Wl-rpath's and/or -L to ensure that the library knows where to find their dependencies. -Because of the amount of combinations we need to produce, only the later tagged versions of most libraries have priority in providing builds for. Daily trunk/master versions are out as well, until we figure out a way to efficiently provide builds for this. +Because of the amount of combinations we need to produce, only the later tagged versions of most libraries have priority +in providing builds for. Daily trunk/master versions are out as well, until we figure out a way to efficiently provide +builds for this. diff --git a/docs/AddingATool.md b/docs/AddingATool.md index f28ec36ee..d4b0b0803 100644 --- a/docs/AddingATool.md +++ b/docs/AddingATool.md @@ -4,7 +4,7 @@ Tools are a way to execute something on your code or the output of a compilation Adding tools requires adding configuration to a properties file for a specific language: -```yaml +```INI tools=rewritecpp tools.rewritecpp.name=rewritecpp @@ -19,25 +19,31 @@ tools.rewritecpp.options=--a tools.rewritecpp.args=--b ``` -The `name` and `exe` are what they say they are, this is the display name for within CE and the tool executable that will be used. +The `name` and `exe` are what they say they are, this is the display name for within CE and the tool executable that +will be used. The `type` of the tool represents the stage in which the tool will run: -* independent - when running a tool on sourcecode -* postcompilation - when running a tool on the assembly or a binary -The `exclude` property is to indicate which compilers are proven to be incompatible with the tool. -You can supply the full id of the compiler, or a partial id (for example 'arm' to exclude all arm compilers). +- independent - when running a tool on sourcecode +- postcompilation - when running a tool on the assembly or a binary -The `class` of the tool says which javascript class is needed to run the tool and process its output. The folder _lib/tooling_ is used for these classes. +The `exclude` property is to indicate which compilers are proven to be incompatible with the tool. You can supply the +full id of the compiler, or a partial id (for example 'arm' to exclude all arm compilers). + +The `class` of the tool says which javascript class is needed to run the tool and process its output. The folder +_lib/tooling_ is used for these classes. Should you want to deviate from the standard behaviour of `base-tool`, which runs the tool on the sourcecode filename, you should add a new class that extends from `base-tool`. -The `stdinHint` is there to show the user a hint as to what the stdin field is used for in the tool. To disable stdin you can use _disabled_ here. +The `stdinHint` is there to show the user a hint as to what the stdin field is used for in the tool. To disable stdin +you can use _disabled_ here. -The `monacoStdin` option makes the stdin editor a separate pane containing a monaco editor. This is useful when a tool has complex input spanning multiple lines and it's more friendly to indent it. +The `monacoStdin` option makes the stdin editor a separate pane containing a monaco editor. This is useful when a tool +has complex input spanning multiple lines and it's more friendly to indent it. -The `languageId` can be used to highlight the output of the tool according to a language known within CE. For example `cppp` will highlight c++ output. Leaving `languageId` empty will use the terminal-like output. +The `languageId` can be used to highlight the output of the tool according to a language known within CE. For example +`cppp` will highlight c++ output. Leaving `languageId` empty will use the terminal-like output. The `options` field is useful for tools that derive `base-tool` and want to add non-user configurable options to it @@ -45,7 +51,8 @@ The `args` field is shown and editable by the user in the UI, and passed automat # compilationInfo -When writing a special class for a tool, you will probably need the `compilationInfo` parameter to pass the correct parameters to the tool. +When writing a special class for a tool, you will probably need the `compilationInfo` parameter to pass the correct +parameters to the tool. The contents of `compilationInfo` varies slightly between the different `type`s of tools. @@ -64,7 +71,8 @@ The contents of `compilationInfo` varies slightly between the different `type`s } ``` -The `filters` can be used to assert boundary conditions or adjust the tooling process based on the filters the user checked on or off. +The `filters` can be used to assert boundary conditions or adjust the tooling process based on the filters the user +checked on or off. The `inputFilename` contains the path to the sourcecode stored on disk. The `source` contains the sourcecode as text. @@ -72,7 +80,6 @@ The `dirPath` can be used to write extra files to disk which the tool might need The `options` are the arguments the user gave for the compilation. - ## compilationInfo for postcompilation tools ```json @@ -97,7 +104,8 @@ The `options` are the arguments the user gave for the compilation. `code` indicates the exitcode of the compilation. Usually, 0 means everything's ok. -`asm` contains the returned assembly. This is the same assembly that is shown within compiler-explorer, including extra information like for which sourcecode line the assembly was generated. +`asm` contains the returned assembly. This is the same assembly that is shown within compiler-explorer, including extra +information like for which sourcecode line the assembly was generated. `stderr` and `stdout` contain the different outputs from the compilation process. diff --git a/docs/AddingAssemblyDocumentation.md b/docs/AddingAssemblyDocumentation.md index 7a35ced59..727b6b6f1 100644 --- a/docs/AddingAssemblyDocumentation.md +++ b/docs/AddingAssemblyDocumentation.md @@ -1,7 +1,7 @@ # Adding Assembly Documentation for a new instruction set -This document explains how to add assembly documentation for a new instruction set to Compiler Explorer -("CE" from here on). +This document explains how to add assembly documentation for a new instruction set to Compiler Explorer ("CE" from here +on). If you were not already aware, CE has both quick-tip and more thorough assembly instruction documentation available for a couple instruction sets (currently JVM bytecode, amd64 and arm32). The feature is demonstrated in the gif below. @@ -12,8 +12,8 @@ To add a new assembly documentation handler, you need to perform the following s ## 1. Find a data source -First you need to find a data source to get our instruction info from. While it is possible to write down -information about every single instruction for an instruction set, it's far from maintainable, and it is a lot of work. +First you need to find a data source to get our instruction info from. While it is possible to write down information +about every single instruction for an instruction set, it's far from maintainable, and it is a lot of work. Existing assembly documentation handlers use some sort of established documentation. The arm32 handler uses the developer.arm.com website and the JVM bytecode handler uses Oracle's documentation. @@ -29,9 +29,9 @@ How you generate this file is completely up to you, just make sure it's easy for well. If you need inspiration on how to write this tool, you can look at the `docenizer-*` scripts found in `/etc/scripts/docenizers` in the source control tree. -CE expects the tool to output the file into the `/lib/asm-docs/generated/` folder with a name following the existing -convention. Each case in the switch should return a piece of formatted HTML to insert into the popup, a tooltip text -for the on-hover tooltip and a URL to external documentation. +CE expects the tool to output the file into the `/lib/asm-docs/generated/` folder with a name following the existing +convention. Each case in the switch should return a piece of formatted HTML to insert into the popup, a tooltip text for +the on-hover tooltip and a URL to external documentation. ```js case "CALL": @@ -48,28 +48,31 @@ Once your tool has generated the JavaScript file, you want to connect it to CE. in the `/lib/asm-docs` directory which is adjacent to your newly generated JavaScript file. First you want to add a new file named after your instruction set which exports a class extending the -`BaseAssemblyDocumentationProvider` class. The class should implement the `getInstructionInformation` method which -in most cases, delegates to your generated JavaScript. Instruction sets like Arm32 have use code to tweak the output -if needed. +`BaseAssemblyDocumentationProvider` class. The class should implement the `getInstructionInformation` method which in +most cases, delegates to your generated JavaScript. Instruction sets like Arm32 have use code to tweak the output if +needed. This method is expected to take the instruction opcode in full uppercase and either return the associated data or null if not found. ```ts -import { getAsmOpcode } from './generated//asm-docs-java'; -import { BaseAssemblyDocumentationProvider } from './base'; +import {getAsmOpcode} from './generated//asm-docs-java'; +import {BaseAssemblyDocumentationProvider} from './base'; export class JavaDocumentationProvider extends BaseAssemblyDocumentationProvider { - // Return the instruction set name - public static get key() { return 'java'; } - public override getInstructionInformation(instruction: string): AssemblyInstructionInfo | null { - return getAsmOpcode(instruction) || null; - } + // Return the instruction set name + public static get key() { + return 'java'; + } + public override getInstructionInformation(instruction: string): AssemblyInstructionInfo | null { + return getAsmOpcode(instruction) || null; + } } ``` Finally we want to tell CE that the new documentation provider exists. This is done by re-exporting the class inside `/lib/asm-docs/_all.ts`. Please keep the exports here in alphabetic order. + ## 4. Testing Testing new assembly documentation providers is really easy. It is just a matter of modifying the `TEST_MATRIX` variable diff --git a/docs/AddingCustomCompilersOverview.md b/docs/AddingCustomCompilersOverview.md index 52586cf31..cf615aae0 100644 --- a/docs/AddingCustomCompilersOverview.md +++ b/docs/AddingCustomCompilersOverview.md @@ -1,23 +1,24 @@ -This is an overview of what building and adding a compiler to the site looks like, using GCC as an example, - but note that the process is similar for all other types of compilers. +This is an overview of what building and adding a compiler to the site looks like, using GCC as an example, but note +that the process is similar for all other types of compilers. -* Build GCC versions with the relevant magic. - We build all our own GCCs using Docker from [this repo](https://github.com/compiler-explorer/gcc-builder) -* For non-trunk builds we manually run the docker image. - For trunk dailies we have a [cron job](https://github.com/compiler-explorer/infra/blob/main/crontab.admin#L8) - that runs a [script](https://github.com/compiler-explorer/infra/blob/main/admin-daily-builds.sh) to build them. -* Built tarballs are uploaded to S3, - and installed by our [custom tool](https://github.com/compiler-explorer/infra/blob/main/bin/lib/ce_install.py) - from a [YAML configuration file](https://github.com/compiler-explorer/infra/blob/main/bin/yaml/cpp.yaml) -* The installation puts compilers on a shared NFS drive at `/opt/compiler-explorer/gcc-some-version/` -* We then configure CE to look for the compiler - [here](https://github.com/compiler-explorer/compiler-explorer/blob/main/etc/config/c%2B%2B.amazon.properties#L9). -* If we need to customise the way we execute the compiler and/or display the results, - then we can change the "[driver](https://github.com/compiler-explorer/compiler-explorer/tree/main/lib/compilers)" - for the compiler. Usually we can just override a few aspects of the driver, - relying on the defaults from the [base driver](https://github.com/compiler-explorer/compiler-explorer/blob/main/lib/base-compiler.js). -* Any UI changes are a bit more work. +- Build GCC versions with the relevant magic. We build all our own GCCs using Docker from + [this repo](https://github.com/compiler-explorer/gcc-builder) +- For non-trunk builds we manually run the docker image. For trunk dailies we have a + [cron job](https://github.com/compiler-explorer/infra/blob/main/crontab.admin#L8) that runs a + [script](https://github.com/compiler-explorer/infra/blob/main/admin-daily-builds.sh) to build them. +- Built tarballs are uploaded to S3, and installed by our + [custom tool](https://github.com/compiler-explorer/infra/blob/main/bin/lib/ce_install.py) from a + [YAML configuration file](https://github.com/compiler-explorer/infra/blob/main/bin/yaml/cpp.yaml) +- The installation puts compilers on a shared NFS drive at `/opt/compiler-explorer/gcc-some-version/` +- We then configure CE to look for the compiler + [here](https://github.com/compiler-explorer/compiler-explorer/blob/main/etc/config/c%2B%2B.amazon.properties#L9). +- If we need to customise the way we execute the compiler and/or display the results, then we can change the + "[driver](https://github.com/compiler-explorer/compiler-explorer/tree/main/lib/compilers)" for the compiler. Usually + we can just override a few aspects of the driver, relying on the defaults from the + [base driver](https://github.com/compiler-explorer/compiler-explorer/blob/main/lib/base-compiler.js). +- Any UI changes are a bit more work. -More info still in [Adding a Compiler](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/AddingACompiler.md), - and if you can bear listening to Matt, here's [a talk](https://www.youtube.com/watch?v=kIoZDUd5DKw) - about some behind the scenes stuff, with [slides online](https://www.youtube.com/watch?v=kIoZDUd5DKw). +More info still in +[Adding a Compiler](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/AddingACompiler.md), and if +you can bear listening to Matt, here's [a talk](https://www.youtube.com/watch?v=kIoZDUd5DKw) about some behind the +scenes stuff, with [slides online](https://www.youtube.com/watch?v=kIoZDUd5DKw). diff --git a/docs/EWARM.md b/docs/EWARM.md index 1e5fff1c6..eaa7a9de6 100644 --- a/docs/EWARM.md +++ b/docs/EWARM.md @@ -1,33 +1,53 @@ # Running EWARM compiler on windows host -This document will show a little insight on how to get the IAR ARM compiler working with compiler explorer *(Some line highlighting is broken as EWAVR is different from EWARM)* + +This document will show a little insight on how to get the IAR ARM compiler working with compiler explorer _(Some line +highlighting is broken as EWAVR is different from EWARM)_ # Prerequisites + To run the IAR ARM compiler you will need: -- A valid installation of the IAR ARM compiler. [EWARM](https://www.iar.com/iar-embedded-workbench/#!?architecture=Arm) has a free 30-day trial on their website -- Technically you need a license as well to run the compiler, however you can get by with the 30-day free trial, as you will be able to run the compiler for 30 days for free +- A valid installation of the IAR ARM compiler. [EWARM](https://www.iar.com/iar-embedded-workbench/#!?architecture=Arm) + has a free 30-day trial on their website +- Technically you need a license as well to run the compiler, however you can get by with the 30-day free trial, as you + will be able to run the compiler for 30 days for free - MinGW C++ toolchain for `c++filt` and `objdump` ## IAR ARM Compiler -This compiler will be installed along with the IAR Embedded Workbench (EWARM). Default installation location is under `C:\Program Files (x86)\IAR Systems\Embedded Workbench 8.2\arm\bin\iccarm.exe` + +This compiler will be installed along with the IAR Embedded Workbench (EWARM). Default installation location is under +`C:\Program Files (x86)\IAR Systems\Embedded Workbench 8.2\arm\bin\iccarm.exe` ## MinGW C++ Toolchain -We need to install this toolchain through [MSYS2](https://www.msys2.org/), as it contains `c++filt` and `objdump`, which are needed to demangle the assembly + +We need to install this toolchain through [MSYS2](https://www.msys2.org/), as it contains `c++filt` and `objdump`, which +are needed to demangle the assembly - First download [MSYS2](https://www.msys2.org/) -- Install it and run it, entering the first command `pacman -Syuu`, this command will update all the internal MSYS2 modules to their latest version. This command will also update all installed modules, such as the toolchain if it was installed. -- When you run the command for the first time, it will exit the bash console. You have to open it again and run the same command again `pacman -Syuu` -- After the second time, everything will be up to date. To install the MinGW toolchain, run `pacman -S mingw-w64-x86_64-toolchain`. This will install the toolchain to your MSYS2 default installation path under `C:\msys64\mingw64\bin` -- Add this path `C:\msys64\mingw64\bin` to windows global `PATH` -- Test by running `c++filt --help` from windows command prompt, if everything is set up correctly, then you should see all the command line options for c++filt +- Install it and run it, entering the first command `pacman -Syuu`, this command will update all the internal MSYS2 + modules to their latest version. This command will also update all installed modules, such as the toolchain if it was + installed. +- When you run the command for the first time, it will exit the bash console. You have to open it again and run the same + command again `pacman -Syuu` +- After the second time, everything will be up to date. To install the MinGW toolchain, run + `pacman -S mingw-w64-x86_64-toolchain`. This will install the toolchain to your MSYS2 default installation path under + `C:\msys64\mingw64\bin` +- Add this path `C:\msys64\mingw64\bin` to windows global `PATH` +- Test by running `c++filt --help` from windows command prompt, if everything is set up correctly, then you should see + all the command line options for c++filt # Setup and Configuration + ## Running compiler explorer on Windows -Refer to the [readme](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/WindowsNative.md) on running Native on Windows for general setup of Compiler Explorer and other compilers. + +Refer to the [readme](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/WindowsNative.md) on running +Native on Windows for general setup of Compiler Explorer and other compilers. ## Setting up c++.local.properties -The next step is to create a `c++.local.properties` file under `etc/config` folder. -The next step is going to be different for everyone, as you can choose what compiler options you pass to the compiler and so on, but im going to paste my template here, and you can just modify, what you need + +The next step is to create a `c++.local.properties` file under `etc/config` folder. The next step is going to be +different for everyone, as you can choose what compiler options you pass to the compiler and so on, but im going to +paste my template here, and you can just modify, what you need ``` # Default settings for C++ @@ -55,8 +75,11 @@ needsMulti=false stubRe=\bmain\b stubText=int main(void){return 0;/*stub provided by Compiler Explorer*/} ``` -**It's important to note that the `compiler.iar8.32.4.compilerType` field is set to `ewarm` this will be the custom compiler key later on** + +**It's important to note that the `compiler.iar8.32.4.compilerType` field is set to `ewarm` this will be the custom +compiler key later on** ## Running Compiler Explorer -You should be able to just `cd` into the compiler explorer repository and run `npm start`. After that just head on to [localhost:10240](http://localhost:10240) +You should be able to just `cd` into the compiler explorer repository and run `npm start`. After that just head on to +[localhost:10240](http://localhost:10240) diff --git a/docs/EWAVR.md b/docs/EWAVR.md index 9b87e9aa3..ccd0dc59d 100644 --- a/docs/EWAVR.md +++ b/docs/EWAVR.md @@ -2,27 +2,37 @@ Contact: [Ethan Slattery](https://github.com/CrustyAuklet) -## Prerequisites +## Prerequisites + To run the IAR compiler for IAR on linux you will need the following things: - - A valid copy of the IAR compiler - - A license for the compiler - - wine set up for win32 and i386 + +- A valid copy of the IAR compiler +- A license for the compiler +- wine set up for win32 and i386 ### Getting a copy of IAR -Assuming you already have a valid copy of IAR installed on a Windows machine, you can simply zip the installation directory. -The installation is "portable" for all use cases needed by compiler explorer. The one thing that doesn't work so far is building a project file. Individual file compilation works well using `iccavr.exe`. -If you installed to the default location this means creating an archive of the directory `C:\Program Files (x86)\IAR Systems\Embedded Workbench 8.0` +Assuming you already have a valid copy of IAR installed on a Windows machine, you can simply zip the installation +directory. The installation is "portable" for all use cases needed by compiler explorer. The one thing that doesn't work +so far is building a project file. Individual file compilation works well using `iccavr.exe`. + +If you installed to the default location this means creating an archive of the directory +`C:\Program Files (x86)\IAR Systems\Embedded Workbench 8.0` ### Compiler license -The machine used for compiling needs to have access to a license, or compilation will fail. -Ensure the server running compiler explorer can access the license server. If you want to use a dongle, then modify the following instructions accordingly, and good luck. -Note: Each time a compilation happens the machine doing that compilation claims the license for 20 minutes. -Each docker instance counts as a different machine. Because of this it is a good idea to ensure that the machine running IAR is a long-lived container/VM/machine to prevent using up all licenses and irritating your coworkers. +The machine used for compiling needs to have access to a license, or compilation will fail. Ensure the server running +compiler explorer can access the license server. If you want to use a dongle, then modify the following instructions +accordingly, and good luck. + +Note: Each time a compilation happens the machine doing that compilation claims the license for 20 minutes. Each docker +instance counts as a different machine. Because of this it is a good idea to ensure that the machine running IAR is a +long-lived container/VM/machine to prevent using up all licenses and irritating your coworkers. ### Wine -There are many places online to learn how to set up wine. A very simplified setup I often use in a fresh ubuntu docker container is: + +There are many places online to learn how to set up wine. A very simplified setup I often use in a fresh ubuntu docker +container is: ```bash $ apt-get update @@ -33,27 +43,32 @@ $ WINEARCH=win32 winecfg ``` ## Setup and Configuration -### Running locally on a Windows workstation or a windows server -Refer to the readme on running [Native on Windows](WindowsNative.md) for general setup of Compiler Explorer and other compilers. -Then add EWAVR as an additional compiler in your `c++.local.properties` file. The example in the compiler explorer -[documentation folder](EWAVR.properties) is written for linux so just modify the paths as needed. -The following properties are the ones that need to be set in addition to the typical settings you do for any compiler. - - `versionRe=^IAR C\/C\+\+ Compiler.*AVR$` - - `isSemVer=true` - - `options=--eec++` - - `supportsDemangler=false` +### Running locally on a Windows workstation or a windows server + +Refer to the readme on running [Native on Windows](WindowsNative.md) for general setup of Compiler Explorer and other +compilers. Then add EWAVR as an additional compiler in your `c++.local.properties` file. The example in the compiler +explorer [documentation folder](EWAVR.properties) is written for linux so just modify the paths as needed. The following +properties are the ones that need to be set in addition to the typical settings you do for any compiler. + +- `versionRe=^IAR C\/C\+\+ Compiler.*AVR$` +- `isSemVer=true` +- `options=--eec++` +- `supportsDemangler=false` ### Running on a linux server using docker + #### Step 1: provide configuration files, compilers, and libraries -*If you are more experienced with docker this can be done with a volume, but I just use a local folder on my server* + +_If you are more experienced with docker this can be done with a volume, but I just use a local folder on my server_ Create a folder on the server `/opt/compiler_explorer`. We are focusing on EWAVR, but you can see we also include -several other embedded compilers, the native compilers, and many open source and internal libraries. The EWAVR specific portions -of `c++.local.properties` is provided in the [example](EWAVR.properties), the rest is generic library and compiler settings. -`compiler-explorer.local.properties` contains server specific sub-domain settings. +several other embedded compilers, the native compilers, and many open source and internal libraries. The EWAVR specific +portions of `c++.local.properties` is provided in the [example](EWAVR.properties), the rest is generic library and +compiler settings. `compiler-explorer.local.properties` contains server specific sub-domain settings. -The EWAVR directories are just the archives of the installation folders from windows un-tarred there, as you can see from the layout. +The EWAVR directories are just the archives of the installation folders from windows un-tarred there, as you can see +from the layout. ```bash /opt/compiler_explorer/ @@ -90,8 +105,10 @@ The EWAVR directories are just the archives of the installation folders from win ``` #### Step 2: Make iccavr callable -To invoke `iccavr` you need to use the command `wine /opt/compiler_explorer/compilers/ewavr_7108/avr/bin/iccavr.exe` which created some issues for me in CE. -I create small bash script aliases using the following commands, for each versions `bin` folder: + +To invoke `iccavr` you need to use the command `wine /opt/compiler_explorer/compilers/ewavr_7108/avr/bin/iccavr.exe` +which created some issues for me in CE. I create small bash script aliases using the following commands, for each +versions `bin` folder: ```bash $ IAR_ROOT=/opt/compiler_explorer/compilers/ewavr_7108 @@ -101,9 +118,11 @@ $ echo -e "#\!/bin/bash\nwine $IAR_ROOT/avr/bin/iccavr.exe\n" > $IAR_ROOT/avr/bi ``` #### Step 3: Start Compiler Explorer as a docker image -A [docker image](https://hub.docker.com/repository/docker/crustyauklet/compiler_explorer) is available that bundles a working version of Compiler Explorer -and wine so that no additional setup is needed on the host server. The IAR license needs to be run once, at system startup to register with the license server, -so that can be seen in the docker command. If you have multiple IAR versions, only one needs to be run, and it doesn't matter which one. + +A [docker image](https://hub.docker.com/repository/docker/crustyauklet/compiler_explorer) is available that bundles a +working version of Compiler Explorer and wine so that no additional setup is needed on the host server. The IAR license +needs to be run once, at system startup to register with the license server, so that can be seen in the docker command. +If you have multiple IAR versions, only one needs to be run, and it doesn't matter which one. ```bash $ IAR_SERVER=my.liscense_server.ip.address diff --git a/docs/Privacy.md b/docs/Privacy.md index b2fcdf31c..0f847d2bd 100644 --- a/docs/Privacy.md +++ b/docs/Privacy.md @@ -1,9 +1,8 @@ -Compiler Explorer and Privacy ------------------------------ +## Compiler Explorer and Privacy -*This is a summary of our Privacy policy, not a legal document, and might be incomplete.* +_This is a summary of our Privacy policy, not a legal document, and might be incomplete._ -*For the full Privacy policy, see `static/policies/privacy.html`, or visit https://godbolt.org/#privacy* +_For the full Privacy policy, see `static/policies/privacy.html`, or visit https://godbolt.org/#privacy_ The main Compiler Explorer site (at https://godbolt.org/) has a cookie and privacy policy, and it's expected that any changes to the code are in compliance with those policies. It's worth taking a look at them if you're touching any area @@ -20,9 +19,9 @@ the sister site www.godbolt.ms and that data is covered by Users have rights over the data they create: so in theory they could ask for any data stored on them to be removed. We have no way of tracking data (a short link, perhaps) back to an individual user, and when I asked some experts on this -the consensus was that we're OK not to supply this. If, however, we ever have user attribution (e.g., we start -having accounts), we need to support the user being able to close their account, and/or delete any data they created -(e.g., short links). All this makes perfect sense and would probably be done anyway, as it seems useful! +the consensus was that we're OK not to supply this. If, however, we ever have user attribution (e.g., we start having +accounts), we need to support the user being able to close their account, and/or delete any data they created (e.g., +short links). All this makes perfect sense and would probably be done anyway, as it seems useful! We anonymise IP addresses so there's no exact mapping back to an individual using an IP. Not that it's trivial to map an IP to a user anyway. @@ -37,10 +36,10 @@ is to not use the main Compiler Explorer but instead run their own local service A very small group of people have administrator rights on the public Compiler Explorer. Those individuals can: -* Read the logs -* Log in to the running Compiler Explorer compilation nodes -* Access the S3 storage where caches and stored information may be kept -* Access and modify the EFS storage where compilers are stored +- Read the logs +- Log in to the running Compiler Explorer compilation nodes +- Access the S3 storage where caches and stored information may be kept +- Access and modify the EFS storage where compilers are stored In short, administrators can see everything that goes on. It is expected that administrators keep this deep responsibility in mind when performing actions on Compiler Explorer, and that they keep users' privacy at the forefront diff --git a/docs/README.md b/docs/README.md index 7e008a39f..46bcf0117 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,41 +1,48 @@ # How do I ? -This is a how-to guide for the user-interface presented by [Compiler Explorer](https://godbolt.org). -This doesn't cover the details of how to set up or modify Compiler Explorer for your own needs. -For that, please check the documents which already cover topics like: -* [Adding a language](AddingALanguage.md) -* [Adding a compiler](AddingACompiler.md) -* [Adding a library](AddingALibrary.md) -* [Adding a tool](AddingATool.md) -* and many more at [compiler-explorer/docs](https://github.com/compiler-explorer/compiler-explorer/tree/main/docs) +This is a how-to guide for the user-interface presented by [Compiler Explorer](https://godbolt.org). This doesn't cover +the details of how to set up or modify Compiler Explorer for your own needs. For that, please check the documents which +already cover topics like: + +- [Adding a language](AddingALanguage.md) +- [Adding a compiler](AddingACompiler.md) +- [Adding a library](AddingALibrary.md) +- [Adding a tool](AddingATool.md) +- and many more at [compiler-explorer/docs](https://github.com/compiler-explorer/compiler-explorer/tree/main/docs) Fast links: + - [How do I ?](#how-do-i-) - [Change the assembly syntax from Intel](#change-the-assembly-syntax-from-intel) - [Compare the time taken by compilation and networking](#compare-the-time-taken-by-compilation-and-networking) - [View intermediate information provided by the compilers](#view-intermediate-information-provided-by-the-compilers) ## Change the assembly syntax from Intel + ![Output, intel and at&t](./images/asm_info.png) -The option to switch assembly from Intel to AT&T syntax is present in the `Output` option of each compiler. -If enough space is not present, the option also presents itself as the gear symbol (⚙) +The option to switch assembly from Intel to AT&T syntax is present in the `Output` option of each compiler. If enough +space is not present, the option also presents itself as the gear symbol (⚙) ## Compare the time taken by compilation and networking + ![Brief overview of UI](./images/brief_overview.png) -This is the symbol that looks like a bar graph (📊). If your compilations are taking long, you can use this to check the time taken by: -* Networking, JavaScript, waiting for events, etc. -* Checking the cache and retrieving from it on a cache-hit -* Compilation (on force compilation or cache-miss) -* Parsing the generated assembly before presenting it +This is the symbol that looks like a bar graph (📊). If your compilations are taking long, you can use this to check the +time taken by: + +- Networking, JavaScript, waiting for events, etc. +- Checking the cache and retrieving from it on a cache-hit +- Compilation (on force compilation or cache-miss) +- Parsing the generated assembly before presenting it ## View intermediate information provided by the compilers -![Options for GCC](./images/add_new_gcc.png) -![Options for Clang](./images/add_new_clang.png) -Though both GCC and Clang create supplementary outputs along with assembly (shown by default), -and an executable (created if an executor has been added), the exact nature of the outputs and their formats differ between the compilers. +![Options for GCC](./images/add_new_gcc.png) ![Options for Clang](./images/add_new_clang.png) -GCC allows the Tree, IPA, RTL and graph outputs, while Clang allows optimization, AST, IR and graph outputs. -Some outputs (e.g. RTL or graph) also have a rich set of options in the UI to enable focussing on a particular function or compiler stage. +Though both GCC and Clang create supplementary outputs along with assembly (shown by default), and an executable +(created if an executor has been added), the exact nature of the outputs and their formats differ between the compilers. + +GCC allows the Tree, IPA, RTL and graph outputs, while Clang allows optimization, AST, IR and graph outputs. Some +outputs (e.g. RTL or graph) also have a rich set of options in the UI to enable focussing on a particular function or +compiler stage. diff --git a/docs/Roadmap.md b/docs/Roadmap.md index e183268ad..532006ce2 100644 --- a/docs/Roadmap.md +++ b/docs/Roadmap.md @@ -9,8 +9,7 @@ This document is an attempt to capture thoughts on the future direction of Compi A number of the open issues are to add more languages, libraries and compilers. Continuing to make it easier for others to submit PRs to add new compilers is very important. This has improved, but not all compilers are installed using the new approach. There's documentation on [adding a compiler](AddingACompiler.md), -[adding a new language](AddingALanguage.md) -and [adding a library](AddingALibrary.md). +[adding a new language](AddingALanguage.md) and [adding a library](AddingALibrary.md). ### Multiple file support @@ -29,6 +28,7 @@ improve code quality (e.g. move to transpiling from Typescript or similar to giv easy to support existing code. ## Considerations + ### Tensions There's an inherent tension between the standalone, run-it-yourself version of CE and the scalable, AWS-backed CE @@ -50,19 +50,18 @@ that has been relaxed slightly to allow up to three company sponsor logos visibl ### 2021 goals -* **Login support**. Support logging in to the site with GitHub, Google, etc. We will _never_ force you to log in for +- **Login support**. Support logging in to the site with GitHub, Google, etc. We will _never_ force you to log in for basic features, and of course will update the Privacy Policy. I won't be selling anything to do with user info etc, either: Logging in will be purely used to make _your_ life easier and allow you to manage things like shared settings and configuration, listing short URLs you've created (and potentially being able to remove them); and _maybe_ being able to make user-named short URLs (e.g., "godbolt.org/u/mattgodbolt/ctad-example"). This goal is a personal pet project of [Matt's](http://github.com/mattgodbolt/). -* **Multi-file support**. Multiple file compilation units to open the door to seeing LTO and maybe modules. This may +- **Multi-file support**. Multiple file compilation units to open the door to seeing LTO and maybe modules. This may include being able to use a `CMake` file to build things. -* **Modernising the codebase**. Moving the codebase to TypeScript, or something similar that will allow us to worry less +- **Modernising the codebase**. Moving the codebase to TypeScript, or something similar that will allow us to worry less about differences between front-end and back-end code (old Javascript versions), and help us attract more people to the project. -* **More compilers and libraries**. Plus finishing off the last stragglers of installation. - +- **More compilers and libraries**. Plus finishing off the last stragglers of installation. ### Prior years' goals diff --git a/docs/Sponsors.md b/docs/Sponsors.md index 973e18669..b40975252 100644 --- a/docs/Sponsors.md +++ b/docs/Sponsors.md @@ -1,9 +1,11 @@ # Sponsorship -Compiler Explorer is funded by sponsors: mostly individuals through Patreon, GitHub sponsors and PayPal one-off payments. -There is potential for corporate sponsorship; though extremely limited due to the goal of making Compiler Explorer a mostly ad-free experience. +Compiler Explorer is funded by sponsors: mostly individuals through Patreon, GitHub sponsors and PayPal one-off +payments. There is potential for corporate sponsorship; though extremely limited due to the goal of making Compiler +Explorer a mostly ad-free experience. -Corporate sponsorship requests should be directed to [Matt](mailto:matt@godbolt.org), who has sole discretion on what kinds of sponsorship is appropriate. +Corporate sponsorship requests should be directed to [Matt](mailto:matt@godbolt.org), who has sole discretion on what +kinds of sponsorship is appropriate. ## The sponsors.yaml format @@ -26,7 +28,7 @@ levels: - name: Level two description: The second level. sponsors: - - bob - - ian - - joe + - bob + - ian + - joe ``` diff --git a/docs/SystemdSocketActivation.md b/docs/SystemdSocketActivation.md index fe1aa4611..eae67d190 100644 --- a/docs/SystemdSocketActivation.md +++ b/docs/SystemdSocketActivation.md @@ -1,10 +1,12 @@ # Using Systemd socket based activation to start Compiler Explorer -This document gives a short overview of how to use Systemd to automatically start Compiler Explorer when the web-interface is accessed. +This document gives a short overview of how to use Systemd to automatically start Compiler Explorer when the +web-interface is accessed. You'll need to create two files in `/etc/systemd/system/`: compiler-explorer.socket: + ``` [Socket] ListenStream=10240 @@ -13,8 +15,8 @@ ListenStream=10240 WantedBy=sockets.target ``` - compiler-explorer.service: + ``` [Service] Type=simple diff --git a/docs/WindowsNative.md b/docs/WindowsNative.md index fe167c4b8..b3fd75982 100644 --- a/docs/WindowsNative.md +++ b/docs/WindowsNative.md @@ -4,35 +4,24 @@ Contact: [Nicole Mazzuca](https://github.com/ubsan) ## Basic Setup -The setup on Windows should be fairly trivial: -the only prerequisite is node. -If you haven't yet installed node yet, you can grab it from -[here](https://nodejs.org/en/); -get the Windows LTS release. +The setup on Windows should be fairly trivial: the only prerequisite is node. If you haven't yet installed node yet, you +can grab it from [here](https://nodejs.org/en/); get the Windows LTS release. -Once you've done this, -and added `npm` to the path, -run the following commands from any command line, -in the directory you want the Compiler Explorer (from here on, CE) -to live: +Once you've done this, and added `npm` to the path, run the following commands from any command line, in the directory +you want the Compiler Explorer (from here on, CE) to live: ```bat git clone https://github.com/compiler-explorer/compiler-explorer.git ``` -Then, we'll need to make a configuration file -which points at your compilers and include directories. -Copy [`docs\WindowsLocal.properties`](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/WindowsLocal.properties) to a new file, -`etc\config\c++.local.properties`, and edit it, -following the instructions in the comments. -If you have any questions, please ping me on discord. - +Then, we'll need to make a configuration file which points at your compilers and include directories. Copy +[`docs\WindowsLocal.properties`](https://github.com/compiler-explorer/compiler-explorer/blob/main/docs/WindowsLocal.properties) +to a new file, `etc\config\c++.local.properties`, and edit it, following the instructions in the comments. If you have +any questions, please ping me on discord. ## Actually Running the danged thing -Once you've finished setting it up, -you can `cd` into the `compiler-explorer` directory, -then run +Once you've finished setting it up, you can `cd` into the `compiler-explorer` directory, then run ```bat npm install @@ -54,36 +43,36 @@ info: ======================================= Now point your favorite web browser at http://localhost:10240, and you should be done! -You only have to run `npm install` the first time; -every time after that, you should just be able to run `npm start`. +You only have to run `npm install` the first time; every time after that, you should just be able to run `npm start`. ## Debugging using VSCode -Similar to [WindowsSubsystemForLinux](WindowsSubsystemForLinux.md), -the following is a `launch.json` that works for attaching to an instance of CE that was launched with `npm run-script debugger` (launches with the `--inspect` flag). +Similar to [WindowsSubsystemForLinux](WindowsSubsystemForLinux.md), the following is a `launch.json` that works for +attaching to an instance of CE that was launched with `npm run-script debugger` (launches with the `--inspect` flag). ```json { - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "attach", - "name": "Attach to Process", - "port": 9229, - "address": "localhost", - "protocol": "inspector", - "localRoot": "${workspaceRoot}", - "remoteRoot": "C:\\Users\\${username}\\compiler-explorer" - } - ] + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "attach", + "name": "Attach to Process", + "port": 9229, + "address": "localhost", + "protocol": "inspector", + "localRoot": "${workspaceRoot}", + "remoteRoot": "C:\\Users\\${username}\\compiler-explorer" + } + ] } ``` -Launch CE with `npm run-script debugger` to have node listen on port 9229. +Launch CE with `npm run-script debugger` to have node listen on port 9229. -Because this only attaches to the process, as opposed to launching the process, in order to debug startup code you need to attach while npm is starting up. -The `debugger` script also enables `debug` logging level so debug print statements can be seen during the CE startup and run. +Because this only attaches to the process, as opposed to launching the process, in order to debug startup code you need +to attach while npm is starting up. The `debugger` script also enables `debug` logging level so debug print statements +can be seen during the CE startup and run. ### Setting up binary mode and execution @@ -91,36 +80,39 @@ To create executables with Visual C++, it's required to install the Windows SDK. You can find the Windows 10 SDK [here](https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk) -When you've installed the SDK, you'll need to set up the library and include paths in Compilers Explorer. -Make sure that in the previously discussed c++.local.properties you have added at least: - * to includePath - - Windows Kits/10/include/*version*/ucrt - - Windows Kits/10/include/*version*/shared - - Windows Kits/10/include/*version*/um - * to libPath (for the x64 compiler) - - Windows Kits/10/Lib/*version*/um/x64 - - Windows Kits/10/Lib/*version*/ucrt/x64 - - VC installation path/lib/x64 +When you've installed the SDK, you'll need to set up the library and include paths in Compilers Explorer. Make sure that +in the previously discussed c++.local.properties you have added at least: -If needed, you can set in your properties file: ```supportsExecute=true``` +- to includePath + - Windows Kits/10/include/_version_/ucrt + - Windows Kits/10/include/_version_/shared + - Windows Kits/10/include/_version_/um +- to libPath (for the x64 compiler) + - Windows Kits/10/Lib/_version_/um/x64 + - Windows Kits/10/Lib/_version_/ucrt/x64 + - VC installation path/lib/x64 + +If needed, you can set in your properties file: `supportsExecute=true` #### Binary mode -For binary mode, you will need a Windows version of Objdump. There are various -versions of MingW available that will offer binutils including objdump. +For binary mode, you will need a Windows version of Objdump. There are various versions of MingW available that will +offer binutils including objdump. -The version of objdump that we have tested with is shipped with MingW-64, -you can find it for download [here](https://sourceforge.net/projects/mingw-w64/) +The version of objdump that we have tested with is shipped with MingW-64, you can find it for download +[here](https://sourceforge.net/projects/mingw-w64/) When you use the installer for MingW-64, make sure you select the right architecture during installation. -When you use the zipped version, after unzipping you will need to add the bin folder to your Windows PATHS environment variable. -Be aware that this PATH needs to be added before any other folders that might contain an objdump. You cannot just point to the .exe as the objdumper without having the proper PATH set, it will not work. +When you use the zipped version, after unzipping you will need to add the bin folder to your Windows PATHS environment +variable. Be aware that this PATH needs to be added before any other folders that might contain an objdump. You cannot +just point to the .exe as the objdumper without having the proper PATH set, it will not work. When you have everything installed, you can add to your properties file the following: + ``` supportsBinary=true objdumper=objdump ``` -*Note that the 32 bit version of MingW does not support 64 bit binaries.* +_Note that the 32 bit version of MingW does not support 64 bit binaries._ diff --git a/docs/WindowsSubsystemForLinux.md b/docs/WindowsSubsystemForLinux.md index 7a27a3c0e..694146fec 100644 --- a/docs/WindowsSubsystemForLinux.md +++ b/docs/WindowsSubsystemForLinux.md @@ -2,26 +2,43 @@ Contact: [@AndrewPardoe](https://github.com/AndrewPardoe) -The Compiler Explorer ("CE" from here on) runs quite well on the [Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/faq) ("WSL"). -Running on WSL enables Linux-based compilers to continue running natively while enabling Windows-based compilers to run in a real Windows environment. +The Compiler Explorer ("CE" from here on) runs quite well on the +[Windows Subsystem for Linux](https://docs.microsoft.com/en-us/windows/wsl/faq) ("WSL"). Running on WSL enables +Linux-based compilers to continue running natively while enabling Windows-based compilers to run in a real Windows +environment. -No special configuration is needed to run CE under WSL. Some configuration is required for hosting the Microsoft Visual C++ ("MSVC") compiler. -Testing has mainly been done on the Ubuntu distro but any distro should work. +No special configuration is needed to run CE under WSL. Some configuration is required for hosting the Microsoft Visual +C++ ("MSVC") compiler. Testing has mainly been done on the Ubuntu distro but any distro should work. ## WSL/Windows interop and its limitations -WSL offers rich interop with Windows processes. You can run any Windows executable, such as "`cl.exe`", from a bash shell. But this interop capability has some limitations. -- Windows volumes: While Windows executables can be run from bash, they cannot see Linux volumes. Windows executables that need to read or write files must be run on a Windows volume. This means all MSVC compiles must be done in the Windows `%TEMP%` directory instead of in the `bash` environment's temp directory. -- Path: The WSL path set in bash prepends the Windows path. While Linux filesystems support odd naming conventions such as spaces and parentheses, Windows' path uses these as a matter of course (e.g., `c:\Program Files (x86)`). Additionally, the Windows path delimiter is `\` instead of `/`, and it uses drive letters instead of mount points that are separated with a colon. -- Path names: A Windows path of `c:\tmp` is normally referred to as `/mnt/c/tmp` in `bash`. However, users can customize their `drvfs` mount points. A tool is provided in newer Windows releases, `/bin/wslpath`, that will convert paths between systems. Code in CE currently does the conversion between the standard conventions using string manipulation. -- Environment variables: While the Windows path is available in bash, Windows environment variables are not. CE uses `cmd.exe /c echo %TEMP%` to determine the Windows temporary directory. -- Execution environment: The execution environment cannot currently be set when doing `childprocess.spawn`. This is a serious issue for the MSVC compiler, which is highly environment-dependent (e.g., `%INCLUDE%`, `%LIBPATH%`, etc.) + +WSL offers rich interop with Windows processes. You can run any Windows executable, such as "`cl.exe`", from a bash +shell. But this interop capability has some limitations. + +- Windows volumes: While Windows executables can be run from bash, they cannot see Linux volumes. Windows executables + that need to read or write files must be run on a Windows volume. This means all MSVC compiles must be done in the + Windows `%TEMP%` directory instead of in the `bash` environment's temp directory. +- Path: The WSL path set in bash prepends the Windows path. While Linux filesystems support odd naming conventions such + as spaces and parentheses, Windows' path uses these as a matter of course (e.g., `c:\Program Files (x86)`). + Additionally, the Windows path delimiter is `\` instead of `/`, and it uses drive letters instead of mount points that + are separated with a colon. +- Path names: A Windows path of `c:\tmp` is normally referred to as `/mnt/c/tmp` in `bash`. However, users can customize + their `drvfs` mount points. A tool is provided in newer Windows releases, `/bin/wslpath`, that will convert paths + between systems. Code in CE currently does the conversion between the standard conventions using string manipulation. +- Environment variables: While the Windows path is available in bash, Windows environment variables are not. CE uses + `cmd.exe /c echo %TEMP%` to determine the Windows temporary directory. +- Execution environment: The execution environment cannot currently be set when doing `childprocess.spawn`. This is a + serious issue for the MSVC compiler, which is highly environment-dependent (e.g., `%INCLUDE%`, `%LIBPATH%`, etc.) ## Configuration -This section is intended for the many WSL users who are new to Linux. + +This section is intended for the many WSL users who are new to Linux. If you plan on debugging CE, you should clone the CE repo on a Windows volume. -CE is built on node.js ("node"). The easiest way to install node is using NVM, the Node Version Manager. Run the following commands from a bash shell: +CE is built on node.js ("node"). The easiest way to install node is using NVM, the Node Version Manager. Run the +following commands from a bash shell: + - `apt-get update` to make sure apt is up-to-date - `apt-get install build-essential libssl-dev`, though you probably have these already - Check https://github.com/creationix/nvm/releases for the latest NVM release, substituting it in the next command. @@ -30,7 +47,8 @@ CE is built on node.js ("node"). The easiest way to install node is using NVM, t - `nvm ls-remote --lts` to show the latest long-term supported (LTS) version of node.js - `nvm install 10.15.3`, substituting the latest LTS version, to install node.js -At this point you can change into the directory where you cloned CE and `make`. `make` will install a bunch of node packages and will finish with a message similar to this: +At this point you can change into the directory where you cloned CE and `make`. `make` will install a bunch of node +packages and will finish with a message similar to this: ``` info: ======================================= @@ -46,49 +64,71 @@ Now you can point your favorite web browser at http://localhost:10240 and see yo CE only required a few changes in order to run properly under WSL. Those changes are listed here: -- `app.js`: - - `process.env.wsl` is set if CE if the string "Microsoft" in found in the output of `uname -a`. This works for all WSL distros as they all run on the base Microsoft Linux kernel. - - If the `-tmpDir` option is specified on the command line, both `process.env.tmpDir` and `process.env.winTmp` are set to the specified value Note that if this is specified as a non-Windows volume, Windows executables will fail to run properly. Otherwise, `process.env.winTmp` is set to the value of the Windows `%TEMP%` directory. -- `lib/exec.js`: Execute the compiler in the temporary directory. If the compiler's binary is located on a mounted volume (`startsWith("/mnt"`)) and CE is running under WSL, run the compiler in the `winTmp` directory. Otherwise, use the Linux temp directory. -- `lib/compilers/wsl-vc.js`: See also `wine-vc.js`, the Wine version of this compiler-specific file. These files provide custom behaviors for a compiler. This file does two interesting things: - - The `CompileCl` function translates from Linux-style directories to Windows-style directories (`/mnt/c/tmp` to `c:/tmp`) so that `CL.exe` can find its input files. - - The `newTempDir` function creates a temporary directory in `winTmp`. CEs creates directories under the temp directory that start with `compiler-explorer-compiler` where the compiler and compiler output lives. This is similar to the function in `lib/base-compiler.js`. -- `etc/config/c++.defaults.properties`: Add a configuration (`&cl19`) for MSVC compilers. This edits in here are currently wrong in two ways, but it doesn't affect the main CE instance as it uses `amazon` properties files, and it doesn't affect anyone running a local copy of CE because CE will just fail silently when it can't find a compiler. - - The locations of these are hardcoded to a particular install location. See **MSVC setup** below for more information. - - Setting of the `%INCLUDE%` path is done with the `/I` switch. This is very clunky and will fall over when command-line limits are hit, but it's the only option currently as environments aren't passed through when starting a Windows process from WSL. +- `app.js`: + - `process.env.wsl` is set if CE if the string "Microsoft" in found in the output of `uname -a`. This works for all + WSL distros as they all run on the base Microsoft Linux kernel. + - If the `-tmpDir` option is specified on the command line, both `process.env.tmpDir` and `process.env.winTmp` are set + to the specified value Note that if this is specified as a non-Windows volume, Windows executables will fail to run + properly. Otherwise, `process.env.winTmp` is set to the value of the Windows `%TEMP%` directory. +- `lib/exec.js`: Execute the compiler in the temporary directory. If the compiler's binary is located on a mounted + volume (`startsWith("/mnt"`)) and CE is running under WSL, run the compiler in the `winTmp` directory. Otherwise, use + the Linux temp directory. +- `lib/compilers/wsl-vc.js`: See also `wine-vc.js`, the Wine version of this compiler-specific file. These files provide + custom behaviors for a compiler. This file does two interesting things: + - The `CompileCl` function translates from Linux-style directories to Windows-style directories (`/mnt/c/tmp` to + `c:/tmp`) so that `CL.exe` can find its input files. + - The `newTempDir` function creates a temporary directory in `winTmp`. CEs creates directories under the temp + directory that start with `compiler-explorer-compiler` where the compiler and compiler output lives. This is similar + to the function in `lib/base-compiler.js`. +- `etc/config/c++.defaults.properties`: Add a configuration (`&cl19`) for MSVC compilers. This edits in here are + currently wrong in two ways, but it doesn't affect the main CE instance as it uses `amazon` properties files, and it + doesn't affect anyone running a local copy of CE because CE will just fail silently when it can't find a compiler. + - The locations of these are hardcoded to a particular install location. See **MSVC setup** below for more + information. + - Setting of the `%INCLUDE%` path is done with the `/I` switch. This is very clunky and will fall over when + command-line limits are hit, but it's the only option currently as environments aren't passed through when starting + a Windows process from WSL. ## Debugging -The only viable option for debugging under WSL is to use [VS Code](https://code.visualstudio.com). Because VS Code doesn't currently run natively under WSL, you have to attach to a running CE instance. The following is a `launch.json` that works for attaching to an instance of CE that was launched with the `--inspect` flag. +The only viable option for debugging under WSL is to use [VS Code](https://code.visualstudio.com). Because VS Code +doesn't currently run natively under WSL, you have to attach to a running CE instance. The following is a `launch.json` +that works for attaching to an instance of CE that was launched with the `--inspect` flag. ```json { - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "attach", - "name": "Attach to Process", - "port": "9229", - "address": "localhost", - "protocol": "inspector", - "localRoot": "${workspaceRoot}", - "remoteRoot": "/mnt/c/src/compiler-explorer" - } - ] + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "request": "attach", + "name": "Attach to Process", + "port": "9229", + "address": "localhost", + "protocol": "inspector", + "localRoot": "${workspaceRoot}", + "remoteRoot": "/mnt/c/src/compiler-explorer" + } + ] } ``` Launch CE with `make NODE_ARGS="--inspect"` to have node listen on port 9229. -Because you can only attach to the process, as opposed to launching the process, you're limited to `printf` debugging for startup code. Search the code for `logger.info` to see examples of how to `printf` debug. +Because you can only attach to the process, as opposed to launching the process, you're limited to `printf` debugging +for startup code. Search the code for `logger.info` to see examples of how to `printf` debug. ## MSVC setup -TODO. There's no real MSVC setup at this point because there's no good way to pass the environment to an invocation of `CL.exe`. Just point the `properties` file at your compiler binary and hack on the `/I` options until something works. +TODO. There's no real MSVC setup at this point because there's no good way to pass the environment to an invocation of +`CL.exe`. Just point the `properties` file at your compiler binary and hack on the `/I` options until something works. -When I get this working in a generalized fashion, CE's config will expect that MSVC drops match the format used by the daily NuGet compiler drops at https://visualcpp.myget/org. (NuGet packages are just renamed ZIP files plus metadata so they make an easy distribution method for compiler toolset drops.) +When I get this working in a generalized fashion, CE's config will expect that MSVC drops match the format used by the +daily NuGet compiler drops at https://visualcpp.myget/org. (NuGet packages are just renamed ZIP files plus metadata so +they make an easy distribution method for compiler toolset drops.) ## Putting it all together -This should be enough information to get you started running CE under WSL. If there's information that you wish you would have had, please submit a PR to document. If there's information you're lacking to get running, please enter an Issue on the CE repo or contact me directly. +This should be enough information to get you started running CE under WSL. If there's information that you wish you +would have had, please submit a PR to document. If there's information you're lacking to get running, please enter an +Issue on the CE repo or contact me directly. diff --git a/docs/internal/AddingLinkableLibrary.md b/docs/internal/AddingLinkableLibrary.md index 5f7640bdb..8ed3ae842 100644 --- a/docs/internal/AddingLinkableLibrary.md +++ b/docs/internal/AddingLinkableLibrary.md @@ -1,51 +1,68 @@ Adding a library that is linked against: -- If the library is a C shared library, you should not use these instructions, use the `after_staging_script` instead to build the library during the installation +- If the library is a C shared library, you should not use these instructions, use the `after_staging_script` instead to + build the library during the installation - Check what buildsystem is used. - If CMake, it's going to be relatively easy. - If something else, it's going to be complicated. - If CMake - If the CMakeLists.txt is in the root folder, everything should be work - - However, at least prefer to include make_targets property in the yaml to avoid any automagick confusion (it would test library name in all kinds of variants and when all fails do make all) + - However, at least prefer to include make_targets property in the yaml to avoid any automagick confusion (it would + test library name in all kinds of variants and when all fails do make all) - If there are multiple ways of generating libraries (shared/static), make a choice here 1. Add to bin/yaml/libraries.yaml - - There's a difference between nightly trunks' and versions, search for "nightly:" to find the nightlies - - Note: the name of the library in the yaml file needs to be the same as the name in the c++.amazon.properties file - - Add basic entry - ``` - unifex: - type: github - method: nightlyclone - repo: facebookexperimental/libunifex - build_type: cmake - make_targets: - - unifex - targets: - - trunk + +- There's a difference between nightly trunks' and versions, search for "nightly:" to find the nightlies +- Note: the name of the library in the yaml file needs to be the same as the name in the c++.amazon.properties file +- Add basic entry + +```yaml +unifex: + type: github + method: nightlyclone + repo: facebookexperimental/libunifex + build_type: cmake + make_targets: + - unifex + targets: + - trunk ``` + 2. Test installing - - `bin/ce_install --enable nightly install 'unifex'` + +- `bin/ce_install --enable nightly install 'unifex'` + 3. Test building - - Make sure you have a compiler installed, for example via `bin/ce_install install 'gcc 10.1.0'` - - `bin/ce_install --enable nightly --buildfor g101 --dry build 'unifex'` - - check one of the buildfolders that are created and see if there are .so's or .a's and otherwise check the cecmakelog.txt and cemakelog_X.txt - - Iterate over this to make it work + +- Make sure you have a compiler installed, for example via `bin/ce_install install 'gcc 10.1.0'` +- `bin/ce_install --enable nightly --buildfor g101 --dry build 'unifex'` +- check one of the buildfolders that are created and see if there are .so's or .a's and otherwise check the + cecmakelog.txt and cemakelog_X.txt +- Iterate over this to make it work + 4. If a static link file has been produced: - - Add to the `c++.amazon.properties` in compiler-explorer in the libs properties for the new library a `libs.libraryname.staticliblink=libraryname` - - libraryname here is without the 'lib' prefix of the .a file - - Example unifex -``` + +- Add to the `c++.amazon.properties` in compiler-explorer in the libs properties for the new library a + `libs.libraryname.staticliblink=libraryname` + - libraryname here is without the 'lib' prefix of the .a file +- Example unifex + +```ini libs.unifex.name=libunifex libs.unifex.versions=trunk libs.unifex.staticliblink=unifex libs.unifex.versions.trunk.version=trunk libs.unifex.versions.trunk.path=/opt/compiler-explorer/libs/unifex/trunk/include ``` -5. If a config header file has been generated based on the compiler configuration, we can only maybe support this if the header does NOT include any defines about the architecture. + +5. If a config header file has been generated based on the compiler configuration, we can only maybe support this if the + header does NOT include any defines about the architecture. 6. Send PR's 7. Merge the amazon.properties to main 8. Start library builder for the new library until no later than 00:00 UTC -9. Await and check libraries @ https://conan.compiler-explorer.com/libraries.html and logs @ https://conan.compiler-explorer.com/failedbuilds.html - - These new libraries won't show up on these pages until you do https://conan.compiler-explorer.com/reinitialize and then go to https://conan.compiler-explorer.com/libraries and hit refresh +9. Await and check libraries @ https://conan.compiler-explorer.com/libraries.html and logs @ + https://conan.compiler-explorer.com/failedbuilds.html +- These new libraries won't show up on these pages until you do https://conan.compiler-explorer.com/reinitialize and + then go to https://conan.compiler-explorer.com/libraries and hit refresh diff --git a/docs/internal/BuildingAdHocCompilers.md b/docs/internal/BuildingAdHocCompilers.md index 969949da1..56ec93b4a 100644 --- a/docs/internal/BuildingAdHocCompilers.md +++ b/docs/internal/BuildingAdHocCompilers.md @@ -1,9 +1,10 @@ ## Brief notes on how to build a compiler -* log into admin node `ce admin` -* start the builder node: `ce builder start` -* log into builder node: `ce builder login` -* sudo docker run --rm --name gcc.build -v/home/ubuntu/.s3cfg:/root/.s3cfg:ro -ti compilerexplorer/gcc-builder bash build.sh 8.2.0 s3://compiler-explorer/opt/ -* Remember to stop the builder node! - * Log out of the builder node - * `ce builder stop` +- log into admin node `ce admin` +- start the builder node: `ce builder start` +- log into builder node: `ce builder login` +- sudo docker run --rm --name gcc.build -v/home/ubuntu/.s3cfg:/root/.s3cfg:ro -ti compilerexplorer/gcc-builder bash + build.sh 8.2.0 s3://compiler-explorer/opt/ +- Remember to stop the builder node! + - Log out of the builder node + - `ce builder stop` diff --git a/docs/internal/FrontendTesting.md b/docs/internal/FrontendTesting.md index 5e3a5a968..c0b4251d5 100644 --- a/docs/internal/FrontendTesting.md +++ b/docs/internal/FrontendTesting.md @@ -1,23 +1,26 @@ # Frontend testing -We have a mixture of typescript in the main website's code (located in `static/tests`) and Cypress (located in `cypress/integration`) to test and report on the workings of that code. +We have a mixture of typescript in the main website's code (located in `static/tests`) and Cypress (located in +`cypress/integration`) to test and report on the workings of that code. But there's always the possibility to use Cypress code to do UI checks and testing. ## Recommended -The recommended way of testing is to use typescript to test the inner workings of the various interfaces that are available. +The recommended way of testing is to use typescript to test the inner workings of the various interfaces that are +available. -This has the advantage of having types and being able to verify your code is consistent with the rest of the website and probably going to run correctly - without having to startup the website and Cypress. +This has the advantage of having types and being able to verify your code is consistent with the rest of the website and +probably going to run correctly - without having to startup the website and Cypress. ## Adding a test Steps to add a test: -* Create a new file in `static/tests` (copy paste from `static/tests/hello-world.ts`) -* Make sure to change the `description` as well as the test -* Add the file to the imports of `static/tests/_all.js` -* Add a `runFrontendTest()` call with the new test description to `cypress/integration/frontend-testing.js` +- Create a new file in `static/tests` (copy paste from `static/tests/hello-world.ts`) +- Make sure to change the `description` as well as the test +- Add the file to the imports of `static/tests/_all.js` +- Add a `runFrontendTest()` call with the new test description to `cypress/integration/frontend-testing.js` ## Starting tests locally @@ -25,4 +28,5 @@ You don't need to install an entire X server to actually run cypress (just xfvb) You can find a complete list at https://docs.cypress.io/guides/getting-started/installing-cypress#System-requirements -If you have the prerequisites installed, you should be able to run `npx cypress run` - however, you will need to start the CE website separately in another terminal before that. +If you have the prerequisites installed, you should be able to run `npx cypress run` - however, you will need to start +the CE website separately in another terminal before that. diff --git a/docs/internal/Preupdate-Checklist.md b/docs/internal/Preupdate-Checklist.md index 0231c309f..9a2acb2ea 100644 --- a/docs/internal/Preupdate-Checklist.md +++ b/docs/internal/Preupdate-Checklist.md @@ -1,52 +1,40 @@ # This document is a Work in Progress +This document pretends to put everything that is important to check before doing a full site release as well as to how +to do it, to ensure that the site fully works upon the release of a new version. -This document pretends to put everything that is important to check - before doing a full site release as well as to how to do it, - to ensure that the site fully works upon the release of a new version. +Depending on the nature of the changes, only some sections of this list will be relevant - Feel free to focus only on +those you deem most important. -Depending on the nature of the changes, only some sections - of this list will be relevant - Feel free to focus only on those - you deem most important. - -If you think we are missing any important point, we greatly appreciate - suggestions. +If you think we are missing any important point, we greatly appreciate suggestions. ## Running the site -First things first, we'll use the beta environment as it lets us run the - site under additional checks that will automate some of the problem - detections for us. + +First things first, we'll use the beta environment as it lets us run the site under additional checks that will automate +some of the problem detections for us. To run the new version on the beta environment we'll use the `ce` utility: -Ensure that the beta environment is active by running - `ce --env beta environment start` - You can skip this step if it's - already running from a previous run or if you'd rather boot it once - the current version is marked as active. +Ensure that the beta environment is active by running `ce --env beta environment start` - You can skip this step if it's +already running from a previous run or if you'd rather boot it once the current version is marked as active. -Check what `versionId` the desired commit has. This can be checked on the - Github CI build logs as its build number for that specific commit, or - by running `ce --env beta builds list` which shows a list of the - most recent builds with their corresponding commit hash. +Check what `versionId` the desired commit has. This can be checked on the Github CI build logs as its build number for +that specific commit, or by running `ce --env beta builds list` which shows a list of the most recent builds with their +corresponding commit hash. -Once you have the desired `versionId`, mark it as the current version to - be used by running `ce --env beta builds set_current {versionId}` +Once you have the desired `versionId`, mark it as the current version to be used by running +`ce --env beta builds set_current {versionId}` -If needed, you can now restart the currently running instances - with `ce --env beta instances restart` if needed. +If needed, you can now restart the currently running instances with `ce --env beta instances restart` if needed. Once this is finished, the `/beta` endpoint should be ready for testing. -- The first issue you might find is that the beta instance does not boot. - This might be caused by the `--ensureNoIdClash` flag shutting the app down - if it detects one or more pairs of compilers sharing the same id - even if they belong to different languages. An error should be logged - with the culprits for easy debugging. - +- The first issue you might find is that the beta instance does not boot. This might be caused by the + `--ensureNoIdClash` flag shutting the app down if it detects one or more pairs of compilers sharing the same id even + if they belong to different languages. An error should be logged with the culprits for easy debugging. ## Basic general site functionality -In-depth documentation follows below, but once the beta site is running, - some basic checks include: -- +In-depth documentation follows below, but once the beta site is running, some basic checks include: +- diff --git a/docs/internal/UpdatingAsmDocsx86.md b/docs/internal/UpdatingAsmDocsx86.md index 2745718f1..c7382fa66 100644 --- a/docs/internal/UpdatingAsmDocsx86.md +++ b/docs/internal/UpdatingAsmDocsx86.md @@ -1,9 +1,11 @@ If you need to update the x86 asm documentation, just run `etc/scripts/docenizers/docenizer.py`, which requires: - - Python 3.x with BeautifulSoup + +- Python 3.x with BeautifulSoup You can use some options in the script: - - `-o`/`--outputpath` - Final destination of the generated JavaScript file - - `-i`/`--inputfolder` - Points to the downloaded and extracted .html files - - `-d`/`--downloadfolder` - Points to the download folder to use in case a new version is needed + +- `-o`/`--outputpath` - Final destination of the generated JavaScript file +- `-i`/`--inputfolder` - Points to the downloaded and extracted .html files +- `-d`/`--downloadfolder` - Points to the download folder to use in case a new version is needed Now you only need to run it, and hope for the best. Please report any problems you encounter diff --git a/docs/internal/library_builder_logging.md b/docs/internal/library_builder_logging.md index ddf197548..aafd50b5a 100644 --- a/docs/internal/library_builder_logging.md +++ b/docs/internal/library_builder_logging.md @@ -5,19 +5,24 @@ The library build status is accessible from https://conan.compiler-explorer.com/ The build process of libraries (started by https://github.com/compiler-explorer/infra/blob/main/admin-daily-builds.sh) has a couple of safeguards to not build libraries allday everyday, namely: -* The compiler needs to have supportsBinary=true on in the current https://github.com/compiler-explorer/compiler-explorer/blob/main/etc/config/c%2B%2B.amazon.properties -* If all libraries are being built, only a commit hash change will result in a new build. -* If a particular compiler has failed to produce a valid build, it will be marked and will not build the library with this compiler anymore. -* There are a couple of hardcoded exceptions that never attempt the build, these can be found in https://github.com/compiler-explorer/infra/blob/main/bin/lib/library_builder.py#L29 -* You can manually trigger a forced-build, by setting the `--build-for=compilerid` parameter, which can also be set by changing the 2nd parameter here -> https://github.com/compiler-explorer/infra/blob/main/admin-daily-builds.sh#L104 -* If you want to trigger all compilers to rebuild a certain library, you will need to manually delete the logging related to this library. - +- The compiler needs to have supportsBinary=true on in the current + https://github.com/compiler-explorer/compiler-explorer/blob/main/etc/config/c%2B%2B.amazon.properties +- If all libraries are being built, only a commit hash change will result in a new build. +- If a particular compiler has failed to produce a valid build, it will be marked and will not build the library with + this compiler anymore. +- There are a couple of hardcoded exceptions that never attempt the build, these can be found in + https://github.com/compiler-explorer/infra/blob/main/bin/lib/library_builder.py#L29 +- You can manually trigger a forced-build, by setting the `--build-for=compilerid` parameter, which can also be set by + changing the 2nd parameter here -> https://github.com/compiler-explorer/infra/blob/main/admin-daily-builds.sh#L104 +- If you want to trigger all compilers to rebuild a certain library, you will need to manually delete the logging + related to this library. # manually delete logging You have to login to the conan instance and delete records from the sqlite database responsible for keeping the logging. Example: + ``` ce conan login sudo -u ce sqlite3 /home/ce/.conan_server/buildslogs.db diff --git a/lib/asm-docs/_all.ts b/lib/asm-docs/_all.ts index ed4ad93bb..fe6a37482 100644 --- a/lib/asm-docs/_all.ts +++ b/lib/asm-docs/_all.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { Amd64DocumentationProvider } from './amd64'; -export { Arm32DocumentationProvider } from './arm32'; -export { AvrDocumentationProvider } from './avr'; -export { JavaDocumentationProvider } from './java'; -export { Mos6502DocumentationProvider } from './mos6502'; +export {Amd64DocumentationProvider} from './amd64'; +export {Arm32DocumentationProvider} from './arm32'; +export {AvrDocumentationProvider} from './avr'; +export {JavaDocumentationProvider} from './java'; +export {Mos6502DocumentationProvider} from './mos6502'; diff --git a/lib/asm-docs/amd64.ts b/lib/asm-docs/amd64.ts index b36d81ca7..e4195f364 100644 --- a/lib/asm-docs/amd64.ts +++ b/lib/asm-docs/amd64.ts @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AssemblyInstructionInfo, BaseAssemblyDocumentationProvider } from './base'; -import { getAsmOpcode } from './generated/asm-docs-amd64'; +import {AssemblyInstructionInfo, BaseAssemblyDocumentationProvider} from './base'; +import {getAsmOpcode} from './generated/asm-docs-amd64'; export class Amd64DocumentationProvider extends BaseAssemblyDocumentationProvider { private static readonly ATT_SUFFIX_REMOVER = /^([a-z]+)[blqw]$/i; - public static get key() { return 'amd64'; } + public static get key() { + return 'amd64'; + } public override getInstructionInformation(instruction: string): AssemblyInstructionInfo | null { // Try both raw opcode and with AT&T suffix removed let info = getAsmOpcode(instruction); diff --git a/lib/asm-docs/avr.ts b/lib/asm-docs/avr.ts index 752ec75b6..41df7743a 100644 --- a/lib/asm-docs/avr.ts +++ b/lib/asm-docs/avr.ts @@ -22,11 +22,13 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AssemblyInstructionInfo, BaseAssemblyDocumentationProvider } from './base'; -import { getAsmOpcode } from './generated/asm-docs-avr'; +import {AssemblyInstructionInfo, BaseAssemblyDocumentationProvider} from './base'; +import {getAsmOpcode} from './generated/asm-docs-avr'; export class AvrDocumentationProvider extends BaseAssemblyDocumentationProvider { - public static get key() { return 'avr'; } + public static get key() { + return 'avr'; + } public override getInstructionInformation(instruction: string): AssemblyInstructionInfo | null { return getAsmOpcode(instruction) || null; } diff --git a/lib/asm-docs/index.ts b/lib/asm-docs/index.ts index 049e3b900..8caaa7598 100644 --- a/lib/asm-docs/index.ts +++ b/lib/asm-docs/index.ts @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BaseAssemblyDocumentationProvider } from './base'; +export {BaseAssemblyDocumentationProvider} from './base'; export * from './_all'; export const getDocumentationProviderTypeByKey = makeKeyedTypeGetter('documentation provider', all); diff --git a/lib/asm-docs/java.ts b/lib/asm-docs/java.ts index c18fab89c..2ecfff08e 100644 --- a/lib/asm-docs/java.ts +++ b/lib/asm-docs/java.ts @@ -22,11 +22,13 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AssemblyInstructionInfo, BaseAssemblyDocumentationProvider } from './base'; -import { getAsmOpcode } from './generated/asm-docs-java'; +import {AssemblyInstructionInfo, BaseAssemblyDocumentationProvider} from './base'; +import {getAsmOpcode} from './generated/asm-docs-java'; export class JavaDocumentationProvider extends BaseAssemblyDocumentationProvider { - public static get key() { return 'java'; } + public static get key() { + return 'java'; + } public override getInstructionInformation(instruction: string): AssemblyInstructionInfo | null { return getAsmOpcode(instruction) || null; } diff --git a/lib/asm-docs/mos6502.ts b/lib/asm-docs/mos6502.ts index 8d9bdc9c5..0cd0a77e2 100644 --- a/lib/asm-docs/mos6502.ts +++ b/lib/asm-docs/mos6502.ts @@ -22,11 +22,13 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AssemblyInstructionInfo, BaseAssemblyDocumentationProvider } from './base'; -import { getAsmOpcode } from './generated/asm-docs-6502'; +import {AssemblyInstructionInfo, BaseAssemblyDocumentationProvider} from './base'; +import {getAsmOpcode} from './generated/asm-docs-6502'; export class Mos6502DocumentationProvider extends BaseAssemblyDocumentationProvider { - public static get key() { return '6502'; } + public static get key() { + return '6502'; + } public override getInstructionInformation(instruction: string): AssemblyInstructionInfo | null { return getAsmOpcode(instruction) || null; } diff --git a/lib/aws.js b/lib/aws.js index c0b299ecd..ae6634d97 100644 --- a/lib/aws.js +++ b/lib/aws.js @@ -24,7 +24,7 @@ import AWS from 'aws-sdk'; -import { logger } from './logger'; +import {logger} from './logger'; export class InstanceFetcher { constructor(properties) { @@ -37,12 +37,10 @@ export class InstanceFetcher { async getInstances() { const result = await this.ec2.describeInstances().promise(); - return result.Reservations - .flatMap(r => r.Instances) - .filter(reservation => { - if (reservation.State.Name !== 'running') return false; - return reservation.Tags.some(t => t.Key === this.tagKey && t.Value === this.tagValue); - }); + return result.Reservations.flatMap(r => r.Instances).filter(reservation => { + if (reservation.State.Name !== 'running') return false; + return reservation.Tags.some(t => t.Key === this.tagKey && t.Value === this.tagValue); + }); } } @@ -76,7 +74,6 @@ export async function initConfig(properties) { } export function getConfig(name) { - if (!awsConfigInit) - throw new Error("Reading AWS config before it's loaded"); + if (!awsConfigInit) throw new Error("Reading AWS config before it's loaded"); return awsConfig[name] || awsProps(name); } diff --git a/lib/buildenvsetup/_all.js b/lib/buildenvsetup/_all.js index 41d6afca3..ea1d6bb00 100644 --- a/lib/buildenvsetup/_all.js +++ b/lib/buildenvsetup/_all.js @@ -22,5 +22,5 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { BuildEnvSetupCeConanDirect } from './ceconan'; -export { BuildEnvSetupCliConan } from './cliconan'; +export {BuildEnvSetupCeConanDirect} from './ceconan'; +export {BuildEnvSetupCliConan} from './cliconan'; diff --git a/lib/buildenvsetup/base.js b/lib/buildenvsetup/base.js index 9a9a8f60e..17c6c83be 100644 --- a/lib/buildenvsetup/base.js +++ b/lib/buildenvsetup/base.js @@ -27,7 +27,7 @@ import path from 'path'; import fs from 'fs-extra'; import _ from 'underscore'; -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; export class BuildEnvSetupBase { @@ -65,7 +65,7 @@ export class BuildEnvSetupBase { } } else if (this.compilerTypeOrGCC === 'gcc') { if (this.compiler.exe.includes('/icpx')) { - result = (arch === 'x86') || (arch === 'x86_64'); + result = arch === 'x86' || arch === 'x86_64'; } else { result = await execCompilerCached(this.compiler.exe, ['--target-help']); } @@ -89,13 +89,12 @@ export class BuildEnvSetupBase { } getCompilerArch() { - let arch = _.find(this.compilerOptionsArr, (option) => { - return option.startsWith('-march='); + let arch = _.find(this.compilerOptionsArr, option => { + return option.startsWith('-march='); }); - let target = _.find(this.compilerOptionsArr, (option) => { - option.startsWith('-target=') || - option.startsWith('--target='); + let target = _.find(this.compilerOptionsArr, option => { + option.startsWith('-target=') || option.startsWith('--target='); }); if (target) { @@ -130,7 +129,7 @@ export class BuildEnvSetupBase { if (match) { return match[1]; } else { - const stdlibOption = _.find(key.options, (option) => { + const stdlibOption = _.find(key.options, option => { return option.startsWith('-stdlib='); }); @@ -149,7 +148,7 @@ export class BuildEnvSetupBase { if (key.options.includes('-m32')) { return 'x86'; } else { - let target = _.find(key.options, (option) => { + let target = _.find(key.options, option => { return option.startsWith('-target=') || option.startsWith('--target='); }); diff --git a/lib/buildenvsetup/cliconan.js b/lib/buildenvsetup/cliconan.js index 9a4c5fa13..4b6f3c888 100644 --- a/lib/buildenvsetup/cliconan.js +++ b/lib/buildenvsetup/cliconan.js @@ -28,9 +28,9 @@ import fs from 'fs-extra'; import _ from 'underscore'; import * as exec from '../exec'; -import { logger } from '../logger'; +import {logger} from '../logger'; -import { BuildEnvSetupBase } from './base'; +import {BuildEnvSetupBase} from './base'; export class BuildEnvSetupCliConan extends BuildEnvSetupBase { static get key() { @@ -53,11 +53,11 @@ export class BuildEnvSetupCliConan extends BuildEnvSetupBase { } hasBinariesToLink(details) { - return (details.libpath.length === 0) && (details.staticliblink.length > 0); + return details.libpath.length === 0 && details.staticliblink.length > 0; } hasAtLeastOneBinaryToLink(libraryDetails) { - return _.some(libraryDetails, (details) => this.hasBinariesToLink(details)); + return _.some(libraryDetails, details => this.hasBinariesToLink(details)); } async prepareConanRequest(libraryDetails, dirPath) { @@ -69,6 +69,7 @@ export class BuildEnvSetupCliConan extends BuildEnvSetupBase { } }); + // prettier-ignore data += '[imports]\n' + 'lib, *.a -> .\n' + @@ -85,6 +86,7 @@ export class BuildEnvSetupCliConan extends BuildEnvSetupBase { const args = ['install', '.']; if (this.remote) args.push('-r', this.remote); + // prettier-ignore args.push( '-s', 'os=Linux', '-s', 'build_type=Debug', @@ -93,7 +95,8 @@ export class BuildEnvSetupCliConan extends BuildEnvSetupBase { '-s', `compiler.libcxx=${libcxx}`, '-s', `arch=${arch}`, '-s', `stdver=${stdver}`, - '-s', `flagcollection=${flagcollection}`); + '-s', `flagcollection=${flagcollection}`, + ); logger.info('Conan install: ', args); return exec.execute(this.exe, args, {customCwd: dirPath}); diff --git a/lib/buildenvsetup/index.js b/lib/buildenvsetup/index.js index a9c944232..e54007435 100644 --- a/lib/buildenvsetup/index.js +++ b/lib/buildenvsetup/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BuildEnvSetupBase } from './base'; +export {BuildEnvSetupBase} from './base'; export * from './_all'; export const getBuildEnvTypeByKey = makeKeyedTypeGetter('buildenv', all); diff --git a/lib/cfg.js b/lib/cfg.js index 04e74aeb3..dbaefe2b3 100644 --- a/lib/cfg.js +++ b/lib/cfg.js @@ -24,7 +24,7 @@ import _ from 'underscore'; -import { logger } from './logger'; +import {logger} from './logger'; import * as utils from './utils'; const InstructionType_jmp = 0; @@ -72,10 +72,7 @@ const gcc = { filterData: asmArr => { const jmpLabelRegex = /\.L\d+:/; const isCode = x => x && x.text && (x.source !== null || jmpLabelRegex.test(x.text) || isFunctionName(x)); - return _.chain(filterTextSection(asmArr)) - .map(_.clone) - .filter(isCode) - .value(); + return _.chain(filterTextSection(asmArr)).map(_.clone).filter(isCode).value(); }, isFunctionEnd: x => x[0] !== ' ' && x[0] !== '.' && x.includes(':'), @@ -101,18 +98,12 @@ const clang = { const removeComments = x => { const pos_x86 = x.text.indexOf('# '); const pos_arm = x.text.indexOf('// '); - if (pos_x86 !== -1) - x.text = utils.trimRight(x.text.substring(0, pos_x86)); - if (pos_arm !== -1) - x.text = utils.trimRight(x.text.substring(0, pos_arm)); + if (pos_x86 !== -1) x.text = utils.trimRight(x.text.substring(0, pos_x86)); + if (pos_arm !== -1) x.text = utils.trimRight(x.text.substring(0, pos_arm)); return x; }; - return _.chain(filterTextSection(asmArr)) - .map(_.clone) - .filter(isCode) - .map(removeComments) - .value(); + return _.chain(filterTextSection(asmArr)).map(_.clone).filter(isCode).map(removeComments).value(); }, isFunctionEnd: x => x[0] !== ' ' && x[0] !== '.' && x.includes(':'), @@ -190,11 +181,13 @@ function splitToCanonicalBasicBlock(basicBlock) { } if (actPosSz === 0) - return [{ - nameId: basicBlock.nameId, - start: basicBlock.start, - end: basicBlock.end, - }]; + return [ + { + nameId: basicBlock.nameId, + start: basicBlock.start, + end: basicBlock.end, + }, + ]; else if (actPosSz === 1) return [ {nameId: basicBlock.nameId, start: basicBlock.start, end: actionPos[0] + 1}, @@ -219,7 +212,6 @@ function splitToCanonicalBasicBlock(basicBlock) { result.push(_.clone(tmp)); return result; - } } @@ -260,8 +252,7 @@ function makeEdges(asmArr, arrOfCanonicalBasicBlock, rules) { const generateName = function (name, suffix) { const pos = name.indexOf('@'); - if (pos === -1) - return name + '@' + suffix; + if (pos === -1) return name + '@' + suffix; return name.substring(0, pos + 1) + suffix; }; @@ -312,12 +303,14 @@ function makeEdges(asmArr, arrOfCanonicalBasicBlock, rules) { } function isLLVMBased(compilerType, version) { - return version.includes('clang') || + return ( + version.includes('clang') || version.includes('LLVM') || version.includes('rustc') || compilerType === 'swift' || compilerType === 'zig' || - compilerType === 'ispc'; + compilerType === 'ispc' + ); } export function generateStructure(compilerType, version, asmArr) { @@ -328,19 +321,25 @@ export function generateStructure(compilerType, version, asmArr) { return funcs; } const result = {}; - _.each(funcs, _.bind(function (rng) { - const basicBlocks = splitToBasicBlocks(code, rng, rules.isBasicBlockEnd, rules.isJmpInstruction); - let arrOfCanonicalBasicBlock = []; - _.each(basicBlocks, _.bind(function (elm) { - const tmp = splitToCanonicalBasicBlock(elm); - arrOfCanonicalBasicBlock = arrOfCanonicalBasicBlock.concat(tmp); - }, this)); + _.each( + funcs, + _.bind(function (rng) { + const basicBlocks = splitToBasicBlocks(code, rng, rules.isBasicBlockEnd, rules.isJmpInstruction); + let arrOfCanonicalBasicBlock = []; + _.each( + basicBlocks, + _.bind(function (elm) { + const tmp = splitToCanonicalBasicBlock(elm); + arrOfCanonicalBasicBlock = arrOfCanonicalBasicBlock.concat(tmp); + }, this), + ); - result[code[rng.start].text] = { - nodes: makeNodes(code, arrOfCanonicalBasicBlock), - edges: makeEdges(code, arrOfCanonicalBasicBlock, rules), - }; - }, this)); + result[code[rng.start].text] = { + nodes: makeNodes(code, arrOfCanonicalBasicBlock), + edges: makeEdges(code, arrOfCanonicalBasicBlock, rules), + }; + }, this), + ); return result; } diff --git a/lib/clientstate.js b/lib/clientstate.js index d2cf9904f..73e6c4129 100644 --- a/lib/clientstate.js +++ b/lib/clientstate.js @@ -118,20 +118,14 @@ export class ClientStateExecutor { } fromJsonData(jsondata) { - if (typeof jsondata.compilerVisible !== 'undefined') - this.compilerVisible = jsondata.compilerVisible; + if (typeof jsondata.compilerVisible !== 'undefined') this.compilerVisible = jsondata.compilerVisible; if (typeof jsondata.compilerOutputVisible !== 'undefined') this.compilerOutputVisible = jsondata.compilerOutputVisible; - if (typeof jsondata.arguments !== 'undefined') - this.arguments = jsondata.arguments; - if (typeof jsondata.argumentsVisible !== 'undefined') - this.argumentsVisible = jsondata.argumentsVisible; - if (typeof jsondata.stdin !== 'undefined') - this.stdin = jsondata.stdin; - if (typeof jsondata.stdinVisible !== 'undefined') - this.stdinVisible = jsondata.stdinVisible; - if (typeof jsondata.wrap !== 'undefined') - this.wrap = jsondata.wrap; + if (typeof jsondata.arguments !== 'undefined') this.arguments = jsondata.arguments; + if (typeof jsondata.argumentsVisible !== 'undefined') this.argumentsVisible = jsondata.argumentsVisible; + if (typeof jsondata.stdin !== 'undefined') this.stdin = jsondata.stdin; + if (typeof jsondata.stdinVisible !== 'undefined') this.stdinVisible = jsondata.stdinVisible; + if (typeof jsondata.wrap !== 'undefined') this.wrap = jsondata.wrap; this.compiler = new ClientStateCompiler(jsondata.compiler); } @@ -225,7 +219,7 @@ export class ClientStateTree { this.newFileId = jsondata.newFileId; } - if (typeof jsondata.compilers !== 'undefined') { + if (typeof jsondata.compilers !== 'undefined') { for (const compilerdata of jsondata.compilers) { const compiler = new ClientStateCompiler(compilerdata); if (compiler.id) { @@ -234,7 +228,7 @@ export class ClientStateTree { } } - if (typeof jsondata.executors !== 'undefined') { + if (typeof jsondata.executors !== 'undefined') { for (const executor of jsondata.executors) { this.executors.push(new ClientStateExecutor(executor)); } diff --git a/lib/compilation-queue.js b/lib/compilation-queue.js index 3a64aa3f2..394d89748 100644 --- a/lib/compilation-queue.js +++ b/lib/compilation-queue.js @@ -37,21 +37,17 @@ export class CompilationQueue { } static fromProps(ceProps) { - return new CompilationQueue( - ceProps('maxConcurrentCompiles', 1), - ceProps('compilationEnvTimeoutMs')); + return new CompilationQueue(ceProps('maxConcurrentCompiles', 1), ceProps('compilationEnvTimeoutMs')); } enqueue(job) { const enqueueAsyncId = executionAsyncId(); // If we're asked to enqueue a job when we're already in a async queued job context, just run it. // This prevents a deadlock. - if (this._running.has(enqueueAsyncId)) - return job(); + if (this._running.has(enqueueAsyncId)) return job(); return this._queue.add(() => { const jobAsyncId = executionAsyncId(); - if (this._running.has(jobAsyncId)) - throw new Error('somehow we entered the context twice'); + if (this._running.has(jobAsyncId)) throw new Error('somehow we entered the context twice'); try { this._running.add(jobAsyncId); return job(); diff --git a/lib/compilers/_all.js b/lib/compilers/_all.js index d0484a31c..46554b3b9 100644 --- a/lib/compilers/_all.js +++ b/lib/compilers/_all.js @@ -22,67 +22,67 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { AdaCompiler } from './ada'; -export { AnalysisTool } from './analysis-tool'; -export { AssemblyCompiler } from './assembly'; -export { NasmCompiler } from './nasm'; -export { Cc65Compiler } from './cc65'; -export { CircleCompiler } from './circle'; -export { ClangCompiler } from './clang'; -export { ClangCudaCompiler } from './clang'; -export { ClangHipCompiler } from './clang'; -export { CleanCompiler } from './clean'; -export { CprocCompiler } from './cproc'; -export { CrystalCompiler } from './crystal'; -export { DartCompiler } from './dart'; -export { DefaultCompiler } from './default'; -export { DMDCompiler } from './dmd'; -export { CSharpCompiler } from './dotnet'; -export { EllccCompiler } from './ellcc'; -export { ErlangCompiler } from './erlang'; -export { EWARMCompiler } from './ewarm'; -export { EWAVRCompiler } from './ewavr'; -export { FakeCompiler } from './fake-for-test'; -export { FSharpCompiler } from './dotnet'; -export { FortranCompiler } from './fortran'; -export { GCCCompiler } from './gcc'; -export { GCCRSCompiler } from './gccrs'; -export { GolangCompiler } from './golang'; -export { HaskellCompiler } from './haskell'; -export { ISPCCompiler } from './ispc'; -export { JavaCompiler } from './java'; -export { KotlinCompiler } from './kotlin'; -export { LDCCompiler } from './ldc'; -export { LLCCompiler } from './llc'; -export { LLVMmcaTool } from './llvm-mca'; -export { NimCompiler } from './nim'; -export { NvccCompiler } from './nvcc'; -export { OCamlCompiler } from './ocaml'; -export { OptCompiler } from './opt'; -export { OSACATool } from './osaca'; -export { FPCCompiler } from './pascal'; -export { PascalWinCompiler } from './pascal-win'; -export { PPCICompiler } from './ppci'; -export { PtxAssembler } from './ptxas'; -export { PythonCompiler } from './python'; -export { RubyCompiler } from './ruby'; -export { RustCompiler } from './rust'; -export { RustcCgGCCCompiler } from './rustc-cg-gcc'; -export { MrustcCompiler } from './mrustc'; -export { ScalaCompiler } from './scala'; -export { SdccCompiler } from './sdcc'; -export { SolidityCompiler } from './solidity'; -export { SPIRVCompiler } from './spirv'; -export { SwiftCompiler } from './swift'; -export { TenDRACompiler } from './tendra'; -export { TinyCCompiler } from './tinyc'; -export { TypeScriptCompiler } from './typescript'; -export { VBCompiler } from './dotnet'; -export { Win32Compiler } from './win32'; -export { Win32VcCompiler } from './win32-vc'; -export { Win32Vc6Compiler } from './win32-vc6'; -export { WineVcCompiler } from './wine-vc'; -export { WslVcCompiler } from './wsl-vc'; -export { ZigCompiler } from './zig'; -export { ZigCC } from './zigcc'; -export { ZigCXX } from './zigcxx'; +export {AdaCompiler} from './ada'; +export {AnalysisTool} from './analysis-tool'; +export {AssemblyCompiler} from './assembly'; +export {NasmCompiler} from './nasm'; +export {Cc65Compiler} from './cc65'; +export {CircleCompiler} from './circle'; +export {ClangCompiler} from './clang'; +export {ClangCudaCompiler} from './clang'; +export {ClangHipCompiler} from './clang'; +export {CleanCompiler} from './clean'; +export {CprocCompiler} from './cproc'; +export {CrystalCompiler} from './crystal'; +export {DartCompiler} from './dart'; +export {DefaultCompiler} from './default'; +export {DMDCompiler} from './dmd'; +export {CSharpCompiler} from './dotnet'; +export {EllccCompiler} from './ellcc'; +export {ErlangCompiler} from './erlang'; +export {EWARMCompiler} from './ewarm'; +export {EWAVRCompiler} from './ewavr'; +export {FakeCompiler} from './fake-for-test'; +export {FSharpCompiler} from './dotnet'; +export {FortranCompiler} from './fortran'; +export {GCCCompiler} from './gcc'; +export {GCCRSCompiler} from './gccrs'; +export {GolangCompiler} from './golang'; +export {HaskellCompiler} from './haskell'; +export {ISPCCompiler} from './ispc'; +export {JavaCompiler} from './java'; +export {KotlinCompiler} from './kotlin'; +export {LDCCompiler} from './ldc'; +export {LLCCompiler} from './llc'; +export {LLVMmcaTool} from './llvm-mca'; +export {NimCompiler} from './nim'; +export {NvccCompiler} from './nvcc'; +export {OCamlCompiler} from './ocaml'; +export {OptCompiler} from './opt'; +export {OSACATool} from './osaca'; +export {FPCCompiler} from './pascal'; +export {PascalWinCompiler} from './pascal-win'; +export {PPCICompiler} from './ppci'; +export {PtxAssembler} from './ptxas'; +export {PythonCompiler} from './python'; +export {RubyCompiler} from './ruby'; +export {RustCompiler} from './rust'; +export {RustcCgGCCCompiler} from './rustc-cg-gcc'; +export {MrustcCompiler} from './mrustc'; +export {ScalaCompiler} from './scala'; +export {SdccCompiler} from './sdcc'; +export {SolidityCompiler} from './solidity'; +export {SPIRVCompiler} from './spirv'; +export {SwiftCompiler} from './swift'; +export {TenDRACompiler} from './tendra'; +export {TinyCCompiler} from './tinyc'; +export {TypeScriptCompiler} from './typescript'; +export {VBCompiler} from './dotnet'; +export {Win32Compiler} from './win32'; +export {Win32VcCompiler} from './win32-vc'; +export {Win32Vc6Compiler} from './win32-vc6'; +export {WineVcCompiler} from './wine-vc'; +export {WslVcCompiler} from './wsl-vc'; +export {ZigCompiler} from './zig'; +export {ZigCC} from './zigcc'; +export {ZigCXX} from './zigcxx'; diff --git a/lib/compilers/analysis-tool.js b/lib/compilers/analysis-tool.js index 6c88a31ac..e6384616e 100644 --- a/lib/compilers/analysis-tool.js +++ b/lib/compilers/analysis-tool.js @@ -22,16 +22,17 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; // Plain compiler, which just runs the tool and returns whatever the output was export class AnalysisTool extends BaseCompiler { - static get key() { return 'analysis-tool'; } + static get key() { + return 'analysis-tool'; + } constructor(info, env) { // Default is to disable all "cosmetic" filters - if (!info.disabledFilters) - info.disabledFilters = ['labels', 'directives', 'commentOnly', 'trim']; + if (!info.disabledFilters) info.disabledFilters = ['labels', 'directives', 'commentOnly', 'trim']; super(info, env); } diff --git a/lib/compilers/assembly.js b/lib/compilers/assembly.js index 5a8bf08e3..bde0cfe46 100644 --- a/lib/compilers/assembly.js +++ b/lib/compilers/assembly.js @@ -25,14 +25,16 @@ import fs from 'fs'; import path from 'path'; -import { BaseCompiler } from '../base-compiler'; -import { AsmRaw } from '../parsers/asm-raw'; +import {BaseCompiler} from '../base-compiler'; +import {AsmRaw} from '../parsers/asm-raw'; import * as utils from '../utils'; -import { BaseParser } from './argument-parsers'; +import {BaseParser} from './argument-parsers'; export class AssemblyCompiler extends BaseCompiler { - static get key() { return 'assembly'; } + static get key() { + return 'assembly'; + } constructor(info, env) { super(info, env); @@ -73,13 +75,18 @@ export class AssemblyCompiler extends BaseCompiler { async runReadelf(fullResult, objectFilename) { let execOptions = this.getDefaultExecOptions(); execOptions.customCwd = path.dirname(objectFilename); - return await this.doBuildstepAndAddToResult(fullResult, 'readelf', this.env.ceProps('readelf'), - ['-h', objectFilename], execOptions); + return await this.doBuildstepAndAddToResult( + fullResult, + 'readelf', + this.env.ceProps('readelf'), + ['-h', objectFilename], + execOptions, + ); } async getArchitecture(fullResult, objectFilename) { const result = await this.runReadelf(fullResult, objectFilename); - const output = result.stdout.map((line) => line.text).join('\n'); + const output = result.stdout.map(line => line.text).join('\n'); if (output.includes('ELF32') && output.includes('80386')) { return 'x86'; } else if (output.includes('ELF64') && output.includes('X86-64')) { diff --git a/lib/compilers/cc65.js b/lib/compilers/cc65.js index 1bc704dc9..27bb34dc2 100644 --- a/lib/compilers/cc65.js +++ b/lib/compilers/cc65.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; export class Cc65Compiler extends BaseCompiler { - static get key() { return 'cc65'; } + static get key() { + return 'cc65'; + } optionsForFilter(filters, outputFilename) { return ['-g', '-o', this.filename(outputFilename)]; diff --git a/lib/compilers/circle.js b/lib/compilers/circle.js index ea5107114..58ac17d3b 100644 --- a/lib/compilers/circle.js +++ b/lib/compilers/circle.js @@ -24,10 +24,12 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; export class CircleCompiler extends BaseCompiler { - static get key() { return 'circle'; } + static get key() { + return 'circle'; + } optionsForFilter(filters, outputFilename) { let options = [`-o=${this.filename(outputFilename)}`]; diff --git a/lib/compilers/cproc.js b/lib/compilers/cproc.js index 7fde9e5b4..50217758a 100644 --- a/lib/compilers/cproc.js +++ b/lib/compilers/cproc.js @@ -24,7 +24,7 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; export class CprocCompiler extends BaseCompiler { static get key() { diff --git a/lib/compilers/crystal.js b/lib/compilers/crystal.js index 058d19d39..d84ab220a 100644 --- a/lib/compilers/crystal.js +++ b/lib/compilers/crystal.js @@ -26,13 +26,15 @@ import path from 'path'; import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; -import { CrystalAsmParser } from '../parsers/asm-parser-crystal'; +import {BaseCompiler} from '../base-compiler'; +import {CrystalAsmParser} from '../parsers/asm-parser-crystal'; -import { CrystalParser } from './argument-parsers'; +import {CrystalParser} from './argument-parsers'; export class CrystalCompiler extends BaseCompiler { - static get key() { return 'crystal'; } + static get key() { + return 'crystal'; + } constructor(compiler, env) { super(compiler, env); diff --git a/lib/compilers/dart.js b/lib/compilers/dart.js index a8a8da5ad..cbcbc73dd 100644 --- a/lib/compilers/dart.js +++ b/lib/compilers/dart.js @@ -24,11 +24,11 @@ import Semver from 'semver'; -import { BaseCompiler } from '../base-compiler'; -import { DartAsmParser } from '../parsers/asm-parser-dart'; +import {BaseCompiler} from '../base-compiler'; +import {DartAsmParser} from '../parsers/asm-parser-dart'; import * as utils from '../utils'; -import { BaseParser } from './argument-parsers'; +import {BaseParser} from './argument-parsers'; export class DartCompiler extends BaseCompiler { constructor(info, env) { @@ -36,7 +36,9 @@ export class DartCompiler extends BaseCompiler { this.asm = new DartAsmParser(); } - static get key() { return 'dart'; } + static get key() { + return 'dart'; + } prepareArguments(userOptions, filters, backendOptions, inputFilename, outputFilename, libraries) { let options = this.optionsForFilter(filters, outputFilename, userOptions); @@ -61,15 +63,9 @@ export class DartCompiler extends BaseCompiler { const dartCompileIntroduction = '2.10.0'; if (Semver.lt(utils.asSafeVer(this.compiler.semver), dartCompileIntroduction, true)) { - return [ - '-k', 'aot', - '-o', this.filename(outputFilename), - ]; + return ['-k', 'aot', '-o', this.filename(outputFilename)]; } else { - return [ - 'compile', 'aot-snapshot', - '-o', this.filename(outputFilename), - ]; + return ['compile', 'aot-snapshot', '-o', this.filename(outputFilename)]; } } diff --git a/lib/compilers/default.js b/lib/compilers/default.js index ee5481977..f8cd1aa66 100644 --- a/lib/compilers/default.js +++ b/lib/compilers/default.js @@ -22,8 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; export class DefaultCompiler extends BaseCompiler { - static get key() { return 'default'; } + static get key() { + return 'default'; + } } diff --git a/lib/compilers/dmd.js b/lib/compilers/dmd.js index 851a4a209..a138276f2 100644 --- a/lib/compilers/dmd.js +++ b/lib/compilers/dmd.js @@ -24,12 +24,14 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; export class DMDCompiler extends BaseCompiler { - static get key() { return 'dmd'; } + static get key() { + return 'dmd'; + } constructor(compiler, env) { super(compiler, env); @@ -49,7 +51,8 @@ export class DMDCompiler extends BaseCompiler { const lPath = path.basename(outputFilename); return this.handlePostProcessResult( result, - await this.exec(postProcesses[0], ['-l', lPath], {customCwd: dirPath, maxOutput: maxSize})); + await this.exec(postProcesses[0], ['-l', lPath], {customCwd: dirPath, maxOutput: maxSize}), + ); } getOutputFilename(dirPath, outputFilebase) { @@ -57,7 +60,7 @@ export class DMDCompiler extends BaseCompiler { } buildExecutable(compiler, options, inputFilename, execOptions) { - options = options.filter((param) => param !== '-c'); + options = options.filter(param => param !== '-c'); return this.runCompiler(compiler, options, inputFilename, execOptions); } diff --git a/lib/compilers/ellcc.js b/lib/compilers/ellcc.js index 362b4ef5d..a06e7c84b 100644 --- a/lib/compilers/ellcc.js +++ b/lib/compilers/ellcc.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { ClangCompiler } from './clang'; +import {ClangCompiler} from './clang'; export class EllccCompiler extends ClangCompiler { - static get key() { return 'ellcc'; } + static get key() { + return 'ellcc'; + } getSharedLibraryPathsAsArguments() { const pathFlag = this.compiler.rpathFlag || '-Wl,-rpath,'; diff --git a/lib/compilers/ewarm.js b/lib/compilers/ewarm.js index 4a5695a4c..e87d5625f 100644 --- a/lib/compilers/ewarm.js +++ b/lib/compilers/ewarm.js @@ -24,12 +24,14 @@ import temp from 'temp'; -import { BaseCompiler } from '../base-compiler'; -import { AsmEWAVRParser } from '../parsers/asm-parser-ewavr'; +import {BaseCompiler} from '../base-compiler'; +import {AsmEWAVRParser} from '../parsers/asm-parser-ewavr'; export class EWARMCompiler extends BaseCompiler { - static get key() { return 'ewarm'; } - + static get key() { + return 'ewarm'; + } + constructor(info, env) { super(info, env); this.asm = new AsmEWAVRParser(this.compilerProps); @@ -38,10 +40,8 @@ export class EWARMCompiler extends BaseCompiler { newTempDir() { return new Promise((resolve, reject) => { temp.mkdir({prefix: 'compiler-explorer-compiler', dir: process.env.TMP}, (err, dirPath) => { - if (err) - reject(`Unable to open temp file: ${err}`); - else - resolve(dirPath); + if (err) reject(`Unable to open temp file: ${err}`); + else resolve(dirPath); }); }); } @@ -50,10 +50,7 @@ export class EWARMCompiler extends BaseCompiler { if (filters.binary) { return []; } - - return [ - '-lB', this.filename(outputFilename), - '-o', this.filename(outputFilename + '.obj'), - ]; + + return ['-lB', this.filename(outputFilename), '-o', this.filename(outputFilename + '.obj')]; } } diff --git a/lib/compilers/ewavr.js b/lib/compilers/ewavr.js index ae3a74c7b..dacdb9d5b 100644 --- a/lib/compilers/ewavr.js +++ b/lib/compilers/ewavr.js @@ -24,11 +24,13 @@ import temp from 'temp'; -import { BaseCompiler } from '../base-compiler'; -import { AsmEWAVRParser } from '../parsers/asm-parser-ewavr'; +import {BaseCompiler} from '../base-compiler'; +import {AsmEWAVRParser} from '../parsers/asm-parser-ewavr'; export class EWAVRCompiler extends BaseCompiler { - static get key() { return 'ewavr'; } + static get key() { + return 'ewavr'; + } constructor(info, env) { info.supportsDemangle = false; @@ -40,10 +42,8 @@ export class EWAVRCompiler extends BaseCompiler { newTempDir() { return new Promise((resolve, reject) => { temp.mkdir({prefix: 'compiler-explorer-compiler', dir: process.env.TMP}, (err, dirPath) => { - if (err) - reject(`Unable to open temp file: ${err}`); - else - resolve(dirPath); + if (err) reject(`Unable to open temp file: ${err}`); + else resolve(dirPath); }); }); } @@ -52,10 +52,7 @@ export class EWAVRCompiler extends BaseCompiler { if (filters.binary) { return []; } - - return [ - '-lB', this.filename(outputFilename), - '-o', this.filename(outputFilename + '.obj'), - ]; + + return ['-lB', this.filename(outputFilename), '-o', this.filename(outputFilename + '.obj')]; } } diff --git a/lib/compilers/fake-for-test.js b/lib/compilers/fake-for-test.js index 1aaf027f5..bef34d7e3 100644 --- a/lib/compilers/fake-for-test.js +++ b/lib/compilers/fake-for-test.js @@ -30,11 +30,14 @@ export class FakeCompiler { } constructor(info) { - this.compiler = Object.assign({ - id: 'fake-for-test', - lang: 'fake-lang', - options: '', - }, info); + this.compiler = Object.assign( + { + id: 'fake-for-test', + lang: 'fake-lang', + options: '', + }, + info, + ); this.lang = {id: this.compiler.lang, name: `Language ${this.compiler.lang}`}; this.info = info; } @@ -67,12 +70,14 @@ export class FakeCompiler { } cmake(files, options) { - return Promise.resolve(_.extend(this.info.fakeResult || {}, { - input: { - files: files, - options: options, - }, - })); + return Promise.resolve( + _.extend(this.info.fakeResult || {}, { + input: { + files: files, + options: options, + }, + }), + ); } initalize() { diff --git a/lib/compilers/fortran.js b/lib/compilers/fortran.js index d7638b85c..c7f0e82f7 100644 --- a/lib/compilers/fortran.js +++ b/lib/compilers/fortran.js @@ -24,11 +24,13 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; import * as utils from '../utils'; export class FortranCompiler extends BaseCompiler { - static get key() { return 'fortran'; } + static get key() { + return 'fortran'; + } async runCompiler(compiler, options, inputFilename, execOptions) { if (!execOptions) { diff --git a/lib/compilers/gcc.js b/lib/compilers/gcc.js index 1cba974c8..3bff222dc 100644 --- a/lib/compilers/gcc.js +++ b/lib/compilers/gcc.js @@ -22,8 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; export class GCCCompiler extends BaseCompiler { - static get key() { return 'gcc'; } + static get key() { + return 'gcc'; + } } diff --git a/lib/compilers/gccrs.js b/lib/compilers/gccrs.js index 6a3c02575..6a288c2db 100644 --- a/lib/compilers/gccrs.js +++ b/lib/compilers/gccrs.js @@ -22,8 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { GCCCompiler } from './gcc'; +import {GCCCompiler} from './gcc'; export class GCCRSCompiler extends GCCCompiler { - static get key() { return 'gccrs'; } + static get key() { + return 'gccrs'; + } } diff --git a/lib/compilers/golang.js b/lib/compilers/golang.js index e68eeb904..8aa0fd985 100644 --- a/lib/compilers/golang.js +++ b/lib/compilers/golang.js @@ -24,10 +24,10 @@ import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; import * as utils from '../utils'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; // Each arch has a list of jump instructions in // Go source src/cmd/asm/internal/arch. @@ -170,7 +170,8 @@ export class GolangCompiler extends BaseCompiler { extractLogging(stdout) { let filepath = `./${this.compileFilename}`; const reLogging = /^[^:]+:\d+:(\d+:)?\s.*/; - return stdout.filter(obj => obj.text.match(reLogging)) + return stdout + .filter(obj => obj.text.match(reLogging)) .map(obj => obj.text.replace(filepath, '')) .join('\n'); } diff --git a/lib/compilers/index.js b/lib/compilers/index.js index dff6a4924..5e2cb899c 100644 --- a/lib/compilers/index.js +++ b/lib/compilers/index.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; diff --git a/lib/compilers/ispc.js b/lib/compilers/ispc.js index 937059141..8c1481b8a 100644 --- a/lib/compilers/ispc.js +++ b/lib/compilers/ispc.js @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { ISPCParser } from './argument-parsers'; +import {ISPCParser} from './argument-parsers'; export class ISPCCompiler extends BaseCompiler { - static get key() { return 'ispc'; } + static get key() { + return 'ispc'; + } constructor(info, env) { super(info, env); diff --git a/lib/compilers/kotlin.js b/lib/compilers/kotlin.js index 0871dfcab..7936acef2 100644 --- a/lib/compilers/kotlin.js +++ b/lib/compilers/kotlin.js @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { KotlinParser } from './argument-parsers'; -import { JavaCompiler } from './java'; +import {KotlinParser} from './argument-parsers'; +import {JavaCompiler} from './java'; export class KotlinCompiler extends JavaCompiler { static get key() { @@ -50,8 +50,9 @@ export class KotlinCompiler extends JavaCompiler { filterUserOptions(userOptions) { // filter options without extra arguments - userOptions = (userOptions || []).filter(option => - option !== '-script' && option !== '-progressive' && !option.startsWith('-Xjavac')); + userOptions = (userOptions || []).filter( + option => option !== '-script' && option !== '-progressive' && !option.startsWith('-Xjavac'), + ); const oneArgForbiddenList = new Set([ // -jdk-home path @@ -72,9 +73,7 @@ export class KotlinCompiler extends JavaCompiler { // Forcibly enable javap filters.binary = true; - return [ - '-Xjavac-arguments="-Xlint:all"', - ]; + return ['-Xjavac-arguments="-Xlint:all"']; } /** diff --git a/lib/compilers/ldc.js b/lib/compilers/ldc.js index 9c3b294f2..0d90c2d2b 100644 --- a/lib/compilers/ldc.js +++ b/lib/compilers/ldc.js @@ -27,13 +27,15 @@ import path from 'path'; import fs from 'fs-extra'; import semverParser from 'semver'; -import { BaseCompiler } from '../base-compiler'; -import { logger } from '../logger'; +import {BaseCompiler} from '../base-compiler'; +import {logger} from '../logger'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; export class LDCCompiler extends BaseCompiler { - static get key() { return 'ldc'; } + static get key() { + return 'ldc'; + } constructor(info, env) { super(info, env); @@ -76,7 +78,8 @@ export class LDCCompiler extends BaseCompiler { const newOptions = options.concat('-vcg-ast'); const execOptions = this.getDefaultExecOptions(); return this.loadASTOutput( - await this.runCompiler(this.compiler.exe, newOptions, this.filename(inputFilename), execOptions)); + await this.runCompiler(this.compiler.exe, newOptions, this.filename(inputFilename), execOptions), + ); } async loadASTOutput(output) { @@ -99,7 +102,6 @@ export class LDCCompiler extends BaseCompiler { // Override the IR file name method for LDC because the output file is different from clang. getIrOutputFilename(inputFilename) { - return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase) - .replace('.s', '.ll'); + return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase).replace('.s', '.ll'); } } diff --git a/lib/compilers/llc.js b/lib/compilers/llc.js index 2d0b8fa64..ceb2ceb0d 100644 --- a/lib/compilers/llc.js +++ b/lib/compilers/llc.js @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; export class LLCCompiler extends BaseCompiler { - static get key() { return 'llc'; } + static get key() { + return 'llc'; + } constructor(info, env) { super(info, env); diff --git a/lib/compilers/llvm-mca.js b/lib/compilers/llvm-mca.js index d320352a4..9fd419cbf 100644 --- a/lib/compilers/llvm-mca.js +++ b/lib/compilers/llvm-mca.js @@ -22,14 +22,18 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AnalysisTool } from './analysis-tool'; -import { ClangParser } from './argument-parsers'; +import {AnalysisTool} from './analysis-tool'; +import {ClangParser} from './argument-parsers'; // Plain compiler, which just runs the tool and returns whatever the output was export class LLVMmcaTool extends AnalysisTool { - static get key() { return 'llvm-mca'; } + static get key() { + return 'llvm-mca'; + } - supportsObjdump() { return false; } + supportsObjdump() { + return false; + } getOutputFilenameArgs(filename) { // TODO: Some tools might require an argument of the form -arg=filename diff --git a/lib/compilers/mrustc.js b/lib/compilers/mrustc.js index 90739e5f9..b608ebcfd 100644 --- a/lib/compilers/mrustc.js +++ b/lib/compilers/mrustc.js @@ -24,24 +24,34 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { MrustcParser } from './argument-parsers'; +import {MrustcParser} from './argument-parsers'; export class MrustcCompiler extends BaseCompiler { - static get key() { return 'mrustc'; } + static get key() { + return 'mrustc'; + } optionsForFilter(filters, outputFilename) { // mrustc always dumps the C code for target in the .c file. // In our case, the actual file in -o is not even created because we are // faking the last step (C compilation). // Craft the 'outname' to have the intermediate .c file writen in outputFilename. - let outname = path.join(path.dirname(this.filename(outputFilename)), - path.basename(this.filename(outputFilename), '.c')); + let outname = path.join( + path.dirname(this.filename(outputFilename)), + path.basename(this.filename(outputFilename), '.c'), + ); // Currently always targets a rlib, no binary support at the moment. - return ['--crate-type', 'rlib', - '-o', outname, '-L', path.join(path.dirname(this.compiler.exe), '..', 'output')]; + return [ + '--crate-type', + 'rlib', + '-o', + outname, + '-L', + path.join(path.dirname(this.compiler.exe), '..', 'output'), + ]; } async runCompiler(compiler, options, inputFilename, execOptions) { @@ -59,5 +69,4 @@ export class MrustcCompiler extends BaseCompiler { getArgumentParser() { return MrustcParser; } - } diff --git a/lib/compilers/nasm.js b/lib/compilers/nasm.js index c0b4d88dc..09cd6b5ee 100644 --- a/lib/compilers/nasm.js +++ b/lib/compilers/nasm.js @@ -26,14 +26,22 @@ import path from 'path'; import * as utils from '../utils'; -import { AssemblyCompiler } from './assembly'; +import {AssemblyCompiler} from './assembly'; export class NasmCompiler extends AssemblyCompiler { - static get key() { return 'nasm'; } + static get key() { + return 'nasm'; + } prepareArguments(userOptions, filters, backendOptions, inputFilename, outputFilename, libraries) { - let options = super.prepareArguments(userOptions, filters, backendOptions, inputFilename, - outputFilename, libraries); + let options = super.prepareArguments( + userOptions, + filters, + backendOptions, + inputFilename, + outputFilename, + libraries, + ); let fmode; if (options.includes('-felf')) { @@ -44,11 +52,11 @@ export class NasmCompiler extends AssemblyCompiler { fmode = 'bin'; } else if (options.includes('-f')) { const idx = options.indexOf('-f'); - fmode = options[idx+1]; + fmode = options[idx + 1]; } if (!fmode) { - options = ['-g','-f','elf','-F','stabs'].concat(options); + options = ['-g', '-f', 'elf', '-F', 'stabs'].concat(options); } return options; diff --git a/lib/compilers/nvcc.js b/lib/compilers/nvcc.js index f559455bb..a3d07a9dc 100644 --- a/lib/compilers/nvcc.js +++ b/lib/compilers/nvcc.js @@ -24,13 +24,15 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; -import { SassAsmParser } from '../parsers/asm-parser-sass'; +import {BaseCompiler} from '../base-compiler'; +import {SassAsmParser} from '../parsers/asm-parser-sass'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; export class NvccCompiler extends BaseCompiler { - static get key() { return 'nvcc'; } + static get key() { + return 'nvcc'; + } constructor(info, env) { super(info, env); diff --git a/lib/compilers/ocaml.js b/lib/compilers/ocaml.js index 1bbd9a6cf..cae0e34c3 100644 --- a/lib/compilers/ocaml.js +++ b/lib/compilers/ocaml.js @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { PascalParser } from './argument-parsers'; +import {PascalParser} from './argument-parsers'; export class OCamlCompiler extends BaseCompiler { - static get key() { return 'ocaml'; } + static get key() { + return 'ocaml'; + } constructor(compilerInfo, env) { super(compilerInfo, env); diff --git a/lib/compilers/opt.js b/lib/compilers/opt.js index 763f41ffd..03bde841d 100644 --- a/lib/compilers/opt.js +++ b/lib/compilers/opt.js @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; export class OptCompiler extends BaseCompiler { - static get key() { return 'opt'; } + static get key() { + return 'opt'; + } optionsForFilter(filters, outputFilename) { return ['-o', this.filename(outputFilename), '-S']; diff --git a/lib/compilers/osaca.js b/lib/compilers/osaca.js index c6a4b3b6f..70487cd35 100644 --- a/lib/compilers/osaca.js +++ b/lib/compilers/osaca.js @@ -22,14 +22,18 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AnalysisTool } from './analysis-tool'; -import { BaseParser } from './argument-parsers'; +import {AnalysisTool} from './analysis-tool'; +import {BaseParser} from './argument-parsers'; // Plain compiler, which just runs the tool and returns whatever the output was export class OSACATool extends AnalysisTool { - static get key() { return 'osaca'; } + static get key() { + return 'osaca'; + } - supportsObjdump() { return false; } + supportsObjdump() { + return false; + } getOutputFilenameArgs(filename) { return ['-o', filename]; @@ -38,7 +42,7 @@ export class OSACATool extends AnalysisTool { optionsForFilter(filters, outputFilename) { return this.getOutputFilenameArgs(outputFilename); } - + getDefaultFilters() { // Disable everything, also intel syntax return { diff --git a/lib/compilers/pascal-win.js b/lib/compilers/pascal-win.js index 5df812edc..41fc03c5b 100644 --- a/lib/compilers/pascal-win.js +++ b/lib/compilers/pascal-win.js @@ -26,15 +26,17 @@ import path from 'path'; import fs from 'fs-extra'; -import { BaseCompiler } from '../base-compiler'; -import { MapFileReaderDelphi } from '../mapfiles/map-file-delphi'; -import { PELabelReconstructor } from '../pe32-support'; +import {BaseCompiler} from '../base-compiler'; +import {MapFileReaderDelphi} from '../mapfiles/map-file-delphi'; +import {PELabelReconstructor} from '../pe32-support'; import * as utils from '../utils'; -import { PascalUtils } from './pascal-utils'; +import {PascalUtils} from './pascal-utils'; export class PascalWinCompiler extends BaseCompiler { - static get key() { return 'pascal-win'; } + static get key() { + return 'pascal-win'; + } constructor(info, env) { super(info, env); @@ -91,24 +93,26 @@ export class PascalWinCompiler extends BaseCompiler { let args = ['-d', outputFilename]; if (intelAsm) args = args.concat(['-M', 'intel']); - return this.exec(this.compiler.objdumper, args, {maxOutput: 1024 * 1024 * 1024}) - .then((objResult) => { - if (objResult.code !== 0) { - result.asm = ''; - } else { - result.asm = objResult.stdout; - } + return this.exec(this.compiler.objdumper, args, {maxOutput: 1024 * 1024 * 1024}).then(objResult => { + if (objResult.code !== 0) { + result.asm = ''; + } else { + result.asm = objResult.stdout; + } - return result; - }); + return result; + }); } async saveDummyProjectFile(filename, unitName, unitPath) { - await fs.writeFile(filename, + await fs.writeFile( + filename, + // prettier-ignore 'program prog;\n' + 'uses ' + unitName + ' in \'' + unitPath + '\';\n' + 'begin\n' + - 'end.\n'); + 'end.\n', + ); } async writeAllFiles(dirPath, source, files, filters) { @@ -159,19 +163,12 @@ export class PascalWinCompiler extends BaseCompiler { options.pop(); - options.unshift( - '-CC', - '-W', - '-H', - '-GD', - '-$D+', - '-V', - '-B'); + options.unshift('-CC', '-W', '-H', '-GD', '-$D+', '-V', '-B'); options.push(projectFile); execOptions.customCwd = tempPath; - return this.exec(compiler, options, execOptions).then((result) => { + return this.exec(compiler, options, execOptions).then(result => { result.inputFilename = inputFilename; result.stdout = utils.parseOutput(result.stdout, inputFilename); result.stderr = utils.parseOutput(result.stderr, inputFilename); @@ -182,11 +179,11 @@ export class PascalWinCompiler extends BaseCompiler { optionsForFilter(filters) { filters.binary = true; filters.dontMaskFilenames = true; - filters.preProcessBinaryAsmLines = (asmLines) => { + filters.preProcessBinaryAsmLines = asmLines => { const mapFileReader = new MapFileReaderDelphi(this.mapFilename); const reconstructor = new PELabelReconstructor(asmLines, false, mapFileReader, false); reconstructor.run('output'); - + return reconstructor.asmLines; }; diff --git a/lib/compilers/pascal.js b/lib/compilers/pascal.js index 2da67f83e..33980a072 100644 --- a/lib/compilers/pascal.js +++ b/lib/compilers/pascal.js @@ -27,11 +27,11 @@ import path from 'path'; import fs from 'fs-extra'; import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; import * as utils from '../utils'; -import { PascalParser } from './argument-parsers'; -import { PascalUtils } from './pascal-utils'; +import {PascalParser} from './argument-parsers'; +import {PascalUtils} from './pascal-utils'; export class FPCCompiler extends BaseCompiler { static get key() { @@ -113,12 +113,9 @@ export class FPCCompiler extends BaseCompiler { const lastLinefeedBeforeStart = input.lastIndexOf('\n', relevantAsmStartsAt); if (lastLinefeedBeforeStart !== -1) { input = - input.substr(0, input.indexOf('00000000004')) + '\n' + - input.substr(lastLinefeedBeforeStart + 1); + input.substr(0, input.indexOf('00000000004')) + '\n' + input.substr(lastLinefeedBeforeStart + 1); } else { - input = - input.substr(0, input.indexOf('00000000004')) + '\n' + - input.substr(relevantAsmStartsAt); + input = input.substr(0, input.indexOf('00000000004')) + '\n' + input.substr(relevantAsmStartsAt); } } return input; @@ -129,11 +126,14 @@ export class FPCCompiler extends BaseCompiler { } async saveDummyProjectFile(filename, unitName, unitPath) { - await fs.writeFile(filename, + await fs.writeFile( + filename, + // prettier-ignore 'program prog;\n' + 'uses ' + unitName + ' in \'' + unitPath + '\';\n' + 'begin\n' + - 'end.\n'); + 'end.\n', + ); } async writeAllFiles(dirPath, source, files, filters) { diff --git a/lib/compilers/ppci.js b/lib/compilers/ppci.js index 8fc10e049..d56860095 100644 --- a/lib/compilers/ppci.js +++ b/lib/compilers/ppci.js @@ -22,21 +22,19 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; import * as exec from '../exec'; -import { logger } from '../logger'; +import {logger} from '../logger'; -const forbiddenOptions = new Set([ - '--report', - '--text-report', - '--html-report', -]); +const forbiddenOptions = new Set(['--report', '--text-report', '--html-report']); export class PPCICompiler extends BaseCompiler { - static get key() { return 'ppci'; } + static get key() { + return 'ppci'; + } filterUserOptions(args) { - return args.filter((item) => { + return args.filter(item => { if (typeof item !== 'string') return true; return !forbiddenOptions.has(item.toLowerCase()); diff --git a/lib/compilers/ptxas.js b/lib/compilers/ptxas.js index 18a8d9966..072d4909f 100644 --- a/lib/compilers/ptxas.js +++ b/lib/compilers/ptxas.js @@ -24,11 +24,11 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; -import { SassAsmParser } from '../parsers/asm-parser-sass'; +import {BaseCompiler} from '../base-compiler'; +import {SassAsmParser} from '../parsers/asm-parser-sass'; import * as utils from '../utils'; -import { BaseParser } from './argument-parsers'; +import {BaseParser} from './argument-parsers'; export class PtxAssembler extends BaseCompiler { static get key() { @@ -111,8 +111,7 @@ export class PtxAssembler extends BaseCompiler { async objdump(outputFilename, result, maxSize) { const dirPath = path.dirname(outputFilename); let args = ['-c', '-g', '-hex', outputFilename]; - const objResult = await this.exec( - this.compiler.objdumper, args, {maxOutput: maxSize, customCwd: dirPath}); + const objResult = await this.exec(this.compiler.objdumper, args, {maxOutput: maxSize, customCwd: dirPath}); result.asm = objResult.stdout; if (objResult.code !== 0) { result.asm = ''; diff --git a/lib/compilers/python.js b/lib/compilers/python.js index 3ee8ac880..293e100ad 100644 --- a/lib/compilers/python.js +++ b/lib/compilers/python.js @@ -22,13 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; -import { resolvePathFromAppRoot } from '../utils'; +import {BaseCompiler} from '../base-compiler'; +import {resolvePathFromAppRoot} from '../utils'; -import { BaseParser } from './argument-parsers'; +import {BaseParser} from './argument-parsers'; export class PythonCompiler extends BaseCompiler { - static get key() { return 'python'; } + static get key() { + return 'python'; + } constructor(compilerInfo, env) { super(compilerInfo, env); @@ -69,11 +71,7 @@ export class PythonCompiler extends BaseCompiler { } optionsForFilter(filters, outputFilename) { - return ['-I', - this.disasmScriptPath, - '--outputfile', - outputFilename, - '--inputfile']; + return ['-I', this.disasmScriptPath, '--outputfile', outputFilename, '--inputfile']; } getArgumentParser() { diff --git a/lib/compilers/ruby.js b/lib/compilers/ruby.js index af31f8d3d..f725601c4 100644 --- a/lib/compilers/ruby.js +++ b/lib/compilers/ruby.js @@ -24,13 +24,15 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; -import { resolvePathFromAppRoot } from '../utils'; +import {BaseCompiler} from '../base-compiler'; +import {resolvePathFromAppRoot} from '../utils'; -import { BaseParser } from './argument-parsers'; +import {BaseParser} from './argument-parsers'; export class RubyCompiler extends BaseCompiler { - static get key() { return 'ruby'; } + static get key() { + return 'ruby'; + } constructor(compilerInfo, env) { super(compilerInfo, env); @@ -82,7 +84,8 @@ export class RubyCompiler extends BaseCompiler { outputFilename, '--fname', path.basename(this.compileFilename), - '--inputfile']; + '--inputfile', + ]; } getArgumentParser() { diff --git a/lib/compilers/rust.js b/lib/compilers/rust.js index 84d0b156c..232e6fe1e 100644 --- a/lib/compilers/rust.js +++ b/lib/compilers/rust.js @@ -26,13 +26,15 @@ import path from 'path'; import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; -import { parseRustOutput } from '../utils'; +import {BaseCompiler} from '../base-compiler'; +import {parseRustOutput} from '../utils'; -import { RustParser } from './argument-parsers'; +import {RustParser} from './argument-parsers'; export class RustCompiler extends BaseCompiler { - static get key() { return 'rust'; } + static get key() { + return 'rust'; + } constructor(info, env) { super(info, env); @@ -57,7 +59,7 @@ export class RustCompiler extends BaseCompiler { optionsForBackend(backendOptions, outputFilename) { // The super class handles the GCC dump files that may be needed by // rustc-cg-gcc subclass. - const opts = super.optionsForBackend (backendOptions, outputFilename); + const opts = super.optionsForBackend(backendOptions, outputFilename); if (backendOptions.produceRustMir && this.compiler.supportsRustMirView) { const of = this.getRustMirOutputFilename(outputFilename); @@ -87,8 +89,7 @@ export class RustCompiler extends BaseCompiler { // Override the IR file name method for rustc because the output file is different from clang. getIrOutputFilename(inputFilename) { - return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase) - .replace('.s', '.ll'); + return this.getOutputFilename(path.dirname(inputFilename), this.outputFilebase).replace('.s', '.ll'); } getArgumentParser() { diff --git a/lib/compilers/rustc-cg-gcc.js b/lib/compilers/rustc-cg-gcc.js index 2024aad27..ff6db168a 100644 --- a/lib/compilers/rustc-cg-gcc.js +++ b/lib/compilers/rustc-cg-gcc.js @@ -24,10 +24,12 @@ import path from 'path'; -import { RustCompiler } from './rust'; +import {RustCompiler} from './rust'; export class RustcCgGCCCompiler extends RustCompiler { - static get key() { return 'rustc-cg-gcc'; } + static get key() { + return 'rustc-cg-gcc'; + } constructor(info, env) { super(info, env); @@ -45,8 +47,8 @@ export class RustcCgGCCCompiler extends RustCompiler { this.compiler.removeEmptyGccDump = false; } - getGccDumpOptions(gccDumpOptions, removeEmptyPasses){ - return [ '-C' , 'llvm-args=' + super.getGccDumpOptions(gccDumpOptions, removeEmptyPasses).join(' ')]; + getGccDumpOptions(gccDumpOptions, removeEmptyPasses) { + return ['-C', 'llvm-args=' + super.getGccDumpOptions(gccDumpOptions, removeEmptyPasses).join(' ')]; } optionsForFilter(filters, outputFilename, userOptions) { @@ -54,13 +56,20 @@ export class RustcCgGCCCompiler extends RustCompiler { // See https://github.com/antoyo/rustc_codegen_gcc let toolroot = path.resolve(path.dirname(this.compiler.exe), '..'); - let options = ['-C', 'panic=abort', - '-Z', 'codegen-backend=librustc_codegen_gcc.so', - '--sysroot', toolroot + '/sysroot' ]; + let options = [ + '-C', + 'panic=abort', + '-Z', + 'codegen-backend=librustc_codegen_gcc.so', + '--sysroot', + toolroot + '/sysroot', + ]; // rust.js makes the asumption that LLVM is used. This may go away when cranelift is available. // Until this is the case and the super() class is refactored, simply ditch -Cllvm arg. - let super_options = super.optionsForFilter(filters, outputFilename, userOptions).filter(arg => !/-Cllvm.*/.test(arg)); + let super_options = super + .optionsForFilter(filters, outputFilename, userOptions) + .filter(arg => !/-Cllvm.*/.test(arg)); options = options.concat(super_options); return options; } diff --git a/lib/compilers/scala.js b/lib/compilers/scala.js index d20c6b9c8..d7acbf301 100644 --- a/lib/compilers/scala.js +++ b/lib/compilers/scala.js @@ -26,8 +26,8 @@ import Semver from 'semver'; import {asSafeVer} from '../utils'; -import { ScalaParser } from './argument-parsers'; -import { JavaCompiler } from './java'; +import {ScalaParser} from './argument-parsers'; +import {JavaCompiler} from './java'; export class ScalaCompiler extends JavaCompiler { static get key() { @@ -50,8 +50,7 @@ export class ScalaCompiler extends JavaCompiler { filterUserOptions(userOptions) { // filter options without extra arguments - userOptions = userOptions.filter(option => - option !== '-Xscript'); + userOptions = userOptions.filter(option => option !== '-Xscript'); const oneArgForbiddenList = new Set([ // -d directory @@ -67,13 +66,9 @@ export class ScalaCompiler extends JavaCompiler { // Forcibly enable javap filters.binary = true; - const scala2Opts = [ - '-Xlint:_', - ]; + const scala2Opts = ['-Xlint:_']; - const scala3Opts = [ - '-deprecation', - ]; + const scala3Opts = ['-deprecation']; return Semver.gte(asSafeVer(this.compiler.semver), '3.0.0', true) ? scala3Opts : scala2Opts; } diff --git a/lib/compilers/sdcc.js b/lib/compilers/sdcc.js index 5a23b6823..ba0ddfc84 100644 --- a/lib/compilers/sdcc.js +++ b/lib/compilers/sdcc.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { GCCCompiler } from './gcc'; +import {GCCCompiler} from './gcc'; export class SdccCompiler extends GCCCompiler { - static get key() { return 'sdcc'; } + static get key() { + return 'sdcc'; + } optionsForFilter(filters, outputFilename) { let options = ['-o', this.filename(outputFilename)]; diff --git a/lib/compilers/spirv.js b/lib/compilers/spirv.js index 567fc76d3..395354a7d 100644 --- a/lib/compilers/spirv.js +++ b/lib/compilers/spirv.js @@ -26,12 +26,14 @@ import path from 'path'; import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; -import { logger } from '../logger'; +import {BaseCompiler} from '../base-compiler'; +import {logger} from '../logger'; import * as utils from '../utils'; export class SPIRVCompiler extends BaseCompiler { - static get key() { return 'spirv'; } + static get key() { + return 'spirv'; + } constructor(compilerInfo, env) { super(compilerInfo, env); @@ -45,8 +47,10 @@ export class SPIRVCompiler extends BaseCompiler { backendOptions = backendOptions || {}; if (this.compiler.options) { - let compilerOptions = _.filter(utils.splitArguments(this.compiler.options), option => - option !== '-fno-crash-diagnostics'); + let compilerOptions = _.filter( + utils.splitArguments(this.compiler.options), + option => option !== '-fno-crash-diagnostics', + ); options = options.concat(compilerOptions); } @@ -68,20 +72,21 @@ export class SPIRVCompiler extends BaseCompiler { } userOptions = this.filterUserOptions(userOptions) || []; - return options.concat(libIncludes, libOptions, libPaths, libLinks, userOptions, - [this.filename(inputFilename)], staticLibLinks); + return options.concat( + libIncludes, + libOptions, + libPaths, + libLinks, + userOptions, + [this.filename(inputFilename)], + staticLibLinks, + ); } optionsForFilter(filters, outputFilename) { const sourceDir = path.dirname(outputFilename); const bitcodeFilename = path.join(sourceDir, this.outputFilebase + '.bc'); - return [ - '-cc1', - '-debug-info-kind=limited', - '-dwarf-version=5', - '-debugger-tuning=gdb', - '-o', bitcodeFilename, - ]; + return ['-cc1', '-debug-info-kind=limited', '-dwarf-version=5', '-debugger-tuning=gdb', '-o', bitcodeFilename]; } getPrimaryOutputFilename(dirPath, outputFilebase) { @@ -125,7 +130,7 @@ export class SPIRVCompiler extends BaseCompiler { } const spvasmFilename = path.join(sourceDir, this.outputFilebase + '.spvasm'); - const disassemblerFlags = [spvBinFilename, '-o', spvasmFilename]; + const disassemblerFlags = [spvBinFilename, '-o', spvasmFilename]; const spvasmOutput = await this.exec(this.disassemblerPath, disassemblerFlags, execOptions); if (spvasmOutput.code !== 0) { @@ -152,7 +157,7 @@ export class SPIRVCompiler extends BaseCompiler { newOptions.concat('-S'); let index = newOptions.indexOf(outputFile); - if (index !== -1){ + if (index !== -1) { newOptions[index] = inputFilename.replace(path.extname(inputFilename), '.ll'); } @@ -160,25 +165,28 @@ export class SPIRVCompiler extends BaseCompiler { } async generateAST(inputFilename, options) { - const newOptions = _.filter(options, option => option !== '-fcolor-diagnostics') - .concat(['-ast-dump']); + const newOptions = _.filter(options, option => option !== '-fcolor-diagnostics').concat(['-ast-dump']); const execOptions = this.getDefaultExecOptions(); execOptions.maxOutput = 1024 * 1024 * 1024; return this.llvmAst.processAst( - await this.runCompilerForASTOrIR(this.compiler.exe, newOptions, this.filename(inputFilename), execOptions)); + await this.runCompilerForASTOrIR(this.compiler.exe, newOptions, this.filename(inputFilename), execOptions), + ); } async generateIR(inputFilename, options, filters) { - const newOptions = _.filter(options, option => option !== '-fcolor-diagnostics') - .concat('-emit-llvm'); + const newOptions = _.filter(options, option => option !== '-fcolor-diagnostics').concat('-emit-llvm'); const execOptions = this.getDefaultExecOptions(); execOptions.maxOutput = 1024 * 1024 * 1024; const output = await this.runCompilerForASTOrIR( - this.compiler.exe, newOptions, this.filename(inputFilename), execOptions); + this.compiler.exe, + newOptions, + this.filename(inputFilename), + execOptions, + ); if (output.code !== 0) { logger.error('Failed to run compiler to get IR code'); return output.stderr; diff --git a/lib/compilers/swift.js b/lib/compilers/swift.js index 9a305cded..437099b2b 100644 --- a/lib/compilers/swift.js +++ b/lib/compilers/swift.js @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; -import { ClangParser } from './argument-parsers'; +import {ClangParser} from './argument-parsers'; export class SwiftCompiler extends BaseCompiler { - static get key() { return 'swift'; } + static get key() { + return 'swift'; + } getSharedLibraryPathsAsArguments() { return []; diff --git a/lib/compilers/tendra.js b/lib/compilers/tendra.js index b98e55ad8..46ba97c3e 100644 --- a/lib/compilers/tendra.js +++ b/lib/compilers/tendra.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { GCCCompiler } from './gcc'; +import {GCCCompiler} from './gcc'; export class TenDRACompiler extends GCCCompiler { - static get key() { return 'tendra'; } + static get key() { + return 'tendra'; + } optionsForFilter(filters, outputFilename) { let options = ['-o', this.filename(outputFilename)]; diff --git a/lib/compilers/tinyc.js b/lib/compilers/tinyc.js index 8c1c1333f..f92733b08 100644 --- a/lib/compilers/tinyc.js +++ b/lib/compilers/tinyc.js @@ -24,16 +24,18 @@ import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; +import {BaseCompiler} from '../base-compiler'; export class TinyCCompiler extends BaseCompiler { - static get key() { return 'tinyc'; } + static get key() { + return 'tinyc'; + } optionsForFilter(filters, outputFilename, userOptions) { - if (_.some(userOptions, (opt) => opt === '--help' || opt === '-h' || opt === '-hh')) { + if (_.some(userOptions, opt => opt === '--help' || opt === '-h' || opt === '-hh')) { return []; } else { - if (!_.some(userOptions, (opt) => opt === '-E')) { + if (!_.some(userOptions, opt => opt === '-E')) { filters.binary = true; } return ['-g', '-o', this.filename(outputFilename)]; @@ -41,6 +43,6 @@ export class TinyCCompiler extends BaseCompiler { } filterUserOptions(userOptions) { - return _.filter(userOptions, (opt) => opt !== '-run'); + return _.filter(userOptions, opt => opt !== '-run'); } } diff --git a/lib/compilers/typescript.js b/lib/compilers/typescript.js index 5fd1037c9..732e482ca 100644 --- a/lib/compilers/typescript.js +++ b/lib/compilers/typescript.js @@ -37,17 +37,18 @@ export class TypeScriptCompiler extends BaseCompiler { async runCompiler(compiler, options, inputFilename, execOptions) { // These options make Clang produce an IR - const newOptions = [ - '--emit=mlir-llvm', - inputFilename, - ]; + const newOptions = ['--emit=mlir-llvm', inputFilename]; if (!this.tscSharedLib) { newOptions.push('-nogc'); } const output = await this.runCompilerRawOutput( - this.tscJit, newOptions, this.filename(inputFilename), execOptions); + this.tscJit, + newOptions, + this.filename(inputFilename), + execOptions, + ); if (output.code !== 0) { return [{text: 'Failed to run compiler to get MLIR code'}]; } @@ -57,10 +58,7 @@ export class TypeScriptCompiler extends BaseCompiler { async generateIR(inputFilename, options, filters) { // These options make Clang produce an IR - const newOptions = [ - '--emit=llvm', - inputFilename, - ]; + const newOptions = ['--emit=llvm', inputFilename]; if (!this.tscSharedLib) { newOptions.push('-nogc'); @@ -71,7 +69,11 @@ export class TypeScriptCompiler extends BaseCompiler { execOptions.maxOutput = 1024 * 1024 * 1024; const output = await this.runCompilerRawOutput( - this.tscJit, newOptions, this.filename(inputFilename), execOptions); + this.tscJit, + newOptions, + this.filename(inputFilename), + execOptions, + ); if (output.code !== 0) { return [{text: 'Failed to run compiler to get IR code'}]; } diff --git a/lib/compilers/win32-vc.js b/lib/compilers/win32-vc.js index 1e346f10f..e5d13662e 100644 --- a/lib/compilers/win32-vc.js +++ b/lib/compilers/win32-vc.js @@ -22,13 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { VcAsmParser } from '../parsers/asm-parser-vc'; +import {VcAsmParser} from '../parsers/asm-parser-vc'; -import { VCParser } from './argument-parsers'; -import { Win32Compiler } from './win32'; +import {VCParser} from './argument-parsers'; +import {Win32Compiler} from './win32'; export class Win32VcCompiler extends Win32Compiler { - static get key() { return 'win32-vc'; } + static get key() { + return 'win32-vc'; + } constructor(info, env) { super(info, env); diff --git a/lib/compilers/win32-vc6.js b/lib/compilers/win32-vc6.js index 5265e5a91..c835394d1 100644 --- a/lib/compilers/win32-vc6.js +++ b/lib/compilers/win32-vc6.js @@ -22,13 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { Vc6AsmParser } from '../parsers/asm-parser-vc6'; +import {Vc6AsmParser} from '../parsers/asm-parser-vc6'; -import { VCParser } from './argument-parsers'; -import { Win32Compiler } from './win32'; +import {VCParser} from './argument-parsers'; +import {Win32Compiler} from './win32'; export class Win32Vc6Compiler extends Win32Compiler { - static get key() { return 'win32-vc6'; } + static get key() { + return 'win32-vc6'; + } constructor(info, env) { super(info, env); diff --git a/lib/compilers/win32.js b/lib/compilers/win32.js index 3ff0f4eef..7d1a6256a 100644 --- a/lib/compilers/win32.js +++ b/lib/compilers/win32.js @@ -27,14 +27,16 @@ import path from 'path'; import temp from 'temp'; import _ from 'underscore'; -import { BaseCompiler } from '../base-compiler'; -import { MapFileReaderVS } from '../mapfiles/map-file-vs'; -import { AsmParser } from '../parsers/asm-parser'; -import { PELabelReconstructor } from '../pe32-support'; +import {BaseCompiler} from '../base-compiler'; +import {MapFileReaderVS} from '../mapfiles/map-file-vs'; +import {AsmParser} from '../parsers/asm-parser'; +import {PELabelReconstructor} from '../pe32-support'; import * as utils from '../utils'; export class Win32Compiler extends BaseCompiler { - static get key() { return 'win32'; } + static get key() { + return 'win32'; + } constructor(compilerInfo, env) { super(compilerInfo, env); @@ -45,10 +47,8 @@ export class Win32Compiler extends BaseCompiler { newTempDir() { return new Promise((resolve, reject) => { temp.mkdir({prefix: 'compiler-explorer-compiler', dir: process.env.TMP}, (err, dirPath) => { - if (err) - reject(`Unable to open temp file: ${err}`); - else - resolve(dirPath); + if (err) reject(`Unable to open temp file: ${err}`); + else resolve(dirPath); }); }); } @@ -68,22 +68,24 @@ export class Win32Compiler extends BaseCompiler { } getSharedLibraryLinks(libraries) { - return _.flatten(_.map(libraries, (selectedLib) => { - const foundVersion = this.findLibVersion(selectedLib); - if (!foundVersion) return false; + return _.flatten( + _.map(libraries, selectedLib => { + const foundVersion = this.findLibVersion(selectedLib); + if (!foundVersion) return false; - return _.map(foundVersion.liblink, (lib) => { - if (lib) { - return '"' + lib + '.lib"'; - } else { - return false; - } - }); - })); + return _.map(foundVersion.liblink, lib => { + if (lib) { + return '"' + lib + '.lib"'; + } else { + return false; + } + }); + }), + ); } getStaticLibraryLinks(libraries) { - return _.map(super.getSortedStaticLibraries(libraries), (lib) => { + return _.map(super.getSortedStaticLibraries(libraries), lib => { return '"' + lib + '.lib"'; }); } @@ -115,8 +117,16 @@ export class Win32Compiler extends BaseCompiler { } userOptions = this.filterUserOptions(userOptions) || []; - return options.concat(libIncludes, libOptions, userOptions, [this.filename(inputFilename)], preLink, libPaths, - libLinks, staticlibLinks); + return options.concat( + libIncludes, + libOptions, + userOptions, + [this.filename(inputFilename)], + preLink, + libPaths, + libLinks, + staticlibLinks, + ); } optionsForFilter(filters, outputFilename) { @@ -124,7 +134,7 @@ export class Win32Compiler extends BaseCompiler { const mapFilename = outputFilename + '.map'; const mapFileReader = new MapFileReaderVS(mapFilename); - filters.preProcessBinaryAsmLines = (asmLines) => { + filters.preProcessBinaryAsmLines = asmLines => { const reconstructor = new PELabelReconstructor(asmLines, false, mapFileReader); reconstructor.run('output.s.obj'); @@ -150,7 +160,7 @@ export class Win32Compiler extends BaseCompiler { } } - processAsm(result, filters/*, options*/) { + processAsm(result, filters /*, options*/) { if (filters.binary) { filters.dontMaskFilenames = true; return this.binaryAsmParser.process(result.asm, filters); diff --git a/lib/compilers/wine-vc.js b/lib/compilers/wine-vc.js index d49c4deb1..653f6289e 100644 --- a/lib/compilers/wine-vc.js +++ b/lib/compilers/wine-vc.js @@ -24,15 +24,17 @@ import path from 'path'; -import { BaseCompiler } from '../base-compiler'; -import { MapFileReaderVS } from '../mapfiles/map-file-vs'; -import { VcAsmParser } from '../parsers/asm-parser-vc'; -import { PELabelReconstructor } from '../pe32-support'; +import {BaseCompiler} from '../base-compiler'; +import {MapFileReaderVS} from '../mapfiles/map-file-vs'; +import {VcAsmParser} from '../parsers/asm-parser-vc'; +import {PELabelReconstructor} from '../pe32-support'; -import { VCParser } from './argument-parsers'; +import {VCParser} from './argument-parsers'; export class WineVcCompiler extends BaseCompiler { - static get key() { return 'wine-vc'; } + static get key() { + return 'wine-vc'; + } constructor(info, env) { info.supportsFiltersInBinary = true; @@ -75,7 +77,7 @@ export class WineVcCompiler extends BaseCompiler { const mapFilename = outputFilename + '.map'; const mapFileReader = new MapFileReaderVS(mapFilename); - filters.preProcessBinaryAsmLines = (asmLines) => { + filters.preProcessBinaryAsmLines = asmLines => { const reconstructor = new PELabelReconstructor(asmLines, false, mapFileReader); reconstructor.run('output.s.obj'); diff --git a/lib/compilers/wsl-vc.js b/lib/compilers/wsl-vc.js index b7b215be8..edc3b8062 100644 --- a/lib/compilers/wsl-vc.js +++ b/lib/compilers/wsl-vc.js @@ -29,12 +29,14 @@ import path from 'path'; import temp from 'temp'; -import { VcAsmParser } from '../parsers/asm-parser-vc'; +import {VcAsmParser} from '../parsers/asm-parser-vc'; -import { Win32VcCompiler } from './win32-vc'; +import {Win32VcCompiler} from './win32-vc'; export class WslVcCompiler extends Win32VcCompiler { - static get key() { return 'wsl-vc'; } + static get key() { + return 'wsl-vc'; + } constructor(info, env) { super(info, env); @@ -56,10 +58,8 @@ export class WslVcCompiler extends Win32VcCompiler { newTempDir() { return new Promise((resolve, reject) => { temp.mkdir({prefix: 'compiler-explorer-compiler', dir: process.env.winTmp}, (err, dirPath) => { - if (err) - reject(`Unable to open temp file: ${err}`); - else - resolve(dirPath); + if (err) reject(`Unable to open temp file: ${err}`); + else resolve(dirPath); }); }); } diff --git a/lib/csp.js b/lib/csp.js index cfbf67d48..55793cb5f 100644 --- a/lib/csp.js +++ b/lib/csp.js @@ -26,26 +26,73 @@ import _ from 'underscore'; export const data = { 'default-src': ["'self'", 'https://*.godbolt.org', 'localhost:*', 'https://*.compiler-explorer.com'], - 'style-src': ["'self'", "'unsafe-inline'", 'https://*.godbolt.org', 'localhost:*', - 'https://*.compiler-explorer.com'], - 'script-src': ["'self'", "'unsafe-inline'", 'data:', 'https://*.godbolt.org', 'localhost:*', + 'style-src': [ + "'self'", + "'unsafe-inline'", + 'https://*.godbolt.org', + 'localhost:*', 'https://*.compiler-explorer.com', - 'https://*.twitter.com', 'https://www.google-analytics.com', - 'https://apis.google.com', 'https://ssl.google-analytics.com', 'https://sentry.io/'], - 'img-src': ["'self'", 'https://*.godbolt.org', 'localhost:*', - 'https://*.compiler-explorer.com', 'data:', 'https://www.google-analytics.com/', - 'https://syndication.twitter.com', 'https://ssl.google-analytics.com', 'https://csi.gstatic.com'], - 'font-src': ["'self'", 'data:', 'https://*.godbolt.org', 'localhost:*', - 'https://*.compiler-explorer.com', 'https://fonts.gstatic.com', - 'https://themes.googleusercontent.com'], - 'frame-src': ["'self'", 'https://*.godbolt.org', 'localhost:*', - 'https://*.compiler-explorer.com', 'https://www.google-analytics.com', - 'https://accounts.google.com/', 'https://content.googleapis.com/', - 'https://sentry.io', 'https://platform.twitter.com/', 'https://syndication.twitter.com/'], - 'connect-src': ["'self'", '*', 'https://*.godbolt.org', 'localhost:*', - 'https://*.compiler-explorer.com', 'https://api.github.com'], - 'media-src': ["'self'", 'https://ssl.gstatic.com', 'https://*.godbolt.org', 'localhost:*', - 'https://*.compiler-explorer.com'], + ], + 'script-src': [ + "'self'", + "'unsafe-inline'", + 'data:', + 'https://*.godbolt.org', + 'localhost:*', + 'https://*.compiler-explorer.com', + 'https://*.twitter.com', + 'https://www.google-analytics.com', + 'https://apis.google.com', + 'https://ssl.google-analytics.com', + 'https://sentry.io/', + ], + 'img-src': [ + "'self'", + 'https://*.godbolt.org', + 'localhost:*', + 'https://*.compiler-explorer.com', + 'data:', + 'https://www.google-analytics.com/', + 'https://syndication.twitter.com', + 'https://ssl.google-analytics.com', + 'https://csi.gstatic.com', + ], + 'font-src': [ + "'self'", + 'data:', + 'https://*.godbolt.org', + 'localhost:*', + 'https://*.compiler-explorer.com', + 'https://fonts.gstatic.com', + 'https://themes.googleusercontent.com', + ], + 'frame-src': [ + "'self'", + 'https://*.godbolt.org', + 'localhost:*', + 'https://*.compiler-explorer.com', + 'https://www.google-analytics.com', + 'https://accounts.google.com/', + 'https://content.googleapis.com/', + 'https://sentry.io', + 'https://platform.twitter.com/', + 'https://syndication.twitter.com/', + ], + 'connect-src': [ + "'self'", + '*', + 'https://*.godbolt.org', + 'localhost:*', + 'https://*.compiler-explorer.com', + 'https://api.github.com', + ], + 'media-src': [ + "'self'", + 'https://ssl.gstatic.com', + 'https://*.godbolt.org', + 'localhost:*', + 'https://*.compiler-explorer.com', + ], }; export const policy = _.map(data, (value, policyKey) => `${policyKey} ${value.join(' ')}`).join(';'); diff --git a/lib/demangler/_all.js b/lib/demangler/_all.js index 696481c7a..1e8ca8dee 100644 --- a/lib/demangler/_all.js +++ b/lib/demangler/_all.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { CppDemangler } from './cpp'; -export { DefaultDemangler } from './default'; -export { PascalDemangler } from './pascal'; -export { Win32Demangler } from './win32'; +export {CppDemangler} from './cpp'; +export {DefaultDemangler} from './default'; +export {PascalDemangler} from './pascal'; +export {Win32Demangler} from './win32'; diff --git a/lib/demangler/cpp.js b/lib/demangler/cpp.js index a61222eb7..c5e98221b 100644 --- a/lib/demangler/cpp.js +++ b/lib/demangler/cpp.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseDemangler } from './base'; +import {BaseDemangler} from './base'; const LabelMetadata = [ {ident: new RegExp('C1E[a-zA-Z0-9_$]*$'), description: 'complete object constructor'}, @@ -34,7 +34,9 @@ const LabelMetadata = [ ]; export class CppDemangler extends BaseDemangler { - static get key() { return 'cpp'; } + static get key() { + return 'cpp'; + } getMetadata(symbol) { return LabelMetadata.filter(metadata => metadata.ident.test(symbol)); diff --git a/lib/demangler/default.js b/lib/demangler/default.js index 27bea89d4..0fe70115d 100644 --- a/lib/demangler/default.js +++ b/lib/demangler/default.js @@ -22,8 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseDemangler } from './base'; +import {BaseDemangler} from './base'; export class DefaultDemangler extends BaseDemangler { - static get key() { return 'default'; } + static get key() { + return 'default'; + } } diff --git a/lib/demangler/index.js b/lib/demangler/index.js index 34a65dc7f..207daa93e 100644 --- a/lib/demangler/index.js +++ b/lib/demangler/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BaseDemangler } from './base'; +export {BaseDemangler} from './base'; export * from './_all'; export const getDemanglerTypeByKey = makeKeyedTypeGetter('demangler', all); diff --git a/lib/demangler/pascal.js b/lib/demangler/pascal.js index c9bf8da6f..7c6eba4ff 100644 --- a/lib/demangler/pascal.js +++ b/lib/demangler/pascal.js @@ -22,12 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { SymbolStore } from '../symbol-store'; +import {SymbolStore} from '../symbol-store'; -import { BaseDemangler } from './base'; +import {BaseDemangler} from './base'; export class PascalDemangler extends BaseDemangler { - static get key() { return 'pascal'; } + static get key() { + return 'pascal'; + } constructor(demanglerExe, compiler) { super(demanglerExe, compiler); @@ -51,11 +53,26 @@ export class PascalDemangler extends BaseDemangler { this.ignoredsymbols = [ '.L', - 'VMT_$', 'INIT_$', 'INIT$_$', 'FINALIZE$_$', 'RTTI_$', - 'VMT_OUTPUT_', 'INIT$_OUTPUT', 'RTTI_OUTPUT_', 'FINALIZE$_OUTPUT', + 'VMT_$', + 'INIT_$', + 'INIT$_$', + 'FINALIZE$_$', + 'RTTI_$', + 'VMT_OUTPUT_', + 'INIT$_OUTPUT', + 'RTTI_OUTPUT_', + 'FINALIZE$_OUTPUT', '_$', - 'DEBUGSTART_$', 'DEBUGEND_$', 'DBG_$', 'DBG2_$', 'DBGREF_$', - 'DEBUGSTART_OUTPUT', 'DEBUGEND_OUTPUT', 'DBG_OUTPUT_', 'DBG2_OUTPUT_', 'DBGREF_OUTPUT_', + 'DEBUGSTART_$', + 'DEBUGEND_$', + 'DBG_$', + 'DBG2_$', + 'DBGREF_$', + 'DEBUGSTART_OUTPUT', + 'DEBUGEND_OUTPUT', + 'DBG_OUTPUT_', + 'DBG2_OUTPUT_', + 'DBGREF_OUTPUT_', ]; } @@ -104,8 +121,14 @@ export class PascalDemangler extends BaseDemangler { return unmangledGlobalVar; } - let idx, paramtype = '', phase = 0; - let unitname = '', classname = '', methodname = '', params = '', resulttype = ''; + let idx, + paramtype = '', + phase = 0; + let unitname = '', + classname = '', + methodname = '', + params = '', + resulttype = ''; idx = text.indexOf('$_$'); if (idx !== -1) { diff --git a/lib/demangler/prefix-tree.js b/lib/demangler/prefix-tree.js index 7295c5110..77034e313 100644 --- a/lib/demangler/prefix-tree.js +++ b/lib/demangler/prefix-tree.js @@ -36,8 +36,7 @@ export class PrefixTree { constructor(mappings) { this.root = []; if (mappings) { - for (const [from, to] of mappings) - this.add(from, to); + for (const [from, to] of mappings) this.add(from, to); } } @@ -45,8 +44,7 @@ export class PrefixTree { let node = this.root; for (let i = 0; i < from.length; ++i) { const character = from.codePointAt(i); - if (!node[character]) - node[character] = []; + if (!node[character]) node[character] = []; node = node[character]; } node.result = to; @@ -61,10 +59,8 @@ export class PrefixTree { for (let i = 0; i < needle.length; ++i) { const character = needle.codePointAt(i); node = node[character]; - if (!node) - break; - if (node.result) - match = [needle.substr(0, i + 1), node.result]; + if (!node) break; + if (node.result) match = [needle.substr(0, i + 1), node.result]; } return match; } @@ -74,11 +70,9 @@ export class PrefixTree { for (let i = 0; i < needle.length; ++i) { const character = needle.codePointAt(i); node = node[character]; - if (!node) - break; + if (!node) break; } - if (node && node['result']) - return node['result']; + if (node && node['result']) return node['result']; return null; } diff --git a/lib/demangler/win32.js b/lib/demangler/win32.js index b59343d2f..78004c7d4 100644 --- a/lib/demangler/win32.js +++ b/lib/demangler/win32.js @@ -22,13 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; -import { CppDemangler } from './cpp'; +import {CppDemangler} from './cpp'; export class Win32Demangler extends CppDemangler { - static get key() { return 'win32'; } + static get key() { + return 'win32'; + } constructor(demanglerExe, compiler) { super(demanglerExe, compiler); @@ -66,10 +68,9 @@ export class Win32Demangler extends CppDemangler { processOutput(translations) { for (const asmLine of this.result.asm) { - const labels = - (this.hasQuotesAroundDecoratedLabels) - ? asmLine.text.match(this.allDecoratedLabelsWithQuotes) - : asmLine.text.match(this.allDecoratedLabels); + const labels = this.hasQuotesAroundDecoratedLabels + ? asmLine.text.match(this.allDecoratedLabelsWithQuotes) + : asmLine.text.match(this.allDecoratedLabels); if (labels) { let [, beforeComment, afterComment] = asmLine.text.match(/(.*)(;.*)?/); for (const label of labels) { diff --git a/lib/formatters/_all.js b/lib/formatters/_all.js index 98b447a77..3c65b705e 100644 --- a/lib/formatters/_all.js +++ b/lib/formatters/_all.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { ClangFormatFormatter } from './clang-format'; -export { DartFormatFormatter } from './dartformat'; -export { GoFmtFormatter } from './gofmt'; -export { RustFmtFormatter } from './rustfmt'; +export {ClangFormatFormatter} from './clang-format'; +export {DartFormatFormatter} from './dartformat'; +export {GoFmtFormatter} from './gofmt'; +export {RustFmtFormatter} from './rustfmt'; diff --git a/lib/formatters/clang-format.js b/lib/formatters/clang-format.js index c4c156355..c12724276 100644 --- a/lib/formatters/clang-format.js +++ b/lib/formatters/clang-format.js @@ -24,7 +24,7 @@ import * as exec from '../exec'; -import { BaseFormatter } from './base'; +import {BaseFormatter} from './base'; export class ClangFormatFormatter extends BaseFormatter { static get key() { diff --git a/lib/formatters/dartformat.js b/lib/formatters/dartformat.js index e9e6b2439..788884723 100644 --- a/lib/formatters/dartformat.js +++ b/lib/formatters/dartformat.js @@ -24,7 +24,7 @@ import * as exec from '../exec'; -import { BaseFormatter } from './base'; +import {BaseFormatter} from './base'; export class DartFormatFormatter extends BaseFormatter { static get key() { @@ -32,7 +32,7 @@ export class DartFormatFormatter extends BaseFormatter { } async format(source) { - return await exec.execute(this.formatterInfo.exe, ['format'], { input: source }); + return await exec.execute(this.formatterInfo.exe, ['format'], {input: source}); } isValidStyle() { diff --git a/lib/formatters/gofmt.js b/lib/formatters/gofmt.js index 06e09f248..67a6a09f2 100644 --- a/lib/formatters/gofmt.js +++ b/lib/formatters/gofmt.js @@ -24,10 +24,12 @@ import * as exec from '../exec'; -import { BaseFormatter } from './base'; +import {BaseFormatter} from './base'; export class GoFmtFormatter extends BaseFormatter { - static get key() { return 'gofmt'; } + static get key() { + return 'gofmt'; + } /** * Format the provided source code diff --git a/lib/formatters/index.js b/lib/formatters/index.js index 5496c4285..f12b5e225 100644 --- a/lib/formatters/index.js +++ b/lib/formatters/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BaseFormatter } from './base'; +export {BaseFormatter} from './base'; export * from './_all'; export const getFormatterTypeByKey = makeKeyedTypeGetter('formatter', all); diff --git a/lib/formatters/rustfmt.js b/lib/formatters/rustfmt.js index ee36223e4..3bbe8e580 100644 --- a/lib/formatters/rustfmt.js +++ b/lib/formatters/rustfmt.js @@ -24,16 +24,21 @@ import * as exec from '../exec'; -import { BaseFormatter } from './base'; +import {BaseFormatter} from './base'; export class RustFmtFormatter extends BaseFormatter { - static get key() { return 'rustfmt'; } + static get key() { + return 'rustfmt'; + } async format(source, options) { const args = [ - '--emit', 'stdout', - '--config', `hard_tabs=${options.useSpaces ? 'false' : 'true'}`, - '--config', `tab_spaces=${options.tabWidth}`, + '--emit', + 'stdout', + '--config', + `hard_tabs=${options.useSpaces ? 'false' : 'true'}`, + '--config', + `tab_spaces=${options.tabWidth}`, ]; return await exec.execute(this.formatterInfo.exe, args, {input: source}); } diff --git a/lib/handlers/compile.js b/lib/handlers/compile.js index 7e7a4d63a..e9b7a0e8c 100644 --- a/lib/handlers/compile.js +++ b/lib/handlers/compile.js @@ -32,8 +32,8 @@ import temp from 'temp'; import _ from 'underscore'; import which from 'which'; -import { getCompilerTypeByKey } from '../compilers'; -import { logger } from '../logger'; +import {getCompilerTypeByKey} from '../compilers'; +import {logger} from '../logger'; import * as utils from '../utils'; temp.track(); @@ -52,7 +52,8 @@ function initialise(compilerEnv) { if (status.busy) { cyclesBusy++; logger.warn( - `temp cleanup skipped, pending: ${status.pending}, waiting: ${status.size}, cycles: ${cyclesBusy}`); + `temp cleanup skipped, pending: ${status.pending}, waiting: ${status.size}, cycles: ${cyclesBusy}`, + ); return; } @@ -187,8 +188,9 @@ export class CompileHandler { logger.info('Compilers created: ' + compilersCreated); if (this.awsProps) { logger.info('Fetching possible arguments from storage'); - await Promise.all(createdCompilers.map( - compiler => compiler.possibleArguments.loadFromStorage(this.awsProps))); + await Promise.all( + createdCompilers.map(compiler => compiler.possibleArguments.loadFromStorage(this.awsProps)), + ); } this.compilersById = compilersById; return createdCompilers.map(compiler => compiler.getInfo()); @@ -198,13 +200,11 @@ export class CompileHandler { } compilerAliasMatch(compiler, compilerId) { - return compiler.compiler.alias && - compiler.compiler.alias.includes(compilerId); + return compiler.compiler.alias && compiler.compiler.alias.includes(compilerId); } compilerIdOrAliasMatch(compiler, compilerId) { - return (compiler.compiler.id === compilerId) || - this.compilerAliasMatch(compiler, compilerId); + return compiler.compiler.id === compilerId || this.compilerAliasMatch(compiler, compilerId); } findCompiler(langId, compilerId) { @@ -267,7 +267,13 @@ export class CompileHandler { } parseRequest(req, compiler) { - let source, options, backendOptions = {}, filters, bypassCache = false, tools, executionParameters = {}; + let source, + options, + backendOptions = {}, + filters, + bypassCache = false, + tools, + executionParameters = {}; let libraries = []; // IF YOU MODIFY ANYTHING HERE PLEASE UPDATE THE DOCUMENTATION! if (req.is('json')) { @@ -275,27 +281,25 @@ export class CompileHandler { this.checkRequestRequirements(req); const requestOptions = req.body.options; source = req.body.source; - if (req.body.bypassCache) - bypassCache = true; + if (req.body.bypassCache) bypassCache = true; options = requestOptions.userArguments; const execParams = requestOptions.executeParameters || {}; executionParameters.args = execParams.args; executionParameters.stdin = execParams.stdin; backendOptions = requestOptions.compilerOptions || {}; - filters = {...(compiler.getDefaultFilters()), ...requestOptions.filters}; + filters = {...compiler.getDefaultFilters(), ...requestOptions.filters}; tools = requestOptions.tools; libraries = requestOptions.libraries || []; } else if (req.body && req.body.compiler) { source = req.body.source; - if (req.body.bypassCache) - bypassCache = true; + if (req.body.bypassCache) bypassCache = true; options = req.body.userArguments; executionParameters.args = req.body.executeParametersArgs; executionParameters.stdin = req.body.executeParametersStdin; filters = compiler.getDefaultFilters(); _.each(filters, (value, item) => { - filters[item] = (req.body[item] === 'true'); + filters[item] = req.body[item] === 'true'; }); backendOptions.skipAsm = req.body.skipAsm === 'true'; @@ -348,7 +352,7 @@ export class CompileHandler { getUsedOptions(req) { if (req.body) { - const data = (typeof req.body === 'string') ? JSON.parse(req.body) : req.body; + const data = typeof req.body === 'string' ? JSON.parse(req.body) : req.body; if (data.presplit) { return data.usedOptions; @@ -391,13 +395,16 @@ export class CompileHandler { this.cmakeCounter.inc({language: compiler.lang.id}); const options = this.parseRequest(req, compiler); - compiler.cmake(req.body.files, options).then(result => { - if (result.didExecute || (result.execResult && result.execResult.didExecute)) - this.cmakeExecuteCounter.inc({language: compiler.lang.id}); - res.send(result); - }).catch(e => { - return this.handleApiError(e, res, next); - }); + compiler + .cmake(req.body.files, options) + .then(result => { + if (result.didExecute || (result.execResult && result.execResult.didExecute)) + this.cmakeExecuteCounter.inc({language: compiler.lang.id}); + res.send(result); + }) + .catch(e => { + return this.handleApiError(e, res, next); + }); } catch (e) { return this.handleApiError(e, res, next); } @@ -425,10 +432,8 @@ export class CompileHandler { return this.handleApiError(error, res, next); } - const { - source, options, backendOptions, filters, - bypassCache, tools, executionParameters, libraries, - } = parsedRequest; + const {source, options, backendOptions, filters, bypassCache, tools, executionParameters, libraries} = + parsedRequest; let files; if (req.body.files) files = req.body.files; @@ -444,8 +449,18 @@ export class CompileHandler { this.compileCounter.inc({language: compiler.lang.id}); // eslint-disable-next-line promise/catch-or-return - compiler.compile(source, options, backendOptions, filters, bypassCache, tools, executionParameters, libraries, - files) + compiler + .compile( + source, + options, + backendOptions, + filters, + bypassCache, + tools, + executionParameters, + libraries, + files, + ) .then( result => { if (result.didExecute || (result.execResult && result.execResult.didExecute)) @@ -478,13 +493,13 @@ export class CompileHandler { } }, error => { - if (typeof (error) !== 'string') { + if (typeof error !== 'string') { if (error.stack) { logger.error('Error during compilation: ', error); Sentry.captureException(error); } else if (error.code) { logger.error('Error during compilation: ', error.code); - if (typeof (error.stderr) === 'string') { + if (typeof error.stderr === 'string') { error.stdout = utils.parseOutput(error.stdout); error.stderr = utils.parseOutput(error.stderr); } @@ -499,7 +514,8 @@ export class CompileHandler { logger.error('Error during compilation: ', {error}); } res.end(JSON.stringify({code: -1, stderr: [{text: error}]})); - }); + }, + ); } } diff --git a/lib/handlers/formatting.js b/lib/handlers/formatting.js index bd64fadce..5470c10a6 100644 --- a/lib/handlers/formatting.js +++ b/lib/handlers/formatting.js @@ -25,8 +25,8 @@ import _ from 'underscore'; import * as exec from '../exec'; -import { getFormatterTypeByKey } from '../formatters'; -import { logger } from '../logger'; +import {getFormatterTypeByKey} from '../formatters'; +import {logger} from '../logger'; export class FormattingHandler { constructor(ceProps) { @@ -57,7 +57,9 @@ export class FormattingHandler { // If there is an explicit version, grab it. Otherwise try to filter the output const version = hasExplicitVersion ? this.ceProps(`formatter.${formatter}.explicitVersion`) - : (match ? match[0] : result.stdout); + : match + ? match[0] + : result.stdout; this.formatters[formatter] = new formatterClass({ name: this.ceProps(`formatter.${formatter}.name`, exe), exe, diff --git a/lib/handlers/health-check.js b/lib/handlers/health-check.js index f9cd771ae..179aaf936 100644 --- a/lib/handlers/health-check.js +++ b/lib/handlers/health-check.js @@ -25,7 +25,7 @@ import * as Sentry from '@sentry/node'; import fs from 'fs-extra'; -import { logger } from '../logger'; +import {logger} from '../logger'; export class HealthCheckHandler { constructor(compilationQueue, filePath) { diff --git a/lib/handlers/noscript.js b/lib/handlers/noscript.js index df1c46ca8..6daaef7d0 100644 --- a/lib/handlers/noscript.js +++ b/lib/handlers/noscript.js @@ -25,9 +25,9 @@ import bodyParser from 'body-parser'; import _ from 'underscore'; -import { ClientState } from '../clientstate'; -import { ClientStateNormalizer } from '../clientstate-normalizer'; -import { logger } from '../logger'; +import {ClientState} from '../clientstate'; +import {ClientStateNormalizer} from '../clientstate-normalizer'; +import {logger} from '../logger'; function isMobileViewer(req) { return req.header('CloudFront-Is-Mobile-Viewer') === 'true'; @@ -63,10 +63,16 @@ export class NoScriptHandler { .get('/noscript/sponsors', (req, res) => { this.staticHeaders(res); this.contentPolicyHeader(res); - res.render('noscript/sponsors', this.renderConfig({ - embedded: false, - mobileViewer: isMobileViewer(req), - }, req.query)); + res.render( + 'noscript/sponsors', + this.renderConfig( + { + embedded: false, + mobileViewer: isMobileViewer(req), + }, + req.query, + ), + ); }) .get('/noscript/:language', (req, res) => { this.staticHeaders(res); @@ -78,7 +84,8 @@ export class NoScriptHandler { storedStateHandlerNoScript(req, res, next) { const id = req.params.id; - this.storageHandler.expandId(id) + this.storageHandler + .expandId(id) .then(result => { const config = JSON.parse(result.config); @@ -145,12 +152,18 @@ export class NoScriptHandler { state = this.createDefaultState(wantedLanguage); } - res.render('noscript/index', this.renderConfig({ - embedded: false, - mobileViewer: isMobileViewer(req), - wantedLanguage: wantedLanguage, - clientstate: state, - storedStateId: req.params.id ? req.params.id : false, - }, req.query)); + res.render( + 'noscript/index', + this.renderConfig( + { + embedded: false, + mobileViewer: isMobileViewer(req), + wantedLanguage: wantedLanguage, + clientstate: state, + storedStateId: req.params.id ? req.params.id : false, + }, + req.query, + ), + ); } } diff --git a/lib/handlers/route-api.js b/lib/handlers/route-api.js index 0dd03edd5..106061a51 100644 --- a/lib/handlers/route-api.js +++ b/lib/handlers/route-api.js @@ -22,12 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { ClientState } from '../clientstate'; -import { ClientStateGoldenifier, ClientStateNormalizer } from '../clientstate-normalizer'; -import { logger } from '../logger'; +import {ClientState} from '../clientstate'; +import {ClientStateGoldenifier, ClientStateNormalizer} from '../clientstate-normalizer'; +import {logger} from '../logger'; import * as utils from '../utils'; -import { ApiHandler } from './api'; +import {ApiHandler} from './api'; export class RouteAPI { constructor(router, config) { @@ -38,8 +38,12 @@ export class RouteAPI { // if for testing purposes if (config.compileHandler) { - this.apiHandler = new ApiHandler(config.compileHandler, config.ceProps, config.storageHandler, - config.clientOptionsHandler.options.urlShortenService); + this.apiHandler = new ApiHandler( + config.compileHandler, + config.ceProps, + config.storageHandler, + config.clientOptionsHandler.options.urlShortenService, + ); this.apiHandler.setReleaseInfo(config.defArgs.gitReleaseName, config.defArgs.releaseBuildNumber); } @@ -58,7 +62,8 @@ export class RouteAPI { storedCodeHandler(req, res, next) { const id = req.params.id; const sessionid = parseInt(req.params.session); - this.storageHandler.expandId(id) + this.storageHandler + .expandId(id) .then(result => { const config = JSON.parse(result.config); @@ -89,7 +94,8 @@ export class RouteAPI { storedStateHandler(req, res, next) { const id = req.params.id; - this.storageHandler.expandId(id) + this.storageHandler + .expandId(id) .then(result => { let config = JSON.parse(result.config); if (config.sessions) { @@ -148,7 +154,8 @@ export class RouteAPI { storedStateHandlerResetLayout(req, res, next) { const id = req.params.id; - this.storageHandler.expandId(id) + this.storageHandler + .expandId(id) .then(result => { let config = JSON.parse(result.config); @@ -174,9 +181,7 @@ export class RouteAPI { } escapeLine(req, line) { - return line.replace(/&/g, '&') - .replace(//g, '>'); + return line.replace(/&/g, '&').replace(//g, '>'); } filterCode(req, code, lang) { @@ -184,9 +189,7 @@ export class RouteAPI { if (lang.previewFilter) { lines = lines.filter(line => !lang.previewFilter.test(line)); } - return lines - .map(line => this.escapeLine(req, line)) - .join('\n'); + return lines.map(line => this.escapeLine(req, line)).join('\n'); } getMetaDataFromLink(req, link, config) { @@ -221,7 +224,7 @@ export class RouteAPI { lang = this.apiHandler.languages[tree.compilerLanguageId]; if (!tree.isCMakeProject) { - const firstSource = tree.files.find((file) => { + const firstSource = tree.files.find(file => { return file.filename.startsWith('example.'); }); @@ -229,7 +232,7 @@ export class RouteAPI { source = firstSource.content; } } else { - const firstSource = tree.files.find((file) => { + const firstSource = tree.files.find(file => { return file.filename.startsWith('CMakeLists.txt'); }); @@ -253,7 +256,6 @@ export class RouteAPI { } else { metadata.ogDescription = source; } - } else if (metadata.ogAuthor && metadata.ogAuthor !== '.') { metadata.ogDescription += `\nAuthor(s): ${metadata.ogAuthor}`; } diff --git a/lib/handlers/source.js b/lib/handlers/source.js index 8e5ebfbab..b07f0321d 100644 --- a/lib/handlers/source.js +++ b/lib/handlers/source.js @@ -47,12 +47,13 @@ export class SourceHandler { next(); return; } - handlerAction.apply(handlerAction, bits.slice(3)) - .then((response) => { + handlerAction + .apply(handlerAction, bits.slice(3)) + .then(response => { this.addStaticHeaders(res); res.send(response); }) - .catch((err) => { + .catch(err => { res.send({err: err}); }); } diff --git a/lib/instructionsets.js b/lib/instructionsets.js index 874c48ec7..c6f5b209b 100644 --- a/lib/instructionsets.js +++ b/lib/instructionsets.js @@ -81,7 +81,7 @@ export class InstructionSets { } async getCompilerInstructionSetHint(compilerArch, exe) { - return new Promise((resolve) => { + return new Promise(resolve => { if (compilerArch) { _.each(this.supported, (method, instructionSet) => { for (let target of method.target) { diff --git a/lib/keyed-type.js b/lib/keyed-type.js index 806ceeeec..08f02f0c8 100644 --- a/lib/keyed-type.js +++ b/lib/keyed-type.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { logger } from './logger'; +import {logger} from './logger'; function makeKeyMap(typeName, objects) { const keyToNameMap = {}; @@ -54,8 +54,7 @@ function makeKeyMap(typeName, objects) { * Once done, we throw to halt instance startup so the logs don't * get lost in a wall of text. */ - if (haveErrors) - throw new Error(`${typeName} KeyedType configuration error`); + if (haveErrors) throw new Error(`${typeName} KeyedType configuration error`); return keyToTypeMap; } diff --git a/lib/languages.js b/lib/languages.js index b4115d705..5c50dee34 100644 --- a/lib/languages.js +++ b/lib/languages.js @@ -199,7 +199,7 @@ export const languages = { analysis: { name: 'Analysis', monaco: 'asm', - extensions: ['.asm'], // maybe add more? Change to a unique one? + extensions: ['.asm'], // maybe add more? Change to a unique one? alias: ['tool', 'tools'], }, cuda: { diff --git a/lib/llvm-ir.js b/lib/llvm-ir.js index cf7a8c62a..adb209f9a 100644 --- a/lib/llvm-ir.js +++ b/lib/llvm-ir.js @@ -143,7 +143,7 @@ export class LlvmIrParser { match = line.match(this.debugReference); if (match) { result.push({ - text: (filters.trim ? utils.squashHorizontalWhitespace(line) : line), + text: filters.trim ? utils.squashHorizontalWhitespace(line) : line, source: source, scope: match[1], }); @@ -159,7 +159,7 @@ export class LlvmIrParser { if (filters.directives && this.isLineLlvmDirective(line)) { continue; } - result.push({text: (filters.trim ? utils.squashHorizontalWhitespace(line) : line), source: source}); + result.push({text: filters.trim ? utils.squashHorizontalWhitespace(line) : line, source: source}); prevLineEmpty = false; } @@ -194,11 +194,13 @@ export class LlvmIrParser { } isLineLlvmDirective(line) { - return !!(/^!\d+ = (distinct )?!(DI|{)/.test(line) - || line.startsWith('!llvm') - || line.startsWith('source_filename = ') - || line.startsWith('target datalayout = ') - || line.startsWith('target triple = ')); + return !!( + /^!\d+ = (distinct )?!(DI|{)/.test(line) || + line.startsWith('!llvm') || + line.startsWith('source_filename = ') || + line.startsWith('target datalayout = ') || + line.startsWith('target triple = ') + ); } isLlvmIr(code) { diff --git a/lib/mapfiles/map-file-delphi.js b/lib/mapfiles/map-file-delphi.js index d065cf301..1465a9cd5 100644 --- a/lib/mapfiles/map-file-delphi.js +++ b/lib/mapfiles/map-file-delphi.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { MapFileReader } from './map-file'; +import {MapFileReader} from './map-file'; export class MapFileReaderDelphi extends MapFileReader { /** @@ -35,7 +35,8 @@ export class MapFileReaderDelphi extends MapFileReader { this.regexDelphiCodeSegmentOffset = /^\s([\da-f]*):([\da-f]*)\s*([\da-f]*)h\s*(\.[$a-z]*)\s*([a-z]*)$/i; this.regexDelphiCodeSegment = /^\s([\da-f]*):([\da-f]*)\s*([\da-f]*)\s*c=code\s*s=.text\s*g=.*m=([\w.]*)\s.*/i; - this.regexDelphiICodeSegment = /^\s([\da-f]*):([\da-f]*)\s*([\da-f]*)\s*c=icode\s*s=.itext\s*g=.*m=([\w.]*)\s.*/i; + this.regexDelphiICodeSegment = + /^\s([\da-f]*):([\da-f]*)\s*([\da-f]*)\s*c=icode\s*s=.itext\s*g=.*m=([\w.]*)\s.*/i; this.regexDelphiNames = /^\s([\da-f]*):([\da-f]*)\s*([\w$.<>@{}]*)$/i; this.regexDelphiLineNumbersStart = /line numbers for (.*)\(.*\) segment \.text/i; this.regexDelphiLineNumber = /^(\d*)\s([\da-f]*):([\da-f]*)/i; @@ -56,7 +57,7 @@ export class MapFileReaderDelphi extends MapFileReader { let codesegmentObject = false; let matches = line.match(this.regexDelphiCodeSegmentOffset); - if (matches && !matches[4].includes('$') && (parseInt(matches[2], 16) >= this.preferredLoadAddress)) { + if (matches && !matches[4].includes('$') && parseInt(matches[2], 16) >= this.preferredLoadAddress) { const addressWithOffset = parseInt(matches[2], 16); this.segmentOffsets.push({ segment: matches[1], @@ -92,7 +93,7 @@ export class MapFileReaderDelphi extends MapFileReader { } else { codesegmentObject.unitName = codesegmentObject.unitName + '.pas'; } - + this.isegments.push(codesegmentObject); } } @@ -136,7 +137,7 @@ export class MapFileReaderDelphi extends MapFileReader { tryReadingLineNumbers(line) { let hasLineNumbers = false; - const references = line.split(' '); // 4 spaces + const references = line.split(' '); // 4 spaces for (const reference of references) { const matches = reference.match(this.regexDelphiLineNumber); if (matches) { diff --git a/lib/mapfiles/map-file-vs.js b/lib/mapfiles/map-file-vs.js index 0619bebb7..49a3ebd98 100644 --- a/lib/mapfiles/map-file-vs.js +++ b/lib/mapfiles/map-file-vs.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { MapFileReader } from './map-file'; +import {MapFileReader} from './map-file'; export class MapFileReaderVS extends MapFileReader { /** @@ -82,7 +82,7 @@ export class MapFileReaderVS extends MapFileReader { let symbolObject = false; const matches = line.match(this.regexVsNames); - if (matches && (matches.length >= 7) && (matches[4] !== '')) { + if (matches && matches.length >= 7 && matches[4] !== '') { const addressWithOffset = parseInt(matches[4], 16); symbolObject = { segment: matches[1], @@ -99,7 +99,8 @@ export class MapFileReaderVS extends MapFileReader { const segment = this.getSegmentInfoAddressWithoutOffsetIsIn( symbolObject.segment, - symbolObject.addressWithoutOffset); + symbolObject.addressWithoutOffset, + ); if (segment && !segment.unitName) { segment.unitName = matches[6]; } diff --git a/lib/mapfiles/map-file.js b/lib/mapfiles/map-file.js index e9f660c5c..ca7991694 100644 --- a/lib/mapfiles/map-file.js +++ b/lib/mapfiles/map-file.js @@ -69,9 +69,9 @@ export class MapFileReader { getLineInfoByAddress(segment, address) { for (let idx = 0; idx < this.lineNumbers.length; idx++) { const lineInfo = this.lineNumbers[idx]; - if (!segment && (lineInfo.addressInt === address)) { + if (!segment && lineInfo.addressInt === address) { return lineInfo; - } else if ((segment === lineInfo.segment) && (lineInfo.addressWithoutOffset === address)) { + } else if (segment === lineInfo.segment && lineInfo.addressWithoutOffset === address) { return lineInfo; } } @@ -189,9 +189,9 @@ export class MapFileReader { getSegmentInfoByStartingAddress(segment, address) { for (let idx = 0; idx < this.segments.length; idx++) { const info = this.segments[idx]; - if (!segment && (info.addressInt === address)) { + if (!segment && info.addressInt === address) { return info; - } else if ((info.segment === segment) && (info.addressWithoutOffset === address)) { + } else if (info.segment === segment && info.addressWithoutOffset === address) { return info; } } @@ -209,11 +209,13 @@ export class MapFileReader { getSegmentInfoAddressIsIn(segment, address) { for (let idx = 0; idx < this.segments.length; idx++) { const info = this.segments[idx]; - if (!segment && (address >= info.addressInt) && (address < (info.addressInt + info.segmentLength))) { + if (!segment && address >= info.addressInt && address < info.addressInt + info.segmentLength) { return info; - } else if ((segment === info.segment) && - (address >= info.addressWithoutOffset) && - (address < (info.addressWithoutOffset + info.segmentLength))) { + } else if ( + segment === info.segment && + address >= info.addressWithoutOffset && + address < info.addressWithoutOffset + info.segmentLength + ) { return info; } } @@ -231,9 +233,11 @@ export class MapFileReader { getSegmentInfoAddressWithoutOffsetIsIn(segment, address) { for (let idx = 0; idx < this.segments.length; idx++) { const info = this.segments[idx]; - if ((segment === info.segment) && - (address >= info.addressWithoutOffset) && - (address < (info.addressWithoutOffset + info.segmentLength))) { + if ( + segment === info.segment && + address >= info.addressWithoutOffset && + address < info.addressWithoutOffset + info.segmentLength + ) { return info; } } @@ -250,9 +254,9 @@ export class MapFileReader { getSymbolAt(segment, address) { for (let idx = 0; idx < this.namedAddresses.length; idx++) { const info = this.namedAddresses[idx]; - if (!segment && (info.addressInt === address)) { + if (!segment && info.addressInt === address) { return info; - } else if ((segment === info.segment) && (info.addressWithoutOffset === address)) { + } else if (segment === info.segment && info.addressWithoutOffset === address) { return info; } } @@ -271,12 +275,12 @@ export class MapFileReader { for (let idx = 0; idx < this.namedAddresses.length; idx++) { const info = this.namedAddresses[idx]; - if (!segment && (info.addressInt <= address)) { - if (!maxNamed || (info.addressInt > maxNamed.addressInt)) { + if (!segment && info.addressInt <= address) { + if (!maxNamed || info.addressInt > maxNamed.addressInt) { maxNamed = info; } - } else if ((segment === info.segment) && (info.addressWithoutOffset <= address)) { - if (!maxNamed || (info.addressInt > maxNamed.addressInt)) { + } else if (segment === info.segment && info.addressWithoutOffset <= address) { + if (!maxNamed || info.addressInt > maxNamed.addressInt) { maxNamed = info; } } @@ -324,8 +328,7 @@ export class MapFileReader { * @param {string} line */ // eslint-disable-next-line no-unused-vars - tryReadingNamedAddress(line) { - } + tryReadingNamedAddress(line) {} /** * Tries to match the given line to code segment information. @@ -334,8 +337,7 @@ export class MapFileReader { * @param {string} line */ // eslint-disable-next-line no-unused-vars - tryReadingCodeSegmentInfo(line) { - } + tryReadingCodeSegmentInfo(line) {} /** * @@ -356,8 +358,7 @@ export class MapFileReader { * @param {string} line */ // eslint-disable-next-line no-unused-vars - tryReadingPreferredAddress(line) { - } + tryReadingPreferredAddress(line) {} /** * Retreives line number references from supplied Map line @@ -393,7 +394,7 @@ export class MapFileReader { if (!currentUnit) { addressStart = symbolObject.addressInt; currentUnit = symbolObject.unitName; - } else if ((symbolObject.unitName !== currentUnit)) { + } else if (symbolObject.unitName !== currentUnit) { const segmentLen = symbolObject.addressInt - addressStart; this.reconstructedSegments.push({ @@ -453,11 +454,10 @@ export class MapFileReader { */ isWithinAddressSpace(spaces, address, size) { for (const spaceAddress of spaces) { - - if (((address >= spaceAddress.startAddress) && - (address < spaceAddress.endAddress)) || - ((address < spaceAddress.startAddress) && - (address + size >= spaceAddress.startAddress))) { + if ( + (address >= spaceAddress.startAddress && address < spaceAddress.endAddress) || + (address < spaceAddress.startAddress && address + size >= spaceAddress.startAddress) + ) { return true; } } diff --git a/lib/metrics-server.ts b/lib/metrics-server.ts index eb8debc5d..23177cbb0 100644 --- a/lib/metrics-server.ts +++ b/lib/metrics-server.ts @@ -13,9 +13,12 @@ export function setupMetricsServer(serverPort: number, hostname: string): void { const metricsServer = express(); metricsServer.get('/metrics', (req, res) => { - PromClient.register.metrics() - .then(metrics => { res.header('Content-Type', PromClient.register.contentType).send(metrics); }) - .catch(err => res.status(500).send(err)); + PromClient.register + .metrics() + .then(metrics => { + res.header('Content-Type', PromClient.register.contentType).send(metrics); + }) + .catch(err => res.status(500).send(err)); }); metricsServer.listen(serverPort, hostname); diff --git a/lib/objdumper/_all.js b/lib/objdumper/_all.js index 4b6750a17..1a39dbec0 100644 --- a/lib/objdumper/_all.js +++ b/lib/objdumper/_all.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { BinutilsObjdumper } from './binutils'; -export { DefaultObjdumper } from './default'; -export { ElfToolChainObjdumper } from './elftoolchain'; -export { LlvmObjdumper } from './llvm'; +export {BinutilsObjdumper} from './binutils'; +export {DefaultObjdumper} from './default'; +export {ElfToolChainObjdumper} from './elftoolchain'; +export {LlvmObjdumper} from './llvm'; diff --git a/lib/objdumper/binutils.js b/lib/objdumper/binutils.js index 9923d51bf..da85d9797 100644 --- a/lib/objdumper/binutils.js +++ b/lib/objdumper/binutils.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseObjdumper } from './base'; +import {BaseObjdumper} from './base'; export class BinutilsObjdumper extends BaseObjdumper { - static get key() { return 'binutils'; } + static get key() { + return 'binutils'; + } constructor() { super(); diff --git a/lib/objdumper/default.js b/lib/objdumper/default.js index 5dec96940..c89ca48d8 100644 --- a/lib/objdumper/default.js +++ b/lib/objdumper/default.js @@ -22,8 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BinutilsObjdumper } from './binutils'; +import {BinutilsObjdumper} from './binutils'; export class DefaultObjdumper extends BinutilsObjdumper { - static get key() { return 'default'; } + static get key() { + return 'default'; + } } diff --git a/lib/objdumper/elftoolchain.js b/lib/objdumper/elftoolchain.js index c6d86636a..d6d5221b6 100644 --- a/lib/objdumper/elftoolchain.js +++ b/lib/objdumper/elftoolchain.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseObjdumper } from './base'; +import {BaseObjdumper} from './base'; export class ElfToolChainObjdumper extends BaseObjdumper { - static get key() { return 'elftoolchain'; } + static get key() { + return 'elftoolchain'; + } constructor() { super(); diff --git a/lib/objdumper/index.js b/lib/objdumper/index.js index 6011df79b..791d8a500 100644 --- a/lib/objdumper/index.js +++ b/lib/objdumper/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BaseObjdumper } from './base'; +export {BaseObjdumper} from './base'; export * from './_all'; export const getObjdumperTypeByKey = makeKeyedTypeGetter('objdumper', all); diff --git a/lib/objdumper/llvm.js b/lib/objdumper/llvm.js index dba2d45be..93e73bc4a 100644 --- a/lib/objdumper/llvm.js +++ b/lib/objdumper/llvm.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseObjdumper } from './base'; +import {BaseObjdumper} from './base'; export class LlvmObjdumper extends BaseObjdumper { - static get key() { return 'llvm'; } + static get key() { + return 'llvm'; + } constructor() { super(); diff --git a/lib/packager.js b/lib/packager.js index e897f0afb..b2c33fb73 100644 --- a/lib/packager.js +++ b/lib/packager.js @@ -31,36 +31,42 @@ export class Packager { unpack(packageFile, destination) { return new Promise((resolve, reject) => { - tarGzip.decompress({ - source: packageFile, - destination: destination, - }, (err) => { - if (err) { - reject(err); - } else { - resolve(destination); - } - }); + tarGzip.decompress( + { + source: packageFile, + destination: destination, + }, + err => { + if (err) { + reject(err); + } else { + resolve(destination); + } + }, + ); }); } tarGzFiles(cwd, destination) { return new Promise((resolve, reject) => { - tarGzip.compress({ - source: cwd, - destination: destination, - level: 6, - memLevel: 6, - options: { - dereference: true, + tarGzip.compress( + { + source: cwd, + destination: destination, + level: 6, + memLevel: 6, + options: { + dereference: true, + }, }, - }, (err) => { - if (err) { - reject(err); - } else { - resolve(destination); - } - }); + err => { + if (err) { + reject(err); + } else { + resolve(destination); + } + }, + ); }); } } diff --git a/lib/parsers/asm-parser-amdgpu.js b/lib/parsers/asm-parser-amdgpu.js index 12c0236f0..285919a62 100644 --- a/lib/parsers/asm-parser-amdgpu.js +++ b/lib/parsers/asm-parser-amdgpu.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AsmParser } from './asm-parser'; +import {AsmParser} from './asm-parser'; export class AmdgpuAsmParser extends AsmParser { constructor() { diff --git a/lib/parsers/asm-parser-crystal.js b/lib/parsers/asm-parser-crystal.js index 4c4b06eea..8cd0b72f2 100644 --- a/lib/parsers/asm-parser-crystal.js +++ b/lib/parsers/asm-parser-crystal.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AsmParser } from './asm-parser'; +import {AsmParser} from './asm-parser'; export class CrystalAsmParser extends AsmParser { constructor() { diff --git a/lib/parsers/asm-parser-dart.js b/lib/parsers/asm-parser-dart.js index 840f41ba2..d4284bb05 100644 --- a/lib/parsers/asm-parser-dart.js +++ b/lib/parsers/asm-parser-dart.js @@ -117,7 +117,7 @@ export class DartAsmParser extends AsmParser { // note: normally the source.file will be null if it's code from example.ext // but with filters.dontMaskFilenames it will be filled with the actual filename // instead we can test source.mainsource in that situation - const isMainsource = source && ((source.file === null) || source.mainsource); + const isMainsource = source && (source.file === null || source.mainsource); if (isMainsource) { mayRemovePreviousLabel = false; } diff --git a/lib/parsers/asm-parser-dotnet.ts b/lib/parsers/asm-parser-dotnet.ts index 9810e3855..acc8c8574 100644 --- a/lib/parsers/asm-parser-dotnet.ts +++ b/lib/parsers/asm-parser-dotnet.ts @@ -24,12 +24,12 @@ import * as utils from '../utils'; -type InlineLabel = { name: string, range: { startCol: number, endCol: number } }; -type Source = { file: string, line: number }; +type InlineLabel = {name: string; range: {startCol: number; endCol: number}}; +type Source = {file: string; line: number}; export class DotNetAsmParser { scanLabelsAndMethods(asmLines: string[], removeUnused: boolean) { - const labelDef: Record = {}; + const labelDef: Record = {}; const methodDef: Record = {}; const labelUsage: Record = {}; const methodUsage: Record = {}; @@ -47,8 +47,7 @@ export class DotNetAsmParser { if (trimmedLine.includes('(')) { methodDef[line] = trimmedLine.substring(0, trimmedLine.length - 1); allAvailable.push(methodDef[line]); - } - else { + } else { labelDef[line] = { name: trimmedLine.substring(0, trimmedLine.length - 1), remove: false, @@ -64,7 +63,7 @@ export class DotNetAsmParser { const index = asmLines[line].indexOf(name) + 1; labelUsage[line] = { name: labelResult.value[1], - range: { startCol: index, endCol: index + name.length }, + range: {startCol: index, endCol: index + name.length}, }; usedLabels.push(labelResult.value[1]); } @@ -76,7 +75,7 @@ export class DotNetAsmParser { const index = asmLines[line].indexOf(name) + 1; methodUsage[line] = { name: methodResult.value[1], - range: { startCol: index, endCol: index + name.length }, + range: {startCol: index, endCol: index + name.length}, }; } } @@ -125,9 +124,9 @@ export class DotNetAsmParser { const startTime = process.hrtime.bigint(); const asm: { - text: string, - source: Source | null, - labels: InlineLabel[], + text: string; + source: Source | null; + labels: InlineLabel[]; }[] = []; let labelDefinitions: [string, number][] = []; @@ -136,7 +135,7 @@ export class DotNetAsmParser { if (filters.commentOnly) { const commentRe = /^\s*(;.*)$/g; - asmLines = asmLines.flatMap(l => commentRe.test(l) ? [] : [l]); + asmLines = asmLines.flatMap(l => (commentRe.test(l) ? [] : [l])); } const result = this.scanLabelsAndMethods(asmLines, filters.labels); @@ -170,11 +169,10 @@ export class DotNetAsmParser { } let lineOffset = 1; - labelDefinitions = labelDefinitions.sort((a, b) => a[1] < b[1] ? -1 : 1); + labelDefinitions = labelDefinitions.sort((a, b) => (a[1] < b[1] ? -1 : 1)); for (const index in labelDefinitions) { - if (result.labelDef[labelDefinitions[index][1]] && - result.labelDef[labelDefinitions[index][1]].remove) { + if (result.labelDef[labelDefinitions[index][1]] && result.labelDef[labelDefinitions[index][1]].remove) { labelDefinitions[index][1] = -1; lineOffset--; continue; diff --git a/lib/parsers/asm-parser-ewavr.js b/lib/parsers/asm-parser-ewavr.js index 46f611652..831e9cc86 100644 --- a/lib/parsers/asm-parser-ewavr.js +++ b/lib/parsers/asm-parser-ewavr.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; -import { AsmParser } from './asm-parser'; -import { AsmRegex } from './asmregex'; +import {AsmParser} from './asm-parser'; +import {AsmRegex} from './asmregex'; export class AsmEWAVRParser extends AsmParser { constructor(compilerProps) { @@ -107,9 +107,9 @@ export class AsmEWAVRParser extends AsmParser { // ; file: string option // ; require: string array } let resultObject = { - prefix: [], // line array - labels: [], // label array - postfix: [], // line array + prefix: [], // line array + labels: [], // label array + postfix: [], // line array }; let currentLabel = null; // func option @@ -125,15 +125,15 @@ export class AsmEWAVRParser extends AsmParser { const createsData = line.match(this.dataStatement); if ((hasopc || createsData) && (currentFile || currentLine)) { return { - file: (currentFile ? currentFile : null), - line: (currentLine ? currentLine : null), + file: currentFile ? currentFile : null, + line: currentLine ? currentLine : null, }; } return null; }; - const checkBeginLabel = (line) => { + const checkBeginLabel = line => { const matches = line.match(this.labelDef); if (matches) { currentLabel = { @@ -142,18 +142,18 @@ export class AsmEWAVRParser extends AsmParser { name: matches[1], file: currentFile, }; - definedLabels[matches[1]] = currentLine; + definedLabels[matches[1]] = currentLine; resultObject.labels.push(currentLabel); } }; - const checkRequiresStatement = (line) => { + const checkRequiresStatement = line => { const matches = line.match(this.requireStatement); if (matches && currentLabel != null) { if (currentLabel.require != null) { currentLabel.require.push(matches[1]); } else { - currentLabel.require = [ matches[1] ]; + currentLabel.require = [matches[1]]; } } }; @@ -171,11 +171,9 @@ export class AsmEWAVRParser extends AsmParser { const emptyLine = {text: '', source: null}; if (seenEnd) { resultObject.postfix.push(emptyLine); - } - else if (currentLabel === null) { + } else if (currentLabel === null) { resultObject.prefix.push(emptyLine); - } - else { + } else { currentLabel.lines.push(emptyLine); } continue; @@ -200,8 +198,7 @@ export class AsmEWAVRParser extends AsmParser { tmp = getLineNumberFromComment(line); if (tmp !== null) { if (currentFile === undefined) { - logger.error('Somehow, we have a line number comment without a file comment: %s', - line); + logger.error('Somehow, we have a line number comment without a file comment: %s', line); } if (currentLabel != null && currentLabel.initialLine === undefined) { currentLabel.initialLine = tmp; @@ -217,14 +214,14 @@ export class AsmEWAVRParser extends AsmParser { continue; } - const shouldSkip = filters.directives && ( - line.match(this.segmentBegin) || - line.match(this.segmentControl) || - line.match(this.definesGlobal) || - line.match(this.definesLocal) || - line.match(this.miscDirective) || - line.match(this.requireStatement) - ); + const shouldSkip = + filters.directives && + (line.match(this.segmentBegin) || + line.match(this.segmentControl) || + line.match(this.definesGlobal) || + line.match(this.definesLocal) || + line.match(this.miscDirective) || + line.match(this.requireStatement)); if (shouldSkip) { continue; @@ -253,7 +250,7 @@ export class AsmEWAVRParser extends AsmParser { // - labels for variables, functions, and code fragments are all the same. // - One exception.. functions SEEM to always have a segment command // with a few lines before the label. is this reliable? - + // NOTES: compiler generated labels // 'Initializer for' is used to init variables. usually at end of file // 'Segment init:' is used to init sections. One per many 'Initializer for' labels. diff --git a/lib/parsers/asm-parser-sass.js b/lib/parsers/asm-parser-sass.js index 13f996219..e970a0d02 100644 --- a/lib/parsers/asm-parser-sass.js +++ b/lib/parsers/asm-parser-sass.js @@ -22,14 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AsmParser } from './asm-parser'; +import {AsmParser} from './asm-parser'; export class SassAsmParser extends AsmParser { constructor() { super(); // These are for parsing the output of nvdisasm. - this.asmOpcodeRe = /^\s*\/\*(?
[^*]+)\*\/()()\s*{?\s*(?[^;}]+)(?:}|;\s*\/\* 0x(?[\da-f]+) \*\/)/; + this.asmOpcodeRe = + /^\s*\/\*(?
[^*]+)\*\/()()\s*{?\s*(?[^;}]+)(?:}|;\s*\/\* 0x(?[\da-f]+) \*\/)/; this.lineRe = /^\s*\/\/## File "([^"]+)", line (?\d+)$/; this.labelRe = /^(?!\.text\.)()(\S[^:]+):$/; } diff --git a/lib/parsers/asm-parser-vc.js b/lib/parsers/asm-parser-vc.js index 7ba44ee87..874d14886 100644 --- a/lib/parsers/asm-parser-vc.js +++ b/lib/parsers/asm-parser-vc.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; -import { AsmParser } from './asm-parser'; -import { AsmRegex } from './asmregex'; +import {AsmParser} from './asm-parser'; +import {AsmRegex} from './asmregex'; export class VcAsmParser extends AsmParser { constructor(compilerProps) { @@ -37,7 +37,8 @@ export class VcAsmParser extends AsmParser { this.commentOnly = /^;/; this.filenameComment = /^; File (.+)/; this.lineNumberComment = /^; Line (\d+)/; - this.beginSegment = /^(CONST|_BSS|\.?[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|\.?text(\$[A-Za-z]+)?)\s+SEGMENT|\s*AREA/; + this.beginSegment = + /^(CONST|_BSS|\.?[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|\.?text(\$[A-Za-z]+)?)\s+SEGMENT|\s*AREA/; this.endSegment = /^(CONST|_BSS|[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|text(\$[A-Za-z]+)?)\s+ENDS/; this.beginFunction = /^; Function compile flags: /; this.endProc = /^([$?@A-Z_a-z][\w$<>?@]*)?\s+ENDP/; @@ -120,9 +121,9 @@ export class VcAsmParser extends AsmParser { // ; initialLine: int // ; file: string option | undefined } let resultObject = { - prefix: [], // line array + prefix: [], // line array functions: [], // func array - postfix: null, // line? + postfix: null, // line? }; let currentFunction = null; // func option @@ -137,15 +138,15 @@ export class VcAsmParser extends AsmParser { const createSourceFor = (hasopc, currentFile, currentLine) => { if (hasopc && (currentFile || currentLine)) { return { - file: (currentFile ? currentFile : null), - line: (currentLine ? currentLine : null), + file: currentFile ? currentFile : null, + line: currentLine ? currentLine : null, }; } return null; }; - const checkUsedDatadefLabels = (line) => { + const checkUsedDatadefLabels = line => { const labels = line.match(this.labelFind); if (!labels) return; labels.splice(0, 1); @@ -156,7 +157,7 @@ export class VcAsmParser extends AsmParser { } }; - const checkBeginFunction = (line) => { + const checkBeginFunction = line => { if (this.beginFunction.test(line)) { currentFunction = { lines: [], @@ -168,7 +169,7 @@ export class VcAsmParser extends AsmParser { } }; - const checkForDdefLabel = (line) => { + const checkForDdefLabel = line => { const ddef = line.match(this.dataDefn); if (ddef && ddef[1]) { datadefLabels.push(ddef[1]); @@ -202,8 +203,7 @@ export class VcAsmParser extends AsmParser { let tmp = getFilenameFromComment(line); if (tmp !== null) { if (currentFunction === null) { - logger.error('We have a file comment outside of a function: %s', - line); + logger.error('We have a file comment outside of a function: %s', line); } // if the file is the "main file", give it the file `null` if (stdInLooking.test(tmp)) { @@ -218,8 +218,7 @@ export class VcAsmParser extends AsmParser { tmp = getLineNumberFromComment(line); if (tmp !== null) { if (currentFile === undefined) { - logger.error('Somehow, we have a line number comment without a file comment: %s', - line); + logger.error('Somehow, we have a line number comment without a file comment: %s', line); } if (currentFunction.initialLine === undefined) { currentFunction.initialLine = tmp; @@ -240,11 +239,12 @@ export class VcAsmParser extends AsmParser { if (filters.commentOnly && this.commentOnly.test(line)) continue; - const shouldSkip = filters.directives && ( - line.match(this.endSegment) || - line.match(this.definesGlobal) || - line.match(this.miscDirective) || - line.match(this.beginSegment)); + const shouldSkip = + filters.directives && + (line.match(this.endSegment) || + line.match(this.definesGlobal) || + line.match(this.miscDirective) || + line.match(this.beginSegment)); if (shouldSkip) { continue; diff --git a/lib/parsers/asm-parser-vc6.js b/lib/parsers/asm-parser-vc6.js index a2cc4cf84..01b6883c6 100644 --- a/lib/parsers/asm-parser-vc6.js +++ b/lib/parsers/asm-parser-vc6.js @@ -22,23 +22,26 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; -import { AsmParser } from './asm-parser'; -import { AsmRegex } from './asmregex'; +import {AsmParser} from './asm-parser'; +import {AsmRegex} from './asmregex'; export class Vc6AsmParser extends AsmParser { constructor(compilerProps) { super(compilerProps); this.asmBinaryParser = new AsmParser(compilerProps); - this.miscDirective = /^\s*(include|INCLUDELIB|TITLE|\.|else$|endif$|if @Version|FLAT|ASSUME|THUMB|ARM64|TTL|END$)/; + this.miscDirective = + /^\s*(include|INCLUDELIB|TITLE|\.|else$|endif$|if @Version|FLAT|ASSUME|THUMB|ARM64|TTL|END$)/; this.localLabelDef = /^([$A-Z_a-z]+) =/; this.commentOnly = /^;/; this.filenameComment = /^; File (.+)/; this.lineNumberComment = /^; Line (\d+)/; - this.beginSegment = /^(CONST|_BSS|_DATA|_TLS|\.?[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|\.?text(\$[A-Za-z]+)?)\s+SEGMENT|\s*AREA/; - this.endSegment = /^(CONST|_BSS|_DATA|_TLS|[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|text(\$[A-Za-z]+)?)\s+ENDS/; + this.beginSegment = + /^(CONST|_BSS|_DATA|_TLS|\.?[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|\.?text(\$[A-Za-z]+)?)\s+SEGMENT|\s*AREA/; + this.endSegment = + /^(CONST|_BSS|_DATA|_TLS|[prx]?data(\$[A-Za-z]+)?|CRT(\$[A-Za-z]+)?|_TEXT|text(\$[A-Za-z]+)?)\s+ENDS/; this.beginFunction = /^; Function compile flags: /; this.endProc = /^([$?@A-Z_a-z][\w$<>?@]*)?\s+ENDP/; // on x86, we use the end of the segment to end a function @@ -120,9 +123,9 @@ export class Vc6AsmParser extends AsmParser { // ; initialLine: int // ; file: string option | undefined } let resultObject = { - prefix: [], // line array + prefix: [], // line array functions: [], // func array - postfix: null, // line? + postfix: null, // line? }; let currentFunction = null; // func option @@ -137,15 +140,15 @@ export class Vc6AsmParser extends AsmParser { const createSourceFor = (hasopc, currentFile, currentLine) => { if (hasopc && (currentFile || currentLine)) { return { - file: (currentFile ? currentFile : null), - line: (currentLine ? currentLine : null), + file: currentFile ? currentFile : null, + line: currentLine ? currentLine : null, }; } return null; }; - const checkUsedDatadefLabels = (line) => { + const checkUsedDatadefLabels = line => { const labels = line.match(this.labelFind); if (!labels) return; labels.splice(0, 1); @@ -156,7 +159,7 @@ export class Vc6AsmParser extends AsmParser { } }; - const checkBeginFunction = (line) => { + const checkBeginFunction = line => { if (this.definesFunction.test(line)) { currentFunction = { lines: [], @@ -168,7 +171,7 @@ export class Vc6AsmParser extends AsmParser { } }; - const checkForDdefLabel = (line) => { + const checkForDdefLabel = line => { const ddef = line.match(this.dataDefn); if (ddef && ddef[1]) { datadefLabels.push(ddef[1]); @@ -202,8 +205,7 @@ export class Vc6AsmParser extends AsmParser { let tmp = getFilenameFromComment(line); if (tmp !== null) { if (currentFunction === null) { - logger.error('We have a file comment outside of a function: %s', - line); + logger.error('We have a file comment outside of a function: %s', line); } // if the file is the "main file", give it the file `null` if (stdInLooking.test(tmp)) { @@ -218,8 +220,7 @@ export class Vc6AsmParser extends AsmParser { tmp = getLineNumberFromComment(line); if (tmp !== null) { if (currentFile === undefined) { - logger.error('Somehow, we have a line number comment without a file comment: %s', - line); + logger.error('Somehow, we have a line number comment without a file comment: %s', line); } if (currentFunction.initialLine === undefined) { currentFunction.initialLine = tmp; @@ -240,11 +241,12 @@ export class Vc6AsmParser extends AsmParser { if (filters.commentOnly && this.commentOnly.test(line)) continue; - const shouldSkip = filters.directives && ( - line.match(this.endSegment) || - line.match(this.definesGlobal) || - line.match(this.miscDirective) || - line.match(this.beginSegment)); + const shouldSkip = + filters.directives && + (line.match(this.endSegment) || + line.match(this.definesGlobal) || + line.match(this.miscDirective) || + line.match(this.beginSegment)); if (shouldSkip) { continue; diff --git a/lib/parsers/asm-parser.js b/lib/parsers/asm-parser.js index d5440e96e..8c55e8c44 100644 --- a/lib/parsers/asm-parser.js +++ b/lib/parsers/asm-parser.js @@ -140,24 +140,19 @@ export class AsmParser extends AsmRegex { inFunction = false; } - if (inCustomAssembly > 0) - line = this.fixLabelIndentation(line); + if (inCustomAssembly > 0) line = this.fixLabelIndentation(line); let match = line.match(this.labelDef); if (match) { - if (inLabelGroup) - currentLabelSet.push(match[1]); - else - currentLabelSet = [match[1]]; + if (inLabelGroup) currentLabelSet.push(match[1]); + else currentLabelSet = [match[1]]; inLabelGroup = true; } else { inLabelGroup = false; } match = line.match(this.definesGlobal); - if (!match) - match = line.match(this.definesWeak); - if (!match) - match = line.match(this.cudaBeginDef); + if (!match) match = line.match(this.definesWeak); + if (!match) match = line.match(this.cudaBeginDef); if (match) { labelsUsed[match[1]] = true; } @@ -200,7 +195,8 @@ export class AsmParser extends AsmRegex { const MaxLabelIterations = 10; for (let iter = 0; iter < MaxLabelIterations; ++iter) { let toAdd = []; - _.each(labelsUsed, (t, label) => { // jshint ignore:line + _.each(labelsUsed, (t, label) => { + // jshint ignore:line _.each(weakUsages[label], nowused => { if (labelsUsed[nowused]) return; toAdd.push(nowused); @@ -307,8 +303,7 @@ export class AsmParser extends AsmRegex { function maybeAddBlank() { const lastBlank = asm.length === 0 || asm[asm.length - 1].text === ''; - if (!lastBlank) - asm.push({text: '', source: null, labels: []}); + if (!lastBlank) asm.push({text: '', source: null, labels: []}); } function handleSource(line) { @@ -419,12 +414,11 @@ export class AsmParser extends AsmRegex { lastOwnSource = null; } - if (filters.libraryCode && !lastOwnSource && source && (source.file !== null) && !source.mainsource) { + if (filters.libraryCode && !lastOwnSource && source && source.file !== null && !source.mainsource) { if (mayRemovePreviousLabel && asm.length > 0) { const lastLine = asm[asm.length - 1]; - const labelDef = lastLine.text - ? lastLine.text.match(this.labelDef) : null; + const labelDef = lastLine.text ? lastLine.text.match(this.labelDef) : null; if (labelDef) { asm.pop(); @@ -443,15 +437,14 @@ export class AsmParser extends AsmRegex { mayRemovePreviousLabel = true; } - if (filters.commentOnly && - ((commentOnly.test(line) && !inNvccCode) || - (commentOnlyNvcc.test(line) && inNvccCode)) + if ( + filters.commentOnly && + ((commentOnly.test(line) && !inNvccCode) || (commentOnlyNvcc.test(line) && inNvccCode)) ) { continue; } - if (inCustomAssembly > 0) - line = this.fixLabelIndentation(line); + if (inCustomAssembly > 0) line = this.fixLabelIndentation(line); let match = line.match(this.labelDef); if (!match) match = line.match(this.assignmentDef); @@ -476,8 +469,7 @@ export class AsmParser extends AsmRegex { } } if (inNvccDef) { - if (this.cudaEndDef.test(line)) - inNvccDef = false; + if (this.cudaEndDef.test(line)) inNvccDef = false; } else if (!match && filters.directives) { // Check for directives only if it wasn't a label; the regexp would // otherwise misinterpret labels as directives. @@ -600,7 +592,7 @@ export class AsmParser extends AsmRegex { // note: normally the source.file will be null if it's code from example.ext // but with filters.dontMaskFilenames it will be filled with the actual filename // instead we can test source.mainsource in that situation - const isMainsource = source && ((source.file === null) || source.mainsource); + const isMainsource = source && (source.file === null || source.mainsource); if (filters.libraryCode && !isMainsource) { if (mayRemovePreviousLabel && asm.length > 0) { const lastLine = asm[asm.length - 1]; diff --git a/lib/parsers/asm-raw.js b/lib/parsers/asm-raw.js index b7e3bcb70..eefd6dc2b 100644 --- a/lib/parsers/asm-raw.js +++ b/lib/parsers/asm-raw.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AsmRegex } from './asmregex'; +import {AsmRegex} from './asmregex'; export class AsmRaw extends AsmRegex { processBinaryAsm(asm, filters) { @@ -60,11 +60,13 @@ export class AsmRaw extends AsmRegex { let links = null; const destMatch = line.match(destRe); if (destMatch) { - links = [{ - offset: disassembly.indexOf(destMatch[1]), - length: destMatch[1].length, - to: parseInt(destMatch[1], 16), - }]; + links = [ + { + offset: disassembly.indexOf(destMatch[1]), + length: destMatch[1].length, + to: parseInt(destMatch[1], 16), + }, + ]; } result.push({opcodes: opcodes, address: address, text: disassembly, source: source, links: links}); } diff --git a/lib/parsers/asmregex.js b/lib/parsers/asmregex.js index a9057195d..e213590f5 100644 --- a/lib/parsers/asmregex.js +++ b/lib/parsers/asmregex.js @@ -34,8 +34,11 @@ export class AsmRegex { static squashHorizontalWhitespace(line, atStart) { const quotes = line.match(findQuotes); if (quotes) { - return this.squashHorizontalWhitespace(quotes[1], atStart) + quotes[2] + - this.squashHorizontalWhitespace(quotes[3], false); + return ( + this.squashHorizontalWhitespace(quotes[1], atStart) + + quotes[2] + + this.squashHorizontalWhitespace(quotes[3], false) + ); } return utils.squashHorizontalWhitespace(line, atStart); } diff --git a/lib/pe32-support.js b/lib/pe32-support.js index da60d3293..47bc5e03c 100644 --- a/lib/pe32-support.js +++ b/lib/pe32-support.js @@ -24,7 +24,7 @@ export class PELabelReconstructor { /** - * + * * @param {Array} asmLines * @param {boolean} dontLabelUnmappedAddresses * @param {MapFileReader} mapFileReader @@ -53,7 +53,7 @@ export class PELabelReconstructor { //this.deleteEverythingBut(unitName); this.deleteSystemUnits(); this.shortenInt3s(); - + this.collectJumpsAndCalls(); this.insertLabels(); } @@ -87,7 +87,7 @@ export class PELabelReconstructor { /** * Remove any assembly or data that isn't part of the given unit * - * @param {string} unitName + * @param {string} unitName */ deleteEverythingBut(unitName) { if (this.needsReconstruction) { @@ -97,8 +97,13 @@ export class PELabelReconstructor { const info = this.mapFileReader.reconstructedSegments[idx]; if (info.unitName !== unitName) { if (info.segmentLength > 0) { - if (!this.mapFileReader.isWithinAddressSpace(unitAddressSpaces, - info.addressInt, info.segmentLength)) { + if ( + !this.mapFileReader.isWithinAddressSpace( + unitAddressSpaces, + info.addressInt, + info.segmentLength, + ) + ) { this.deleteLinesBetweenAddresses(info.addressInt, info.addressInt + info.segmentLength); } } @@ -112,11 +117,11 @@ export class PELabelReconstructor { this.deleteLinesBetweenAddresses(info.addressInt, info.addressInt + info.segmentLength); } } - + for (idx = 0; idx < this.mapFileReader.isegments.length; idx++) { info = this.mapFileReader.isegments[idx]; if (info.unitName !== unitName) { - this.deleteLinesBetweenAddresses(info.addressInt, info.addressInt + info.segmentLength); + this.deleteLinesBetweenAddresses(info.addressInt, info.addressInt + info.segmentLength); } } } @@ -136,15 +141,15 @@ export class PELabelReconstructor { for (idx = 0; idx < this.mapFileReader.isegments.length; idx++) { info = this.mapFileReader.isegments[idx]; if (systemUnits.has(info.unitName)) { - this.deleteLinesBetweenAddresses(info.addressInt, info.addressInt + info.segmentLength); + this.deleteLinesBetweenAddresses(info.addressInt, info.addressInt + info.segmentLength); } } } /** - * - * @param {number} beginAddress - * @param {number} endAddress + * + * @param {number} beginAddress + * @param {number} endAddress */ deleteLinesBetweenAddresses(beginAddress, endAddress) { let startIdx = -1; @@ -157,12 +162,12 @@ export class PELabelReconstructor { const matches = line.match(this.addressRegex); if (matches) { const lineAddr = parseInt(matches[1], 16); - if ((startIdx === -1) && (lineAddr >= beginAddress)) { + if (startIdx === -1 && lineAddr >= beginAddress) { startIdx = lineIdx; if (line.endsWith(':') || line.endsWith('<.text>:') || line.endsWith('<.itext>:')) { startIdx++; } - } else if (endAddress && (lineAddr >= endAddress)) { + } else if (endAddress && lineAddr >= endAddress) { this.asmLines.splice(startIdx, lineIdx - startIdx - 1); linesRemoved = true; break; @@ -172,7 +177,7 @@ export class PELabelReconstructor { lineIdx++; } - if (!linesRemoved && (startIdx !== -1)) { + if (!linesRemoved && startIdx !== -1) { this.asmLines.splice(startIdx, this.asmLines.length - startIdx); } } @@ -181,8 +186,8 @@ export class PELabelReconstructor { * Replaces an address used in a jmp or call instruction by its label. * Does not replace an address if it has an offset. * - * @param {int} lineIdx - * @param {regex} regex + * @param {int} lineIdx + * @param {regex} regex */ addAddressAsLabelAndReplaceLine(lineIdx, regex) { const line = this.asmLines[lineIdx]; @@ -249,7 +254,7 @@ export class PELabelReconstructor { if (namedAddr) { labelLine = matches[1] + ' <' + namedAddr.displayName + '>:'; } - + if (!this.dontLabelUnmappedAddresses || namedAddr) { this.asmLines.splice(lineIdx, 0, labelLine); lineIdx++; @@ -269,14 +274,10 @@ export class PELabelReconstructor { const lineInfo = this.mapFileReader.getLineInfoByAddress(false, address); if (lineInfo && currentSegment.unitName) { - this.asmLines.splice(lineIdx, 0, - '/app/' + currentSegment.unitName + - ':' + lineInfo.lineNumber); + this.asmLines.splice(lineIdx, 0, '/app/' + currentSegment.unitName + ':' + lineInfo.lineNumber); lineIdx++; } else if (segmentChanged) { - this.asmLines.splice(lineIdx, 0, - '/app/' + currentSegment.unitName + - ':0'); + this.asmLines.splice(lineIdx, 0, '/app/' + currentSegment.unitName + ':0'); lineIdx++; } } diff --git a/lib/properties.js b/lib/properties.js index 50be6d0f4..0d2f23476 100644 --- a/lib/properties.js +++ b/lib/properties.js @@ -27,8 +27,8 @@ import path from 'path'; import _ from 'underscore'; -import { logger } from './logger'; -import { toProperty } from './utils'; +import {logger} from './logger'; +import {toProperty} from './utils'; let properties = {}; @@ -134,7 +134,7 @@ export class CompilerProps { this.ceProps = ceProps; // Instantiate a function to access records concerning the chosen language in hidden object props.properties - _.each(this.languages, lang => this.propsByLangId[lang.id] = propsFor(lang.id)); + _.each(this.languages, lang => (this.propsByLangId[lang.id] = propsFor(lang.id))); } $getInternal(langId, key, defaultValue) { @@ -184,5 +184,5 @@ export function setDebug(debug) { } export function fakeProps(fake) { - return (prop, def) => fake[prop] === undefined ? def : fake[prop]; + return (prop, def) => (fake[prop] === undefined ? def : fake[prop]); } diff --git a/lib/shortener/_all.js b/lib/shortener/_all.js index 9b6fccc64..fb14b29e8 100644 --- a/lib/shortener/_all.js +++ b/lib/shortener/_all.js @@ -22,5 +22,5 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { DefaultShortener } from './default'; -export { TinyUrlShortener } from './tinyurl'; +export {DefaultShortener} from './default'; +export {TinyUrlShortener} from './tinyurl'; diff --git a/lib/shortener/base.js b/lib/shortener/base.js index 3baef496d..381802851 100644 --- a/lib/shortener/base.js +++ b/lib/shortener/base.js @@ -28,6 +28,5 @@ export class BaseShortener { } // eslint-disable-next-line no-unused-vars - handle(req, res) { - } + handle(req, res) {} } diff --git a/lib/shortener/default.js b/lib/shortener/default.js index d8bded207..c16634d7b 100644 --- a/lib/shortener/default.js +++ b/lib/shortener/default.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseShortener } from './base'; +import {BaseShortener} from './base'; export class DefaultShortener extends BaseShortener { - static get key() { return 'default'; } + static get key() { + return 'default'; + } handle(req, res) { return this.storageHandler.handler(req, res); diff --git a/lib/shortener/index.js b/lib/shortener/index.js index bd38d22c3..02dfc4680 100644 --- a/lib/shortener/index.js +++ b/lib/shortener/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BaseShortener } from './base'; +export {BaseShortener} from './base'; export * from './_all'; export const getShortenerTypeByKey = makeKeyedTypeGetter('shortener', all); diff --git a/lib/shortener/tinyurl.js b/lib/shortener/tinyurl.js index 51b92630f..cd75ac287 100644 --- a/lib/shortener/tinyurl.js +++ b/lib/shortener/tinyurl.js @@ -24,10 +24,12 @@ import request from 'request'; -import { BaseShortener } from './base'; +import {BaseShortener} from './base'; export class TinyUrlShortener extends BaseShortener { - static get key() { return 'tinyurl'; } + static get key() { + return 'tinyurl'; + } handle(req, res) { const url = `${req.protocol}://${req.get('host')}#${req.body.config}`; diff --git a/lib/sources/browser.ts b/lib/sources/browser.ts index 992e8e4df..a76d35fdf 100644 --- a/lib/sources/browser.ts +++ b/lib/sources/browser.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import type { Source, SourceEntry } from './index'; +import type {Source, SourceEntry} from './index'; // This is a fake plugin. All of the functionality is in the browser code. export const browser: Source = { diff --git a/lib/sources/builtin.ts b/lib/sources/builtin.ts index eecc69eec..58534de33 100644 --- a/lib/sources/builtin.ts +++ b/lib/sources/builtin.ts @@ -28,7 +28,7 @@ import path from 'path'; import * as props from '../properties'; -import type { Source, SourceEntry } from './index'; +import type {Source, SourceEntry} from './index'; const EXAMPLES_PATH = props.get('builtin', 'sourcePath', './examples/'); const NAME_SUBSTUTION_PATTERN = new RegExp('_', 'g'); diff --git a/lib/sources/index.ts b/lib/sources/index.ts index 92ff5a447..4d0341e60 100644 --- a/lib/sources/index.ts +++ b/lib/sources/index.ts @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { browser } from './browser'; -import { builtin } from './builtin'; +import {browser} from './browser'; +import {builtin} from './builtin'; export interface SourceEntry { /** The file name of the source file */ @@ -45,7 +45,4 @@ export interface Source { save: unknown; } -export const sources = [ - browser, - builtin, -]; +export const sources = [browser, builtin]; diff --git a/lib/sponsors.js b/lib/sponsors.js index 3d71d4f6f..a81c453dc 100644 --- a/lib/sponsors.js +++ b/lib/sponsors.js @@ -25,7 +25,7 @@ import yaml from 'yaml'; function namify(mapOrString) { - if (typeof (mapOrString) == 'string') return { name: mapOrString }; + if (typeof mapOrString == 'string') return {name: mapOrString}; return mapOrString; } @@ -56,13 +56,8 @@ export function loadSponsorsFromString(stringConfig) { sponsorConfig.icons = []; for (const level of sponsorConfig.levels) { for (const required of ['name', 'description']) - if (!level[required]) - throw new Error(`Level is missing '${required}'`); - level.sponsors = level.sponsors - .map(namify) - .map(clickify) - .map(getIconUrl) - .sort(compareSponsors); + if (!level[required]) throw new Error(`Level is missing '${required}'`); + level.sponsors = level.sponsors.map(namify).map(clickify).map(getIconUrl).sort(compareSponsors); sponsorConfig.icons.push(...level.sponsors.filter(sponsor => sponsor.topIcon && sponsor.icon)); } return sponsorConfig; diff --git a/lib/storage/_all.js b/lib/storage/_all.js index ebd17eff3..659587050 100644 --- a/lib/storage/_all.js +++ b/lib/storage/_all.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { StorageLocal } from './local'; -export { StorageNull } from './null'; -export { StorageRemote } from './remote'; -export { StorageS3 } from './s3'; +export {StorageLocal} from './local'; +export {StorageNull} from './null'; +export {StorageRemote} from './remote'; +export {StorageS3} from './s3'; diff --git a/lib/storage/base.js b/lib/storage/base.js index 36e9fe4d5..774799190 100644 --- a/lib/storage/base.js +++ b/lib/storage/base.js @@ -24,7 +24,7 @@ import profanities from 'profanities'; -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; const FILE_HASH_VERSION = 'Compiler Explorer Config Hasher 2'; @@ -101,8 +101,10 @@ export class StorageBase { const {config, configHash} = StorageBase.getSafeHash(origConfig); this.findUniqueSubhash(configHash) .then(result => { - logger.info(`Unique subhash '${result.uniqueSubHash}' ` + - `(${result.alreadyPresent ? 'was already present' : 'newly-created'})`); + logger.info( + `Unique subhash '${result.uniqueSubHash}' ` + + `(${result.alreadyPresent ? 'was already present' : 'newly-created'})`, + ); if (!result.alreadyPresent) { const storedObject = { prefix: result.prefix, diff --git a/lib/storage/index.js b/lib/storage/index.js index cbff0608f..dc8ea4d2f 100644 --- a/lib/storage/index.js +++ b/lib/storage/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { StorageBase } from './base'; +export {StorageBase} from './base'; export * from './_all'; export const getStorageTypeByKey = makeKeyedTypeGetter('storage', all); diff --git a/lib/storage/local.js b/lib/storage/local.js index ec4a41d87..0bc2ea3f7 100644 --- a/lib/storage/local.js +++ b/lib/storage/local.js @@ -27,14 +27,16 @@ import path from 'path'; import fs from 'fs-extra'; import _ from 'underscore'; -import { logger } from '../logger'; +import {logger} from '../logger'; -import { StorageBase } from './base'; +import {StorageBase} from './base'; const MIN_STORED_ID_LENGTH = 6; export class StorageLocal extends StorageBase { - static get key() { return 'local'; } + static get key() { + return 'local'; + } constructor(httpRootDir, compilerProps) { super(httpRootDir, compilerProps); diff --git a/lib/storage/null.js b/lib/storage/null.js index 04eb27417..0314382ce 100644 --- a/lib/storage/null.js +++ b/lib/storage/null.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { StorageBase } from './base'; +import {StorageBase} from './base'; export class StorageNull extends StorageBase { - static get key() { return 'null'; } + static get key() { + return 'null'; + } async storeItem(item) { return item; @@ -46,6 +48,5 @@ export class StorageNull extends StorageBase { }; } - async incrementViewCount() { - } + async incrementViewCount() {} } diff --git a/lib/storage/remote.js b/lib/storage/remote.js index 3de14eada..261ec86f3 100644 --- a/lib/storage/remote.js +++ b/lib/storage/remote.js @@ -22,16 +22,18 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { promisify } from 'util'; +import {promisify} from 'util'; import request from 'request'; -import { logger } from '../logger'; +import {logger} from '../logger'; -import { StorageBase } from './base'; +import {StorageBase} from './base'; export class StorageRemote extends StorageBase { - static get key() { return 'remote'; } + static get key() { + return 'remote'; + } constructor(httpRootDir, compilerProps) { super(httpRootDir, compilerProps); @@ -84,6 +86,5 @@ export class StorageRemote extends StorageBase { }; } - async incrementViewCount() { - } + async incrementViewCount() {} } diff --git a/lib/storage/s3.js b/lib/storage/s3.js index 0c2a2c77c..1cacbd546 100644 --- a/lib/storage/s3.js +++ b/lib/storage/s3.js @@ -27,11 +27,11 @@ import assert from 'assert'; import AWS from 'aws-sdk'; import _ from 'underscore'; -import { logger } from '../logger'; -import { S3Bucket } from '../s3-handler'; -import { anonymizeIp } from '../utils'; +import {logger} from '../logger'; +import {S3Bucket} from '../s3-handler'; +import {anonymizeIp} from '../utils'; -import { StorageBase } from './base'; +import {StorageBase} from './base'; /* * NEVER CHANGE THIS VALUE @@ -54,7 +54,9 @@ const MIN_STORED_ID_LENGTH = 9; assert(MIN_STORED_ID_LENGTH >= PREFIX_LENGTH, 'MIN_STORED_ID_LENGTH must be at least PREFIX_LENGTH'); export class StorageS3 extends StorageBase { - static get key() { return 's3'; } + static get key() { + return 's3'; + } constructor(httpRootDir, compilerProps, awsProps) { super(httpRootDir, compilerProps); @@ -62,8 +64,10 @@ export class StorageS3 extends StorageBase { const bucket = awsProps('storageBucket'); this.prefix = awsProps('storagePrefix'); this.table = awsProps('storageDynamoTable'); - logger.info(`Using s3 storage solution on ${region}, bucket ${bucket}, ` + - `prefix ${this.prefix}, dynamo table ${this.table}`); + logger.info( + `Using s3 storage solution on ${region}, bucket ${bucket}, ` + + `prefix ${this.prefix}, dynamo table ${this.table}`, + ); AWS.config.update({region: region}); this.s3 = new S3Bucket(bucket, region); this.dynamoDb = new AWS.DynamoDB(); @@ -81,19 +85,21 @@ export class StorageS3 extends StorageBase { now.setSeconds(0, 0); try { await Promise.all([ - this.dynamoDb.putItem({ - TableName: this.table, - Item: { - prefix: {S: item.prefix}, - unique_subhash: {S: item.uniqueSubHash}, - full_hash: {S: item.fullHash}, - stats: { - M: {clicks: {N: '0'}}, + this.dynamoDb + .putItem({ + TableName: this.table, + Item: { + prefix: {S: item.prefix}, + unique_subhash: {S: item.uniqueSubHash}, + full_hash: {S: item.fullHash}, + stats: { + M: {clicks: {N: '0'}}, + }, + creation_ip: {S: ip}, + creation_date: {S: now.toISOString()}, }, - creation_ip: {S: ip}, - creation_date: {S: now.toISOString()}, - }, - }).promise(), + }) + .promise(), this.s3.put(item.fullHash, item.config, this.prefix, {}), ]); return item; @@ -105,20 +111,16 @@ export class StorageS3 extends StorageBase { async findUniqueSubhash(hash) { const prefix = hash.substring(0, PREFIX_LENGTH); - const data = await this.dynamoDb.query({ - TableName: this.table, - ProjectionExpression: 'unique_subhash, full_hash', - KeyConditionExpression: 'prefix = :prefix', - ExpressionAttributeValues: {':prefix': {S: prefix}}, - }).promise(); - const subHashes = _.chain(data.Items) - .pluck('unique_subhash') - .pluck('S') - .value(); - const fullHashes = _.chain(data.Items) - .pluck('full_hash') - .pluck('S') - .value(); + const data = await this.dynamoDb + .query({ + TableName: this.table, + ProjectionExpression: 'unique_subhash, full_hash', + KeyConditionExpression: 'prefix = :prefix', + ExpressionAttributeValues: {':prefix': {S: prefix}}, + }) + .promise(); + const subHashes = _.chain(data.Items).pluck('unique_subhash').pluck('S').value(); + const fullHashes = _.chain(data.Items).pluck('full_hash').pluck('S').value(); for (let i = MIN_STORED_ID_LENGTH; i < hash.length - 1; i++) { let subHash = hash.substring(0, i); // Check if the current base is present in the subHashes array @@ -157,18 +159,18 @@ export class StorageS3 extends StorageBase { async expandId(id) { // By just getting the item and not trying to update it, we save an update when the link does not exist // for which we have less resources allocated, but get one extra read (But we do have more reserved for it) - const item = await this.dynamoDb.getItem({ - TableName: this.table, - Key: this.getKeyStruct(id), - }).promise(); + const item = await this.dynamoDb + .getItem({ + TableName: this.table, + Key: this.getKeyStruct(id), + }) + .promise(); const attributes = item.Item; - if (!attributes) - throw new Error(`ID ${id} not present in links table`); + if (!attributes) throw new Error(`ID ${id} not present in links table`); const result = await this.s3.get(attributes.full_hash.S, this.prefix); // If we're here, we are pretty confident there is a match. But never hurts to double check - if (!result.hit) - throw new Error(`ID ${id} not present in storage`); + if (!result.hit) throw new Error(`ID ${id} not present in storage`); const metadata = attributes.named_metadata ? attributes.named_metadata.M : null; return { config: result.data.toString(), @@ -178,15 +180,17 @@ export class StorageS3 extends StorageBase { async incrementViewCount(id) { try { - await this.dynamoDb.updateItem({ - TableName: this.table, - Key: this.getKeyStruct(id), - UpdateExpression: 'SET stats.clicks = stats.clicks + :inc', - ExpressionAttributeValues: { - ':inc': {N: '1'}, - }, - ReturnValues: 'NONE', - }).promise(); + await this.dynamoDb + .updateItem({ + TableName: this.table, + Key: this.getKeyStruct(id), + UpdateExpression: 'SET stats.clicks = stats.clicks + :inc', + ExpressionAttributeValues: { + ':inc': {N: '1'}, + }, + ReturnValues: 'NONE', + }) + .promise(); } catch (err) { // Swallow up errors logger.error(`Error when incrementing view count for ${id}`, err); diff --git a/lib/toolchain-utils.js b/lib/toolchain-utils.js index c95986c5a..eccc78c5a 100644 --- a/lib/toolchain-utils.js +++ b/lib/toolchain-utils.js @@ -28,10 +28,10 @@ import _ from 'underscore'; export function getToolchainPath(compilerExe, compilerOptions) { const options = compilerOptions ? compilerOptions.split(' ') : []; - const existingChain = _.find(options, (elem) => elem.includes('--gcc-toolchain=')); + const existingChain = _.find(options, elem => elem.includes('--gcc-toolchain=')); if (!existingChain) { - const gxxname = _.find(options, (elem) => elem.includes('--gxx-name=')); + const gxxname = _.find(options, elem => elem.includes('--gxx-name=')); if (gxxname) { return path.resolve(path.dirname(gxxname.substr(11)), '..'); } else if (typeof compilerExe === 'string' && compilerExe.includes('/g++')) { diff --git a/lib/tooling/_all.js b/lib/tooling/_all.js index 20cd6d601..77e7fd085 100644 --- a/lib/tooling/_all.js +++ b/lib/tooling/_all.js @@ -22,17 +22,17 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -export { ClangFormatTool } from './clang-format-tool'; -export { ClangQueryTool } from './clang-query-tool'; -export { ClangTidyTool } from './clang-tidy-tool'; -export { CompilerDropinTool } from './compiler-dropin-tool'; -export { LLVMMcaTool } from './llvm-mca-tool'; -export { MicrosoftAnalysisTool } from './microsoft-analysis-tool'; -export { OSACATool } from './osaca-tool'; -export { PaholeTool } from './pahole-tool'; -export { PvsStudioTool } from './pvs-studio-tool'; -export { ReadElfTool } from './readelf-tool'; -export { RustFmtTool } from './rustfmt-tool'; -export { StringsTool } from './strings-tool'; -export { x86to6502Tool } from './x86to6502-tool'; -export { TestingTool } from './testing-tool'; +export {ClangFormatTool} from './clang-format-tool'; +export {ClangQueryTool} from './clang-query-tool'; +export {ClangTidyTool} from './clang-tidy-tool'; +export {CompilerDropinTool} from './compiler-dropin-tool'; +export {LLVMMcaTool} from './llvm-mca-tool'; +export {MicrosoftAnalysisTool} from './microsoft-analysis-tool'; +export {OSACATool} from './osaca-tool'; +export {PaholeTool} from './pahole-tool'; +export {PvsStudioTool} from './pvs-studio-tool'; +export {ReadElfTool} from './readelf-tool'; +export {RustFmtTool} from './rustfmt-tool'; +export {StringsTool} from './strings-tool'; +export {x86to6502Tool} from './x86to6502-tool'; +export {TestingTool} from './testing-tool'; diff --git a/lib/tooling/base-tool.js b/lib/tooling/base-tool.js index 568f1127e..8c95f67f3 100755 --- a/lib/tooling/base-tool.js +++ b/lib/tooling/base-tool.js @@ -27,7 +27,7 @@ import path from 'path'; import _ from 'underscore'; import * as exec from '../exec'; -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; export class BaseTool { @@ -60,7 +60,7 @@ export class BaseTool { } // Even if the include key is truthy, we fall back to the exclusion list. } - return this.tool.exclude.find((excl) => compilerId.includes(excl)); + return this.tool.exclude.find(excl => compilerId.includes(excl)); } exec(toolExe, args, options) { @@ -97,24 +97,28 @@ export class BaseTool { getIncludeArguments(libraries, supportedLibraries) { const includeFlag = '-I'; - return _.flatten(_.map(libraries, (selectedLib) => { - const foundVersion = this.findLibVersion(selectedLib, supportedLibraries); - if (!foundVersion) return false; + return _.flatten( + _.map(libraries, selectedLib => { + const foundVersion = this.findLibVersion(selectedLib, supportedLibraries); + if (!foundVersion) return false; - return _.map(foundVersion.path, (path) => includeFlag + path); - })); + return _.map(foundVersion.path, path => includeFlag + path); + }), + ); } getLibraryOptions(libraries, supportedLibraries) { - return _.flatten(_.map(libraries, (selectedLib) => { - const foundVersion = this.findLibVersion(selectedLib, supportedLibraries); - if (!foundVersion) return false; + return _.flatten( + _.map(libraries, selectedLib => { + const foundVersion = this.findLibVersion(selectedLib, supportedLibraries); + if (!foundVersion) return false; - return foundVersion.options; - })); + return foundVersion.options; + }), + ); } - async runTool(compilationInfo, inputFilepath, args, stdin/*, supportedLibraries*/) { + async runTool(compilationInfo, inputFilepath, args, stdin /*, supportedLibraries*/) { let execOptions = this.getDefaultExecOptions(); if (inputFilepath) execOptions.customCwd = path.dirname(inputFilepath); execOptions.input = stdin; diff --git a/lib/tooling/clang-format-tool.js b/lib/tooling/clang-format-tool.js index a1f296953..65c765660 100644 --- a/lib/tooling/clang-format-tool.js +++ b/lib/tooling/clang-format-tool.js @@ -26,10 +26,12 @@ import path from 'path'; import fs from 'fs-extra'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class ClangFormatTool extends BaseTool { - static get key() { return 'clang-format-tool'; } + static get key() { + return 'clang-format-tool'; + } constructor(toolInfo, env) { super(toolInfo, env); @@ -43,7 +45,7 @@ export class ClangFormatTool extends BaseTool { const options = compilationInfo.options; const dir = path.dirname(sourcefile); - let compileFlags = options.filter(option => (option !== sourcefile)); + let compileFlags = options.filter(option => option !== sourcefile); if (!compilerExe.includes('clang++')) { compileFlags = compileFlags.concat(this.tool.options); } diff --git a/lib/tooling/clang-query-tool.js b/lib/tooling/clang-query-tool.js index 990de7042..2447e73af 100644 --- a/lib/tooling/clang-query-tool.js +++ b/lib/tooling/clang-query-tool.js @@ -26,10 +26,12 @@ import path from 'path'; import fs from 'fs-extra'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class ClangQueryTool extends BaseTool { - static get key() { return 'clang-query-tool'; } + static get key() { + return 'clang-query-tool'; + } constructor(toolInfo, env) { super(toolInfo, env); @@ -43,7 +45,7 @@ export class ClangQueryTool extends BaseTool { const options = compilationInfo.options; const dir = path.dirname(sourcefile); - const compileFlags = options.filter(option => (option !== sourcefile)); + const compileFlags = options.filter(option => option !== sourcefile); if (!compilerExe.includes('clang++')) { compileFlags.push(this.tool.options); } diff --git a/lib/tooling/compiler-dropin-tool.js b/lib/tooling/compiler-dropin-tool.js index 30142ad6e..ab7be7c33 100644 --- a/lib/tooling/compiler-dropin-tool.js +++ b/lib/tooling/compiler-dropin-tool.js @@ -24,13 +24,15 @@ import _ from 'underscore'; -import { getToolchainPath } from '../toolchain-utils'; +import {getToolchainPath} from '../toolchain-utils'; import * as utils from '../utils'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class CompilerDropinTool extends BaseTool { - static get key() { return 'compiler-dropin-tool'; } + static get key() { + return 'compiler-dropin-tool'; + } constructor(toolInfo, env) { super(toolInfo, env); @@ -54,17 +56,17 @@ export class CompilerDropinTool extends BaseTool { const toolchainPath = this.getToolchainPath(compilationInfo); - let compilerOptions = compilationInfo.compiler.options ? - utils.splitArguments(compilationInfo.compiler.options) : []; + let compilerOptions = compilationInfo.compiler.options + ? utils.splitArguments(compilationInfo.compiler.options) + : []; if (toolchainPath) { // note: needs toolchain argument twice as the first time its sometimes ignored compileFlags = compileFlags.concat('--gcc-toolchain=' + toolchainPath); compileFlags = compileFlags.concat('--gcc-toolchain=' + toolchainPath); - compilerOptions = _.filter(compilerOptions, (option) => { - return !((option.indexOf('--gcc-toolchain=') === 0) || - (option.indexOf('--gxx-name=') === 0)); + compilerOptions = _.filter(compilerOptions, option => { + return !(option.indexOf('--gcc-toolchain=') === 0 || option.indexOf('--gxx-name=') === 0); }); } else { return false; @@ -83,7 +85,7 @@ export class CompilerDropinTool extends BaseTool { args ? args : []; compileFlags = compileFlags.concat(args); - compileFlags = _.map(compileFlags, (option) => { + compileFlags = _.map(compileFlags, option => { if (option && option.length > 1) { if (option[0] === '/') { return false; @@ -104,7 +106,7 @@ export class CompilerDropinTool extends BaseTool { const compileFlags = this.getOrderedArguments(compilationInfo, includeflags, libOptions, args, sourcefile); if (!compileFlags) { - return new Promise((resolve) => { + return new Promise(resolve => { resolve(this.createErrorResponse('Unable to run tool with selected compiler')); }); } diff --git a/lib/tooling/index.js b/lib/tooling/index.js index bbf08a203..ca6790811 100644 --- a/lib/tooling/index.js +++ b/lib/tooling/index.js @@ -22,11 +22,11 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { makeKeyedTypeGetter } from '../keyed-type'; +import {makeKeyedTypeGetter} from '../keyed-type'; import * as all from './_all'; -export { BaseTool } from './base-tool'; +export {BaseTool} from './base-tool'; export * from './_all'; export const getToolTypeByKey = makeKeyedTypeGetter('tool', all); diff --git a/lib/tooling/llvm-mca-tool.js b/lib/tooling/llvm-mca-tool.js index ba7f7e98b..f16a769ef 100644 --- a/lib/tooling/llvm-mca-tool.js +++ b/lib/tooling/llvm-mca-tool.js @@ -24,7 +24,7 @@ import fs from 'fs-extra'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class LLVMMcaTool extends BaseTool { static get key() { diff --git a/lib/tooling/microsoft-analysis-tool.js b/lib/tooling/microsoft-analysis-tool.js index c4919cc82..4aa279bba 100644 --- a/lib/tooling/microsoft-analysis-tool.js +++ b/lib/tooling/microsoft-analysis-tool.js @@ -24,13 +24,15 @@ import path from 'path'; -import { logger } from '../logger'; +import {logger} from '../logger'; import * as utils from '../utils'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class MicrosoftAnalysisTool extends BaseTool { - static get key() { return 'microsoft-analysis-tool'; } + static get key() { + return 'microsoft-analysis-tool'; + } constructor(toolInfo, env) { super(toolInfo, env); @@ -38,7 +40,7 @@ export class MicrosoftAnalysisTool extends BaseTool { this.addOptionsToToolArgs = false; } - async runCompilerTool(compilationInfo, inputFilepath, args, stdin/*, supportedLibraries*/) { + async runCompilerTool(compilationInfo, inputFilepath, args, stdin /*, supportedLibraries*/) { let execOptions = this.getDefaultExecOptions(); if (inputFilepath) execOptions.customCwd = path.dirname(inputFilepath); execOptions.input = stdin; @@ -79,10 +81,18 @@ export class MicrosoftAnalysisTool extends BaseTool { let compileFlags = utils.splitArguments(compilationInfo.compiler.options); compileFlags = compileFlags.concat(includeflags, libOptions); - const manualCompileFlags = options.filter(option => (option !== sourcefile)); - compileFlags = compileFlags.concat(manualCompileFlags, '/nologo', '/analyze:plugin', - 'EspXEngine.dll', '/analyze:external-', '/external:env:INCLUDE', '/external:W0', this.tool.options); - + const manualCompileFlags = options.filter(option => option !== sourcefile); + compileFlags = compileFlags.concat( + manualCompileFlags, + '/nologo', + '/analyze:plugin', + 'EspXEngine.dll', + '/analyze:external-', + '/external:env:INCLUDE', + '/external:W0', + this.tool.options, + ); + return await this.runCompilerTool(compilationInfo, sourcefile, compileFlags); } } diff --git a/lib/tooling/osaca-tool.js b/lib/tooling/osaca-tool.js index 721aa2e06..887f3fcef 100644 --- a/lib/tooling/osaca-tool.js +++ b/lib/tooling/osaca-tool.js @@ -24,16 +24,18 @@ import fs from 'fs-extra'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class OSACATool extends BaseTool { - static get key() { return 'osaca-tool'; } + static get key() { + return 'osaca-tool'; + } async writeAsmFile(asmParser, asm, filters, destination) { // Applying same filters as applied to compiler outpu - const filteredAsm = asmParser.process(asm, filters).asm.reduce( - function (acc, line) {return acc + line.text + '\n';}, - ''); + const filteredAsm = asmParser.process(asm, filters).asm.reduce(function (acc, line) { + return acc + line.text + '\n'; + }, ''); return fs.writeFile(destination, filteredAsm); } @@ -48,8 +50,11 @@ export class OSACATool extends BaseTool { const rewrittenOutputFilename = compilationInfo.outputFilename + '.osaca'; await this.writeAsmFile( - compilationInfo.asmParser, compilationInfo.asm, compilationInfo.filters, - rewrittenOutputFilename); + compilationInfo.asmParser, + compilationInfo.asm, + compilationInfo.filters, + rewrittenOutputFilename, + ); return super.runTool(compilationInfo, rewrittenOutputFilename, args); } } diff --git a/lib/tooling/pahole-tool.js b/lib/tooling/pahole-tool.js index 073fcd647..e7c320f59 100644 --- a/lib/tooling/pahole-tool.js +++ b/lib/tooling/pahole-tool.js @@ -24,10 +24,12 @@ import fs from 'fs-extra'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class PaholeTool extends BaseTool { - static get key() { return 'pahole-tool'; } + static get key() { + return 'pahole-tool'; + } async runTool(compilationInfo, inputFilepath, args) { if (!compilationInfo.filters.binary) { diff --git a/lib/tooling/readelf-tool.js b/lib/tooling/readelf-tool.js index 3e349eb61..618e8ce6d 100644 --- a/lib/tooling/readelf-tool.js +++ b/lib/tooling/readelf-tool.js @@ -22,16 +22,17 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { fileExists } from '../utils'; +import {fileExists} from '../utils'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class ReadElfTool extends BaseTool { - static get key() { return 'readelf-tool'; } + static get key() { + return 'readelf-tool'; + } async runTool(compilationInfo, inputFilename, args) { - if (!compilationInfo.filters.binary) - { + if (!compilationInfo.filters.binary) { return this.createErrorResponse('readelf requires an executable'); } diff --git a/lib/tooling/rustfmt-tool.js b/lib/tooling/rustfmt-tool.js index 1693bed91..6cb3c086e 100644 --- a/lib/tooling/rustfmt-tool.js +++ b/lib/tooling/rustfmt-tool.js @@ -22,10 +22,12 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class RustFmtTool extends BaseTool { - static get key() { return 'rustfmt-tool'; } + static get key() { + return 'rustfmt-tool'; + } convertResult(result, inputFilepath, exeDir) { // Rustfmt outputs files to stdout with the format diff --git a/lib/tooling/strings-tool.js b/lib/tooling/strings-tool.js index 0c2cc57f8..a504efc2c 100644 --- a/lib/tooling/strings-tool.js +++ b/lib/tooling/strings-tool.js @@ -22,16 +22,17 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { fileExists } from '../utils'; +import {fileExists} from '../utils'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class StringsTool extends BaseTool { - static get key() { return 'strings-tool'; } + static get key() { + return 'strings-tool'; + } async runTool(compilationInfo, inputFilename, args) { - if (!compilationInfo.filters.binary) - { + if (!compilationInfo.filters.binary) { return this.createErrorResponse('Strings requires a binary output'); } if (await fileExists(compilationInfo.executableFilename)) { diff --git a/lib/tooling/testing-tool.js b/lib/tooling/testing-tool.js index 2ac4f9d3d..f697e82b5 100644 --- a/lib/tooling/testing-tool.js +++ b/lib/tooling/testing-tool.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class TestingTool extends BaseTool { static get key() { diff --git a/lib/tooling/x86to6502-tool.js b/lib/tooling/x86to6502-tool.js index 6d1f56725..f0e7242ca 100644 --- a/lib/tooling/x86to6502-tool.js +++ b/lib/tooling/x86to6502-tool.js @@ -24,22 +24,24 @@ import _ from 'underscore'; -import { AsmParser } from '../parsers/asm-parser'; +import {AsmParser} from '../parsers/asm-parser'; -import { BaseTool } from './base-tool'; +import {BaseTool} from './base-tool'; export class x86to6502Tool extends BaseTool { - static get key() { return 'x86to6502-tool'; } + static get key() { + return 'x86to6502-tool'; + } runTool(compilationInfo, sourcefile, args) { if (compilationInfo.filters.intel) { - return new Promise((resolve) => { + return new Promise(resolve => { resolve(this.createErrorResponse('')); }); } if (compilationInfo.filters.binary) { - return new Promise((resolve) => { + return new Promise(resolve => { resolve(this.createErrorResponse('')); }); } @@ -49,7 +51,7 @@ export class x86to6502Tool extends BaseTool { const result = parser.process(compilationInfo.asm, filters); - const asm = _.map(result.asm, (obj) => { + const asm = _.map(result.asm, obj => { if (typeof obj.text !== 'string' || obj.text.trim() === '') { return ''; } else if (/.*:/.test(obj.text)) { diff --git a/package.json b/package.json index 694dc2798..f7ee53b96 100644 --- a/package.json +++ b/package.json @@ -168,10 +168,10 @@ "sentry": "npx -p @sentry/cli sentry-cli", "update-browserslist": "npx browserslist@latest -- --update-db", "prepare": "husky install", - "format": "prettier --ignore-unknown ./static/**/*.ts", - "format-fix": "prettier --write --ignore-unknown ./static/**/*.ts", + "format": "prettier --ignore-unknown .", + "format-fix": "prettier --write .", "format-fix-files": "prettier --write --ignore-unknown", - "format-check": "prettier --ignore-unknown --check ./static/**/*.ts", + "format-check": "prettier --check .", "ts-compile": "tsc", "ts-check": "tsc -p ./tsconfig.backend.json --noEmit --module esnext && tsc -p ./tsconfig.frontend.json --noEmit", "webpack": "webpack --node-env=production" @@ -180,6 +180,9 @@ "*.[jt]s": [ "npm run format-fix-files --", "npm run ci-lint-files --" + ], + "*.{html,md}": [ + "npm run format-fix-files --" ] }, "license": "BSD-2-Clause" diff --git a/static/compiler-service.js b/static/compiler-service.js index 31536c639..02089123b 100644 --- a/static/compiler-service.js +++ b/static/compiler-service.js @@ -40,14 +40,22 @@ function CompilerService(eventHub) { }, }); this.compilersByLang = {}; - _.each(options.compilers, function (compiler) { - if (!this.compilersByLang[compiler.lang]) this.compilersByLang[compiler.lang] = {}; - this.compilersByLang[compiler.lang][compiler.id] = compiler; - }, this); + _.each( + options.compilers, + function (compiler) { + if (!this.compilersByLang[compiler.lang]) this.compilersByLang[compiler.lang] = {}; + this.compilersByLang[compiler.lang][compiler.id] = compiler; + }, + this + ); // settingsChange is triggered on page load - eventHub.on('settingsChange', function (newSettings) { - this.allowStoreCodeDebug = newSettings.allowStoreCodeDebug; - }, this); + eventHub.on( + 'settingsChange', + function (newSettings) { + this.allowStoreCodeDebug = newSettings.allowStoreCodeDebug; + }, + this + ); } CompilerService.prototype.getDefaultCompilerForLang = function (langId) { @@ -69,19 +77,23 @@ CompilerService.prototype.processFromLangAndCompiler = function (languageId, com foundCompiler = compilers[_.first(_.keys(compilers))]; } } else if (compilerId) { - var matchingCompilers =_.map(options.languages, function (lang) { - var compiler = this.findCompiler(lang.id, compilerId); - if (compiler) { - return { - langId: lang.id, - compiler: compiler, - }; - } - return null; - }, this); + var matchingCompilers = _.map( + options.languages, + function (lang) { + var compiler = this.findCompiler(lang.id, compilerId); + if (compiler) { + return { + langId: lang.id, + compiler: compiler, + }; + } + return null; + }, + this + ); return _.find(matchingCompilers, function (match) { - return (match !== null); + return match !== null; }); } else { var firstLang = _.first(_.values(options.languages)); @@ -108,10 +120,8 @@ CompilerService.prototype.getGroupsInUse = function (langId) { .map(function (compiler) { return {value: compiler.group, label: compiler.groupName || compiler.group}; }) - .sort(function (a, b){ - return a.label.localeCompare(b.label, - undefined /* Ignore language */, - { sensitivity: 'base' }); + .sort(function (a, b) { + return a.label.localeCompare(b.label, undefined /* Ignore language */, {sensitivity: 'base'}); }) .value(); }; @@ -182,28 +192,30 @@ CompilerService.prototype.submit = function (request) { }); } } - return new Promise(_.bind(function (resolve, reject) { - var bindHandler = _.partial(handleRequestError, request, reject); - var compilerId = encodeURIComponent(request.compiler); - $.ajax({ - type: 'POST', - url: window.location.origin + this.base + 'api/compiler/' + compilerId + '/compile', - dataType: 'json', - contentType: 'application/json', - data: jsonRequest, - success: _.bind(function (result) { - if (result && result.okToCache && options.doCache) { - this.cache.set(jsonRequest, result); - } - resolve({ - request: request, - result: result, - localCacheHit: false, - }); - }, this), - error: bindHandler, - }); - }, this)); + return new Promise( + _.bind(function (resolve, reject) { + var bindHandler = _.partial(handleRequestError, request, reject); + var compilerId = encodeURIComponent(request.compiler); + $.ajax({ + type: 'POST', + url: window.location.origin + this.base + 'api/compiler/' + compilerId + '/compile', + dataType: 'json', + contentType: 'application/json', + data: jsonRequest, + success: _.bind(function (result) { + if (result && result.okToCache && options.doCache) { + this.cache.set(jsonRequest, result); + } + resolve({ + request: request, + result: result, + localCacheHit: false, + }); + }, this), + error: bindHandler, + }); + }, this) + ); }; CompilerService.prototype.submitCMake = function (request) { @@ -219,51 +231,55 @@ CompilerService.prototype.submitCMake = function (request) { }); } } - return new Promise(_.bind(function (resolve, reject) { - var bindHandler = _.partial(handleRequestError, request, reject); - var compilerId = encodeURIComponent(request.compiler); - $.ajax({ - type: 'POST', - url: window.location.origin + this.base + 'api/compiler/' + compilerId + '/cmake', - dataType: 'json', - contentType: 'application/json', - data: jsonRequest, - success: _.bind(function (result) { - if (result && result.okToCache && options.doCache) { - this.cache.set(jsonRequest, result); - } - resolve({ - request: request, - result: result, - localCacheHit: false, - }); - }, this), - error: bindHandler, - }); - }, this)); + return new Promise( + _.bind(function (resolve, reject) { + var bindHandler = _.partial(handleRequestError, request, reject); + var compilerId = encodeURIComponent(request.compiler); + $.ajax({ + type: 'POST', + url: window.location.origin + this.base + 'api/compiler/' + compilerId + '/cmake', + dataType: 'json', + contentType: 'application/json', + data: jsonRequest, + success: _.bind(function (result) { + if (result && result.okToCache && options.doCache) { + this.cache.set(jsonRequest, result); + } + resolve({ + request: request, + result: result, + localCacheHit: false, + }); + }, this), + error: bindHandler, + }); + }, this) + ); }; CompilerService.prototype.requestPopularArguments = function (compilerId, options) { - return new Promise(_.bind(function (resolve, reject) { - var bindHandler = _.partial(handleRequestError, compilerId, reject); - $.ajax({ - type: 'POST', - url: window.location.origin + this.base + 'api/popularArguments/' + compilerId, - dataType: 'json', - data: JSON.stringify({ - usedOptions: options, - presplit: false, - }), - success: _.bind(function (result) { - resolve({ - request: compilerId, - result: result, - localCacheHit: false, - }); - }, this), - error: bindHandler, - }); - }, this)); + return new Promise( + _.bind(function (resolve, reject) { + var bindHandler = _.partial(handleRequestError, compilerId, reject); + $.ajax({ + type: 'POST', + url: window.location.origin + this.base + 'api/popularArguments/' + compilerId, + dataType: 'json', + data: JSON.stringify({ + usedOptions: options, + presplit: false, + }), + success: _.bind(function (result) { + resolve({ + request: compilerId, + result: result, + localCacheHit: false, + }); + }, this), + error: bindHandler, + }); + }, this) + ); }; CompilerService.prototype.expand = function (source) { @@ -273,18 +289,26 @@ CompilerService.prototype.expand = function (source) { _.each(lines, function (line, lineNumZeroBased) { var match = line.match(includeFind); if (match) { - promises.push(new Promise(function (resolve) { - var req = $.get(match[1], function (data) { - data = '#line 1 "' + match[1] + '"\n' + data + '\n\n#line ' + - (lineNumZeroBased + 1) + ' ""\n'; + promises.push( + new Promise(function (resolve) { + 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(); - }); - })); + lines[lineNumZeroBased] = data; + resolve(); + }); + req.fail(function () { + resolve(); + }); + }) + ); } }); return Promise.all(promises).then(function () { @@ -293,11 +317,7 @@ CompilerService.prototype.expand = function (source) { }; CompilerService.prototype.getSelectizerOrder = function () { - return [ - {field: '$order'}, - {field: '$score'}, - {field: 'name'}, - ]; + return [{field: '$order'}, {field: '$score'}, {field: 'name'}]; }; CompilerService.prototype.doesCompilationResultHaveWarnings = function (result) { @@ -364,9 +384,7 @@ function color(status) { CompilerService.prototype.handleCompilationStatus = function (statusLabel, statusIcon, status) { if (statusLabel != null) { - statusLabel - .toggleClass('error', status.code === 3) - .toggleClass('warning', status.code === 2); + statusLabel.toggleClass('error', status.code === 3).toggleClass('warning', status.code === 2); } if (statusIcon != null) { @@ -393,9 +411,7 @@ CompilerService.prototype.handleOutputButtonTitle = function (element, result) { return line.text.replace(asciiColorsRe, ''); } - var output =_.map(stdout, filterAsciiColors) - .concat(_.map(stderr, filterAsciiColors)) - .join('\n'); + var output = _.map(stdout, filterAsciiColors).concat(_.map(stderr, filterAsciiColors)).join('\n'); element.prop('title', output); }; diff --git a/static/explorer.scss b/static/explorer.scss index 0f4d87922..cad6c08ea 100644 --- a/static/explorer.scss +++ b/static/explorer.scss @@ -1,5 +1,5 @@ -@import "~@fortawesome/fontawesome-free/css/all.min.css"; -@import "~vis-network/styles/vis-network.css"; +@import '~@fortawesome/fontawesome-free/css/all.min.css'; +@import '~vis-network/styles/vis-network.css'; /* * https://github.com/Microsoft/monaco-editor/issues/417 @@ -19,7 +19,7 @@ // These blocks should be removed once a downstream release of monaco is cut :root { // updated at runtime - --user-selected-font-stack: Consolas, "Liberation Mono", Courier, monospace; + --user-selected-font-stack: Consolas, 'Liberation Mono', Courier, monospace; } .monaco-editor .codelens-decoration { font-family: var(--user-selected-font-stack); @@ -242,7 +242,8 @@ pre.content.wrap * { font-weight: 600; } -.modal { /* maximum for all modal dialogs */ +.modal { + /* maximum for all modal dialogs */ width: 100%; height: 100%; padding: 1.75rem; @@ -260,7 +261,7 @@ pre.content.wrap * { #history { .modal-content { - min-width: calc(80vw); /* force min-width on html element containing history editor */ + min-width: calc(80vw); /* force min-width on html element containing history editor */ } } @@ -428,7 +429,8 @@ label#vim-label { top: 3px; } -#settings input, #embedsettings input { +#settings input, +#embedsettings input { margin-right: 3px; } @@ -436,12 +438,13 @@ label#vim-label { user-select: none; } -#settings select, #settings input:not([type=checkbox]):not([type=range]) { +#settings select, +#settings input:not([type='checkbox']):not([type='range']) { display: block; } input.vim-check { - margin-bottom: 4px + margin-bottom: 4px; } .opens-new-window { @@ -457,7 +460,7 @@ input.vim-check { } .program-exec-output { - font-family: "Courier New", Courier, monospace; + font-family: 'Courier New', Courier, monospace; padding-left: 2%; } @@ -606,7 +609,9 @@ div.populararguments div.dropdown-menu { .ces-content-root { min-height: 100px; - max-height: calc(100vh - 306px); /* works on my machine :) - 306px = the height of the footer + borders/margins/paddings - guessed/tried out */ + max-height: calc( + 100vh - 306px + ); /* works on my machine :) - 306px = the height of the footer + borders/margins/paddings - guessed/tried out */ overflow: auto; /* move scrollbar into sponsor part - keep quickaccess buttons on screen */ } @@ -632,7 +637,7 @@ div.populararguments div.dropdown-menu { flex-wrap: wrap; justify-content: space-around; align-items: center; - font-size: 60% + font-size: 60%; } @media (min-height: 700px) { @@ -780,19 +785,24 @@ span.badge.badge-pill { margin-left: 2pt; } -.theme-light-only, .theme-dark-only { +.theme-light-only, +.theme-dark-only { display: none; } -html[data-theme=default] { - @import "themes/default-theme"; - .theme-light-only { display: inline } +html[data-theme='default'] { + @import 'themes/default-theme'; + .theme-light-only { + display: inline; + } } -html[data-theme=dark] { - @import "themes/dark-theme"; +html[data-theme='dark'] { + @import 'themes/dark-theme'; background-color: #333 !important; - .theme-dark-only { display: inline } + .theme-dark-only { + display: inline; + } } .socialsharing { @@ -800,11 +810,12 @@ html[data-theme=dark] { } .ts-input { - height: 100% + height: 100%; } -.ts-input, .ts-dropdown .option { - font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; +.ts-input, +.ts-dropdown .option { + font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px; } diff --git a/static/noscript.scss b/static/noscript.scss index 1e1c75a2b..81aa4ffab 100644 --- a/static/noscript.scss +++ b/static/noscript.scss @@ -1,5 +1,5 @@ -@import "~@fortawesome/fontawesome-free/css/all.min.css"; -@import "~vis-network/styles/vis-network.css"; +@import '~@fortawesome/fontawesome-free/css/all.min.css'; +@import '~vis-network/styles/vis-network.css'; html body { overflow: auto; diff --git a/static/panes/conformance-view.js b/static/panes/conformance-view.js index 8bb9b5355..ff01e3c51 100644 --- a/static/panes/conformance-view.js +++ b/static/panes/conformance-view.js @@ -72,21 +72,27 @@ function Conformance(hub, container, state) { }); // Dismiss the popover on escape. - $(document).on('keyup.editable', _.bind(function (e) { - if (e.which === 27) { - this.libsButton.popover('hide'); - } - }, this)); + $(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)); + $(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) + ); } Conformance.prototype.onLibsChanged = function () { @@ -123,17 +129,25 @@ Conformance.prototype.initButtons = function () { }; Conformance.prototype.initCallbacks = function () { - this.container.on('destroy', function () { - this.eventHub.unsubscribe(); - this.eventHub.emit('conformanceViewClose', this.editorId); - }, this); + this.container.on( + 'destroy', + function () { + this.eventHub.unsubscribe(); + this.eventHub.emit('conformanceViewClose', this.editorId); + }, + this + ); this.paneRenaming.on('renamePane', this.saveState.bind(this)); this.container.on('destroy', this.close, this); - this.container.on('open', function () { - this.eventHub.emit('conformanceViewOpen', this.editorId); - }, this); + this.container.on( + 'open', + function () { + this.eventHub.emit('conformanceViewOpen', this.editorId); + }, + this + ); this.container.on('resize', this.resize, this); this.container.on('shown', this.resize, this); @@ -142,10 +156,13 @@ Conformance.prototype.initCallbacks = function () { this.eventHub.on('editorClose', this.onEditorClose, this); this.eventHub.on('languageChange', this.onLanguageChange, this); - this.addCompilerButton.on('click', _.bind(function () { - this.addCompilerPicker(); - this.saveState(); - }, this)); + this.addCompilerButton.on( + 'click', + _.bind(function () { + this.addCompilerPicker(); + this.saveState(); + }, this) + ); }; Conformance.prototype.getPaneName = function () { @@ -179,20 +196,29 @@ Conformance.prototype.addCompilerPicker = function (config) { prependOptions: null, }; - var onOptionsChange = _.debounce(_.bind(function () { - this.saveState(); - this.compileChild(newCompilerEntry); - }, this), 800); + var onOptionsChange = _.debounce( + _.bind(function () { + this.saveState(); + this.compileChild(newCompilerEntry); + }, this), + 800 + ); - newCompilerEntry.optionsField = newSelector.find('.conformance-options') + newCompilerEntry.optionsField = newSelector + .find('.conformance-options') .val(config.options) .on('change', onOptionsChange) .on('keyup', onOptionsChange); - newSelector.find('.close').not('.extract-compiler') - .on('click', _.bind(function () { - this.removeCompilerPicker(newCompilerEntry); - }, this)); + newSelector + .find('.close') + .not('.extract-compiler') + .on( + 'click', + _.bind(function () { + this.removeCompilerPicker(newCompilerEntry); + }, this) + ); newCompilerEntry.statusIcon = newSelector.find('.status-icon'); newCompilerEntry.prependOptions = newSelector.find('.prepend-options'); @@ -210,24 +236,33 @@ Conformance.prototype.addCompilerPicker = function (config) { }, this); newCompilerEntry.picker = new CompilerPicker( - $(newSelector[0]), this.hub, this.langId, - config.compilerId, _.bind(onCompilerChange, this) + $(newSelector[0]), + this.hub, + this.langId, + config.compilerId, + _.bind(onCompilerChange, this) ); var getCompilerConfig = _.bind(function () { return Components.getCompilerWith( - this.editorId, undefined, newCompilerEntry.optionsField.val(), - newCompilerEntry.picker.lastCompilerId, this.langId, this.lastState.libs + this.editorId, + undefined, + newCompilerEntry.optionsField.val(), + newCompilerEntry.picker.lastCompilerId, + this.langId, + this.lastState.libs ); }, this); this.container.layoutManager.createDragSource(popCompilerButton, getCompilerConfig); - popCompilerButton.click(_.bind(function () { - var insertPoint = this.hub.findParentRowOrColumn(this.container) || - this.container.layoutManager.root.contentItems[0]; - insertPoint.addChild(getCompilerConfig); - }, this)); + popCompilerButton.click( + _.bind(function () { + var insertPoint = + this.hub.findParentRowOrColumn(this.container) || this.container.layoutManager.root.contentItems[0]; + insertPoint.addChild(getCompilerConfig); + }, this) + ); this.selectorList.append(newSelector); this.compilerPickers.push(newCompilerEntry); @@ -239,7 +274,8 @@ Conformance.prototype.setCompilationOptionsPopover = function (element, content) element.popover('dispose'); element.popover({ content: content || 'No options in use', - template: '', @@ -260,11 +296,13 @@ Conformance.prototype.removeCompilerPicker = function (compilerEntry) { Conformance.prototype.expandSource = function () { if (this.sourceNeedsExpanding || !this.expandedSource) { - return this.compilerService.expand(this.source).then(_.bind(function (expandedSource) { - this.expandedSource = expandedSource; - this.sourceNeedsExpanding = false; - return expandedSource; - }, this)); + return this.compilerService.expand(this.source).then( + _.bind(function (expandedSource) { + this.expandedSource = expandedSource; + this.sourceNeedsExpanding = false; + return expandedSource; + }, this) + ); } return Promise.resolve(this.expandedSource); }; @@ -326,47 +364,57 @@ Conformance.prototype.compileChild = function (compilerEntry) { // Hide previous status icons this.handleStatusIcon(compilerEntry.statusIcon, {code: 4}); - this.expandSource().then(_.bind(function (expandedSource) { - var request = { - source: expandedSource, - compiler: compilerId, - options: { - userArguments: compilerEntry.optionsField.val() || '', - filters: {}, - compilerOptions: {produceAst: false, produceOptInfo: false, skipAsm: true}, - libraries: [], - }, - lang: this.langId, - files: [], - }; + this.expandSource().then( + _.bind(function (expandedSource) { + var request = { + source: expandedSource, + compiler: compilerId, + options: { + userArguments: compilerEntry.optionsField.val() || '', + filters: {}, + compilerOptions: {produceAst: false, produceOptInfo: false, skipAsm: true}, + libraries: [], + }, + lang: this.langId, + files: [], + }; - _.each(this.currentLibs, function (item) { - request.options.libraries.push({ - id: item.name, - version: item.ver, - }); - }); - - // 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(compilerEntry, x.result); - }, this)) - .catch(_.bind(function (x) { - this.onCompileResponse(compilerEntry, { - asm: '', - code: -1, - stdout: '', - stderr: x.error, + _.each(this.currentLibs, function (item) { + request.options.libraries.push({ + id: item.name, + version: item.ver, }); - }, this)); - }, this)); + }); + + // 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(compilerEntry, x.result); + }, this) + ) + .catch( + _.bind(function (x) { + this.onCompileResponse(compilerEntry, { + asm: '', + code: -1, + stdout: '', + stderr: x.error, + }); + }, this) + ); + }, this) + ); }; Conformance.prototype.compileAll = function () { - _.each(this.compilerPickers, _.bind(function (compilerEntry) { - this.compileChild(compilerEntry); - }, this)); + _.each( + this.compilerPickers, + _.bind(function (compilerEntry) { + this.compileChild(compilerEntry); + }, this) + ); }; Conformance.prototype.handleToolbarUI = function () { @@ -412,9 +460,12 @@ Conformance.prototype.resize = function () { }; Conformance.prototype.getOverlappingLibraries = function (compilerIds) { - var compilers = _.map(compilerIds, _.bind(function (compilerId) { - return this.compilerService.findCompiler(this.langId, compilerId); - }, this)); + var compilers = _.map( + compilerIds, + _.bind(function (compilerId) { + return this.compilerService.findCompiler(this.langId, compilerId); + }, this) + ); var langId = this.langId; @@ -422,25 +473,24 @@ Conformance.prototype.getOverlappingLibraries = function (compilerIds) { var first = true; _.forEach(compilers, function (compiler) { if (compiler) { - var filteredLibraries = LibUtils.getSupportedLibraries(compiler.libsArr, langId, - compiler.remote); - + var filteredLibraries = LibUtils.getSupportedLibraries(compiler.libsArr, langId, compiler.remote); + if (first) { libraries = _.extend({}, filteredLibraries); first = false; } else { - var libsInCommon = _.intersection(_.keys(libraries), - _.keys(filteredLibraries)); + var libsInCommon = _.intersection(_.keys(libraries), _.keys(filteredLibraries)); _.forEach(libraries, function (lib, libkey) { if (libsInCommon.includes(libkey)) { - var versionsInCommon = _.intersection(_.keys(lib.versions), - _.keys(filteredLibraries[libkey].versions)); + var versionsInCommon = _.intersection( + _.keys(lib.versions), + _.keys(filteredLibraries[libkey].versions) + ); - libraries[libkey].versions = _.pick(lib.versions, - function (version, versionkey) { - return versionsInCommon.includes(versionkey); - }); + libraries[libkey].versions = _.pick(lib.versions, function (version, versionkey) { + return versionsInCommon.includes(versionkey); + }); } else { libraries[libkey] = false; } @@ -461,20 +511,17 @@ Conformance.prototype.getCurrentCompilersIds = function () { _.filter( _.map(this.compilerPickers, function (compilerEntry) { return getCompilerId(compilerEntry); - }) - , function (compilerId) { + }), + function (compilerId) { return compilerId !== ''; - }) + } + ) ); }; Conformance.prototype.updateLibraries = function () { var compilerIds = this.getCurrentCompilersIds(); - this.libsWidget.setNewLangId( - this.langId, - compilerIds.join('|'), - this.getOverlappingLibraries(compilerIds) - ); + this.libsWidget.setNewLangId(this.langId, compilerIds.join('|'), this.getOverlappingLibraries(compilerIds)); }; Conformance.prototype.onLanguageChange = function (editorId, newLangId) { diff --git a/static/panes/device-view.js b/static/panes/device-view.js index 38e34f149..cdd226e64 100644 --- a/static/panes/device-view.js +++ b/static/panes/device-view.js @@ -45,12 +45,15 @@ function DeviceAsm(hub, container, state) { this.prevDecorations = []; var root = this.domRoot.find('.monaco-placeholder'); - this.deviceEditor = monaco.editor.create(root[0], monacoConfig.extendConfig({ - language: 'asm', - readOnly: true, - glyphMargin: true, - lineNumbersMinChars: 3, - })); + this.deviceEditor = monaco.editor.create( + root[0], + monacoConfig.extendConfig({ + language: 'asm', + readOnly: true, + glyphMargin: true, + lineNumbersMinChars: 3, + }) + ); this._compilerId = state.id; this._compilerName = state.compilerName; @@ -129,15 +132,18 @@ DeviceAsm.prototype.initButtons = function (state) { DeviceAsm.prototype.initCallbacks = function () { this.linkedFadeTimeoutId = -1; this.mouseMoveThrottledFunction = _.throttle(_.bind(this.onMouseMove, this), 50); - this.deviceEditor.onMouseMove(_.bind(function (e) { - this.mouseMoveThrottledFunction(e); - }, this)); + this.deviceEditor.onMouseMove( + _.bind(function (e) { + this.mouseMoveThrottledFunction(e); + }, this) + ); - this.cursorSelectionThrottledFunction = - _.throttle(_.bind(this.onDidChangeCursorSelection, this), 500); - this.deviceEditor.onDidChangeCursorSelection(_.bind(function (e) { - this.cursorSelectionThrottledFunction(e); - }, this)); + this.cursorSelectionThrottledFunction = _.throttle(_.bind(this.onDidChangeCursorSelection, this), 500); + this.deviceEditor.onDidChangeCursorSelection( + _.bind(function (e) { + this.cursorSelectionThrottledFunction(e); + }, this) + ); this.fontScale.on('change', _.bind(this.updateState, this)); this.selectize.on('change', _.bind(this.onDeviceSelect, this)); @@ -188,23 +194,30 @@ DeviceAsm.prototype.onCompileResponse = function (id, compiler, result) { DeviceAsm.prototype.makeDeviceSelector = function (deviceNames) { var selectize = this.selectize; - _.each(selectize.options, function (p) { - if (deviceNames.indexOf(p.name) === -1) { - selectize.removeOption(p.name); - } - }, this); + _.each( + selectize.options, + function (p) { + if (deviceNames.indexOf(p.name) === -1) { + selectize.removeOption(p.name); + } + }, + this + ); - _.each(deviceNames, function (p) { - selectize.addOption({name: p}); - }, this); + _.each( + deviceNames, + function (p) { + selectize.addOption({name: p}); + }, + this + ); if (!this.selectedDevice && deviceNames.length > 0) { this.selectedDevice = deviceNames[0]; selectize.setValue(this.selectedDevice, true); } else if (this.selectedDevice && deviceNames.indexOf(this.selectedDevice) === -1) { selectize.clear(true); - this.showDeviceAsmResults( - [{text: ''}]); + this.showDeviceAsmResults([{text: ''}]); } else { selectize.setValue(this.selectedDevice, true); this.updateDeviceAsm(); @@ -220,12 +233,11 @@ DeviceAsm.prototype.onDeviceSelect = function () { DeviceAsm.prototype.updateDeviceAsm = function () { if (this.selectedDevice && this.devices[this.selectedDevice]) this.showDeviceAsmResults(this.devices[this.selectedDevice].asm); - else - this.showDeviceAsmResults([{text: ''}]); + else this.showDeviceAsmResults([{text: ''}]); }; DeviceAsm.prototype.getPaneTag = function () { - if(this._editorId) { + if (this._editorId) { return this._compilerName + ' (Editor #' + this._editorId + ', Compiler #' + this._compilerId + ')'; } else { return this._compilerName + ' (Tree #' + this._treeId + ', Compiler #' + this._compilerId + ')'; @@ -247,14 +259,14 @@ DeviceAsm.prototype.updateTitle = function () { DeviceAsm.prototype.showDeviceAsmResults = function (deviceCode) { if (!this.deviceEditor) return; this.deviceCode = deviceCode; - this.deviceEditor.getModel().setValue( - deviceCode.length ? _.pluck(deviceCode, 'text').join('\n') : ''); + this.deviceEditor + .getModel() + .setValue(deviceCode.length ? _.pluck(deviceCode, 'text').join('\n') : ''); if (!this.awaitingInitialResults) { if (this.selection) { this.deviceEditor.setSelection(this.selection); - this.deviceEditor.revealLinesInCenter(this.selection.startLineNumber, - this.selection.endLineNumber); + this.deviceEditor.revealLinesInCenter(this.selection.startLineNumber, this.selection.endLineNumber); } this.awaitingInitialResults = true; } @@ -358,10 +370,11 @@ DeviceAsm.prototype.onDidChangeCursorSelection = function (e) { } }; - DeviceAsm.prototype.updateDecorations = function () { this.prevDecorations = this.deviceEditor.deltaDecorations( - this.prevDecorations, _.flatten(_.values(this.decorations))); + this.prevDecorations, + _.flatten(_.values(this.decorations)) + ); }; DeviceAsm.prototype.clearLinkedLines = function () { @@ -393,10 +406,13 @@ DeviceAsm.prototype.onPanesLinkLine = function (compilerId, lineNumber, revealLi if (this.linkedFadeTimeoutId !== -1) { clearTimeout(this.linkedFadeTimeoutId); } - this.linkedFadeTimeoutId = setTimeout(_.bind(function () { - this.clearLinkedLines(); - this.linkedFadeTimeoutId = -1; - }, this), 5000); + this.linkedFadeTimeoutId = setTimeout( + _.bind(function () { + this.clearLinkedLines(); + this.linkedFadeTimeoutId = -1; + }, this), + 5000 + ); this.updateDecorations(); } }; diff --git a/static/panes/diff.js b/static/panes/diff.js index bff554d00..1ce4d3711 100644 --- a/static/panes/diff.js +++ b/static/panes/diff.js @@ -33,8 +33,7 @@ var TomSelect = require('tom-select'); var PaneRenaming = require('../widgets/pane-renaming').PaneRenaming; // note that these variables are saved to state, so don't change, only add to it -var - DiffType_ASM = 0, +var DiffType_ASM = 0, DiffType_CompilerStdOut = 1, DiffType_CompilerStdErr = 2, DiffType_ExecStdOut = 3, @@ -73,22 +72,17 @@ State.prototype.refresh = function () { output = this.result.stderr || []; break; case DiffType_ExecStdOut: - if (this.result.execResult) - output = this.result.execResult.stdout || []; + if (this.result.execResult) output = this.result.execResult.stdout || []; break; case DiffType_ExecStdErr: - if (this.result.execResult) - output = this.result.execResult.stderr || []; + if (this.result.execResult) output = this.result.execResult.stderr || []; break; case DiffType_GNAT_ExpandedCode: - if (this.result.hasGnatDebugOutput) - output = this.result.gnatDebugOutput || []; + if (this.result.hasGnatDebugOutput) output = this.result.gnatDebugOutput || []; break; case DiffType_GNAT_Tree: - if (this.result.hasGnatDebugTreeOutput) - output = this.result.gnatDebugTreeOutput || []; + if (this.result.hasGnatDebugTreeOutput) output = this.result.gnatDebugTreeOutput || []; break; - } } this.model.setValue(_.pluck(output, 'text').join('\n')); @@ -126,94 +120,104 @@ function Diff(hub, container, state) { this.selectize = {}; - this.domRoot[0].querySelectorAll('.difftype-picker').forEach(_.bind(function (picker) { - - var instance = new TomSelect(picker, { - sortField: 'name', - valueField: 'id', - labelField: 'name', - searchField: ['name'], - options: [ - {id: DiffType_ASM, name: 'Assembly'}, - {id: DiffType_CompilerStdOut, name: 'Compiler stdout'}, - {id: DiffType_CompilerStdErr, name: 'Compiler stderr'}, - {id: DiffType_ExecStdOut, name: 'Execution stdout'}, - {id: DiffType_ExecStdErr, name: 'Execution stderr'}, - {id: DiffType_GNAT_ExpandedCode, name: 'GNAT Expanded Code'}, - {id: DiffType_GNAT_Tree, name: 'GNAT Tree Code'}, - ], - items: [], - render: { - option: function (item, escape) { - return '
' + escape(item.name) + '
'; + this.domRoot[0].querySelectorAll('.difftype-picker').forEach( + _.bind(function (picker) { + var instance = new TomSelect(picker, { + sortField: 'name', + valueField: 'id', + labelField: 'name', + searchField: ['name'], + options: [ + {id: DiffType_ASM, name: 'Assembly'}, + {id: DiffType_CompilerStdOut, name: 'Compiler stdout'}, + {id: DiffType_CompilerStdErr, name: 'Compiler stderr'}, + {id: DiffType_ExecStdOut, name: 'Execution stdout'}, + {id: DiffType_ExecStdErr, name: 'Execution stderr'}, + {id: DiffType_GNAT_ExpandedCode, name: 'GNAT Expanded Code'}, + {id: DiffType_GNAT_Tree, name: 'GNAT Tree Code'}, + ], + items: [], + render: { + option: function (item, escape) { + return '
' + escape(item.name) + '
'; + }, }, - }, - dropdownParent: 'body', - plugins: ['input_autogrow'], - onChange: _.bind(function (value) { - if (picker.classList.contains('lhsdifftype')) { - this.lhs.difftype = parseInt(value); - this.lhs.refresh(); - } else { - this.rhs.difftype = parseInt(value); - this.rhs.refresh(); - } - this.updateState(); - }, this), - }); + dropdownParent: 'body', + plugins: ['input_autogrow'], + onChange: _.bind(function (value) { + if (picker.classList.contains('lhsdifftype')) { + this.lhs.difftype = parseInt(value); + this.lhs.refresh(); + } else { + this.rhs.difftype = parseInt(value); + this.rhs.refresh(); + } + this.updateState(); + }, this), + }); - if (picker.classList.contains('lhsdifftype')) { - this.selectize.lhsdifftype = instance; - } else { - this.selectize.rhsdifftype = instance; - } + if (picker.classList.contains('lhsdifftype')) { + this.selectize.lhsdifftype = instance; + } else { + this.selectize.rhsdifftype = instance; + } + }, this) + ); - }, this)); - - - this.domRoot[0].querySelectorAll('.diff-picker').forEach(_.bind(function (picker) { - var instance = new TomSelect(picker, { - sortField: 'name', - valueField: 'id', - labelField: 'name', - searchField: ['name'], - options: [], - items: [], - render: { - option: function (item, escape) { - var origin = item.editorId !== false ? 'Editor #' + item.editorId : 'Tree #' + item.treeId; - return '
' + - '' + escape(item.compiler.name) + '' + - '' + escape(item.options) + '' + - '
    ' + - '
  • ' + escape(origin) + '
  • ' + - '
  • ' + escape(getItemDisplayTitle(item)) + '
  • ' + - '
'; + this.domRoot[0].querySelectorAll('.diff-picker').forEach( + _.bind(function (picker) { + var instance = new TomSelect(picker, { + sortField: 'name', + valueField: 'id', + labelField: 'name', + searchField: ['name'], + options: [], + items: [], + render: { + option: function (item, escape) { + var origin = item.editorId !== false ? 'Editor #' + item.editorId : 'Tree #' + item.treeId; + return ( + '
' + + '' + + escape(item.compiler.name) + + '' + + '' + + escape(item.options) + + '' + + '
    ' + + '
  • ' + + escape(origin) + + '
  • ' + + '
  • ' + + escape(getItemDisplayTitle(item)) + + '
  • ' + + '
' + ); + }, }, - }, - dropdownParent: 'body', - plugins: ['input_autogrow'], - onChange: _.bind(function (value) { + dropdownParent: 'body', + plugins: ['input_autogrow'], + onChange: _.bind(function (value) { + var compiler = this.compilers[value]; + if (!compiler) return; + if (picker.classList.contains('lhs')) { + this.lhs.compiler = compiler; + this.lhs.id = compiler.id; + } else { + this.rhs.compiler = compiler; + this.rhs.id = compiler.id; + } + this.onDiffSelect(compiler.id); + }, this), + }); - var compiler = this.compilers[value]; - if (!compiler) return; - if (picker.classList.contains('lhs')) { - this.lhs.compiler = compiler; - this.lhs.id = compiler.id; - } else { - this.rhs.compiler = compiler; - this.rhs.id = compiler.id; - } - this.onDiffSelect(compiler.id); - }, this), - }); - - if (picker.classList.contains('lhs')) { - this.selectize.lhs = instance; - } else { - this.selectize.rhs = instance; - } - }, this)); + if (picker.classList.contains('lhs')) { + this.selectize.lhs = instance; + } else { + this.selectize.rhs = instance; + } + }, this) + ); this.paneRenaming = new PaneRenaming(this, state); @@ -283,10 +287,14 @@ Diff.prototype.initCallbacks = function () { this.eventHub.on('executorClose', this.onExecutorClose, this); this.eventHub.on('settingsChange', this.onSettingsChange, this); this.eventHub.on('themeChange', this.onThemeChange, this); - this.container.on('destroy', function () { - this.eventHub.unsubscribe(); - this.outputEditor.dispose(); - }, this); + this.container.on( + 'destroy', + function () { + this.eventHub.unsubscribe(); + this.outputEditor.dispose(); + }, + this + ); this.container.on('resize', this.resize, this); this.container.on('shown', this.resize, this); @@ -369,9 +377,13 @@ Diff.prototype.getPaneName = function () { Diff.prototype.updateCompilersFor = function (selectize, id) { selectize.clearOptions(); - _.each(this.compilers, function (compiler) { - selectize.addOption(compiler); - }, this); + _.each( + this.compilers, + function (compiler) { + selectize.addOption(compiler); + }, + this + ); if (this.compilers[id]) { selectize.setValue(id); } @@ -398,8 +410,7 @@ Diff.prototype.updateState = function () { }; Diff.prototype.onThemeChange = function (newTheme) { - if (this.outputEditor) - this.outputEditor.updateOptions({theme: newTheme.monaco}); + if (this.outputEditor) this.outputEditor.updateOptions({theme: newTheme.monaco}); }; Diff.prototype.onSettingsChange = function (newSettings) { diff --git a/static/rison.js b/static/rison.js index 118561dbf..29026c930 100644 --- a/static/rison.js +++ b/static/rison.js @@ -1,4 +1,5 @@ /* eslint-disable */ +// prettier-ignore // Taken from https://github.com/Nanonid/rison at 917679fb6cafa15e2a186cd5a47163792899b321 // Uses CommonJS, AMD or browser globals to create a module. // Based on: https://github.com/umdjs/umd/blob/master/commonjsStrict.js diff --git a/static/themes/dark-theme.scss b/static/themes/dark-theme.scss index 0ee9f6d39..f546f2580 100644 --- a/static/themes/dark-theme.scss +++ b/static/themes/dark-theme.scss @@ -1,4 +1,4 @@ -@import "~golden-layout/src/css/goldenlayout-dark-theme"; +@import '~golden-layout/src/css/goldenlayout-dark-theme'; /* * replace low res golden-layout icons with svg recreations to improve high DPI displays @@ -145,14 +145,18 @@ a.navbar-brand img.logo.normal { .rainbow-decoration { -webkit-background-clip: text; -webkit-text-fill-color: transparent; - background-image: -webkit-gradient(linear, left top, right bottom, - color-stop(0.00, red), - color-stop(16%, orange), - color-stop(32%, yellow), - color-stop(48%, green), - color-stop(60%, blue), - color-stop(76%, indigo), - color-stop(1.00, violet)); + background-image: -webkit-gradient( + linear, + left top, + right bottom, + color-stop(0, red), + color-stop(16%, orange), + color-stop(32%, yellow), + color-stop(48%, green), + color-stop(60%, blue), + color-stop(76%, indigo), + color-stop(1, violet) + ); } .ts-wrapper.single .ts-control { @@ -166,7 +170,7 @@ a.navbar-brand img.logo.normal { border-color: #728690 transparent transparent transparent; } -.ts-dropdown .option:hover{ +.ts-dropdown .option:hover { background-color: #8d8d8e; } .ts-dropdown .active { @@ -354,7 +358,7 @@ textarea.form-control { .ts-dropdown .optgroup-header { background-color: #555 !important; - color: #EEE !important; + color: #eee !important; text-shadow: none !important; } @@ -370,7 +374,12 @@ textarea.form-control { border-color: #464545 !important; } -.popover, .popover-content, .libs-container, .lib-list, .popover-body, .popover-header { +.popover, +.popover-content, +.libs-container, +.lib-list, +.popover-body, +.popover-header { background-color: #151515 !important; color: #f2f2f2 !important; } @@ -379,12 +388,14 @@ textarea.form-control { background-color: #333 !important; } -#socialshare .share-twitter, .share-twitter { +#socialshare .share-twitter, +.share-twitter { background-color: #1da1f2 !important; color: white !important; } -#socialshare .share-reddit, .share-reddit { +#socialshare .share-reddit, +.share-reddit { background-color: #ff4500 !important; color: white !important; } @@ -486,7 +497,8 @@ a { color: #45bbe0 !important; } -.fa, .fas { +.fa, +.fas { color: white; } @@ -495,8 +507,8 @@ a { } .navbar-light .navbar-toggler { - color: rgba(255,255,255,.5); - border-color: rgba(255,255,255,.1); + color: rgba(255, 255, 255, 0.5); + border-color: rgba(255, 255, 255, 0.1); } #library-selection .libs-selected-col button { @@ -519,7 +531,8 @@ a { border-bottom: 1px solid #3e3e3e; } -.tree ul, .tree li { +.tree ul, +.tree li { background-color: #222222 !important; color: white; } diff --git a/static/themes/default-theme.scss b/static/themes/default-theme.scss index 12eefeaad..5e34dc199 100644 --- a/static/themes/default-theme.scss +++ b/static/themes/default-theme.scss @@ -1,4 +1,4 @@ -@import "~golden-layout/src/css/goldenlayout-light-theme"; +@import '~golden-layout/src/css/goldenlayout-light-theme'; /* * replace low res golden-layout icons with svg recreations to improve high DPI displays @@ -45,7 +45,7 @@ } body { - background-color: #FFFFFF; + background-color: #ffffff; } .navbar-nav a.nav-link { @@ -108,14 +108,18 @@ a.navbar-brand img.logo.normal { .rainbow-decoration { -webkit-background-clip: text; -webkit-text-fill-color: transparent; - background-image: -webkit-gradient(linear, left top, right bottom, - color-stop(0.00, red), - color-stop(16%, orange), - color-stop(32%, yellow), - color-stop(48%, green), - color-stop(60%, blue), - color-stop(76%, indigo), - color-stop(1.00, violet)); + background-image: -webkit-gradient( + linear, + left top, + right bottom, + color-stop(0, red), + color-stop(16%, orange), + color-stop(32%, yellow), + color-stop(48%, green), + color-stop(60%, blue), + color-stop(76%, indigo), + color-stop(1, violet) + ); } .font-option { @@ -131,7 +135,7 @@ a.navbar-brand img.logo.normal { } .font-option-active:hover { - background: #4477AA; + background: #4477aa; } .linked-code-decoration-margin { @@ -189,7 +193,7 @@ a.navbar-brand img.logo.normal { } .graph-placeholder { - background-color: #FFFFFF; + background-color: #ffffff; } .text-count { @@ -208,7 +212,10 @@ a.navbar-brand img.logo.normal { background-color: #f2f2f2; } -.popover, .popover-content, .libs-container, .lib-list { +.popover, +.popover-content, +.libs-container, +.lib-list { background-color: #fefefe; } @@ -216,12 +223,14 @@ a.navbar-brand img.logo.normal { background-color: green; } -#socialshare .share-twitter, .share-twitter { +#socialshare .share-twitter, +.share-twitter { background-color: #1da1f2; color: white; } -#socialshare .share-reddit, .share-reddit { +#socialshare .share-reddit, +.share-reddit { background-color: #ff4500; color: white; } diff --git a/test/_setup-log.js b/test/_setup-log.js index a020ba908..85391881f 100644 --- a/test/_setup-log.js +++ b/test/_setup-log.js @@ -24,9 +24,9 @@ // This file is not force-required: it must be loaded by mocha to get access // to `before`. -import { suppressConsoleLog } from '../lib/logger'; +import {suppressConsoleLog} from '../lib/logger'; -if (typeof (before) === 'function') { +if (typeof before === 'function') { // this hook will run once before any tests are executed before(() => { suppressConsoleLog(); diff --git a/test/analysis-tests.js b/test/analysis-tests.js index 28a899fd0..39f47f7d0 100644 --- a/test/analysis-tests.js +++ b/test/analysis-tests.js @@ -22,9 +22,9 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { LLVMmcaTool } from '../lib/compilers/llvm-mca'; +import {LLVMmcaTool} from '../lib/compilers/llvm-mca'; -import { makeCompilationEnvironment } from './utils'; +import {makeCompilationEnvironment} from './utils'; const languages = { analysis: {id: 'analysis'}, diff --git a/test/asm-tests.js b/test/asm-tests.js index c106cfc7b..94fb0aecc 100644 --- a/test/asm-tests.js +++ b/test/asm-tests.js @@ -22,9 +22,9 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AsmParser } from '../lib/parsers/asm-parser'; -import { VcAsmParser } from '../lib/parsers/asm-parser-vc'; -import { AsmRegex } from '../lib/parsers/asmregex'; +import {AsmParser} from '../lib/parsers/asm-parser'; +import {VcAsmParser} from '../lib/parsers/asm-parser-vc'; +import {AsmRegex} from '../lib/parsers/asmregex'; describe('ASM CL parser', () => { it('should work for error documents', () => { @@ -33,10 +33,12 @@ describe('ASM CL parser', () => { directives: true, }); - result.asm.should.deep.equal([{ - source: null, - text: '', - }]); + result.asm.should.deep.equal([ + { + source: null, + text: '', + }, + ]); }); }); @@ -52,10 +54,12 @@ describe('ASM regex base class', () => { it('should keep whitespace in strings', () => { AsmRegex.filterAsmLine('equs "this string"', {trim: true}).should.equal('equs "this string"'); AsmRegex.filterAsmLine(' equs "this string"', {trim: true}).should.equal(' equs "this string"'); - AsmRegex.filterAsmLine('equs "this \\" string \\""', {trim: true}).should.equal('equs "this \\" string \\""'); + AsmRegex.filterAsmLine('equs "this \\" string \\""', {trim: true}).should.equal( + 'equs "this \\" string \\""', + ); }); it('should not get upset by mismatched strings', () => { - AsmRegex.filterAsmLine("a \"string 'yeah", {trim: true}).should.equal("a \"string 'yeah"); + AsmRegex.filterAsmLine('a "string \'yeah', {trim: true}).should.equal('a "string \'yeah'); }); }); diff --git a/test/aws-tests.js b/test/aws-tests.js index e86172943..8b31783c6 100644 --- a/test/aws-tests.js +++ b/test/aws-tests.js @@ -65,12 +65,7 @@ function setup() { AWS.mock('EC2', 'describeInstances', { Reservations: [ { - Instances: [ - instanceA, - instanceB, - instanceC, - instanceD, - ], + Instances: [instanceA, instanceB, instanceC, instanceD], }, ], }); @@ -87,7 +82,6 @@ function setup() { }, ], }); - }); afterEach(() => AWS.restore()); } @@ -117,12 +111,13 @@ describe('AWS instance fetcher tests', () => { describe('AWS config tests', () => { setup(); - it('Doesn\'t fetch unless region is configured', () => { + it("Doesn't fetch unless region is configured", () => { const fakeProps = { region: '', configValue: 'fromConfigFile', }; - return aws.initConfig(prop => fakeProps[prop]) + return aws + .initConfig(prop => fakeProps[prop]) .then(() => { aws.getConfig('configValue').should.equal('fromConfigFile'); }); @@ -134,7 +129,8 @@ describe('AWS config tests', () => { configValue: 'fromConfigFile', notInAmazon: 'yay', }; - return aws.initConfig(prop => fakeProps[prop]) + return aws + .initConfig(prop => fakeProps[prop]) .then(() => { aws.getConfig('configValue').should.equal('fromAws'); aws.getConfig('onlyOnAws').should.equal('bibble'); diff --git a/test/base-compiler-tests.js b/test/base-compiler-tests.js index c982ecfe0..8c5e4a73b 100644 --- a/test/base-compiler-tests.js +++ b/test/base-compiler-tests.js @@ -22,14 +22,14 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { match, mock, restore, stub } from 'sinon'; +import {match, mock, restore, stub} from 'sinon'; -import { BaseCompiler } from '../lib/base-compiler'; -import { BuildEnvSetupBase } from '../lib/buildenvsetup'; -import { Win32Compiler } from '../lib/compilers/win32'; +import {BaseCompiler} from '../lib/base-compiler'; +import {BuildEnvSetupBase} from '../lib/buildenvsetup'; +import {Win32Compiler} from '../lib/compilers/win32'; import * as exec from '../lib/exec'; -import { fs, makeCompilationEnvironment, path, should } from './utils'; +import {fs, makeCompilationEnvironment, path, should} from './utils'; const languages = { 'c++': {id: 'c++'}, @@ -51,15 +51,21 @@ describe('Basic compiler invariants', function () { it('should recognize when optOutput has been request', () => { compiler.optOutputRequested(['please', 'recognize', '-fsave-optimization-record']).should.equal(true); - compiler.optOutputRequested(['please', 'don\'t', 'recognize']).should.equal(false); + compiler.optOutputRequested(['please', "don't", 'recognize']).should.equal(false); }); // Overkill test, but now we're safer! it('should recognize cfg compilers', () => { - compiler.isCfgCompiler('clang version 5.0.0 (https://github.com/asutton/clang.git 449c8c3e91355a3b2b6761e11d9fb5d3c125b791) (https://github.com/llvm-mirror/llvm.git 40b1e969f9cb2a0c697e247435193fb006ef1311)').should.equal(true); + compiler + .isCfgCompiler( + 'clang version 5.0.0 (https://github.com/asutton/clang.git 449c8c3e91355a3b2b6761e11d9fb5d3c125b791) (https://github.com/llvm-mirror/llvm.git 40b1e969f9cb2a0c697e247435193fb006ef1311)', + ) + .should.equal(true); compiler.isCfgCompiler('clang version 4.0.0 (tags/RELEASE_400/final 299826)').should.equal(true); compiler.isCfgCompiler('clang version 7.0.0 (trunk 325868)').should.equal(true); compiler.isCfgCompiler('clang version 3.3 (tags/RELEASE_33/final)').should.equal(true); - compiler.isCfgCompiler('clang version 6.0.0 (tags/RELEASE_600/final 327031) (llvm/tags/RELEASE_600/final 327028)').should.equal(true); + compiler + .isCfgCompiler('clang version 6.0.0 (tags/RELEASE_600/final 327031) (llvm/tags/RELEASE_600/final 327028)') + .should.equal(true); compiler.isCfgCompiler('g++ (GCC-Explorer-Build) 4.9.4').should.equal(true); compiler.isCfgCompiler('g++ (GCC-Explorer-Build) 8.0.1 20180223 (experimental)').should.equal(true); @@ -73,8 +79,12 @@ describe('Basic compiler invariants', function () { compiler.isCfgCompiler('fake-for-test (Based on g++)').should.equal(false); compiler.isCfgCompiler('gdc (crosstool-NG 203be35 - 20160205-2.066.1-e95a735b97) 5.2.0').should.equal(true); - compiler.isCfgCompiler('gdc (crosstool-NG hg+unknown-20131212.080758 - 20140430-2.064.2-404a037d26) 4.8.2').should.equal(true); - compiler.isCfgCompiler('gdc (crosstool-NG crosstool-ng-1.20.0-232-gc746732 - 20150830-2.066.1-d0dd4a83de) 4.9.3').should.equal(true); + compiler + .isCfgCompiler('gdc (crosstool-NG hg+unknown-20131212.080758 - 20140430-2.064.2-404a037d26) 4.8.2') + .should.equal(true); + compiler + .isCfgCompiler('gdc (crosstool-NG crosstool-ng-1.20.0-232-gc746732 - 20150830-2.066.1-d0dd4a83de) 4.9.3') + .should.equal(true); compiler.isCfgCompiler('fake-for-test (Based on gdc)').should.equal(false); }); @@ -178,7 +188,14 @@ describe('Compiler execution', function () { const outputFilename = 'example.s'; const libraries = []; - const args = compiler.prepareArguments(userOptions, filters, backendOptions, inputFilename, outputFilename, libraries); + const args = compiler.prepareArguments( + userOptions, + filters, + backendOptions, + inputFilename, + outputFilename, + libraries, + ); args.should.deep.equal([ '-g', '-o', @@ -199,7 +216,14 @@ describe('Compiler execution', function () { const outputFilename = 'example.s'; const libraries = []; - const win32args = win32compiler.prepareArguments(userOptions, filters, backendOptions, inputFilename, outputFilename, libraries); + const win32args = win32compiler.prepareArguments( + userOptions, + filters, + backendOptions, + inputFilename, + outputFilename, + libraries, + ); win32args.should.deep.equal([ '/nologo', '/FA', @@ -239,15 +263,7 @@ describe('Compiler execution', function () { stdout: 'stdout', stderr: 'stderr', }); - const result = await compiler.compile( - 'source', - 'options', - {}, - {}, - false, - [], - {}, - []); + const result = await compiler.compile('source', 'options', {}, {}, false, [], {}, []); result.code.should.equal(0); result.compilationOptions.should.contain('options'); result.compilationOptions.should.contain(result.inputFilename); @@ -268,15 +284,7 @@ describe('Compiler execution', function () { stdout: '', stderr: 'oh noes', }); - const result = await compiler.compile( - 'source', - 'options', - {}, - {}, - false, - [], - {}, - []); + const result = await compiler.compile('source', 'options', {}, {}, false, [], {}, []); result.code.should.equal(1); result.asm.should.deep.equal([{labels: [], source: null, text: ''}]); }); @@ -294,15 +302,7 @@ describe('Compiler execution', function () { const source = 'Some cacheable source'; const options = 'Some cacheable options'; ceMock.expects('cachePut').withArgs(match({source, options}), match(fakeExecResults)).resolves(); - const uncachedResult = await compiler.compile( - source, - options, - {}, - {}, - false, - [], - {}, - []); + const uncachedResult = await compiler.compile(source, options, {}, {}, false, [], {}, []); uncachedResult.code.should.equal(0); ceMock.verify(); }); @@ -320,15 +320,7 @@ describe('Compiler execution', function () { ceMock.expects('cachePut').never(); const source = 'Some cacheable source'; const options = 'Some cacheable options'; - const uncachedResult = await compiler.compile( - source, - options, - {}, - {}, - false, - [], - {}, - []); + const uncachedResult = await compiler.compile(source, options, {}, {}, false, [], {}, []); uncachedResult.code.should.equal(0); ceMock.verify(); }); @@ -338,15 +330,7 @@ describe('Compiler execution', function () { const source = 'Some previously cached source'; const options = 'Some previously cached options'; ceMock.expects('cacheGet').withArgs(match({source, options})).resolves({code: 123}); - const cachedResult = await compiler.compile( - source, - options, - {}, - {}, - false, - [], - {}, - []); + const cachedResult = await compiler.compile(source, options, {}, {}, false, [], {}, []); cachedResult.code.should.equal(123); ceMock.verify(); }); @@ -364,15 +348,7 @@ describe('Compiler execution', function () { ceMock.expects('cacheGet').never(); const execStub = stub(compiler, 'exec'); stubOutCallToExec(execStub, compiler, 'This is the output file', fakeExecResults); - const uncachedResult = await compiler.compile( - source, - options, - {}, - {}, - true, - [], - {}, - []); + const uncachedResult = await compiler.compile(source, options, {}, {}, true, [], {}, []); uncachedResult.code.should.equal(0); ceMock.verify(); }); @@ -380,18 +356,30 @@ describe('Compiler execution', function () { it('should execute', async () => { const execMock = mock(exec); const execStub = stub(compiler, 'exec'); - stubOutCallToExec(execStub, compiler, 'This is the output asm file', { - code: 0, - okToCache: true, - stdout: 'asm stdout', - stderr: 'asm stderr', - }, 0); - stubOutCallToExec(execStub, compiler, 'This is the output binary file', { - code: 0, - okToCache: true, - stdout: 'binary stdout', - stderr: 'binary stderr', - }, 1); + stubOutCallToExec( + execStub, + compiler, + 'This is the output asm file', + { + code: 0, + okToCache: true, + stdout: 'asm stdout', + stderr: 'asm stderr', + }, + 0, + ); + stubOutCallToExec( + execStub, + compiler, + 'This is the output binary file', + { + code: 0, + okToCache: true, + stdout: 'binary stdout', + stderr: 'binary stderr', + }, + 1, + ); execMock.expects('sandbox').withArgs(match.string, match.array, match.object).resolves({ code: 0, stdout: 'exec stdout', @@ -414,18 +402,30 @@ describe('Compiler execution', function () { compiler.compiler.executionWrapper = executionWrapper; const execMock = mock(exec); const execStub = stub(compiler, 'exec'); - stubOutCallToExec(execStub, compiler, 'This is the output asm file', { - code: 0, - okToCache: true, - stdout: 'asm stdout', - stderr: 'asm stderr', - }, 0); - stubOutCallToExec(execStub, compiler, 'This is the output binary file', { - code: 0, - okToCache: true, - stdout: 'binary stdout', - stderr: 'binary stderr', - }, 1); + stubOutCallToExec( + execStub, + compiler, + 'This is the output asm file', + { + code: 0, + okToCache: true, + stdout: 'asm stdout', + stderr: 'asm stderr', + }, + 0, + ); + stubOutCallToExec( + execStub, + compiler, + 'This is the output binary file', + { + code: 0, + okToCache: true, + stdout: 'binary stdout', + stderr: 'binary stderr', + }, + 1, + ); execMock.expects('sandbox').withArgs(executionWrapper, match.array, match.object).resolves({ code: 0, stdout: 'exec stdout', @@ -438,18 +438,30 @@ describe('Compiler execution', function () { it('should not execute where not supported', async () => { const execMock = mock(exec); const execStub = stub(compilerNoExec, 'exec'); - stubOutCallToExec(execStub, compilerNoExec, 'This is the output asm file', { - code: 0, - okToCache: true, - stdout: 'asm stdout', - stderr: 'asm stderr', - }, 0); - stubOutCallToExec(execStub, compilerNoExec, 'This is the output binary file', { - code: 0, - okToCache: true, - stdout: 'binary stdout', - stderr: 'binary stderr', - }, 1); + stubOutCallToExec( + execStub, + compilerNoExec, + 'This is the output asm file', + { + code: 0, + okToCache: true, + stdout: 'asm stdout', + stderr: 'asm stderr', + }, + 0, + ); + stubOutCallToExec( + execStub, + compilerNoExec, + 'This is the output binary file', + { + code: 0, + okToCache: true, + stdout: 'binary stdout', + stderr: 'binary stderr', + }, + 1, + ); const result = await compilerNoExec.compile('source', 'options', {}, {execute: true}, false, [], {}, []); result.code.should.equal(0); result.execResult.didExecute.should.be.false; @@ -483,15 +495,7 @@ describe('Compiler execution', function () { }); }); - const result = await compiler.compile( - 'source', - 'options', - {}, - {demangle: true}, - false, - [], - {}, - []); + const result = await compiler.compile('source', 'options', {}, {demangle: true}, false, [], {}, []); result.code.should.equal(0); result.asm.should.deep.equal([{source: null, labels: [], text: 'someDemangledSymbol:'}]); // TODO all with demangle: false @@ -517,41 +521,24 @@ describe('Compiler execution', function () { }); }); compiler.supportsObjdump().should.be.true; - const result = await compiler.objdump( - 'output', - {}, - 123456, - true, - true); + const result = await compiler.objdump('output', {}, 123456, true, true); result.asm.should.deep.equal(''); } it('should run default objdump properly', async () => { - return objdumpTest('default', [ - '-d', 'output', - '-l', '--insn-width=16', - '-C', '-M', 'intel']); + return objdumpTest('default', ['-d', 'output', '-l', '--insn-width=16', '-C', '-M', 'intel']); }); it('should run binutils objdump properly', async () => { - return objdumpTest('binutils', [ - '-d', 'output', - '-l', '--insn-width=16', - '-C', '-M', 'intel']); + return objdumpTest('binutils', ['-d', 'output', '-l', '--insn-width=16', '-C', '-M', 'intel']); }); it('should run ELF Tool Chain objdump properly', async () => { - return objdumpTest('elftoolchain', [ - '-d', 'output', - '-l', - '-C', '-M', 'intel']); + return objdumpTest('elftoolchain', ['-d', 'output', '-l', '-C', '-M', 'intel']); }); it('should run LLVM objdump properly', async () => { - return objdumpTest('llvm', [ - '-d', 'output', - '-l', - '-C', '--x86-asm-syntax=intel']); + return objdumpTest('llvm', ['-d', 'output', '-l', '-C', '--x86-asm-syntax=intel']); }); it('should run process opt output', async () => { @@ -567,15 +554,17 @@ Args: [] const optPath = path.join(dirPath, 'temp.out'); await fs.writeFile(optPath, test); const a = await compiler.processOptOutput(optPath); - a.should.deep.equal([{ - Args: [], - DebugLoc: {Column: 21, File: 'example.cpp', Line: 4}, - Function: 'main', - Name: 'NeverInline', - Pass: 'inline', - displayString: '', - optType: 'Missed', - }]); + a.should.deep.equal([ + { + Args: [], + DebugLoc: {Column: 21, File: 'example.cpp', Line: 4}, + Function: 'main', + Name: 'NeverInline', + Pass: 'inline', + displayString: '', + optType: 'Missed', + }, + ]); }); it('should normalize extra file path', () => { @@ -606,7 +595,9 @@ Args: [] } try { - compiler.getExtraFilepath('/tmp/somefolder', '/tmp/someotherfolder/test.h').should.equal('/tmp/somefolder/tmp/someotherfolder/test.h'); + compiler + .getExtraFilepath('/tmp/somefolder', '/tmp/someotherfolder/test.h') + .should.equal('/tmp/somefolder/tmp/someotherfolder/test.h'); } catch (error) { if (!(error instanceof Error)) { throw error; @@ -637,7 +628,9 @@ Args: [] } try { - compiler.getExtraFilepath('/tmp/somefolder', 'subfolder/hello.h').should.equal('/tmp/somefolder/subfolder/hello.h'); + compiler + .getExtraFilepath('/tmp/somefolder', 'subfolder/hello.h') + .should.equal('/tmp/somefolder/subfolder/hello.h'); } catch (error) { if (!(error instanceof Error)) { throw error; diff --git a/test/base-formatter-tests.js b/test/base-formatter-tests.js index 28bce0639..0115c48c4 100644 --- a/test/base-formatter-tests.js +++ b/test/base-formatter-tests.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { BaseFormatter } from '../lib/formatters/base'; +import {BaseFormatter} from '../lib/formatters/base'; describe('Basic formatter functionality', () => { it('should be one-true-style if the styles are empty', () => { diff --git a/test/cfg-tests.js b/test/cfg-tests.js index b992e01fc..bdacda9ba 100644 --- a/test/cfg-tests.js +++ b/test/cfg-tests.js @@ -24,7 +24,7 @@ import * as cfg from '../lib/cfg'; -import { fs, path, resolvePathFromTestRoot } from './utils'; +import {fs, path, resolvePathFromTestRoot} from './utils'; async function DoCfgTest(cfgArg, filename) { const contents = await fs.readJson(filename, 'utf-8'); diff --git a/test/checks.js b/test/checks.js index 355410bf1..ab266066d 100644 --- a/test/checks.js +++ b/test/checks.js @@ -24,10 +24,10 @@ import _ from 'underscore'; -import { languages } from '../lib/languages'; +import {languages} from '../lib/languages'; import * as properties from '../lib/properties'; -import { fs } from './utils'; +import {fs} from './utils'; describe('Live site checks', () => { let ceProps; @@ -64,6 +64,9 @@ describe('Live site checks', () => { differences[lang] = difference; } }); - differences.should.be.eql({}, 'One or more defined libraries are not listed on their corresponding language libs property array'); + differences.should.be.eql( + {}, + 'One or more defined libraries are not listed on their corresponding language libs property array', + ); }); }); diff --git a/test/compilation-env.js b/test/compilation-env.js index afc21b156..12f5ed870 100644 --- a/test/compilation-env.js +++ b/test/compilation-env.js @@ -23,8 +23,8 @@ // POSSIBILITY OF SUCH DAMAGE. import './utils'; -import { CompilationEnvironment } from '../lib/compilation-env'; -import { CompilerProps, fakeProps } from '../lib/properties'; +import {CompilationEnvironment} from '../lib/compilation-env'; +import {CompilerProps, fakeProps} from '../lib/properties'; const props = { optionsAllowedRe: '.*', @@ -41,20 +41,26 @@ describe('Compilation environment', () => { it('Should cache by default', () => { const ce = new CompilationEnvironment(compilerProps); - return ce.cacheGet('foo').should.eventually.equal(null) + return ce + .cacheGet('foo') + .should.eventually.equal(null) .then(() => ce.cachePut('foo', {res: 'bar'})) .then(() => ce.cacheGet('foo').should.eventually.eql({res: 'bar'})) .then(() => ce.cacheGet('baz').should.eventually.equal(null)); }); it('Should cache when asked', () => { const ce = new CompilationEnvironment(compilerProps, undefined, true); - return ce.cacheGet('foo').should.eventually.equal(null) + return ce + .cacheGet('foo') + .should.eventually.equal(null) .then(() => ce.cachePut('foo', {res: 'bar'})) .then(() => ce.cacheGet('foo').should.eventually.eql({res: 'bar'})); }); - it('Shouldn\'t cache when asked', () => { + it("Shouldn't cache when asked", () => { const ce = new CompilationEnvironment(compilerProps, undefined, false); - return ce.cacheGet('foo').should.eventually.equal(null) + return ce + .cacheGet('foo') + .should.eventually.equal(null) .then(() => ce.cachePut('foo', {res: 'bar'})) .then(() => ce.cacheGet('foo').should.eventually.equal(null)); }); diff --git a/test/compiler-finder-tests.js b/test/compiler-finder-tests.js index a2b616e5a..2d4c5b393 100644 --- a/test/compiler-finder-tests.js +++ b/test/compiler-finder-tests.js @@ -23,7 +23,7 @@ // POSSIBILITY OF SUCH DAMAGE. import './utils'; -import { CompilerFinder } from '../lib/compiler-finder'; +import {CompilerFinder} from '../lib/compiler-finder'; import * as properties from '../lib/properties'; const languages = { @@ -118,7 +118,6 @@ describe('Compiler-finder', function () { }); it('should not hang for undefined groups (Bug #860)', () => { - const finder = new CompilerFinder({}, compilerProps, properties.fakeProps({}), {}, optionsHandler); return finder.getCompilers().should.eventually.have.lengthOf(2); }); diff --git a/test/compilers/argument-parsers-tests.js b/test/compilers/argument-parsers-tests.js index 4c541d57b..c38d051f5 100644 --- a/test/compilers/argument-parsers-tests.js +++ b/test/compilers/argument-parsers-tests.js @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { CompilerArguments } from '../../lib/compiler-arguments'; -import { BaseParser, ClangParser, GCCParser, PascalParser } from '../../lib/compilers/argument-parsers'; -import { FakeCompiler } from '../../lib/compilers/fake-for-test'; -import { makeCompilationEnvironment, should } from '../utils'; +import {CompilerArguments} from '../../lib/compiler-arguments'; +import {BaseParser, ClangParser, GCCParser, PascalParser} from '../../lib/compilers/argument-parsers'; +import {FakeCompiler} from '../../lib/compilers/fake-for-test'; +import {makeCompilationEnvironment, should} from '../utils'; const languages = { 'c++': {id: 'c++'}, @@ -79,11 +79,12 @@ describe('option parser', () => { }); }); it('handles non-option text', () => { - return BaseParser.getOptions(makeCompiler('-foo=123\nthis is a fish\n-badger=123')).should.eventually.deep.equals( - { - '-foo=123': {description: 'this is a fish', timesused: 0}, - '-badger=123': {description: '', timesused: 0}, - }); + return BaseParser.getOptions( + makeCompiler('-foo=123\nthis is a fish\n-badger=123'), + ).should.eventually.deep.equals({ + '-foo=123': {description: 'this is a fish', timesused: 0}, + '-badger=123': {description: '', timesused: 0}, + }); }); it('should ignore if errors occur', () => { return BaseParser.getOptions(makeCompiler('--foo\n', '--bar\n', 1)).should.eventually.deep.equals({}); @@ -97,21 +98,20 @@ describe('gcc parser', () => { result.compiler.options.should.equals(''); }); it('should handle options', () => { - return GCCParser.parse(makeCompiler('-masm=intel\n-fdiagnostics-color=[blah]\n-fdump-tree-all')) - .should.eventually.satisfy(result => { - return Promise.all([ - result.compiler.supportsGccDump.should.equals(true), - result.compiler.supportsIntel.should.equals(true), - result.compiler.intelAsm.should.equals('-masm=intel'), - result.compiler.options.should.equals('-fdiagnostics-color=always'), - ]); - }); + return GCCParser.parse( + makeCompiler('-masm=intel\n-fdiagnostics-color=[blah]\n-fdump-tree-all'), + ).should.eventually.satisfy(result => { + return Promise.all([ + result.compiler.supportsGccDump.should.equals(true), + result.compiler.supportsIntel.should.equals(true), + result.compiler.intelAsm.should.equals('-masm=intel'), + result.compiler.options.should.equals('-fdiagnostics-color=always'), + ]); + }); }); it('should handle undefined options', () => { return GCCParser.parse(makeCompiler('-fdiagnostics-color=[blah]')).should.eventually.satisfy(result => { - return Promise.all([ - result.compiler.options.should.equals('-fdiagnostics-color=always'), - ]); + return Promise.all([result.compiler.options.should.equals('-fdiagnostics-color=always')]); }); }); }); @@ -119,32 +119,29 @@ describe('gcc parser', () => { describe('clang parser', () => { it('should handle empty options', () => { return ClangParser.parse(makeCompiler()).should.eventually.satisfy(result => { - return Promise.all([ - result.compiler.options.should.equals(''), - ]); + return Promise.all([result.compiler.options.should.equals('')]); }); }); it('should handle options', () => { - return ClangParser.parse(makeCompiler('-fno-crash-diagnostics\n-fsave-optimization-record\n-fcolor-diagnostics')) - .should.eventually.satisfy(result => { - return Promise.all([ - result.compiler.supportsOptOutput.should.equals(true), - result.compiler.optArg.should.equals('-fsave-optimization-record'), + return ClangParser.parse( + makeCompiler('-fno-crash-diagnostics\n-fsave-optimization-record\n-fcolor-diagnostics'), + ).should.eventually.satisfy(result => { + return Promise.all([ + result.compiler.supportsOptOutput.should.equals(true), + result.compiler.optArg.should.equals('-fsave-optimization-record'), - result.compiler.options.should.include('-fcolor-diagnostics'), - result.compiler.options.should.include('-fno-crash-diagnostics'), - result.compiler.options.should.not.include('-fsave-optimization-record'), - ]); - }); + result.compiler.options.should.include('-fcolor-diagnostics'), + result.compiler.options.should.include('-fno-crash-diagnostics'), + result.compiler.options.should.not.include('-fsave-optimization-record'), + ]); + }); }); }); describe('pascal parser', () => { it('should handle empty options', () => { return PascalParser.parse(makeCompiler()).should.eventually.satisfy(result => { - return Promise.all([ - result.compiler.options.should.equals(''), - ]); + return Promise.all([result.compiler.options.should.equals('')]); }); }); }); @@ -153,7 +150,9 @@ describe('popular compiler arguments', () => { let compiler; before(() => { - compiler = makeCompiler('-fsave-optimization-record\n-x\n-g\n-fcolor-diagnostics\n-O optimization level\n-std='); + compiler = makeCompiler( + '-fsave-optimization-record\n-x\n-g\n-fcolor-diagnostics\n-O optimization level\n-std=', + ); }); it('should return 5 arguments', () => { diff --git a/test/compilers/clang-tests.js b/test/compilers/clang-tests.js index b31bac8cd..539defd62 100644 --- a/test/compilers/clang-tests.js +++ b/test/compilers/clang-tests.js @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { ClangCompiler } from '../../lib/compilers'; -import { chai, makeCompilationEnvironment } from '../utils'; +import {ClangCompiler} from '../../lib/compilers'; +import {chai, makeCompilationEnvironment} from '../utils'; const expect = chai.expect; @@ -44,7 +44,8 @@ describe('clang tests', () => { expect(clang.splitDeviceCode('mov eax, 00h\nadd r0, r0, #1\n')).to.be.null; }); it('should separate out bundles ', () => { - expect(clang.splitDeviceCode(`# __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-unknown-linux-gnu + expect( + clang.splitDeviceCode(`# __CLANG_OFFLOAD_BUNDLE____START__ openmp-x86_64-unknown-linux-gnu i am some linux remote stuff # __CLANG_OFFLOAD_BUNDLE____END__ openmp-x86_64-unknown-linux-gnu @@ -53,7 +54,8 @@ describe('clang tests', () => { whereas i am host code # __CLANG_OFFLOAD_BUNDLE____END__ host-x86_64-unknown-linux-gnu -`)).to.deep.equal({ +`), + ).to.deep.equal({ 'host-x86_64-unknown-linux-gnu': ' whereas\n i am host code\n', 'openmp-x86_64-unknown-linux-gnu': ' i am some\n linux remote stuff\n', }); diff --git a/test/d-tests.js b/test/d-tests.js index 3dc0276e7..795592db2 100644 --- a/test/d-tests.js +++ b/test/d-tests.js @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { DMDCompiler } from '../lib/compilers/dmd'; -import { LDCCompiler } from '../lib/compilers/ldc'; +import {DMDCompiler} from '../lib/compilers/dmd'; +import {LDCCompiler} from '../lib/compilers/ldc'; -import { makeCompilationEnvironment } from './utils'; +import {makeCompilationEnvironment} from './utils'; const languages = { d: {id: 'd'}, diff --git a/test/embedding.html b/test/embedding.html index 3b4d9f609..045e61ede 100644 --- a/test/embedding.html +++ b/test/embedding.html @@ -1,17 +1,21 @@ - - - Embedding test - - - -
- Test; here's some inline Compiler Explorer stuff: -
- - -
And here's some text after
- + + + Embedding test + + +
Test; here's some inline Compiler Explorer stuff:
+ + +
And here's some text after
+ diff --git a/test/filter-tests.js b/test/filter-tests.js index 3b39be761..14b7c979b 100644 --- a/test/filter-tests.js +++ b/test/filter-tests.js @@ -26,24 +26,23 @@ import path from 'path'; import approvals from 'approvals'; -import { AsmParser } from '../lib/parsers/asm-parser'; -import { SassAsmParser } from '../lib/parsers/asm-parser-sass'; -import { VcAsmParser } from '../lib/parsers/asm-parser-vc'; +import {AsmParser} from '../lib/parsers/asm-parser'; +import {SassAsmParser} from '../lib/parsers/asm-parser-sass'; +import {VcAsmParser} from '../lib/parsers/asm-parser-vc'; -import { fs, resolvePathFromTestRoot } from './utils'; +import {fs, resolvePathFromTestRoot} from './utils'; approvals.mocha(); function processAsm(filename, filters) { const file = fs.readFileSync(filename, 'utf-8'); let parser; - if (file.includes('Microsoft')) - parser = new VcAsmParser(); - else if (filename.includes('sass-')) - parser = new SassAsmParser(); + if (file.includes('Microsoft')) parser = new VcAsmParser(); + else if (filename.includes('sass-')) parser = new SassAsmParser(); else { parser = new AsmParser(); - parser.binaryHideFuncRe = /^(__.*|_(init|start|fini)|(de)?register_tm_clones|call_gmon_start|frame_dummy|\.plt.*|_dl_relocate_static_pie)$/; + parser.binaryHideFuncRe = + /^(__.*|_(init|start|fini)|(de)?register_tm_clones|call_gmon_start|frame_dummy|\.plt.*|_dl_relocate_static_pie)$/; } return parser.process(file, filters); } @@ -68,11 +67,7 @@ function testFilter(filename, suffix, filters) { const result = processAsm(filename, filters); delete result.parsingTime; delete result.filteredCount; - approvals.verifyAsJSON( - casesRoot, - testName, - result, - optionsOverride); + approvals.verifyAsJSON(casesRoot, testName, result, optionsOverride); }).timeout(5000); // Bump the timeout a bit so that we don't fail for slow cases } @@ -81,7 +76,6 @@ function testFilter(filename, suffix, filters) { That's sad because then we can't have cases be loaded in a before() for every describe child to see. */ describe('Filter test cases', function () { - describe('No filters', function () { for (const x of cases) testFilter(x, '.none', {}); }); @@ -147,14 +141,23 @@ describe('Filter test cases', function () { }); describe('Directives, labels, comments and library code', function () { for (const x of cases) { - testFilter(x, '.directives.labels.comments.library', - {directives: true, labels: true, commentOnly: true, libraryCode: true}); + testFilter(x, '.directives.labels.comments.library', { + directives: true, + labels: true, + commentOnly: true, + libraryCode: true, + }); } }); describe('Directives, labels, comments and library code with dontMaskFilenames', function () { for (const x of cases) { - testFilter(x, '.directives.labels.comments.library.dontMaskFilenames', - {directives: true, labels: true, commentOnly: true, libraryCode: true, dontMaskFilenames: true}); + testFilter(x, '.directives.labels.comments.library.dontMaskFilenames', { + directives: true, + labels: true, + commentOnly: true, + libraryCode: true, + dontMaskFilenames: true, + }); } }); }); diff --git a/test/golang-tests.js b/test/golang-tests.js index 131b2176f..022ff090f 100644 --- a/test/golang-tests.js +++ b/test/golang-tests.js @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { GolangCompiler } from '../lib/compilers/golang'; +import {GolangCompiler} from '../lib/compilers/golang'; import * as utils from '../lib/utils'; -import { fs, makeCompilationEnvironment } from './utils'; +import {fs, makeCompilationEnvironment} from './utils'; const languages = { go: {id: 'go'}, @@ -44,7 +44,7 @@ function testGoAsm(basefilename) { const asmLines = utils.splitLines(fs.readFileSync(basefilename + '.asm').toString()); const result = { - stderr: asmLines.map((line) => { + stderr: asmLines.map(line => { return { text: line, }; diff --git a/test/google-tests.js b/test/google-tests.js index 566ae7163..67e982363 100644 --- a/test/google-tests.js +++ b/test/google-tests.js @@ -37,41 +37,27 @@ describe('Google short URL resolver tests', () => { const resolver = new google.ShortLinkResolver(); it('Resolves simple URLs', async () => { - nock(googlDomain) - .head(shortUrl) - .reply(302, {}, { location: 'http://long.url/' }); + nock(googlDomain).head(shortUrl).reply(302, {}, {location: 'http://long.url/'}); const resp = await resolver.resolve(googlDomain + shortUrl); - resp.should.deep.equal({ longUrl: 'http://long.url/' }); + resp.should.deep.equal({longUrl: 'http://long.url/'}); }); it('Handles missing long urls', () => { - nock(googlDomain) - .head(shortUrl) - .reply(404); + nock(googlDomain).head(shortUrl).reply(404); - return resolver - .resolve(googlDomain + shortUrl) - .should.be.rejectedWith('Got response 404'); + return resolver.resolve(googlDomain + shortUrl).should.be.rejectedWith('Got response 404'); }); it('Handles missing location header', () => { - nock(googlDomain) - .head(shortUrl) - .reply(302); + nock(googlDomain).head(shortUrl).reply(302); - return resolver - .resolve(googlDomain + shortUrl) - .should.be.rejectedWith('Missing location url in undefined'); + return resolver.resolve(googlDomain + shortUrl).should.be.rejectedWith('Missing location url in undefined'); }); it('Handles failed requests', () => { - nock(googlDomain) - .head(shortUrl) - .replyWithError('Something went wrong'); + nock(googlDomain).head(shortUrl).replyWithError('Something went wrong'); - return resolver - .resolve(googlDomain + shortUrl) - .should.be.rejectedWith('Something went wrong'); + return resolver.resolve(googlDomain + shortUrl).should.be.rejectedWith('Something went wrong'); }); }); diff --git a/test/handlers/api-tests.js b/test/handlers/api-tests.js index 6c1757ba6..3ca112867 100644 --- a/test/handlers/api-tests.js +++ b/test/handlers/api-tests.js @@ -24,9 +24,9 @@ import express from 'express'; -import { ApiHandler } from '../../lib/handlers/api'; -import { StorageNull } from '../../lib/storage'; -import { chai } from '../utils'; +import {ApiHandler} from '../../lib/handlers/api'; +import {StorageNull} from '../../lib/storage'; +import {chai} from '../utils'; const languages = { 'c++': { @@ -92,7 +92,8 @@ describe('API handling', () => { handleCmake: res => res.send('cmake'), handlePopularArguments: res => res.send('ok'), handleOptimizationArguments: res => res.send('ok'), - }, (key, def) => { + }, + (key, def) => { switch (key) { case 'formatters': return 'formatt:badformatt'; @@ -107,14 +108,16 @@ describe('API handling', () => { } }, new StorageNull('/', {}), - 'default'); + 'default', + ); app.use('/api', apiHandler.handle); apiHandler.setCompilers(compilers); apiHandler.setLanguages(languages); }); it('should respond to plain text compiler requests', () => { - return chai.request(app) + return chai + .request(app) .get('/api/compilers') .then(res => { res.should.have.status(200); @@ -128,7 +131,8 @@ describe('API handling', () => { }); }); it('should respond to JSON compiler requests', () => { - return chai.request(app) + return chai + .request(app) .get('/api/compilers') .set('Accept', 'application/json') .then(res => { @@ -141,7 +145,8 @@ describe('API handling', () => { }); }); it('should respond to JSON compiler requests with all fields', () => { - return chai.request(app) + return chai + .request(app) .get('/api/compilers?fields=all') .set('Accept', 'application/json') .then(res => { @@ -154,7 +159,8 @@ describe('API handling', () => { }); }); it('should respond to JSON compiler requests with limited fields', () => { - return chai.request(app) + return chai + .request(app) .get('/api/compilers?fields=id,name') .set('Accept', 'application/json') .then(res => { @@ -167,7 +173,8 @@ describe('API handling', () => { }); }); it('should respond to JSON compilers requests with c++ filter', () => { - return chai.request(app) + return chai + .request(app) .get('/api/compilers/c++') .set('Accept', 'application/json') .then(res => { @@ -180,7 +187,8 @@ describe('API handling', () => { }); }); it('should respond to JSON compilers requests with pascal filter', () => { - return chai.request(app) + return chai + .request(app) .get('/api/compilers/pascal') .set('Accept', 'application/json') .then(res => { @@ -193,7 +201,8 @@ describe('API handling', () => { }); }); it('should respond to plain text language requests', () => { - return chai.request(app) + return chai + .request(app) .get('/api/languages') .then(res => { res.should.have.status(200); @@ -209,7 +218,8 @@ describe('API handling', () => { }); }); it('should respond to JSON languages requests', () => { - return chai.request(app) + return chai + .request(app) .get('/api/languages') .set('Accept', 'application/json') .then(res => { @@ -223,8 +233,10 @@ describe('API handling', () => { }); // TODO(supergrecko): re-write this test case it.skip('should list the formatters', () => { - if (process.platform !== 'win32') { // Expects an executable called echo - return chai.request(app) + if (process.platform !== 'win32') { + // Expects an executable called echo + return chai + .request(app) .get('/api/formats') .set('Accept', 'application/json') .then(res => { @@ -238,13 +250,14 @@ describe('API handling', () => { } }); it('should not go through with invalid tools', () => { - return chai.request(app) + return chai + .request(app) .post('/api/format/invalid') .set('Accept', 'application/json') .then(res => { res.should.have.status(422); res.should.be.json; - res.body.should.deep.equals({exit: 2, answer: 'Unknown format tool \'invalid\''}); + res.body.should.deep.equals({exit: 2, answer: "Unknown format tool 'invalid'"}); }); }); /* diff --git a/test/handlers/asm-docs-tests.js b/test/handlers/asm-docs-tests.js index 9ab52aeb4..b4dc5dec5 100644 --- a/test/handlers/asm-docs-tests.js +++ b/test/handlers/asm-docs-tests.js @@ -22,22 +22,55 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { expect } from 'chai'; +import {expect} from 'chai'; import express from 'express'; -import { withAssemblyDocumentationProviders } from '../../lib/handlers/assembly-documentation'; -import { chai } from '../utils'; +import {withAssemblyDocumentationProviders} from '../../lib/handlers/assembly-documentation'; +import {chai} from '../utils'; /** Test matrix of architecture to [opcode, tooptip, html, url] */ export const TEST_MATRIX = { - 6502: [['lda', 'Load Accumulator with Memory', 'data is transferred from memory to the accumulator', 'https://www.pagetable.com/c64ref/6502/']], + 6502: [ + [ + 'lda', + 'Load Accumulator with Memory', + 'data is transferred from memory to the accumulator', + 'https://www.pagetable.com/c64ref/6502/', + ], + ], amd64: [ ['mov', 'Copies the second operand', 'Copies the second operand', 'www.felixcloutier.com'], - ['shr', 'Shifts the bits in the first operand', 'Shifts the bits in the first operand', 'www.felixcloutier.com'], // regression test for #3541 + [ + 'shr', + 'Shifts the bits in the first operand', + 'Shifts the bits in the first operand', + 'www.felixcloutier.com', + ], // regression test for #3541 + ], + arm32: [ + [ + 'mov', + 'writes an immediate value', + 'writes an immediate value to the destination register', + 'https://developer.arm.com/documentation/', + ], + ], + avr: [ + [ + 'mov', + 'Copy Register', + 'makes a copy of one register into another', + 'https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf', + ], + ], + java: [ + [ + 'iload_0', + 'Load int from local variable', + 'Load int from local variable', + 'https://docs.oracle.com/javase/specs/jvms/se16/html/', + ], ], - arm32: [['mov', 'writes an immediate value', 'writes an immediate value to the destination register', 'https://developer.arm.com/documentation/']], - avr: [['mov', 'Copy Register', 'makes a copy of one register into another', 'https://ww1.microchip.com/downloads/en/DeviceDoc/AVR-InstructionSet-Manual-DS40002198.pdf']], - java: [['iload_0', 'Load int from local variable', 'Load int from local variable', 'https://docs.oracle.com/javase/specs/jvms/se16/html/']], }; describe('Assembly Documentation API', () => { @@ -51,46 +84,44 @@ describe('Assembly Documentation API', () => { }); it('should return 404 for unknown architecture', async () => { - const res = await chai.request(app).get(`/api/asm/not_an_arch/mov`) - .set('Accept', 'application/json'); + const res = await chai.request(app).get(`/api/asm/not_an_arch/mov`).set('Accept', 'application/json'); expect(res).to.have.status(404); expect(res).to.be.json; - expect(res.body).to.deep.equal({ error: `No documentation for 'not_an_arch'` }); + expect(res.body).to.deep.equal({error: `No documentation for 'not_an_arch'`}); }); for (const [arch, cases] of Object.entries(TEST_MATRIX)) { for (const [opcode, tooltip, html, url] of cases) { it(`should process ${arch} text requests`, async () => { - const res = await chai.request(app).get(`/api/asm/${arch}/${opcode}`) - .set('Accept', 'text/plain'); + const res = await chai.request(app).get(`/api/asm/${arch}/${opcode}`).set('Accept', 'text/plain'); expect(res).to.have.status(200); expect(res).to.be.html; expect(res.text).to.contain(html); }); - + it(`should process ${arch} json requests`, async () => { - const res = await chai.request(app).get(`/api/asm/${arch}/${opcode}`) - .set('Accept', 'application/json'); - - expect(res).to.have.status(200); - expect(res).to.be.json; - expect(res.body.html).to.contain(html); - expect(res.body.tooltip).to.contain(tooltip); - expect(res.body.url).to.contain(url); + const res = await chai.request(app).get(`/api/asm/${arch}/${opcode}`).set('Accept', 'application/json'); + + expect(res).to.have.status(200); + expect(res).to.be.json; + expect(res.body.html).to.contain(html); + expect(res.body.tooltip).to.contain(tooltip); + expect(res.body.url).to.contain(url); }); - + it(`should return 404 for ${arch} unknown opcode requests`, async () => { - const res = await chai.request(app).get(`/api/asm/${arch}/not_an_opcode`) + const res = await chai + .request(app) + .get(`/api/asm/${arch}/not_an_opcode`) .set('Accept', 'application/json'); expect(res).to.have.status(404); expect(res).to.be.json; - expect(res.body).to.deep.equal({ error: 'Unknown opcode \'NOT_AN_OPCODE\'' }); + expect(res.body).to.deep.equal({error: "Unknown opcode 'NOT_AN_OPCODE'"}); }); - + it(`should return 406 for ${arch} bad accept type requests`, async () => { - const res = await chai.request(app).get(`/api/asm/${arch}/${opcode}`) - .set('Accept', 'application/pdf'); - expect(res).to.have.status(406); + const res = await chai.request(app).get(`/api/asm/${arch}/${opcode}`).set('Accept', 'application/pdf'); + expect(res).to.have.status(406); }); } } diff --git a/test/handlers/compile-tests.js b/test/handlers/compile-tests.js index 92002c615..827333afe 100644 --- a/test/handlers/compile-tests.js +++ b/test/handlers/compile-tests.js @@ -25,8 +25,8 @@ import bodyParser from 'body-parser'; import express from 'express'; -import { CompileHandler, SetTestMode } from '../../lib/handlers/compile'; -import { chai, makeCompilationEnvironment } from '../utils'; +import {CompileHandler, SetTestMode} from '../../lib/handlers/compile'; +import {chai, makeCompilationEnvironment} from '../utils'; SetTestMode(); @@ -55,203 +55,247 @@ describe('Compiler tests', () => { }); it('throws for unknown compilers', () => { - return chai.request(app) + return chai + .request(app) .post('/NOT_A_COMPILER/compile') - .then((res) => { + .then(res => { res.should.have.status(404); }); }); describe('Noscript API', () => { it('supports compile', () => { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: { - code: 0, - stdout: [{text: 'Something from stdout'}], - stderr: [{text: 'Something from stderr'}], - asm: [{text: 'ASMASMASM'}], - }, - }]).then(() => { - return chai.request(app) - .post('/noscript/compile') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send('compiler=fake-for-test&source=I am a program') - .then(res => { - res.should.have.status(200); - res.should.be.text; - res.text.should.contain('Something from stdout'); - res.text.should.contain('Something from stderr'); - res.text.should.contain('ASMASMASM'); - }) - .catch(err => { - throw err; - }); - }); + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: { + code: 0, + stdout: [{text: 'Something from stdout'}], + stderr: [{text: 'Something from stderr'}], + asm: [{text: 'ASMASMASM'}], + }, + }, + ]) + .then(() => { + return chai + .request(app) + .post('/noscript/compile') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send('compiler=fake-for-test&source=I am a program') + .then(res => { + res.should.have.status(200); + res.should.be.text; + res.text.should.contain('Something from stdout'); + res.text.should.contain('Something from stderr'); + res.text.should.contain('ASMASMASM'); + }) + .catch(err => { + throw err; + }); + }); }); }); describe('Curl API', () => { it('supports compile', () => { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: { - code: 0, - stdout: [{text: 'Something from stdout'}], - stderr: [{text: 'Something from stderr'}], - asm: [{text: 'ASMASMASM'}], - }, - }]).then(() => { - return chai.request(app) - .post('/fake-for-test/compile') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send('I am a program /* &compiler=NOT_A_COMPILER&source=etc */') - .then(res => { - res.should.have.status(200); - res.should.be.text; - res.text.should.contain('Something from stdout'); - res.text.should.contain('Something from stderr'); - res.text.should.contain('ASMASMASM'); - }) - .catch(err => { - throw err; - }); - }); + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: { + code: 0, + stdout: [{text: 'Something from stdout'}], + stderr: [{text: 'Something from stderr'}], + asm: [{text: 'ASMASMASM'}], + }, + }, + ]) + .then(() => { + return chai + .request(app) + .post('/fake-for-test/compile') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send('I am a program /* &compiler=NOT_A_COMPILER&source=etc */') + .then(res => { + res.should.have.status(200); + res.should.be.text; + res.text.should.contain('Something from stdout'); + res.text.should.contain('Something from stderr'); + res.text.should.contain('ASMASMASM'); + }) + .catch(err => { + throw err; + }); + }); }); it('supports alias compile', () => { - return compileHandler.setCompilers([{ - id: 'newcompilerid', - alias: ['oldid1', 'oldid2'], - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: { - code: 0, - stdout: [{text: 'Something from stdout'}], - stderr: [{text: 'Something from stderr'}], - asm: [{text: 'ASMASMASM'}], - }, - }]).then(() => { - return chai.request(app) - .post('/oldid1/compile') - .set('Content-Type', 'application/x-www-form-urlencoded') - .send('I am a program /* &compiler=NOT_A_COMPILER&source=etc */') - .then(res => { - res.should.have.status(200); - res.should.be.text; - res.text.should.contain('Something from stdout'); - res.text.should.contain('Something from stderr'); - res.text.should.contain('ASMASMASM'); - }) - .catch(err => { - throw err; - }); - }); + return compileHandler + .setCompilers([ + { + id: 'newcompilerid', + alias: ['oldid1', 'oldid2'], + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: { + code: 0, + stdout: [{text: 'Something from stdout'}], + stderr: [{text: 'Something from stderr'}], + asm: [{text: 'ASMASMASM'}], + }, + }, + ]) + .then(() => { + return chai + .request(app) + .post('/oldid1/compile') + .set('Content-Type', 'application/x-www-form-urlencoded') + .send('I am a program /* &compiler=NOT_A_COMPILER&source=etc */') + .then(res => { + res.should.have.status(200); + res.should.be.text; + res.text.should.contain('Something from stdout'); + res.text.should.contain('Something from stderr'); + res.text.should.contain('ASMASMASM'); + }) + .catch(err => { + throw err; + }); + }); }); }); describe('JSON API', () => { it('handles text output', () => { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: { + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: { + code: 0, + stdout: [{text: 'Something from stdout'}], + stderr: [{text: 'Something from stderr'}], + asm: [{text: 'ASMASMASM'}], + }, + }, + ]) + .then(() => { + return chai + .request(app) + .post('/fake-for-test/compile') + .send({ + options: {}, + source: 'I am a program', + }) + .then(res => { + res.should.have.status(200); + res.should.be.text; + res.text.should.contain('Something from stdout'); + res.text.should.contain('Something from stderr'); + res.text.should.contain('ASMASMASM'); + }) + .catch(err => { + throw err; + }); + }); + }); + + function makeFakeJson(source, options, fakeResult) { + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: fakeResult || {}, + }, + ]) + .then(() => + chai + .request(app) + .post('/fake-for-test/compile') + .set('Accept', 'application/json') + .send({ + options: options || {}, + source: source || '', + }), + ); + } + + function makeFakeWithExtraFilesJson(source, options, files, fakeResult) { + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: fakeResult || {}, + }, + ]) + .then(() => + chai + .request(app) + .post('/fake-for-test/compile') + .set('Accept', 'application/json') + .send({ + options: options || {}, + source: source || '', + files: files || [], + }), + ); + } + + function makeFakeCmakeJson(source, options, fakeResult, files) { + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: fakeResult || {}, + }, + ]) + .then(() => + chai + .request(app) + .post('/fake-for-test/cmake') + .set('Accept', 'application/json') + .send({ + options: options || {}, + source: source || '', + files: files || [], + }), + ); + } + + it('handles JSON output', () => { + return makeFakeJson( + 'I am a program', + {}, + { code: 0, stdout: [{text: 'Something from stdout'}], stderr: [{text: 'Something from stderr'}], asm: [{text: 'ASMASMASM'}], }, - }]).then(() => { - return chai.request(app) - .post('/fake-for-test/compile') - .send({ - options: {}, - source: 'I am a program', - }) - .then(res => { - res.should.have.status(200); - res.should.be.text; - res.text.should.contain('Something from stdout'); - res.text.should.contain('Something from stderr'); - res.text.should.contain('ASMASMASM'); - }) - .catch(err => { - throw err; + ) + .then(res => { + res.should.have.status(200); + res.should.be.json; + res.body.should.deep.equals({ + asm: [{text: 'ASMASMASM'}], + code: 0, + input: { + backendOptions: {}, + filters: {}, + options: [], + source: 'I am a program', + }, + stderr: [{text: 'Something from stderr'}], + stdout: [{text: 'Something from stdout'}], }); - }); - }); - - function makeFakeJson(source, options, fakeResult) { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: fakeResult || {}, - }]) - .then(() => chai.request(app) - .post('/fake-for-test/compile') - .set('Accept', 'application/json') - .send({ - options: options || {}, - source: source || '', - })); - } - - function makeFakeWithExtraFilesJson(source, options, files, fakeResult) { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: fakeResult || {}, - }]) - .then(() => chai.request(app) - .post('/fake-for-test/compile') - .set('Accept', 'application/json') - .send({ - options: options || {}, - source: source || '', - files: files || [], - })); - } - - function makeFakeCmakeJson(source, options, fakeResult, files) { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: fakeResult || {}, - }]) - .then(() => chai.request(app) - .post('/fake-for-test/cmake') - .set('Accept', 'application/json') - .send({ - options: options || {}, - source: source || '', - files: files || [], - })); - } - - it('handles JSON output', () => { - return makeFakeJson('I am a program', {}, { - code: 0, - stdout: [{text: 'Something from stdout'}], - stderr: [{text: 'Something from stderr'}], - asm: [{text: 'ASMASMASM'}], - }).then(res => { - res.should.have.status(200); - res.should.be.json; - res.body.should.deep.equals({ - asm: [{text: 'ASMASMASM'}], - code: 0, - input: { - backendOptions: {}, - filters: {}, - options: [], - source: 'I am a program', - }, - stderr: [{text: 'Something from stderr'}], - stdout: [{text: 'Something from stdout'}], - }); - }) + }) .catch(err => { throw err; }); @@ -261,94 +305,115 @@ describe('Compiler tests', () => { return makeFakeJson('I am a program', { userArguments: '-O1 -monkey "badger badger"', filters: {a: true, b: true, c: true}, - }) - .then(res => { - res.should.have.status(200); - res.should.be.json; - res.body.input.options.should.deep.equals(['-O1', '-monkey', 'badger badger']); - res.body.input.filters.should.deep.equals({a: true, b: true, c: true}); - }); + }).then(res => { + res.should.have.status(200); + res.should.be.json; + res.body.input.options.should.deep.equals(['-O1', '-monkey', 'badger badger']); + res.body.input.filters.should.deep.equals({a: true, b: true, c: true}); + }); }); it('parses extra files', () => { - return makeFakeWithExtraFilesJson('I am a program', { - userArguments: '-O1 -monkey "badger badger"', - filters: {a: true, b: true, c: true}, - }, [{ - filename: 'myresource.txt', - contents: 'Hello, World!\nHow are you?\n', - }], {}) - .then(res => { - res.should.have.status(200); - res.should.be.json; - res.body.input.options.should.deep.equals(['-O1', '-monkey', 'badger badger']); - res.body.input.filters.should.deep.equals({a: true, b: true, c: true}); - res.body.input.files.should.deep.equals([{ + return makeFakeWithExtraFilesJson( + 'I am a program', + { + userArguments: '-O1 -monkey "badger badger"', + filters: {a: true, b: true, c: true}, + }, + [ + { filename: 'myresource.txt', contents: 'Hello, World!\nHow are you?\n', - }]); - }); + }, + ], + {}, + ).then(res => { + res.should.have.status(200); + res.should.be.json; + res.body.input.options.should.deep.equals(['-O1', '-monkey', 'badger badger']); + res.body.input.filters.should.deep.equals({a: true, b: true, c: true}); + res.body.input.files.should.deep.equals([ + { + filename: 'myresource.txt', + contents: 'Hello, World!\nHow are you?\n', + }, + ]); + }); }); it('cmakes', () => { - return makeFakeCmakeJson('I am a program', { - userArguments: '-O1 -monkey "badger badger"', - filters: {a: true, b: true, c: true}, - }, { - }, [{ - filename: 'myresource.txt', - contents: 'Hello, World!\nHow are you?\n', - }]) - .then(res => { - res.should.have.status(200); - res.should.be.json; - res.body.input.options.should.deep.equals({ - backendOptions: {}, - bypassCache: false, - executionParameters: { - args: [], - }, - filters: { - a: true, - b: true, - c: true, - }, - libraries: [], - options: ['-O1', '-monkey', 'badger badger'], - source: 'I am a program', - tools: [], - }); - res.body.input.files.should.deep.equals([{ + return makeFakeCmakeJson( + 'I am a program', + { + userArguments: '-O1 -monkey "badger badger"', + filters: {a: true, b: true, c: true}, + }, + {}, + [ + { filename: 'myresource.txt', contents: 'Hello, World!\nHow are you?\n', - }]); + }, + ], + ).then(res => { + res.should.have.status(200); + res.should.be.json; + res.body.input.options.should.deep.equals({ + backendOptions: {}, + bypassCache: false, + executionParameters: { + args: [], + }, + filters: { + a: true, + b: true, + c: true, + }, + libraries: [], + options: ['-O1', '-monkey', 'badger badger'], + source: 'I am a program', + tools: [], }); + res.body.input.files.should.deep.equals([ + { + filename: 'myresource.txt', + contents: 'Hello, World!\nHow are you?\n', + }, + ]); + }); }); }); describe('Query API', () => { function makeFakeQuery(source, query, fakeResult) { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: fakeResult || {}, - }]) - .then(() => chai.request(app) - .post('/fake-for-test/compile') - .query(query || {}) - .set('Accept', 'application/json') - .send(source || '')); + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: fakeResult || {}, + }, + ]) + .then(() => + chai + .request(app) + .post('/fake-for-test/compile') + .query(query || {}) + .set('Accept', 'application/json') + .send(source || ''), + ); } it('error on empty request body', () => { - return compileHandler.setCompilers([{ - compilerType: 'fake-for-test', - exe: 'fake', - fakeResult: {}, - }]) - .then(() => chai.request(app) - .post('/fake-for-test/compile') - .set('Accept', 'application/json')) + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + exe: 'fake', + fakeResult: {}, + }, + ]) + .then(() => chai.request(app).post('/fake-for-test/compile').set('Accept', 'application/json')) .then(res => { res.should.have.status(500); }) @@ -412,37 +477,37 @@ describe('Compiler tests', () => { describe('Multi language', () => { function makeFakeJson(compiler, lang) { - return compileHandler.setCompilers([ - { - compilerType: 'fake-for-test', - id: 'a', - lang: 'a', - exe: 'fake', - fakeResult: {code: 0, stdout: [], stderr: [], asm: [{text: 'LANG A'}]}, - }, - { - compilerType: 'fake-for-test', - id: 'b', - lang: 'b', - exe: 'fake', - fakeResult: {code: 0, stdout: [], stderr: [], asm: [{text: 'LANG B'}]}, - }, - { - compilerType: 'fake-for-test', - id: 'a', - lang: 'b', - exe: 'fake', - fakeResult: {code: 0, stdout: [], stderr: [], asm: [{text: 'LANG B but A'}]}, - }, - ]) - .then(() => chai.request(app) - .post(`/${compiler}/compile`) - .set('Accept', 'application/json') - .send({ + return compileHandler + .setCompilers([ + { + compilerType: 'fake-for-test', + id: 'a', + lang: 'a', + exe: 'fake', + fakeResult: {code: 0, stdout: [], stderr: [], asm: [{text: 'LANG A'}]}, + }, + { + compilerType: 'fake-for-test', + id: 'b', + lang: 'b', + exe: 'fake', + fakeResult: {code: 0, stdout: [], stderr: [], asm: [{text: 'LANG B'}]}, + }, + { + compilerType: 'fake-for-test', + id: 'a', + lang: 'b', + exe: 'fake', + fakeResult: {code: 0, stdout: [], stderr: [], asm: [{text: 'LANG B but A'}]}, + }, + ]) + .then(() => + chai.request(app).post(`/${compiler}/compile`).set('Accept', 'application/json').send({ lang: lang, options: {}, source: '', - })); + }), + ); } it('finds without language', () => { diff --git a/test/handlers/health-check-tests.js b/test/handlers/health-check-tests.js index babf69576..5e0f62784 100644 --- a/test/handlers/health-check-tests.js +++ b/test/handlers/health-check-tests.js @@ -25,9 +25,9 @@ import express from 'express'; import mockfs from 'mock-fs'; -import { CompilationQueue } from '../../lib/compilation-queue'; -import { HealthCheckHandler } from '../../lib/handlers/health-check'; -import { chai } from '../utils'; +import {CompilationQueue} from '../../lib/compilation-queue'; +import {HealthCheckHandler} from '../../lib/handlers/health-check'; +import {chai} from '../utils'; describe('Health checks', () => { let app; diff --git a/test/handlers/source-tests.js b/test/handlers/source-tests.js index cb972ee82..29a89bf73 100644 --- a/test/handlers/source-tests.js +++ b/test/handlers/source-tests.js @@ -24,23 +24,27 @@ import express from 'express'; -import { SourceHandler } from '../../lib/handlers/source'; -import { chai } from '../utils'; +import {SourceHandler} from '../../lib/handlers/source'; +import {chai} from '../utils'; describe('Sources', () => { const app = express(); const handler = new SourceHandler( - [{ - urlpart: 'moose', - list: () => Promise.resolve({moose: 'pig'}), - load: name => Promise.resolve({file: `File called ${name}`}), - save: null, - }], - res => res.setHeader('Yibble', 'boing')); + [ + { + urlpart: 'moose', + list: () => Promise.resolve({moose: 'pig'}), + load: name => Promise.resolve({file: `File called ${name}`}), + save: null, + }, + ], + res => res.setHeader('Yibble', 'boing'), + ); app.use('/source', handler.handle.bind(handler)); it('should list', () => { - return chai.request(app) + return chai + .request(app) .get('/source/moose/list') .then(res => { res.should.have.status(200); @@ -53,7 +57,8 @@ describe('Sources', () => { }); }); it('should fetch files', () => { - return chai.request(app) + return chai + .request(app) .get('/source/moose/load/Grunkle') .then(res => { res.should.have.status(200); diff --git a/test/lang-tests.js b/test/lang-tests.js index e2dd0d076..6db425ae2 100644 --- a/test/lang-tests.js +++ b/test/lang-tests.js @@ -22,16 +22,16 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { languages } from '../lib/languages'; +import {languages} from '../lib/languages'; -import { fs, path, should } from './utils'; +import {fs, path, should} from './utils'; describe('Language definitions tests', () => { it('Has id equal to object key', () => { - for (const languageKey of Object.keys(languages)) should.equal(languages[languageKey].id, languageKey); + for (const languageKey of Object.keys(languages)) should.equal(languages[languageKey].id, languageKey); }); it('Has extensions with leading dots', () => { - for (const languageKey of Object.keys(languages)) should.equal(languages[languageKey].extensions[0][0], '.'); + for (const languageKey of Object.keys(languages)) should.equal(languages[languageKey].extensions[0][0], '.'); }); it('Has examples & are initialized', () => { for (const languageKey of Object.keys(languages)) { diff --git a/test/llvm-ast-parser-tests.js b/test/llvm-ast-parser-tests.js index d8f151469..d51f05b68 100644 --- a/test/llvm-ast-parser-tests.js +++ b/test/llvm-ast-parser-tests.js @@ -24,18 +24,18 @@ import cloneDeep from 'lodash.clonedeep'; -import { LlvmAstParser } from '../lib/llvm-ast'; +import {LlvmAstParser} from '../lib/llvm-ast'; import * as properties from '../lib/properties'; import * as utils from '../lib/utils'; -import { fs, should } from './utils'; +import {fs, should} from './utils'; const languages = { 'c++': {id: 'c++'}, }; function mockAstOutput(astLines) { - return { stdout : astLines.map(l => ( { text : l } ))}; + return {stdout: astLines.map(l => ({text: l}))}; } describe('llvm-ast', function () { diff --git a/test/llvm-ir-parser-tests.js b/test/llvm-ir-parser-tests.js index 7796a2096..56c5fed79 100644 --- a/test/llvm-ir-parser-tests.js +++ b/test/llvm-ir-parser-tests.js @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { LlvmIrParser } from '../lib/llvm-ir'; +import {LlvmIrParser} from '../lib/llvm-ir'; import * as properties from '../lib/properties'; -import { chai } from './utils'; +import {chai} from './utils'; const expect = chai.expect; @@ -55,40 +55,48 @@ describe('llvm-ir parseMetaNode', function () { }); it('should parse distinct DILexicalBlock', function () { - llvmIrParser.parseMetaNode('!50 = distinct !DILexicalBlock(scope: !44, file: !1, line: 8, column: 5)').should.deep.equal({ - metaType: 'LexicalBlock', - metaId: '!50', - scope: '!44', - file: '!1', - line: '8', - column: '5', - }); + llvmIrParser + .parseMetaNode('!50 = distinct !DILexicalBlock(scope: !44, file: !1, line: 8, column: 5)') + .should.deep.equal({ + metaType: 'LexicalBlock', + metaId: '!50', + scope: '!44', + file: '!1', + line: '8', + column: '5', + }); }); it('should parse all value types', function () { - llvmIrParser.parseMetaNode('!44 = distinct !DISubprogram(name: "func", ' + - 'scope: !1, line: 7, isLocal: false, isDefinition: true, flags: ' + - 'DIFlagPrototyped, ceEmpty: "", ceTest: "a:b\\"c,d")').should.deep.equal({ - metaType: 'Subprogram', - metaId: '!44', - name: 'func', - line: '7', - scope: '!1', - isLocal: 'false', - isDefinition: 'true', - flags: 'DIFlagPrototyped', - ceTest: 'a:b\\"c,d', - ceEmpty: '', - }); + llvmIrParser + .parseMetaNode( + '!44 = distinct !DISubprogram(name: "func", ' + + 'scope: !1, line: 7, isLocal: false, isDefinition: true, flags: ' + + 'DIFlagPrototyped, ceEmpty: "", ceTest: "a:b\\"c,d")', + ) + .should.deep.equal({ + metaType: 'Subprogram', + metaId: '!44', + name: 'func', + line: '7', + scope: '!1', + isLocal: 'false', + isDefinition: 'true', + flags: 'DIFlagPrototyped', + ceTest: 'a:b\\"c,d', + ceEmpty: '', + }); }); it('should parse distinct DILexicalBlock', function () { - llvmIrParser.parseMetaNode('!1 = !DIFile(filename: "/tmp/example.cpp", directory: "/home/compiler-explorer")').should.deep.equal({ - metaType: 'File', - metaId: '!1', - filename: '/tmp/example.cpp', - directory: '/home/compiler-explorer', - }); + llvmIrParser + .parseMetaNode('!1 = !DIFile(filename: "/tmp/example.cpp", directory: "/home/compiler-explorer")') + .should.deep.equal({ + metaType: 'File', + metaId: '!1', + filename: '/tmp/example.cpp', + directory: '/home/compiler-explorer', + }); }); }); @@ -104,13 +112,13 @@ describe('llvm-ir getSourceLineNumber', function () { }); const debugInfo = { - '!10': { line: 10 }, - '!20': { line: 20, scope: '!10' }, - '!11': { scope: '!10' }, - '!12': { line: 0, scope: '!10' }, - '!14': { }, - '!15': { scope: '!14' }, - '!16': { scope: '!42' }, + '!10': {line: 10}, + '!20': {line: 20, scope: '!10'}, + '!11': {scope: '!10'}, + '!12': {line: 0, scope: '!10'}, + '!14': {}, + '!15': {scope: '!14'}, + '!16': {scope: '!42'}, }; it('should return a line number', function () { @@ -145,13 +153,13 @@ describe('llvm-ir getSourceColumn', function () { }); const debugInfo = { - '!10': { column: 10 }, - '!20': { column: 20, scope: '!10' }, - '!11': { scope: '!10' }, - '!12': { column: 0, scope: '!10' }, - '!14': { }, - '!15': { scope: '!14' }, - '!16': { scope: '!42' }, + '!10': {column: 10}, + '!20': {column: 20, scope: '!10'}, + '!11': {scope: '!10'}, + '!12': {column: 0, scope: '!10'}, + '!14': {}, + '!15': {scope: '!14'}, + '!16': {scope: '!42'}, }; it('should return a column number', function () { @@ -186,12 +194,12 @@ describe('llvm-ir getFileName', function () { llvmIrParser = new LlvmIrParser(compilerProps); }); const debugInfo = { - '!10': { filename: '/test.cpp' }, - '!20': { filename: '/example.cpp' }, - '!11': { file: '!10' }, - '!21': { file: '!20' }, - '!12': { scope: '!11' }, - '!13': { scope: '!12' }, + '!10': {filename: '/test.cpp'}, + '!20': {filename: '/example.cpp'}, + '!11': {file: '!10'}, + '!21': {file: '!20'}, + '!12': {scope: '!11'}, + '!13': {scope: '!12'}, }; it('should return a filename', function () { diff --git a/test/llvm-ir-tests.js b/test/llvm-ir-tests.js index 12faf6c7a..b1245b6dd 100644 --- a/test/llvm-ir-tests.js +++ b/test/llvm-ir-tests.js @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { LLCCompiler } from '../lib/compilers/llc'; -import { OptCompiler } from '../lib/compilers/opt'; +import {LLCCompiler} from '../lib/compilers/llc'; +import {OptCompiler} from '../lib/compilers/opt'; -import { makeCompilationEnvironment } from './utils'; +import {makeCompilationEnvironment} from './utils'; const languages = { llvm: {id: 'llvm'}, @@ -55,39 +55,64 @@ describe('LLVM IR Compiler', () => { }); it('llc options for at&t assembly', function () { - compiler.optionsForFilter({ - intel: false, - binary: false, - }, 'output.s').should.eql(['-o', 'output.s']); + compiler + .optionsForFilter( + { + intel: false, + binary: false, + }, + 'output.s', + ) + .should.eql(['-o', 'output.s']); }); it('llc options for intel assembly', function () { - compiler.optionsForFilter({ - intel: true, - binary: false, - }, 'output.s').should.eql(['-o', 'output.s', '-x86-asm-syntax=intel']); + compiler + .optionsForFilter( + { + intel: true, + binary: false, + }, + 'output.s', + ) + .should.eql(['-o', 'output.s', '-x86-asm-syntax=intel']); }); it('llc options for at&t binary', function () { - compiler.optionsForFilter({ - intel: false, - binary: true, - }, 'output.s').should.eql(['-o', 'output.s', '-filetype=obj']); + compiler + .optionsForFilter( + { + intel: false, + binary: true, + }, + 'output.s', + ) + .should.eql(['-o', 'output.s', '-filetype=obj']); }); it('llc options for intel binary', function () { - compiler.optionsForFilter({ - intel: true, - binary: true, - }, 'output.s').should.eql(['-o', 'output.s', '-filetype=obj']); + compiler + .optionsForFilter( + { + intel: true, + binary: true, + }, + 'output.s', + ) + .should.eql(['-o', 'output.s', '-filetype=obj']); }); it('opt options', function () { const compiler = createCompiler(OptCompiler); - compiler.optionsForFilter({ - intel: false, - binary: false, - }, 'output.s').should.eql(['-o', 'output.s', '-S']); + compiler + .optionsForFilter( + { + intel: false, + binary: false, + }, + 'output.s', + ) + .should.eql(['-o', 'output.s', '-S']); }); }); diff --git a/test/map-file-tests.js b/test/map-file-tests.js index 45be1bda7..838bd9e72 100644 --- a/test/map-file-tests.js +++ b/test/map-file-tests.js @@ -22,8 +22,8 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { MapFileReaderDelphi } from '../lib/mapfiles/map-file-delphi'; -import { MapFileReaderVS } from '../lib/mapfiles/map-file-vs'; +import {MapFileReaderDelphi} from '../lib/mapfiles/map-file-delphi'; +import {MapFileReaderVS} from '../lib/mapfiles/map-file-vs'; describe('Map setup', function () { it('VS-map preferred load address', function () { @@ -32,7 +32,7 @@ describe('Map setup', function () { reader.tryReadingPreferredAddress(' Preferred load address is 00400000'); reader.preferredLoadAddress.should.equal(0x400000); - + reader.tryReadingPreferredAddress(' Preferred load address is 00410000'); reader.preferredLoadAddress.should.equal(0x410000); }); @@ -92,7 +92,7 @@ describe('Code Segments', function () { info = reader.getSegmentInfoAddressIsIn(false, reader.getSegmentOffset('0001') + 0x2838 + 0x10); info.addressInt.should.equal(reader.getSegmentOffset('0001') + 0x2838); - + info = reader.getSegmentInfoAddressIsIn('0001', reader.getSegmentOffset('0001') + 0x2837); info.should.equal(false); }); @@ -100,7 +100,9 @@ describe('Code Segments', function () { it('Repair VS-Map code segment info', function () { const reader = new MapFileReaderVS(); reader.tryReadingCodeSegmentInfo(' 0002:00000000 00004c73H .text$mn CODE'); - reader.tryReadingNamedAddress(' 0002:000007f0 _main 004117f0 f ConsoleApplication1.obj'); + reader.tryReadingNamedAddress( + ' 0002:000007f0 _main 004117f0 f ConsoleApplication1.obj', + ); let info = reader.getSegmentInfoByStartingAddress('0002', 0); info.unitName.should.equal('ConsoleApplication1.obj'); @@ -117,7 +119,7 @@ describe('Symbol info', function () { const reader = new MapFileReaderDelphi(); reader.tryReadingNamedAddress(' 0001:00002838 Square'); reader.namedAddresses.length.should.equal(1); - + let info = reader.getSymbolAt('0001', 0x2838); info.should.not.equal(false, 'Symbol Square should have been returned 1'); info.displayName.should.equal('Square'); @@ -132,25 +134,27 @@ describe('Symbol info', function () { reader.tryReadingNamedAddress(' 0001:00002C4C output.MaxArray'); reader.namedAddresses.length.should.equal(1); - let info = reader.getSymbolAt('0001', 0x2C4C); + let info = reader.getSymbolAt('0001', 0x2c4c); info.should.not.equal(false, 'Symbol MaxArray should have been returned'); info.displayName.should.equal('output.MaxArray'); - info = reader.getSymbolAt(false, reader.getSegmentOffset('0001') + 0x2C4C); + info = reader.getSymbolAt(false, reader.getSegmentOffset('0001') + 0x2c4c); info.should.not.equal(false, 'Symbol MaxArray should have been returned'); info.displayName.should.equal('output.MaxArray'); }); it('VS-Map symbol test', function () { const reader = new MapFileReaderVS(); - reader.tryReadingNamedAddress(' 0002:000006b0 ??$__vcrt_va_start_verify_argument_type@QBD@@YAXXZ 004116b0 f i ConsoleApplication1.obj'); + reader.tryReadingNamedAddress( + ' 0002:000006b0 ??$__vcrt_va_start_verify_argument_type@QBD@@YAXXZ 004116b0 f i ConsoleApplication1.obj', + ); reader.namedAddresses.length.should.equal(1); - let info = reader.getSymbolAt('0002', 0x6B0); + let info = reader.getSymbolAt('0002', 0x6b0); info.should.not.equal(false, 'Symbol start_verify_argument should have been returned 1'); info.displayName.should.equal('??$__vcrt_va_start_verify_argument_type@QBD@@YAXXZ'); - - info = reader.getSymbolAt(false, 0x4116B0); + + info = reader.getSymbolAt(false, 0x4116b0); info.should.not.equal(false, 'Symbol start_verify_argument should have been returned 2'); info.displayName.should.equal('??$__vcrt_va_start_verify_argument_type@QBD@@YAXXZ'); }); @@ -159,7 +163,7 @@ describe('Symbol info', function () { const reader = new MapFileReaderDelphi(); reader.tryReadingNamedAddress(' 0001:00002838 Square'); reader.namedAddresses.length.should.equal(1); - + reader.tryReadingNamedAddress(' 0001:00002838 Square'); reader.namedAddresses.length.should.equal(1); }); @@ -175,16 +179,18 @@ describe('Delphi-Map Line number info', function () { const reader = new MapFileReaderDelphi(); reader.tryReadingLineNumbers(' 17 0001:000028A4').should.equal(true); - let lineInfo = reader.getLineInfoByAddress('0001', 0x28A4); + let lineInfo = reader.getLineInfoByAddress('0001', 0x28a4); lineInfo.lineNumber.should.equal(17); - lineInfo = reader.getLineInfoByAddress(false, reader.getSegmentOffset('0001') + 0x28A4); + lineInfo = reader.getLineInfoByAddress(false, reader.getSegmentOffset('0001') + 0x28a4); lineInfo.lineNumber.should.equal(17); }); it('Multiple lines', function () { const reader = new MapFileReaderDelphi(); - reader.tryReadingLineNumbers(' 12 0001:00002838 13 0001:0000283B 14 0001:00002854 15 0001:00002858').should.equal(true); + reader + .tryReadingLineNumbers(' 12 0001:00002838 13 0001:0000283B 14 0001:00002854 15 0001:00002858') + .should.equal(true); let lineInfo = reader.getLineInfoByAddress('0001', 0x2838); lineInfo.lineNumber.should.equal(12); @@ -195,7 +201,7 @@ describe('Delphi-Map Line number info', function () { lineInfo = reader.getLineInfoByAddress('0001', 0x2854); lineInfo.lineNumber.should.equal(14); - lineInfo = reader.getLineInfoByAddress('0001', 0x283B); + lineInfo = reader.getLineInfoByAddress('0001', 0x283b); lineInfo.lineNumber.should.equal(13); }); }); @@ -210,12 +216,12 @@ describe('Delphi-Map load test', function () { reader.namedAddresses.length.should.equal(11); let info = reader.getSegmentInfoByUnitName('output.pas'); - info.addressInt.should.equal(reader.getSegmentOffset('0001') + 0x2C4C); + info.addressInt.should.equal(reader.getSegmentOffset('0001') + 0x2c4c); info = reader.getICodeSegmentInfoByUnitName('output.pas'); info.segment.should.equal('0002'); - info.addressWithoutOffset.should.equal(0xB0); - info.addressInt.should.equal(0x4040B0); + info.addressWithoutOffset.should.equal(0xb0); + info.addressInt.should.equal(0x4040b0); }); }); @@ -231,8 +237,8 @@ describe('VS-Map load test', function () { reader.getSegmentOffset('0002').should.equal(0x411000, 'offset 2'); reader.getSegmentOffset('0003').should.equal(0x416000, 'offset 3'); reader.getSegmentOffset('0004').should.equal(0x419000, 'offset 4'); - reader.getSegmentOffset('0005').should.equal(0x41A000, 'offset 5'); - reader.getSegmentOffset('0007').should.equal(0x41C000, 'offset 7'); + reader.getSegmentOffset('0005').should.equal(0x41a000, 'offset 5'); + reader.getSegmentOffset('0007').should.equal(0x41c000, 'offset 7'); }); }); @@ -241,7 +247,7 @@ describe('VS-Map address checking', function () { const reader = new MapFileReaderVS(); const mainAddresses = [ - {startAddress: 1, startAddressHex: '00000001', endAddress: 10, endAddressHex: '0000000A'}, + {startAddress: 1, startAddressHex: '00000001', endAddress: 10, endAddressHex: '0000000A'}, {startAddress: 16, startAddressHex: '00000010', endAddress: 255, endAddressHex: '000000FF'}, ]; @@ -256,7 +262,7 @@ describe('VS-Map address checking', function () { const reader = new MapFileReaderVS(); const mainAddresses = [ - {startAddress: 1, startAddressHex: '00000001', endAddress: 10, endAddressHex: '0000000A'}, + {startAddress: 1, startAddressHex: '00000001', endAddress: 10, endAddressHex: '0000000A'}, {startAddress: 16, startAddressHex: '00000010', endAddress: 255, endAddressHex: '000000FF'}, ]; diff --git a/test/nim-tests.js b/test/nim-tests.js index 67d53e58a..613ceb230 100644 --- a/test/nim-tests.js +++ b/test/nim-tests.js @@ -24,9 +24,9 @@ import path from 'path'; -import { NimCompiler } from '../lib/compilers/nim'; +import {NimCompiler} from '../lib/compilers/nim'; -import { makeCompilationEnvironment, should } from './utils'; +import {makeCompilationEnvironment, should} from './utils'; const languages = { nim: {id: 'nim'}, diff --git a/test/options-handler.js b/test/options-handler.js index add0e4f36..5e4963bd7 100644 --- a/test/options-handler.js +++ b/test/options-handler.js @@ -22,15 +22,15 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { fileURLToPath } from 'url'; +import {fileURLToPath} from 'url'; import _ from 'underscore'; -import { BaseCompiler } from '../lib/base-compiler'; -import { ClientOptionsHandler } from '../lib/options-handler'; +import {BaseCompiler} from '../lib/base-compiler'; +import {ClientOptionsHandler} from '../lib/options-handler'; import * as properties from '../lib/properties'; -import { should } from './utils'; +import {should} from './utils'; const languages = { fake: { @@ -85,10 +85,13 @@ const optionsProps = { }; if (process.platform === 'win32') { - optionsProps['libs.fakelib.versions.twoPaths.path'] = - optionsProps['libs.fakelib.versions.twoPaths.path'].replace(':', ';'); - optionsProps['libs.fakelib.versions.twoPaths.libpath'] = - optionsProps['libs.fakelib.versions.twoPaths.libpath'].replace(':', ';'); + optionsProps['libs.fakelib.versions.twoPaths.path'] = optionsProps['libs.fakelib.versions.twoPaths.path'].replace( + ':', + ';', + ); + optionsProps['libs.fakelib.versions.twoPaths.libpath'] = optionsProps[ + 'libs.fakelib.versions.twoPaths.libpath' + ].replace(':', ';'); } const moreLibProps = { @@ -176,22 +179,29 @@ describe('Options handler', () => { dependencies: [], alias: [], lookupversion: 'no-paths123', - options: [ - '-DHELLO123', - '-DETC', - '--some thing with spaces'], + options: ['-DHELLO123', '-DETC', '--some thing with spaces'], hidden: false, }, onePath: { - path: ['/dev/null'], version: 'one path', staticliblink: [], dependencies: [], + path: ['/dev/null'], + version: 'one path', + staticliblink: [], + dependencies: [], liblink: ['hello'], - libpath: ['/lib/null'], alias: [], options: [], + libpath: ['/lib/null'], + alias: [], + options: [], hidden: false, }, twoPaths: { - path: ['/dev/null', '/dev/urandom'], staticliblink: [], dependencies: [], + path: ['/dev/null', '/dev/urandom'], + staticliblink: [], + dependencies: [], liblink: ['hello1', 'hello2'], - libpath: ['/lib/null', '/lib/urandom'], version: 'two paths', alias: [], options: [], + libpath: ['/lib/null', '/lib/urandom'], + version: 'two paths', + alias: [], + options: [], hidden: false, }, }, @@ -312,7 +322,11 @@ describe('Options handler', () => { }; optionsHandler.setCompilers(compilers); _.each(optionsHandler.get().compilers, compiler => { - should.equal(compiler['$order'], expectedOrder[compiler.group][compiler.id], `group: ${compiler.group} id: ${compiler.id}`); + should.equal( + compiler['$order'], + expectedOrder[compiler.group][compiler.id], + `group: ${compiler.group} id: ${compiler.id}`, + ); }); optionsHandler.setCompilers([]); }); @@ -321,8 +335,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); @@ -343,8 +356,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); @@ -359,7 +371,8 @@ describe('Options handler', () => { staticlinks = compiler.getSortedStaticLibraries([ {id: 'fs', version: 'std'}, - {id: 'someotherlib', version: 'trunk'}]); + {id: 'someotherlib', version: 'trunk'}, + ]); staticlinks.should.deep.equal(['someotherlib', 'c++fs', 'rt', 'pthread']); }); it('library sort special case 1', () => { @@ -367,8 +380,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); @@ -378,8 +390,7 @@ describe('Options handler', () => { }, }); - let staticlinks = compiler.getSortedStaticLibraries([ - {id: 'fs', version: 'std'}]); + let staticlinks = compiler.getSortedStaticLibraries([{id: 'fs', version: 'std'}]); staticlinks.should.deep.equal(['fsextra', 'c++fs', 'rt', 'pthread']); }); it('library sort special case 2', () => { @@ -387,8 +398,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); @@ -401,7 +411,8 @@ describe('Options handler', () => { let staticlinks = compiler.getSortedStaticLibraries([ {id: 'yalib', version: 'trunk'}, {id: 'fs', version: 'std'}, - {id: 'someotherlib', version: 'trunk'}]); + {id: 'someotherlib', version: 'trunk'}, + ]); staticlinks.should.deep.equal(['yalib', 'someotherlib', 'fsextra', 'c++fs', 'rt', 'pthread']); }); it('library sort special case 3', () => { @@ -409,8 +420,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); compiler.initialiseLibraries({ @@ -422,7 +432,8 @@ describe('Options handler', () => { let staticlinks = compiler.getSortedStaticLibraries([ {id: 'fourthlib', version: 'trunk'}, {id: 'fs', version: 'std'}, - {id: 'someotherlib', version: 'trunk'}]); + {id: 'someotherlib', version: 'trunk'}, + ]); staticlinks.should.deep.equal(['fourthlib', 'yalib', 'someotherlib', 'fsextra', 'c++fs', 'rt', 'pthread']); }); it('filtered library list', () => { @@ -430,8 +441,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; compilerInfo.libsArr = ['fs.std', 'someotherlib']; @@ -451,8 +461,7 @@ describe('Options handler', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); @@ -474,13 +483,12 @@ describe('Options handler', () => { ]); obj.options.should.deep.equal(['-O3', '--std=c++17']); }); - it('server-side library alias support (just in case client doesn\'t support it)', () => { + it("server-side library alias support (just in case client doesn't support it)", () => { const libs = moreOptionsHandler.parseLibraries({fake: moreLibProps.libs}); const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); @@ -490,8 +498,7 @@ describe('Options handler', () => { }, }); - let staticlinks = compiler.getSortedStaticLibraries([ - {id: 'someotherlib', version: 'master'}]); + let staticlinks = compiler.getSortedStaticLibraries([{id: 'someotherlib', version: 'master'}]); staticlinks.should.deep.equal(['someotherlib', 'c++fs']); }); it('should be able to parse basic tools', () => { diff --git a/test/packager-tests.js b/test/packager-tests.js index dc69e7998..4223ef072 100644 --- a/test/packager-tests.js +++ b/test/packager-tests.js @@ -24,17 +24,15 @@ import temp from 'temp'; -import { Packager } from '../lib/packager'; +import {Packager} from '../lib/packager'; -import { fs, path } from './utils'; +import {fs, path} from './utils'; function newTempDir() { return new Promise((resolve, reject) => { temp.mkdir({prefix: 'compiler-explorer-compiler', dir: process.env.tmpDir}, (err, dirPath) => { - if (err) - reject(`Unable to open temp file: ${err}`); - else - resolve(dirPath); + if (err) reject(`Unable to open temp file: ${err}`); + else resolve(dirPath); }); }); } @@ -56,7 +54,7 @@ describe('Packager', function () { await fs.exists(targzPath).should.eventually.equal(true); }); - it('should be able to unpack', async () => { + it('should be able to unpack', async () => { const pack = new Packager(); const dirPath = await newTempDir(); diff --git a/test/pascal-tests.js b/test/pascal-tests.js index 3b525575f..4b145dd65 100644 --- a/test/pascal-tests.js +++ b/test/pascal-tests.js @@ -24,13 +24,13 @@ import path from 'path'; -import { FPCCompiler } from '../lib/compilers/pascal'; -import { PascalUtils } from '../lib/compilers/pascal-utils'; -import { PascalWinCompiler } from '../lib/compilers/pascal-win'; -import { PascalDemangler } from '../lib/demangler'; +import {FPCCompiler} from '../lib/compilers/pascal'; +import {PascalUtils} from '../lib/compilers/pascal-utils'; +import {PascalWinCompiler} from '../lib/compilers/pascal-win'; +import {PascalDemangler} from '../lib/demangler'; import * as utils from '../lib/utils'; -import { fs, makeCompilationEnvironment } from './utils'; +import {fs, makeCompilationEnvironment} from './utils'; const languages = { pascal: {id: 'pascal'}, @@ -64,17 +64,25 @@ describe('Pascal', () => { it('Handle 0 parameter methods', function () { demangler.composeReadableMethodSignature('', '', 'myfunc', '').should.equal('myfunc()'); demangler.composeReadableMethodSignature('output', '', 'myfunc', '').should.equal('myfunc()'); - demangler.composeReadableMethodSignature('output', 'tmyclass', 'myfunc', '').should.equal('tmyclass.myfunc()'); + demangler + .composeReadableMethodSignature('output', 'tmyclass', 'myfunc', '') + .should.equal('tmyclass.myfunc()'); }); it('Handle 1 parameter methods', function () { demangler.composeReadableMethodSignature('output', '', 'myfunc', 'integer').should.equal('myfunc(integer)'); - demangler.composeReadableMethodSignature('output', 'tmyclass', 'myfunc', 'integer').should.equal('tmyclass.myfunc(integer)'); + demangler + .composeReadableMethodSignature('output', 'tmyclass', 'myfunc', 'integer') + .should.equal('tmyclass.myfunc(integer)'); }); it('Handle 2 parameter methods', function () { - demangler.composeReadableMethodSignature('output', '', 'myfunc', 'integer,string').should.equal('myfunc(integer,string)'); - demangler.composeReadableMethodSignature('output', 'tmyclass', 'myfunc', 'integer,string').should.equal('tmyclass.myfunc(integer,string)'); + demangler + .composeReadableMethodSignature('output', '', 'myfunc', 'integer,string') + .should.equal('myfunc(integer,string)'); + demangler + .composeReadableMethodSignature('output', 'tmyclass', 'myfunc', 'integer,string') + .should.equal('tmyclass.myfunc(integer,string)'); }); }); @@ -82,7 +90,9 @@ describe('Pascal', () => { const demangler = new PascalDemangler(); it('Should demangle OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE', function () { - demangler.demangle('OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:').should.equal('maxarray(array_of_double,array_of_double)'); + demangler + .demangle('OUTPUT_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:') + .should.equal('maxarray(array_of_double,array_of_double)'); }); it('Should demangle OUTPUT_TMYCLASS_$__MYPROC$ANSISTRING', function () { @@ -122,11 +132,15 @@ describe('Pascal', () => { }); it('Should demangle OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE', function () { - demangler.demangle('OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:').should.equal('maxarray(array_of_double,array_of_double)'); + demangler + .demangle('OUTPUT_$$_MAXARRAY$array_of_DOUBLE$array_of_DOUBLE:') + .should.equal('maxarray(array_of_double,array_of_double)'); }); it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING', function () { - demangler.demangle('OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING:').should.equal('tmyclass.myproc(ansistring)'); + demangler + .demangle('OUTPUT$_$TMYCLASS_$__$$_MYPROC$ANSISTRING:') + .should.equal('tmyclass.myproc(ansistring)'); }); it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$$ANSISTRING', function () { @@ -134,11 +148,15 @@ describe('Pascal', () => { }); it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER', function () { - demangler.demangle('OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER:').should.equal('tmyclass.myfunc(ansistring)'); + demangler + .demangle('OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$$INTEGER:') + .should.equal('tmyclass.myfunc(ansistring)'); }); it('Should demangle OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER', function () { - demangler.demangle('OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER:').should.equal('tmyclass.myfunc(ansistring,integer,integer)'); + demangler + .demangle('OUTPUT$_$TMYCLASS_$__$$_MYFUNC$ANSISTRING$INTEGER$INTEGER$$INTEGER:') + .should.equal('tmyclass.myfunc(ansistring,integer,integer)'); }); it('Should demangle OUTPUT_$$_NOPARAMFUNC$$ANSISTRING', function () { @@ -263,8 +281,12 @@ describe('Pascal', () => { demangler.demangleIfNeeded(' movl U_$OUTPUT_$$_MYGLOBALVAR,%eax').should.equal(' movl myglobalvar,%eax'); demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYTEST2').should.equal(' call tmyclass.mytest2()'); demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYTEST').should.equal(' call tmyclass.mytest()'); - demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING').should.equal(' call tmyclass.myoverload(ansistring)'); - demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER').should.equal(' call tmyclass.myoverload(integer)'); + demangler + .demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING') + .should.equal(' call tmyclass.myoverload(ansistring)'); + demangler + .demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER') + .should.equal(' call tmyclass.myoverload(integer)'); demangler.demangleIfNeeded('.Le1').should.equal('.Le1'); demangler.demangleIfNeeded('_$SomeThing').should.equal('_$SomeThing'); @@ -283,8 +305,12 @@ describe('Pascal', () => { demangler.demangleIfNeeded(' movl U_$OUTPUT_$$_MYGLOBALVAR,%eax').should.equal(' movl myglobalvar,%eax'); demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYTEST2').should.equal(' call tmyclass.mytest2()'); demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYTEST').should.equal(' call tmyclass.mytest()'); - demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING').should.equal(' call tmyclass.myoverload(ansistring)'); - demangler.demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER').should.equal(' call tmyclass.myoverload(integer)'); + demangler + .demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$ANSISTRING') + .should.equal(' call tmyclass.myoverload(ansistring)'); + demangler + .demangleIfNeeded(' call OUTPUT$_$TMYCLASS_$__$$_MYOVERLOAD$INTEGER') + .should.equal(' call tmyclass.myoverload(integer)'); demangler.demangleIfNeeded('.Le1').should.equal('.Le1'); }); @@ -315,14 +341,16 @@ describe('Pascal', () => { const asmLines = utils.splitLines(buffer.toString()); compiler.preProcessLines(asmLines); - resolve(Promise.all([ - asmLines.should.include('# [output.pas]'), - asmLines.should.include(' .file 1 "output.pas"'), - asmLines.should.include('# [13] Square := num * num + 14;'), - asmLines.should.include(' .loc 1 13 0'), - asmLines.should.include('.Le0:'), - asmLines.should.include(' .cfi_endproc'), - ])); + resolve( + Promise.all([ + asmLines.should.include('# [output.pas]'), + asmLines.should.include(' .file 1 "output.pas"'), + asmLines.should.include('# [13] Square := num * num + 14;'), + asmLines.should.include(' .loc 1 13 0'), + asmLines.should.include('.Le0:'), + asmLines.should.include(' .cfi_endproc'), + ]), + ); }); }); }); @@ -352,9 +380,11 @@ describe('Pascal', () => { compiler.parseOutput(result, '/tmp/path/output.pas', '/tmp/path').should.deep.equal({ inputFilename: 'output.pas', - stdout: [{ - text: 'Hello, world!', - }], + stdout: [ + { + text: 'Hello, world!', + }, + ], stderr: [], }); }); @@ -386,10 +416,10 @@ describe('Pascal', () => { remote: true, lang: languages.pascal.id, }; - + compiler = new FPCCompiler(info, ce); }); - + it('Original behaviour (old unitname)', async function () { const dirPath = await compiler.newTempDir(); const filters = {}; @@ -438,10 +468,12 @@ describe('Pascal', () => { it('Writing program with a unit', async function () { const dirPath = await compiler.newTempDir(); const filters = {}; - const files = [{ - filename: 'example.pas', - contents: '{ hello\n world }', - }]; + const files = [ + { + filename: 'example.pas', + contents: '{ hello\n world }', + }, + ]; const source = fs.readFileSync('test/pascal/prog.dpr').toString('utf8'); const writeSummary = await compiler.writeAllFiles(dirPath, source, files, filters); @@ -464,10 +496,10 @@ describe('Pascal', () => { remote: true, lang: languages.pascal.id, }; - + compiler = new PascalWinCompiler(info, ce); }); - + it('Original behaviour (old unitname)', async function () { const dirPath = await compiler.newTempDir(); const filters = {}; @@ -516,10 +548,12 @@ describe('Pascal', () => { it('Writing program with a unit', async function () { const dirPath = await compiler.newTempDir(); const filters = {}; - const files = [{ - filename: 'example.pas', - contents: '{ hello\n world }', - }]; + const files = [ + { + filename: 'example.pas', + contents: '{ hello\n world }', + }, + ]; const source = fs.readFileSync('test/pascal/prog.dpr').toString('utf8'); const writeSummary = await compiler.writeAllFiles(dirPath, source, files, filters); diff --git a/test/pe32-tests.js b/test/pe32-tests.js index c5fbd1546..bfbfba05a 100644 --- a/test/pe32-tests.js +++ b/test/pe32-tests.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { PELabelReconstructor } from '../lib/pe32-support'; +import {PELabelReconstructor} from '../lib/pe32-support'; describe('Basic reconstructions', function () { it('No lines', function () { diff --git a/test/pp-output-test.js b/test/pp-output-test.js index 69986babb..69fd0e2c1 100644 --- a/test/pp-output-test.js +++ b/test/pp-output-test.js @@ -24,7 +24,7 @@ import * as fs from 'fs'; -import { BaseCompiler } from '../lib/base-compiler'; +import {BaseCompiler} from '../lib/base-compiler'; import * as properties from '../lib/properties'; import * as filterTests from './pp-output-cases/filter-tests'; @@ -48,8 +48,7 @@ describe('Preprocessor Output Handling', () => { const compilerInfo = makeFakeCompilerInfo('g82', 'c++', 'cpp', '8.2', true); const env = { ceProps: properties.fakeProps({}), - compilerProps: () => { - }, + compilerProps: () => {}, }; const compiler = new BaseCompiler(compilerInfo, env); for (const testCase of filterTests.cases) { diff --git a/test/ppci-tests.js b/test/ppci-tests.js index caf7ad3bd..39a53c764 100644 --- a/test/ppci-tests.js +++ b/test/ppci-tests.js @@ -22,9 +22,9 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { PPCICompiler } from '../lib/compilers/ppci'; +import {PPCICompiler} from '../lib/compilers/ppci'; -import { makeCompilationEnvironment } from './utils'; +import {makeCompilationEnvironment} from './utils'; const languages = { c: {id: 'c'}, @@ -44,16 +44,22 @@ describe('PPCI', function () { it('Should be ok with most arguments', () => { const compiler = new PPCICompiler(info, ce); - compiler.filterUserOptions(['hello', '-help', '--something']).should.deep.equal(['hello', '-help', '--something']); + compiler + .filterUserOptions(['hello', '-help', '--something']) + .should.deep.equal(['hello', '-help', '--something']); }); it('Should be ok with path argument', () => { const compiler = new PPCICompiler(info, ce); - compiler.filterUserOptions(['hello', '--stuff', '/proc/cpuinfo']).should.deep.equal(['hello', '--stuff', '/proc/cpuinfo']); + compiler + .filterUserOptions(['hello', '--stuff', '/proc/cpuinfo']) + .should.deep.equal(['hello', '--stuff', '/proc/cpuinfo']); }); it('Should be Not ok with report arguments', () => { const compiler = new PPCICompiler(info, ce); - compiler.filterUserOptions(['hello', '--report', '--text-report', '--html-report']).should.deep.equal(['hello']); + compiler + .filterUserOptions(['hello', '--report', '--text-report', '--html-report']) + .should.deep.equal(['hello']); }); }); diff --git a/test/properties-test.js b/test/properties-test.js index 564e1b7c1..4c6e7fe47 100644 --- a/test/properties-test.js +++ b/test/properties-test.js @@ -24,7 +24,7 @@ import * as properties from '../lib/properties'; -import { should } from './utils'; +import {should} from './utils'; const languages = { a: {id: 'a'}, @@ -37,9 +37,12 @@ describe('Properties', () => { properties.initialize('test/example-config/', ['test', 'overridden-base', 'overridden-tip']); casesProps = properties.propsFor('cases'); overridingProps = properties.propsFor('overwrite'); - compilerProps = new properties.CompilerProps(languages, properties.fakeProps({ - foo: '1', - })); + compilerProps = new properties.CompilerProps( + languages, + properties.fakeProps({ + foo: '1', + }), + ); }); after(() => { @@ -163,9 +166,11 @@ describe('Properties', () => { describe('Properties blob parsing', () => { it('Normal properties', () => { const props = properties.parseProperties( + // prettier-ignore 'hello = test \n' + 'etc=123\n' + - 'mybool=false\n'); + 'mybool=false\n', + ); props.hello.should.equal('test'); props.etc.should.equal(123); props.mybool.should.equal(false); diff --git a/test/sponsors-test.js b/test/sponsors-test.js index 970643f55..082b8444e 100644 --- a/test/sponsors-test.js +++ b/test/sponsors-test.js @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { loadSponsorsFromString } from '../lib/sponsors'; +import {loadSponsorsFromString} from '../lib/sponsors'; describe('Sponsors', () => { it('should load a simple example', () => { @@ -59,10 +59,7 @@ levels: - Just a string - name: An object `).levels[0].sponsors; - folks.should.deep.equalInAnyOrder([ - {name: 'An object'}, - {name: 'Just a string'}, - ]); + folks.should.deep.equalInAnyOrder([{name: 'An object'}, {name: 'Just a string'}]); }); it('should sort sponsors by name', () => { @@ -77,12 +74,7 @@ levels: - A - B `).levels[0].sponsors; - peeps.should.deep.equals([ - {name: 'A'}, - {name: 'B'}, - {name: 'C'}, - {name: 'D'}, - ]); + peeps.should.deep.equals([{name: 'A'}, {name: 'B'}, {name: 'C'}, {name: 'D'}]); }); it('should sort sponsors by priority then name', () => { const peeps = loadSponsorsFromString(` @@ -135,9 +127,7 @@ levels: icon: icon icon_dark: dark `).levels[0].sponsors; - things.should.deep.equalInAnyOrder([ - {name: 'batman', icon: 'icon', icon_dark: 'dark', img: 'not_an_icon'}, - ]); + things.should.deep.equalInAnyOrder([{name: 'batman', icon: 'icon', icon_dark: 'dark', img: 'not_an_icon'}]); }); it('should pick out the top level icons', () => { diff --git a/test/statenormalisation-tests.js b/test/statenormalisation-tests.js index 7688d08b3..7f99f66ed 100644 --- a/test/statenormalisation-tests.js +++ b/test/statenormalisation-tests.js @@ -22,16 +22,16 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { ClientState } from '../lib/clientstate'; -import { ClientStateGoldenifier, ClientStateNormalizer } from '../lib/clientstate-normalizer'; +import {ClientState} from '../lib/clientstate'; +import {ClientStateGoldenifier, ClientStateNormalizer} from '../lib/clientstate-normalizer'; -import { fs } from './utils'; +import {fs} from './utils'; describe('Normalizing clientstate', () => { it('Should translate 2 compilers GL layout to clientstate', () => { const normalizer = new ClientStateNormalizer(); - const data = JSON.parse(fs.readFileSync('test/state/twocompilers.json')); + const data = JSON.parse(fs.readFileSync('test/state/twocompilers.json')); normalizer.fromGoldenLayout(data); const resultdata = JSON.parse(fs.readFileSync('test/state/twocompilers.json.normalized')); @@ -45,7 +45,7 @@ describe('Normalizing clientstate', () => { it('Should recognize everything and kitchensink as well', () => { const normalizer = new ClientStateNormalizer(); - const data = JSON.parse(fs.readFileSync('test/state/andthekitchensink.json')); + const data = JSON.parse(fs.readFileSync('test/state/andthekitchensink.json')); normalizer.fromGoldenLayout(data); @@ -59,7 +59,7 @@ describe('Normalizing clientstate', () => { it('Should support conformanceview', () => { const normalizer = new ClientStateNormalizer(); - const data = JSON.parse(fs.readFileSync('test/state/conformanceview.json')); + const data = JSON.parse(fs.readFileSync('test/state/conformanceview.json')); normalizer.fromGoldenLayout(data); @@ -73,7 +73,7 @@ describe('Normalizing clientstate', () => { it('Should support executors', () => { const normalizer = new ClientStateNormalizer(); - const data = JSON.parse(fs.readFileSync('test/state/executor.json')); + const data = JSON.parse(fs.readFileSync('test/state/executor.json')); normalizer.fromGoldenLayout(data); @@ -87,7 +87,7 @@ describe('Normalizing clientstate', () => { it('Should support newer features', () => { const normalizer = new ClientStateNormalizer(); - const data = JSON.parse(fs.readFileSync('test/state/executorwrap.json')); + const data = JSON.parse(fs.readFileSync('test/state/executorwrap.json')); normalizer.fromGoldenLayout(data); @@ -100,7 +100,7 @@ describe('Normalizing clientstate', () => { it('Allow output without editor id', () => { const normalizer = new ClientStateNormalizer(); - const data = JSON.parse(fs.readFileSync('test/state/output-editor-id.json')); + const data = JSON.parse(fs.readFileSync('test/state/output-editor-id.json')); normalizer.fromGoldenLayout(data); const resultdata = JSON.parse(fs.readFileSync('test/state/output-editor-id.normalized.json')); @@ -115,11 +115,8 @@ describe('ClientState parsing', () => { it('Should work without executors', () => { const state = new ClientState({ sessions: [ - {id:1, - language:'c++', - source:'int main() {}', - compilers:[{id:'g91',options:'-O3 -std=c++2a'}], - }], + {id: 1, language: 'c++', source: 'int main() {}', compilers: [{id: 'g91', options: '-O3 -std=c++2a'}]}, + ], }); state.sessions[0].compilers.length.should.equal(1); @@ -129,14 +126,18 @@ describe('ClientState parsing', () => { it('Should work with executor', () => { const state = new ClientState({ sessions: [ - {id:1, - language:'c++', - source:'int main() {}', + { + id: 1, + language: 'c++', + source: 'int main() {}', compilers: [], - executors:[{ - compiler:{id:'g91',options:'-O3 -std=c++2a'}, - }], - }], + executors: [ + { + compiler: {id: 'g91', options: '-O3 -std=c++2a'}, + }, + ], + }, + ], }); state.sessions[0].compilers.length.should.equal(0); diff --git a/test/storage/storage-tests.js b/test/storage/storage-tests.js index 0ddd0f691..351f72292 100644 --- a/test/storage/storage-tests.js +++ b/test/storage/storage-tests.js @@ -22,10 +22,10 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { replace, restore, stub } from 'sinon'; +import {replace, restore, stub} from 'sinon'; -import { StorageBase } from '../../lib/storage'; -import { should } from '../utils'; +import {StorageBase} from '../../lib/storage'; +import {should} from '../utils'; describe('Hash tests', () => { afterEach(() => restore()); @@ -46,8 +46,10 @@ describe('Hash tests', () => { const testCase = {some: 'test'}; const goodResult = 'uy3AkJTC9PRg8LfxqcxuUgKrCb-OatsRW7FAAVi3-4M'; // L in 13th place: OK const callback = stub() - .onFirstCall().returns(badResult) - .onSecondCall().returns(badResult) // force nonce to update a couple of times + .onFirstCall() + .returns(badResult) + .onSecondCall() + .returns(badResult) // force nonce to update a couple of times .returns(goodResult); replace(StorageBase, 'encodeBuffer', callback); const {config, configHash} = StorageBase.getSafeHash(testCase); diff --git a/test/symbol-store-tests.js b/test/symbol-store-tests.js index 3a2795bbe..a1bfe5901 100644 --- a/test/symbol-store-tests.js +++ b/test/symbol-store-tests.js @@ -23,7 +23,7 @@ // POSSIBILITY OF SUCH DAMAGE. import './utils'; -import { SymbolStore } from '../lib/symbol-store'; +import {SymbolStore} from '../lib/symbol-store'; describe('SymbolStore', function () { it('should be empty initially', function () { @@ -107,7 +107,7 @@ describe('SymbolStore', function () { translations.length.should.equal(1); translations[0][0].should.equal('test123456'); }); - + it('should be able to check contents', function () { const store = new SymbolStore(); store.addMany(['test123', 'test123456', 'test123']); diff --git a/test/unfurl-tests.js b/test/unfurl-tests.js index 34d2cc74e..b998b4308 100644 --- a/test/unfurl-tests.js +++ b/test/unfurl-tests.js @@ -1,6 +1,6 @@ -import { RouteAPI } from '../lib/handlers/route-api'; +import {RouteAPI} from '../lib/handlers/route-api'; -import { fs } from './utils'; +import {fs} from './utils'; describe('Basic unfurls', () => { const router = null; @@ -16,7 +16,7 @@ describe('Basic unfurls', () => { }, }, storageHandler: { - expandId: async (id) => { + expandId: async id => { const json = await fs.readFile('test/state/' + id + '.json'); return { config: json, @@ -42,7 +42,9 @@ describe('Basic unfurls', () => { }, compilers: [], }; - routeApi.storedStateHandler({ params: { id: '../example-states/default-state' }}, null, () => { reject('Error in test'); }); + routeApi.storedStateHandler({params: {id: '../example-states/default-state'}}, null, () => { + reject('Error in test'); + }); }); const res = await prom; @@ -68,13 +70,16 @@ describe('Basic unfurls', () => { }, compilers: [], }; - routeApi.storedStateHandler({ params: { id: 'andthekitchensink' }}, null, () => { reject('Error in test'); }); + routeApi.storedStateHandler({params: {id: 'andthekitchensink'}}, null, () => { + reject('Error in test'); + }); }); const res = await prom; res.metadata.should.deep.equal({ ogAuthor: null, - ogDescription: '\ntemplate<typename T>\nconcept TheSameAndAddable = requires(T a, T b) {\n {a+b} -> T;\n};\n\ntemplate<TheSameAndAddable T>\nT sum(T x, T y) {\n return x + y;\n}\n\n#include <string>\n\nint main() {\n int z = 0;\n int w;\n\n return sum(z, w);\n}\n', + ogDescription: + '\ntemplate<typename T>\nconcept TheSameAndAddable = requires(T a, T b) {\n {a+b} -> T;\n};\n\ntemplate<TheSameAndAddable T>\nT sum(T x, T y) {\n return x + y;\n}\n\n#include <string>\n\nint main() {\n int z = 0;\n int w;\n\n return sum(z, w);\n}\n', ogTitle: 'Compiler Explorer - C++', }); }); @@ -94,7 +99,9 @@ describe('Basic unfurls', () => { }, compilers: [], }; - routeApi.storedStateHandler({ params: { id: 'tree-gl' }}, null, () => { reject('Error in test'); }); + routeApi.storedStateHandler({params: {id: 'tree-gl'}}, null, () => { + reject('Error in test'); + }); }); const res = await prom; diff --git a/test/utils-tests.js b/test/utils-tests.js index 062a17019..ef1f97b8c 100644 --- a/test/utils-tests.js +++ b/test/utils-tests.js @@ -23,12 +23,12 @@ // POSSIBILITY OF SUCH DAMAGE. import path from 'path'; -import { fileURLToPath } from 'url'; +import {fileURLToPath} from 'url'; -import { logger } from '../lib/logger'; +import {logger} from '../lib/logger'; import * as utils from '../lib/utils'; -import { fs } from './utils'; +import {fs} from './utils'; describe('Splits lines', () => { it('handles empty input', () => { @@ -44,12 +44,10 @@ describe('Splits lines', () => { utils.splitLines('A line\nAnother line\n').should.deep.equals(['A line', 'Another line']); }); it('handles multiple lines ending on a non-newline', () => { - utils.splitLines('A line\nAnother line\nLast line').should.deep.equals( - ['A line', 'Another line', 'Last line']); + utils.splitLines('A line\nAnother line\nLast line').should.deep.equals(['A line', 'Another line', 'Last line']); }); it('handles empty lines', () => { - utils.splitLines('A line\n\nA line after an empty').should.deep.equals( - ['A line', '', 'A line after an empty']); + utils.splitLines('A line\n\nA line after an empty').should.deep.equals(['A line', '', 'A line after an empty']); }); it('handles a single empty line', () => { utils.splitLines('\n').should.deep.equals(['']); @@ -84,10 +82,7 @@ describe('Expands tabs', () => { describe('Parses compiler output', () => { it('handles simple cases', () => { - utils.parseOutput('Line one\nLine two', 'bob.cpp').should.deep.equals([ - {text: 'Line one'}, - {text: 'Line two'}, - ]); + utils.parseOutput('Line one\nLine two', 'bob.cpp').should.deep.equals([{text: 'Line one'}, {text: 'Line two'}]); utils.parseOutput('Line one\nbob.cpp:1 Line two', 'bob.cpp').should.deep.equals([ {text: 'Line one'}, { @@ -120,15 +115,16 @@ describe('Parses compiler output', () => { ]); }); it('treats as if it were the compiler source', () => { - utils.parseOutput(':120:25: error: variable or field \'transform_data\' declared void', 'bob.cpp') + utils + .parseOutput(":120:25: error: variable or field 'transform_data' declared void", 'bob.cpp') .should.deep.equals([ { tag: { column: 25, line: 120, - text: 'error: variable or field \'transform_data\' declared void', + text: "error: variable or field 'transform_data' declared void", }, - text: ':120:25: error: variable or field \'transform_data\' declared void', + text: ":120:25: error: variable or field 'transform_data' declared void", }, ]); }); @@ -149,41 +145,48 @@ describe('Pascal compiler output', () => { }); it('recognize fpc exiting error', () => { - utils.parseOutput('output.pas(17) Fatal: There were 1 errors compiling module, stopping', 'output.pas').should.deep.equals([ - { - tag: { - column: 0, - line: 17, - text: 'Fatal: There were 1 errors compiling module, stopping', + utils + .parseOutput('output.pas(17) Fatal: There were 1 errors compiling module, stopping', 'output.pas') + .should.deep.equals([ + { + tag: { + column: 0, + line: 17, + text: 'Fatal: There were 1 errors compiling module, stopping', + }, + text: '(17) Fatal: There were 1 errors compiling module, stopping', }, - text: '(17) Fatal: There were 1 errors compiling module, stopping', - }, - ]); + ]); }); it('removes the temp path', () => { - utils.parseOutput('Compiling /tmp/path/prog.dpr\noutput.pas(17) Fatal: There were 1 errors compiling module, stopping', 'output.pas', '/tmp/path/').should.deep.equals([ - { - text: 'Compiling prog.dpr', - }, - { - tag: { - column: 0, - line: 17, - text: 'Fatal: There were 1 errors compiling module, stopping', + utils + .parseOutput( + 'Compiling /tmp/path/prog.dpr\noutput.pas(17) Fatal: There were 1 errors compiling module, stopping', + 'output.pas', + '/tmp/path/', + ) + .should.deep.equals([ + { + text: 'Compiling prog.dpr', }, - text: '(17) Fatal: There were 1 errors compiling module, stopping', - }, - ]); + { + tag: { + column: 0, + line: 17, + text: 'Fatal: There were 1 errors compiling module, stopping', + }, + text: '(17) Fatal: There were 1 errors compiling module, stopping', + }, + ]); }); }); describe('Rust compiler output', () => { it('handles simple cases', () => { - utils.parseRustOutput('Line one\nLine two', 'bob.rs').should.deep.equals([ - {text: 'Line one'}, - {text: 'Line two'}, - ]); + utils + .parseRustOutput('Line one\nLine two', 'bob.rs') + .should.deep.equals([{text: 'Line one'}, {text: 'Line two'}]); utils.parseRustOutput('Unrelated\nLine one\n --> bob.rs:1\nUnrelated', 'bob.rs').should.deep.equals([ {text: 'Unrelated'}, { @@ -222,58 +225,66 @@ describe('Rust compiler output', () => { }); it('treats as if it were the compiler source', () => { - utils.parseRustOutput('error: is sad\n --> :120:25', 'bob.rs') - .should.deep.equals([ - { - tag: {column: 25, line: 120, text: 'error: is sad'}, - text: 'error: is sad', - }, - { - tag: {column: 25, line: 120, text: ''}, - text: ' --> :120:25', - }, - ]); + utils.parseRustOutput('error: is sad\n --> :120:25', 'bob.rs').should.deep.equals([ + { + tag: {column: 25, line: 120, text: 'error: is sad'}, + text: 'error: is sad', + }, + { + tag: {column: 25, line: 120, text: ''}, + text: ' --> :120:25', + }, + ]); }); }); describe('Tool output', () => { it('removes the relative path', () => { - utils.parseOutput('./example.cpp:1:1: Fatal: There were 1 errors compiling module, stopping', './example.cpp').should.deep.equals([ - { - tag: { - column: 1, - line: 1, - text: 'Fatal: There were 1 errors compiling module, stopping', + utils + .parseOutput('./example.cpp:1:1: Fatal: There were 1 errors compiling module, stopping', './example.cpp') + .should.deep.equals([ + { + tag: { + column: 1, + line: 1, + text: 'Fatal: There were 1 errors compiling module, stopping', + }, + text: ':1:1: Fatal: There were 1 errors compiling module, stopping', }, - text: ':1:1: Fatal: There were 1 errors compiling module, stopping', - }, - ]); + ]); }); it('removes fortran relative path', () => { - utils.parseOutput('./example.f90:5:22: error: No explicit type declared for \'y\'', './example.f90').should.deep.equals([ - { - tag: { - column: 22, - line: 5, - text: 'error: No explicit type declared for \'y\'', + utils + .parseOutput("./example.f90:5:22: error: No explicit type declared for 'y'", './example.f90') + .should.deep.equals([ + { + tag: { + column: 22, + line: 5, + text: "error: No explicit type declared for 'y'", + }, + text: ":5:22: error: No explicit type declared for 'y'", }, - text: ':5:22: error: No explicit type declared for \'y\'', - }, - ]); + ]); }); it('removes the jailed path', () => { - utils.parseOutput('/home/ubuntu/example.cpp:1:1: Fatal: There were 1 errors compiling module, stopping', './example.cpp').should.deep.equals([ - { - tag: { - column: 1, - line: 1, - text: 'Fatal: There were 1 errors compiling module, stopping', + utils + .parseOutput( + '/home/ubuntu/example.cpp:1:1: Fatal: There were 1 errors compiling module, stopping', + './example.cpp', + ) + .should.deep.equals([ + { + tag: { + column: 1, + line: 1, + text: 'Fatal: There were 1 errors compiling module, stopping', + }, + text: ':1:1: Fatal: There were 1 errors compiling module, stopping', }, - text: ':1:1: Fatal: There were 1 errors compiling module, stopping', - }, - ]); + ]); }); }); @@ -330,17 +341,25 @@ describe('Logger functionality', () => { describe('Hash interface', () => { it('correctly hashes strings', () => { const version = 'Compiler Explorer Tests Version 0'; - utils.getHash('cream cheese', version).should.equal('cfff2d1f7a213e314a67cce8399160ae884f794a3ee9d4a01cd37a8c22c67d94'); - utils.getHash('large eggs', version).should.equal('9144dec50b8df5bc5cc24ba008823cafd6616faf2f268af84daf49ac1d24feb0'); - utils.getHash('sugar', version).should.equal('afa3c89d0f6a61de6805314c9bd7c52d020425a3a3c7bbdfa7c0daec594e5ef1'); + utils + .getHash('cream cheese', version) + .should.equal('cfff2d1f7a213e314a67cce8399160ae884f794a3ee9d4a01cd37a8c22c67d94'); + utils + .getHash('large eggs', version) + .should.equal('9144dec50b8df5bc5cc24ba008823cafd6616faf2f268af84daf49ac1d24feb0'); + utils + .getHash('sugar', version) + .should.equal('afa3c89d0f6a61de6805314c9bd7c52d020425a3a3c7bbdfa7c0daec594e5ef1'); }); it('correctly hashes objects', () => { - utils.getHash({ - toppings: [ - {name: 'raspberries', optional: false}, - {name: 'ground cinnamon', optional: true}, - ], - }).should.equal('e205d63abd5db363086621fdc62c4c23a51b733bac5855985a8b56642d570491'); + utils + .getHash({ + toppings: [ + {name: 'raspberries', optional: false}, + {name: 'ground cinnamon', optional: true}, + ], + }) + .should.equal('e205d63abd5db363086621fdc62c4c23a51b733bac5855985a8b56642d570491'); }); }); @@ -393,31 +412,29 @@ describe('squashes horizontal whitespace', () => { describe('replaces all substrings', () => { it('works with no substitutions', () => { const string = 'This is a line with no replacements'; - utils.replaceAll(string, 'not present', 'won\'t be substituted').should.equal(string); + utils.replaceAll(string, 'not present', "won't be substituted").should.equal(string); }); it('handles odd cases', () => { utils.replaceAll('', '', '').should.equal(''); utils.replaceAll('Hello', '', '').should.equal('Hello'); }); it('works with single replacement', () => { - utils.replaceAll('This is a line with a mistook in it', 'mistook', 'mistake') + utils + .replaceAll('This is a line with a mistook in it', 'mistook', 'mistake') .should.equal('This is a line with a mistake in it'); - utils.replaceAll('This is a line with a mistook', 'mistook', 'mistake') + utils + .replaceAll('This is a line with a mistook', 'mistook', 'mistake') .should.equal('This is a line with a mistake'); - utils.replaceAll('Mistooks were made', 'Mistooks', 'Mistakes') - .should.equal('Mistakes were made'); + utils.replaceAll('Mistooks were made', 'Mistooks', 'Mistakes').should.equal('Mistakes were made'); }); it('works with multiple replacements', () => { - utils.replaceAll('A mistook is a mistook', 'mistook', 'mistake') - .should.equal('A mistake is a mistake'); - utils.replaceAll('aaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a', 'b') - .should.equal('bbbbbbbbbbbbbbbbbbbbbbbbbbb'); + utils.replaceAll('A mistook is a mistook', 'mistook', 'mistake').should.equal('A mistake is a mistake'); + utils.replaceAll('aaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a', 'b').should.equal('bbbbbbbbbbbbbbbbbbbbbbbbbbb'); }); it('works with overlapping replacements', () => { - utils.replaceAll('aaaaaaaa', 'a', 'ba') - .should.equal('babababababababa'); + utils.replaceAll('aaaaaaaa', 'a', 'ba').should.equal('babababababababa'); }); }); @@ -462,7 +479,7 @@ describe('fileExists', () => { it('Returns true for files that exists', async () => { (await utils.fileExists(fileURLToPath(import.meta.url))).should.be.true; }); - it('Returns false for files that don\'t exist', async () => { + it("Returns false for files that don't exist", async () => { (await utils.fileExists('./ABC-FileThatDoesNotExist.extension')).should.be.false; }); it('Returns false for directories that exist', async () => { diff --git a/test/utils.js b/test/utils.js index 33252f31e..99ab21965 100644 --- a/test/utils.js +++ b/test/utils.js @@ -23,13 +23,13 @@ // POSSIBILITY OF SUCH DAMAGE. import path from 'path'; -import { fileURLToPath } from 'url'; +import {fileURLToPath} from 'url'; import chai from 'chai'; -import { CompilationEnvironment } from '../lib/compilation-env'; -import { CompilationQueue } from '../lib/compilation-queue'; -import { CompilerProps, fakeProps } from '../lib/properties'; +import {CompilationEnvironment} from '../lib/compilation-env'; +import {CompilationQueue} from '../lib/compilation-queue'; +import {CompilerProps, fakeProps} from '../lib/properties'; export function makeCompilationEnvironment(options) { const compilerProps = new CompilerProps(options.languages, fakeProps(options.props || {})); diff --git a/test/win-path-tests.js b/test/win-path-tests.js index c9c84bc4d..175d1c9c8 100644 --- a/test/win-path-tests.js +++ b/test/win-path-tests.js @@ -24,10 +24,10 @@ import child_process from 'child_process'; -import { WineVcCompiler } from '../lib/compilers/wine-vc'; -import { WslVcCompiler } from '../lib/compilers/wsl-vc'; +import {WineVcCompiler} from '../lib/compilers/wine-vc'; +import {WslVcCompiler} from '../lib/compilers/wsl-vc'; -import { makeCompilationEnvironment } from './utils'; +import {makeCompilationEnvironment} from './utils'; const languages = { 'c++': {id: 'c++'}, @@ -81,7 +81,8 @@ function createCompiler(compiler) { return new compiler(info, ce); } -if (process.platform === 'linux' && child_process.execSync('uname -a').toString().includes('Microsoft')) { // WSL +if (process.platform === 'linux' && child_process.execSync('uname -a').toString().includes('Microsoft')) { + // WSL describe('Wsl compiler', () => { let compiler; @@ -90,16 +91,16 @@ if (process.platform === 'linux' && child_process.execSync('uname -a').toString( }); it('Can set working directory', () => { - return compiler.runCompiler('pwd', [], 'c:/this-should-be-run-in-mnt-c') + return compiler + .runCompiler('pwd', [], 'c:/this-should-be-run-in-mnt-c') .then(testExecOutput) - .should.eventually.deep.equals( - { - code: 0, - inputFilename: 'c:/this-should-be-run-in-mnt-c', - okToCache: true, - stderr: [], - stdout: [{text: '/mnt/c'}], - }); + .should.eventually.deep.equals({ + code: 0, + inputFilename: 'c:/this-should-be-run-in-mnt-c', + okToCache: true, + stderr: [], + stdout: [{text: '/mnt/c'}], + }); }); }); } diff --git a/types/features/assembly-documentation.interfaces.ts b/types/features/assembly-documentation.interfaces.ts index aed90e44f..4d0359623 100644 --- a/types/features/assembly-documentation.interfaces.ts +++ b/types/features/assembly-documentation.interfaces.ts @@ -22,7 +22,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. -import { AssemblyInstructionInfo } from '../../lib/asm-docs/base'; +import {AssemblyInstructionInfo} from '../../lib/asm-docs/base'; export interface AssemblyDocumentationRequest { /** Specifies which instruction set to look for */ diff --git a/types/languages.interfaces.ts b/types/languages.interfaces.ts index b0c5faa59..9efe6e699 100644 --- a/types/languages.interfaces.ts +++ b/types/languages.interfaces.ts @@ -6,11 +6,11 @@ export interface Language { // Monaco Editor language ID (Selects which language Monaco will use to highlight the code) monaco: string; // Usual extensions associated with the language. First one is used as file input etx - extensions: string[] + extensions: string[]; // Different ways in which we can also refer to this language - alias: string[] + alias: string[]; // Format API name to use (See https://godbolt.org/api/formats) - formatter: string | null + formatter: string | null; // Whether there's at least 1 compiler in this language that supportsExecute - supportsExecute: boolean | null + supportsExecute: boolean | null; }