├── .gitignore ├── resources ├── icon.png ├── build.gif ├── hover.gif └── completion.gif ├── languages ├── configurations │ ├── cabal.json │ └── haskell.json └── snippets │ └── haskell.json ├── .vscodeignore ├── src ├── utils │ ├── promise.ts │ ├── print.ts │ ├── document.ts │ ├── workDir.ts │ ├── syncSpawn.ts │ └── other.ts ├── Providers │ ├── Definition │ │ └── index.ts │ ├── InteroLocationDecoder.ts │ ├── Reference │ │ └── index.ts │ ├── Type │ │ └── index.ts │ ├── Completion │ │ └── index.ts │ ├── InitIntero.ts │ └── InteroSpawn.ts ├── extension.ts ├── Basic │ ├── buttons.ts │ └── commands.ts └── helpers │ └── testCode.ts ├── tsconfig.json ├── test ├── utils │ └── promise.test.ts ├── extension.test.ts ├── index.ts └── Providers │ ├── Definition │ └── index.test.ts │ └── Reference │ └── index.test.ts ├── .vscode ├── settings.json ├── launch.json └── tasks.json ├── README.md ├── package.json └── License.txt /.gitignore: -------------------------------------------------------------------------------- 1 | /.vscode-test 2 | node_modules 3 | out/ 4 | -------------------------------------------------------------------------------- /resources/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/haskelly-dev/Haskelly/HEAD/resources/icon.png -------------------------------------------------------------------------------- /resources/build.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/haskelly-dev/Haskelly/HEAD/resources/build.gif -------------------------------------------------------------------------------- /resources/hover.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/haskelly-dev/Haskelly/HEAD/resources/hover.gif -------------------------------------------------------------------------------- /resources/completion.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/haskelly-dev/Haskelly/HEAD/resources/completion.gif -------------------------------------------------------------------------------- /languages/configurations/cabal.json: -------------------------------------------------------------------------------- 1 | { 2 | "comments": { 3 | "lineComment": "--", 4 | "blockComment": [] 5 | } 6 | } -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .vscode-test/** 3 | out/test/** 4 | test/** 5 | src/** 6 | **/*.map 7 | .gitignore 8 | tsconfig.json 9 | vsc-extension-quickstart.md 10 | -------------------------------------------------------------------------------- /src/utils/promise.ts: -------------------------------------------------------------------------------- 1 | 2 | export function delay(msec: number): Promise { 3 | return new Promise((resolve, reject) => { 4 | setTimeout(resolve, msec); 5 | }); 6 | } 7 | -------------------------------------------------------------------------------- /src/utils/print.ts: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | 3 | fs.readFile(process.argv[2], 'utf8', function (err,data) { 4 | if (err) { 5 | console.log(err); 6 | } 7 | console.log(data); 8 | }); -------------------------------------------------------------------------------- /src/utils/document.ts: -------------------------------------------------------------------------------- 1 | export function normalizePath(dirtyPath) { 2 | let filePath = dirtyPath; 3 | 4 | if (process.platform === 'win32') { 5 | filePath = filePath.charAt(0).toUpperCase() + filePath.substr(1); 6 | } 7 | 8 | return filePath; 9 | } 10 | 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "outDir": "out", 6 | "lib": [ 7 | "es6" 8 | ], 9 | "sourceMap": true, 10 | "rootDir": "." 11 | }, 12 | "exclude": [ 13 | "node_modules", 14 | ".vscode-test" 15 | ] 16 | } -------------------------------------------------------------------------------- /test/utils/promise.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from 'assert'; 2 | 3 | import {delay} from '../../src/utils/promise'; 4 | 5 | suite("PromiseUtils", () => { 6 | 7 | test("`delay` postpones the execution of following lines", async () => { 8 | const timeStart = new Date().getTime(); 9 | await delay(50); 10 | const timeEnd = new Date().getTime(); 11 | assert.ok(timeEnd - timeStart >= 50); 12 | }); 13 | 14 | }); 15 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "out": false // set this to true to hide the "out" folder with the compiled JS files 5 | }, 6 | "search.exclude": { 7 | "out": true // set this to false to include "out" folder in search results 8 | }, 9 | "typescript.tsdk": "./node_modules/typescript/lib" // we want to use the TS server from our node_modules folder to control its version 10 | } -------------------------------------------------------------------------------- /src/utils/workDir.ts: -------------------------------------------------------------------------------- 1 | import { execSync } from 'child_process'; 2 | import { dirname, resolve } from 'path'; 3 | 4 | export function getWorkDir(filepath) { 5 | try { 6 | const path = execSync("stack query", { cwd: dirname(filepath) }).toString(); 7 | const re = /.*\spath:\s*(.*?)\s*?\n/ 8 | var extract = re.exec(path)[1]; 9 | 10 | // Windows 11 | if (/^win/.test(process.platform)) { 12 | extract = extract.replace(/\\/g, "/"); 13 | // Windows also include the drive 14 | // extract = extract.slice(2, extract.length); 15 | } 16 | 17 | return { cwd: extract }; 18 | } catch (e) { 19 | return {}; 20 | } 21 | } -------------------------------------------------------------------------------- /test/extension.test.ts: -------------------------------------------------------------------------------- 1 | // 2 | // Note: This example test is leveraging the Mocha test framework. 3 | // Please refer to their documentation on https://mochajs.org/ for help. 4 | // 5 | 6 | // The module 'assert' provides assertion methods from node 7 | import * as assert from 'assert'; 8 | 9 | // You can import and use all API from the 'vscode' module 10 | // as well as import your extension to test it 11 | import * as vscode from 'vscode'; 12 | import * as myExtension from '../src/extension'; 13 | 14 | // Defines a Mocha test suite to group tests of similar kind together 15 | suite("Extension Tests", () => { 16 | 17 | // Defines a Mocha unit test 18 | test("Something 1", () => { 19 | assert.equal(-1, [1, 2, 3].indexOf(5)); 20 | assert.equal(-1, [1, 2, 3].indexOf(0)); 21 | }); 22 | }); -------------------------------------------------------------------------------- /languages/configurations/haskell.json: -------------------------------------------------------------------------------- 1 | { 2 | "comments": { 3 | "lineComment": "--", 4 | "blockComment": ["{-", "-}"] 5 | }, 6 | "brackets": [ 7 | ["{", "}"], 8 | ["[", "]"], 9 | ["(", ")"] 10 | ], 11 | "autoClosingPairs": [ 12 | { "open": "{", "close": "}" }, 13 | { "open": "[", "close": "]" }, 14 | { "open": "(", "close": ")" }, 15 | { "open": "\"", "close": "\"", "notIn": ["string"] }, 16 | { "open": "`", "close": "`", "notIn": ["string", "comment"] } 17 | ], 18 | "surroundingPairs": [ 19 | ["{", "}"], 20 | ["[", "]"], 21 | ["(", ")"], 22 | ["'", "'"], 23 | ["\"", "\""], 24 | ["`", "`"] 25 | ], 26 | "indentationRules": { 27 | "decreaseIndentPattern": "[\\]})][ \\t]*$/m", 28 | "increaseIndentPattern": "((\\b(if\\b.*|then|else|do|of|let|in|where))|=|->|>>=|>=>|=<<|(^(data)( |\t)+(\\w|')+( |\\t)*))( |\\t)*$/" 29 | } 30 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.1.0", 3 | "configurations": [ 4 | { 5 | "name": "Launch Extension", 6 | "type": "extensionHost", 7 | "request": "launch", 8 | "runtimeExecutable": "${execPath}", 9 | "args": ["--extensionDevelopmentPath=${workspaceRoot}" ], 10 | "stopOnEntry": false, 11 | "sourceMaps": true, 12 | "outFiles": [ "${workspaceRoot}/out/src/**/*.js" ], 13 | "preLaunchTask": "npm" 14 | }, 15 | { 16 | "name": "Launch Tests", 17 | "type": "extensionHost", 18 | "request": "launch", 19 | "runtimeExecutable": "${execPath}", 20 | "args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ], 21 | "stopOnEntry": false, 22 | "sourceMaps": true, 23 | "outFiles": [ "${workspaceRoot}/out/test/**/*.js" ], 24 | "preLaunchTask": "npm" 25 | } 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | // 2 | // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING 3 | // 4 | // This file is providing the test runner to use when running extension tests. 5 | // By default the test runner in use is Mocha based. 6 | // 7 | // You can provide your own test runner if you want to override it by exporting 8 | // a function run(testRoot: string, clb: (error:Error) => void) that the extension 9 | // host can call to run the tests. The test runner is expected to use console.log 10 | // to report the results back to the caller. When the tests are finished, return 11 | // a possible error to the callback or null if none. 12 | 13 | var testRunner = require('vscode/lib/testrunner'); 14 | 15 | // You can directly control Mocha options by uncommenting the following lines 16 | // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info 17 | testRunner.configure({ 18 | ui: 'tdd', // the TDD UI is being used in extension.test.ts (suite, test, etc.) 19 | useColors: true // colored output from test results 20 | }); 21 | 22 | module.exports = testRunner; -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // Available variables which can be used inside of strings. 2 | // ${workspaceRoot}: the root folder of the team 3 | // ${file}: the current opened file 4 | // ${fileBasename}: the current opened file's basename 5 | // ${fileDirname}: the current opened file's dirname 6 | // ${fileExtname}: the current opened file's extension 7 | // ${cwd}: the current working directory of the spawned process 8 | 9 | // A task runner that calls a custom npm script that compiles the extension. 10 | { 11 | "version": "0.1.0", 12 | 13 | // we want to run npm 14 | "command": "npm", 15 | 16 | // the command is a shell script 17 | "isShellCommand": true, 18 | 19 | // show the output window only if unrecognized errors occur. 20 | "showOutput": "silent", 21 | 22 | // we run the custom script "compile" as defined in package.json 23 | "args": ["run", "compile", "--loglevel", "silent"], 24 | 25 | // The tsc compiler is started in watching mode 26 | "isWatching": true, 27 | 28 | // use the standard tsc in watch mode problem matcher to find compile problems in the output. 29 | "problemMatcher": "$tsc-watch" 30 | } -------------------------------------------------------------------------------- /src/Providers/Definition/index.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import InteroSpawn from '../InteroSpawn'; 3 | import { getNearWord } from '../../utils/other'; 4 | import { normalizePath } from '../../utils/document'; 5 | import InteroLocationDecoder from '../InteroLocationDecoder'; 6 | 7 | export default class HaskellDefinitionProvider implements vscode.DefinitionProvider { 8 | private interoSpawn: InteroSpawn; 9 | private interoLocationDecoder: InteroLocationDecoder; 10 | 11 | public constructor(interoSpawn: InteroSpawn) { 12 | this.interoSpawn = interoSpawn; 13 | this.interoLocationDecoder = new InteroLocationDecoder(); 14 | } 15 | 16 | public async provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise { 17 | const wordInfo = getNearWord(position, document.getText()); 18 | const filePath = normalizePath(document.uri.fsPath); 19 | 20 | const definitionLocation = await this.interoSpawn.requestDefinition(filePath, position, wordInfo); 21 | return this.interoLocationDecoder.decode(definitionLocation); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Providers/InteroLocationDecoder.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | 3 | export default class InteroLocationDecoder { 4 | public decode(interoLocation: string): vscode.Location { 5 | return this.buildLocation(interoLocation); 6 | } 7 | 8 | private buildLocation(interoLocation) { 9 | const {filePath, rangeInFile} = this.splitPathAndRange(interoLocation); 10 | const uri = vscode.Uri.file(filePath); 11 | const range = this.extractRange(rangeInFile); 12 | return new vscode.Location(uri, range); 13 | } 14 | 15 | private splitPathAndRange(interoLocation) { 16 | const separatorIndex = interoLocation.lastIndexOf(':'); 17 | return { 18 | filePath: interoLocation.slice(0, separatorIndex), 19 | rangeInFile: interoLocation.slice(separatorIndex + 1) 20 | }; 21 | } 22 | 23 | private extractRange(symbolLoc) { 24 | const [line1, column1, line2, column2] = symbolLoc 25 | .match(/^\((\d+),(\d+)\)-\((\d+),(\d+)\)$/) 26 | .slice(1, 5) 27 | .map(num => parseInt(num, 10) - 1); 28 | return new vscode.Range(line1, column1, line2, column2); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Providers/Reference/index.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import InteroSpawn from '../InteroSpawn'; 3 | import { getNearWord } from '../../utils/other'; 4 | import { normalizePath } from '../../utils/document'; 5 | import InteroLocationDecoder from '../InteroLocationDecoder'; 6 | 7 | export default class HaskellReferenceProvider implements vscode.ReferenceProvider { 8 | private interoSpawn: InteroSpawn; 9 | private interoLocationDecoder: InteroLocationDecoder; 10 | 11 | public constructor(interoSpawn: InteroSpawn) { 12 | this.interoSpawn = interoSpawn; 13 | this.interoLocationDecoder = new InteroLocationDecoder(); 14 | } 15 | 16 | public async provideReferences( 17 | document: vscode.TextDocument, 18 | position: vscode.Position, 19 | options: { includeDeclaration: boolean }, 20 | token: vscode.CancellationToken 21 | ): Promise { 22 | const wordInfo = getNearWord(position, document.getText()); 23 | const filePath = normalizePath(document.uri.fsPath); 24 | 25 | const definitionLocations = await this.interoSpawn.requestReferences(filePath, position, wordInfo); 26 | return definitionLocations.split(' ') 27 | .map(location => this.interoLocationDecoder.decode(location)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Providers/Type/index.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import InteroSpawn from '../InteroSpawn'; 3 | import { getNearWord } from '../../utils/other'; 4 | import { normalizePath } from '../../utils/document'; 5 | 6 | class TypeProvider implements vscode.HoverProvider { 7 | public provideHover(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable { 8 | return new Promise((resolve, reject) => { 9 | // current editor 10 | const editor = vscode.window.activeTextEditor; 11 | let filePath = normalizePath(document.uri.fsPath); 12 | 13 | // check if there is no selection 14 | if (editor.selection.isEmpty || !editor.selection.contains(position)) { 15 | const wordInfo = getNearWord(position, document.getText()); 16 | InteroSpawn.getInstance().requestType(filePath, position, wordInfo) 17 | .then(hover => { 18 | resolve(hover); 19 | }); 20 | } else { 21 | InteroSpawn.getInstance().requestType(filePath, position, { word: "", start: editor.selection.start.character, end: editor.selection.end.character }) 22 | .then(hover => { 23 | resolve(hover); 24 | }); 25 | } 26 | }) 27 | } 28 | } 29 | 30 | export default TypeProvider; 31 | -------------------------------------------------------------------------------- /src/utils/syncSpawn.ts: -------------------------------------------------------------------------------- 1 | import { spawn } from 'child_process'; 2 | import { getWorkDir } from './workDir' 3 | const StreamSplitter = require('stream-splitter'); 4 | 5 | export default class SyncSpawn { 6 | private shell; 7 | private positiveOutput:String; 8 | private negativeOutput:String; 9 | private callback; 10 | 11 | public constructor(commands: Array, positiveOutput: String, negativeOutput: String, options, callback) { 12 | this.positiveOutput = positiveOutput 13 | this.negativeOutput = negativeOutput; 14 | 15 | this.shell = spawn(commands[0], commands.slice(1, commands.length), options); 16 | this.callback = callback; 17 | this.readOutput(); 18 | } 19 | 20 | private readOutput() { 21 | const splitter = this.shell.stdout.pipe(StreamSplitter("\n")); 22 | splitter.encoding = 'utf8'; 23 | 24 | splitter.on('token', (line) => { 25 | // console.log(line); 26 | if (line.indexOf(this.positiveOutput) !== -1) { 27 | this.callback(line); 28 | } else if (line.indexOf(this.negativeOutput) !== -1) { // Error 29 | this.killProcess(); 30 | this.callback(line, true); 31 | } 32 | }); 33 | 34 | splitter.on('done', () => { 35 | console.log("Sync shell terminated.") 36 | }); 37 | 38 | splitter.on('error', (error) => { 39 | console.log("Error: ", error); 40 | this.killProcess(); 41 | this.callback(error, true); 42 | }); 43 | } 44 | 45 | public runCommand(command, positiveOutput, negativeOutput, callback) { 46 | this.positiveOutput = positiveOutput; 47 | this.negativeOutput = negativeOutput; 48 | this.callback = callback; 49 | 50 | this.shell.stdin.write(command + '\n'); 51 | } 52 | 53 | public runSyncCommand(command) { 54 | this.shell.stdin.write(command + '\n'); 55 | } 56 | 57 | public getShell() { 58 | return this.shell; 59 | } 60 | 61 | private killProcess() { 62 | this.shell.stdin.pause(); 63 | this.shell.kill(); 64 | } 65 | } -------------------------------------------------------------------------------- /src/Providers/Completion/index.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import { spawn } from 'child_process'; 3 | import InteroSpawn from '../InteroSpawn'; 4 | import { getWord } from '../../utils/other'; 5 | import { normalizePath } from '../../utils/document'; 6 | const fs = require('fs'); 7 | 8 | class CompletionProvider implements vscode.CompletionItemProvider { 9 | snippets:Array; 10 | 11 | constructor(context:vscode.ExtensionContext) { 12 | const snippetsConf = vscode.workspace.getConfiguration('haskelly')['snippets']; 13 | if (snippetsConf && snippetsConf['important']) { 14 | fs.readFile(`${context.extensionPath}/languages/snippets/haskell.json`, 'utf8', (err, data) => { 15 | if (err) console.log(err); 16 | else this.snippets = JSON.parse(data); 17 | }); 18 | } else { 19 | this.snippets = []; 20 | } 21 | } 22 | 23 | private getCompletionsAtPosition(position, document): Promise { 24 | return new Promise((resolve, reject) => { 25 | const word = getWord(position, document.getText()); 26 | let filePath = normalizePath(document.uri.fsPath); 27 | 28 | // Request completions 29 | InteroSpawn.getInstance().requestCompletions(filePath, position, word) 30 | .then((suggestions:Array) => { 31 | let filteredSuggestions = []; 32 | 33 | // No snippets 34 | if (this.snippets.length == 0) { 35 | filteredSuggestions = suggestions; 36 | } else { 37 | // Filter suggestions from snippets 38 | suggestions.forEach(suggestion => { 39 | if (!this.snippets[suggestion.label]) { 40 | filteredSuggestions.push(suggestion); 41 | } 42 | }); 43 | } 44 | 45 | resolve(filteredSuggestions); 46 | }) 47 | .catch(err => reject(err)); 48 | }); 49 | } 50 | 51 | public provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Thenable { 52 | return new Promise((resolve, reject) => { 53 | this.getCompletionsAtPosition(position, document) 54 | .then((completions: vscode.CompletionItem[]) => { 55 | resolve(completions); 56 | }).catch(e => console.error(e)); 57 | }); 58 | } 59 | } 60 | 61 | export default CompletionProvider; 62 | -------------------------------------------------------------------------------- /test/Providers/Definition/index.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from 'assert'; 2 | 3 | import * as vscode from 'vscode'; 4 | import HaskellDefinitionProvider from '../../../src/Providers/Definition'; 5 | import InteroSpawn from '../../../src/Providers/InteroSpawn'; 6 | 7 | suite("HaskellDefinitionProvider", () => { 8 | 9 | test("it passes the path of the file that has the focused symbol when asking intero to locate the definition", async () => { 10 | const {requestToIntero} = await executeProvider(); 11 | assert.equal('FILE_PATH', requestToIntero.filePath); 12 | }); 13 | 14 | test("it passes the position of on a cursor to intero", async () => { 15 | const {requestToIntero} = await executeProvider(); 16 | assert.deepEqual({line: 3, character: 2}, requestToIntero.position); 17 | }); 18 | 19 | test("it passes the whole symbol to intero", async () => { 20 | const {requestToIntero} = await executeProvider(); 21 | assert.deepEqual('TEST', requestToIntero.wordInfo.word); 22 | }); 23 | 24 | test("it receives the location of the definition from intero", async () => { 25 | const {location} = await executeProvider(); 26 | assert.equal('/ABSOLUTE_PATH_TO/FILE', location.uri.fsPath); 27 | assert.ok(location.range.isEqual(new vscode.Range(9, 0, 9, 4))); 28 | }); 29 | 30 | async function executeProvider(): Promise<{location, requestToIntero}> { 31 | const {interoSpawn, requestToIntero} = createFakeInteroSpawn(); 32 | const haskellProvider = new HaskellDefinitionProvider(interoSpawn); 33 | const document = { 34 | getText: () => 'THIS\nIS\nA\nTEST\n.', 35 | uri: {fsPath: 'FILE_PATH'} 36 | }; 37 | const token = new vscode.CancellationTokenSource().token; 38 | const position = {line: 3, character: 2}; 39 | const location = await haskellProvider.provideDefinition( 40 | document as vscode.TextDocument, 41 | position as vscode.Position, 42 | token 43 | ); 44 | return {location, requestToIntero}; 45 | } 46 | 47 | function createFakeInteroSpawn() { 48 | const requestToIntero = {}; 49 | const interoSpawn = Object.assign({}, InteroSpawn.getInstance(), { 50 | requestDefinition(filePath: String, position: vscode.Position, wordInfo: Object): Promise { 51 | Object.assign(requestToIntero, {filePath, position, wordInfo}); 52 | return Promise.resolve('/ABSOLUTE_PATH_TO/FILE:(10,1)-(10,5)'); 53 | } 54 | }); 55 | return {interoSpawn, requestToIntero}; 56 | } 57 | }); 58 | -------------------------------------------------------------------------------- /src/utils/other.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | 3 | export type WordInfo = { 4 | word: string, 5 | start: number, 6 | end: number 7 | }; 8 | 9 | export function getWord(position: vscode.Position, text: String) { 10 | const lines = text.split('\n'); 11 | const line = lines[position.line]; 12 | let word = ''; 13 | 14 | for (let i = position.character - 1; i >= 0; i--) { 15 | if (line[i] === ' ') { 16 | break; 17 | } 18 | word = `${line[i]}${word}`; 19 | } 20 | 21 | return word; 22 | } 23 | 24 | function cleanWord(word: string, start: number, end: number) { 25 | let cleanWord = word; 26 | let first = cleanWord[0]; 27 | let last = cleanWord[cleanWord.length - 1]; 28 | let newStart = start; 29 | let newEnd = end; 30 | 31 | // Helps fix situations like: (Implication a c))) when hovering on c 32 | while (1) { 33 | if (first === '"' || first === '(' || first === '[') { 34 | cleanWord = cleanWord.substring(1); 35 | 36 | first = cleanWord[0]; 37 | last = cleanWord[cleanWord.length - 1]; 38 | newStart++; 39 | 40 | continue; 41 | } 42 | 43 | if (last === '"' || last === ')' || last === ']') { 44 | cleanWord = cleanWord.slice(0, cleanWord.length - 1); 45 | 46 | first = cleanWord[0]; 47 | last = cleanWord[cleanWord.length - 1]; 48 | newEnd--; 49 | 50 | continue; 51 | } 52 | 53 | break; 54 | } 55 | 56 | 57 | if (first === '\'' && last === '\'') { 58 | cleanWord = cleanWord.slice(0, cleanWord.length - 1); 59 | cleanWord = cleanWord.substring(1); 60 | newStart++; 61 | newEnd--; 62 | } 63 | 64 | return { word:cleanWord, start: newStart, end: newEnd }; 65 | } 66 | 67 | export function getNearWord(position: vscode.Position, text: String): WordInfo { 68 | const lines = text.split('\n'); 69 | const line = lines[position.line]; 70 | let word = ''; 71 | let start = position.character; 72 | let end = position.character; 73 | 74 | // Charaters before 75 | for (let i = position.character - 1; i >= 0; i--) { 76 | if (line[i] === ' ') { 77 | break; 78 | } 79 | word = `${line[i]}${word}`; 80 | start--; 81 | } 82 | 83 | // Characters after 84 | for (let i = position.character; i >= 0; i++) { 85 | if (line[i] === ' ' || i > line.length || line[i] === undefined) { 86 | break; 87 | } 88 | word = `${word}${line[i]}`; 89 | end++; 90 | } 91 | 92 | return cleanWord(word, start, end); 93 | } 94 | -------------------------------------------------------------------------------- /src/Providers/InitIntero.ts: -------------------------------------------------------------------------------- 1 | import { spawn } from 'child_process'; 2 | import { getWorkDir } from '../utils/workDir' 3 | const StreamSplitter = require('stream-splitter'); 4 | 5 | export default class SyncSpawn { 6 | private shell; 7 | private callback; 8 | private spawnCallback; 9 | private isStack; 10 | 11 | public constructor(commands:Array, options, isStack, callback) { 12 | this.spawnCallback = callback; 13 | this.isStack = isStack; 14 | this.shell = spawn(commands[0], commands.slice(1, commands.length), options); 15 | 16 | this.runSyncCommand(":set prompt \"lambda> \""); 17 | 18 | this.readOutput(); 19 | } 20 | 21 | public killProcess() { 22 | this.shell.stdin.pause(); 23 | this.shell.kill(); 24 | } 25 | 26 | private readOutput() { 27 | const splitter = this.shell.stdout.pipe(StreamSplitter("\n")); 28 | splitter.encoding = 'utf8'; 29 | let stackOutput = ""; 30 | let intent = 0; 31 | 32 | splitter.on('token', (line) => { 33 | stackOutput += line; 34 | }); 35 | 36 | const endSplitter = this.shell.stdout.pipe(StreamSplitter("lambda>")); 37 | endSplitter.on('token', (line) => { 38 | this.analyseInitOutput(stackOutput, intent); 39 | intent++; 40 | }); 41 | 42 | const errSplitter = this.shell.stderr.pipe(StreamSplitter("\n")); 43 | errSplitter.on('token', (line) => { 44 | stackOutput += line; 45 | }); 46 | } 47 | 48 | private analyseInitOutput(output, intent) { 49 | if (output.indexOf('Failed') > 0) { 50 | this.killProcess(); 51 | if (this.isStack) { 52 | this.spawnCallback(true); 53 | } else { 54 | if (intent === 0) { 55 | this.spawnCallback(true); 56 | } else { 57 | this.callback(true); 58 | } 59 | } 60 | } else { 61 | if (this.isStack) { 62 | this.spawnCallback(false); 63 | } else { 64 | if (intent === 0) { 65 | this.spawnCallback(false); 66 | } else { 67 | this.callback(false); 68 | } 69 | } 70 | } 71 | } 72 | 73 | public runCommand(command, callback) { 74 | this.callback = callback; 75 | this.shell.stdin.write(command + '\n'); 76 | } 77 | 78 | public runSyncCommand(command) { 79 | this.shell.stdin.write(command + '\n'); 80 | } 81 | 82 | public getShell() { 83 | return this.shell; 84 | } 85 | } -------------------------------------------------------------------------------- /test/Providers/Reference/index.test.ts: -------------------------------------------------------------------------------- 1 | import * as assert from 'assert'; 2 | 3 | import * as vscode from 'vscode'; 4 | import HaskellReferenceProvider from '../../../src/Providers/Reference'; 5 | import InteroSpawn from '../../../src/Providers/InteroSpawn'; 6 | 7 | suite("HaskellReferenceProvider", () => { 8 | 9 | test("it passes the path of the file that has the focused symbol when asking intero to locate all references", async () => { 10 | const {requestToIntero} = await executeProvider(); 11 | assert.equal('FILE_PATH', requestToIntero.filePath); 12 | }); 13 | 14 | test("it passes the position of on a cursor to intero", async () => { 15 | const {requestToIntero} = await executeProvider(); 16 | assert.deepEqual({line: 3, character: 2}, requestToIntero.position); 17 | }); 18 | 19 | test("it passes the whole symbol to intero", async () => { 20 | const {requestToIntero} = await executeProvider(); 21 | assert.deepEqual('TEST', requestToIntero.wordInfo.word); 22 | }); 23 | 24 | test("it receives all the locations of references from intero", async () => { 25 | const {locations} = await executeProvider(); 26 | assert.equal('/ABSOLUTE_PATH_TO/FILE1', locations[0].uri.fsPath); 27 | assert.ok(locations[0].range.isEqual(new vscode.Range(9, 0, 9, 4))); 28 | assert.equal('/ABSOLUTE_PATH_TO/FILE2', locations[1].uri.fsPath); 29 | assert.ok(locations[1].range.isEqual(new vscode.Range(6, 6, 6, 10))); 30 | }); 31 | 32 | async function executeProvider(): Promise<{locations, requestToIntero}> { 33 | const {interoSpawn, requestToIntero} = createFakeInteroSpawn(); 34 | const haskellProvider = new HaskellReferenceProvider(interoSpawn); 35 | const document = { 36 | getText: () => 'THIS\nIS\nA\nTEST\n.', 37 | uri: {fsPath: 'FILE_PATH'} 38 | }; 39 | const position = {line: 3, character: 2}; 40 | const options = {includeDeclaration: true}; 41 | const token = new vscode.CancellationTokenSource().token; 42 | const locations = await haskellProvider.provideReferences( 43 | document as vscode.TextDocument, 44 | position as vscode.Position, 45 | options, 46 | token 47 | ); 48 | return {locations, requestToIntero}; 49 | } 50 | 51 | function createFakeInteroSpawn() { 52 | const requestToIntero = {}; 53 | const interoSpawn = Object.assign({}, InteroSpawn.getInstance(), { 54 | requestReferences(filePath: String, position: vscode.Position, wordInfo: Object): Promise { 55 | Object.assign(requestToIntero, {filePath, position, wordInfo}); 56 | return Promise.resolve([ 57 | '/ABSOLUTE_PATH_TO/FILE1:(10,1)-(10,5)', 58 | '/ABSOLUTE_PATH_TO/FILE2:(7,7)-(7,11)' 59 | ].join(' ')); 60 | } 61 | }); 62 | return {interoSpawn, requestToIntero}; 63 | } 64 | }); 65 | -------------------------------------------------------------------------------- /src/extension.ts: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | // The module 'vscode' contains the VS Code extensibility API 3 | // Import the module and reference it with the alias vscode in your code below 4 | import * as vscode from 'vscode'; 5 | const fs = require('fs'); 6 | 7 | import initCommands from './Basic/commands'; 8 | import initButtons from './Basic/buttons'; 9 | 10 | import InteroSpawn from './Providers/InteroSpawn'; 11 | import CompletionProvider from './Providers/Completion/index'; 12 | import HaskellDefinitionProvider from './Providers/Definition'; 13 | import HaskellReferenceProvider from './Providers/Reference'; 14 | import TypeProvider from './Providers/Type/index'; 15 | 16 | 17 | export function activate(context: vscode.ExtensionContext) { 18 | const config = vscode.workspace.getConfiguration('haskelly'); 19 | const documentPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri.fsPath 20 | : vscode.workspace.textDocuments[0].uri.fsPath; 21 | 22 | /* Init commands */ 23 | initCommands(context); 24 | 25 | /* Init bottom buttons */ 26 | initButtons(context); 27 | 28 | /* Init Intero process */ 29 | InteroSpawn.getInstance().tryNewIntero(documentPath) 30 | .catch(error => console.log(error)); 31 | 32 | const sel:vscode.DocumentSelector = [ 33 | { language: 'haskell', scheme: 'file' }, 34 | { language: 'haskell', scheme: 'untitled' } 35 | ]; 36 | 37 | /* Type hover */ 38 | context.subscriptions.push(vscode.languages.registerHoverProvider(sel, new TypeProvider())); 39 | 40 | /* Code completion */ 41 | if (config['codeCompletion'] === false) { 42 | console.log('Disabled code completion'); 43 | } else { 44 | context.subscriptions.push(vscode.languages.registerCompletionItemProvider(sel, new CompletionProvider(context), '.', '\"')); 45 | } 46 | 47 | /* Definition */ 48 | context.subscriptions.push(vscode.languages.registerDefinitionProvider(sel, new HaskellDefinitionProvider(InteroSpawn.getInstance()))); 49 | 50 | /* Reference */ 51 | context.subscriptions.push(vscode.languages.registerReferenceProvider(sel, new HaskellReferenceProvider(InteroSpawn.getInstance()))); 52 | 53 | /* Custom snippets */ 54 | const snippetsFilePath = `${context.extensionPath}/languages/snippets/haskell.json`; 55 | fs.readFile(snippetsFilePath, 'utf8', (err, data) => { 56 | if (err) console.log(err); 57 | else { 58 | const snippets = JSON.parse(data); 59 | const mergedSnippets = { 60 | ...snippets, 61 | ...config['snippets']['custom'], 62 | }; 63 | 64 | // Modify the snippets file 65 | fs.writeFile(snippetsFilePath, JSON.stringify(mergedSnippets, null, 4), function(err) { 66 | if (err) { 67 | console.log(err); 68 | } 69 | }); 70 | } 71 | }); 72 | } 73 | 74 | export function deactivate() { 75 | // Cleanup of Spawn process 76 | InteroSpawn.getInstance().killCurrentShell(); 77 | } 78 | -------------------------------------------------------------------------------- /src/Basic/buttons.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | 3 | import { testHaskellFile } from '../helpers/testCode'; 4 | import { getWorkDir } from '../utils/workDir' 5 | 6 | const fs = require('fs'); 7 | const path = require('path'); 8 | 9 | 10 | let shownButtons : Array = []; 11 | 12 | function createButtons(context, buttons) { 13 | for (let i = 0; i < buttons.length; i++) { 14 | const button = vscode.window.createStatusBarItem(1, 0); 15 | button.text = buttons[i][0]; 16 | button.command = buttons[i][1]; 17 | button.show(); 18 | 19 | shownButtons.push(button); 20 | } 21 | } 22 | 23 | function removeAllButtons() { 24 | return new Promise((resolve, reject) => { 25 | for (let i = 0; i < shownButtons.length; i++) { 26 | shownButtons[i].hide(); 27 | } 28 | 29 | shownButtons = []; 30 | resolve(); 31 | }); 32 | } 33 | 34 | function showButtons(context, buttonsConfig, isStack) { 35 | if (buttonsConfig) { 36 | const buttons = []; 37 | if (buttonsConfig['ghci'] === true || buttonsConfig['ghci'] === undefined) { 38 | buttons.push(['Load GHCi', 'editor.ghci']); 39 | } 40 | 41 | if (isStack) { 42 | if (buttonsConfig['stackTest'] === true || buttonsConfig['stackTest'] === undefined) { 43 | buttons.push(['Stack Test', 'editor.stackTest']); 44 | } 45 | 46 | if (buttonsConfig['stackBuild'] === true || buttonsConfig['stackBuild'] === undefined) { 47 | buttons.push(['Stack Build', 'editor.stackBuild']); 48 | } 49 | 50 | if (buttonsConfig['stackRun'] === true || buttonsConfig['stackRun'] === undefined) { 51 | buttons.push(['Stack Run', 'editor.stackRun']); 52 | } 53 | } else { 54 | if (buttonsConfig['runfile'] === true || buttonsConfig['runfile'] === undefined) { 55 | buttons.push(['Run File', 'editor.runHaskell']); 56 | } 57 | 58 | if (buttonsConfig['quickcheck'] === true || buttonsConfig['quickcheck'] === undefined) { 59 | buttons.push(['QuickCheck', 'editor.runQuickCheck']); 60 | } 61 | } 62 | 63 | createButtons(context, buttons); 64 | } else { 65 | if (isStack) { 66 | createButtons(context, [['Load GHCi', 'editor.ghci'], ['Stack Build', 'editor.stackBuild'], 67 | ['Stack Run', 'editor.stackRun'], ['Stack Test', 'editor.stackTest']]); 68 | } else { 69 | createButtons(context, [['Load GHCi', 'editor.ghci'], ['Run File', 'editor.runHaskell'], ['QuickCheck', 'editor.runQuickCheck']]); 70 | } 71 | } 72 | } 73 | 74 | export default function initButtons(context:vscode.ExtensionContext) { 75 | const config = vscode.workspace.getConfiguration('haskelly'); 76 | const buttonsConfig = config['buttons']; 77 | const documentPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri.fsPath 78 | : vscode.workspace.textDocuments[0].uri.fsPath; 79 | 80 | let stackWd = getWorkDir(documentPath)["cwd"]; 81 | let isStack = stackWd !== undefined; 82 | 83 | /* Set up Stack buttons */ 84 | const loadButtons = (document:vscode.TextDocument) => { 85 | stackWd = getWorkDir(document.uri.fsPath)["cwd"]; 86 | isStack = stackWd !== undefined; 87 | showButtons(context, buttonsConfig, isStack); 88 | }; 89 | 90 | /* Load initial buttons */ 91 | loadButtons(vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document 92 | : vscode.workspace.textDocuments[0]); 93 | 94 | /* Listen for document change to update buttons */ 95 | vscode.window.onDidChangeActiveTextEditor((editor:vscode.TextEditor) => { 96 | if (editor) { // Avoid the double callback when opening a new file 97 | removeAllButtons() 98 | .then(() => { 99 | loadButtons(editor.document); 100 | }); 101 | } 102 | }); 103 | } 104 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Haskelly 2 | 3 | [Release notes](https://github.com/haskelly-dev/Haskelly/releases) | [Roadmap](https://trello.com/b/vsMlLU4h/haskelly-features) | [Demo Video](https://www.youtube.com/watch?v=r3x64iz5xDk) 4 | 5 | `Haskelly` is a [Visual Studio Code](https://code.visualstudio.com/) extension that supports Haskell development. 6 | 7 | ## Features 8 | 9 | * __Code highlight__ 10 | - Haskell (`.hs` and `.lhs`) and Cabal via automatic dependency on [Haskell Syntax Highlighting](https://marketplace.visualstudio.com/items?itemName=justusadam.language-haskell). 11 | 12 | * __Code snippets__ 13 | - Structures : `data`, `newtype`, etc. 14 | - Popular functions : `map`, `fold`, etc. 15 | 16 | 17 | * __Type hovers__ 18 | - ![hover](resources/hover.gif) 19 | 20 | 21 | * __Jump to definition__ 22 | - Jump to symbol definitions/declarations 23 | 24 | 25 | * __Find references__ 26 | - Find references within a module or depending modules. See limitations on [#62](https://github.com/haskelly-dev/Haskelly/issues/62) 27 | 28 | 29 | * __Code completion__ : 30 | - Local functions and constants 31 | - Standard library 32 | - Imported modules 33 | 34 | ![completion](resources/completion.gif) 35 | 36 | 37 | * __Integrated REPL, Build, Test and Run commands__ 38 | - repl with `GHCi` 39 | - build with `stack` 40 | - run with `runHaskell` 41 | - test current file `prop_*` properties with `QuickCheck` 42 | - run full test suite with `Stack test` 43 | 44 | ## Installation 45 | 46 | * Install the [Haskelly](https://marketplace.visualstudio.com/items?itemName=UCL.haskelly) VS Code extension. 47 | 48 | * Install [Stack](https://www.haskellstack.org) and add it to your PATH. Note that Stack folder naming conventions must be followed for it to work correctly, i.e. capitalizing folder names. 49 | 50 | ```shell 51 | curl -sSL https://get.haskellstack.org/ | sh 52 | ``` 53 | 54 | * Install [Intero](https://github.com/commercialhaskell/intero) (code completion and type information), and [QuickCheck](https://hackage.haskell.org/package/QuickCheck) (test suite) 55 | 56 | ```shell 57 | stack install intero QuickCheck # for a global installation 58 | stack build intero QuickCheck # for a local installation 59 | ``` 60 | 61 | ## Configuration 62 | 63 | Haskelly is customizable 64 | (see `Code` > `Preferences` > `Workspace Settings`). 65 | 66 | | Parameter | Description | Default | 67 | |---------------------------- |-------------------------------------------------|----------| 68 | | `haskelly.codeCompletion` | Code completion enabled | `true` | 69 | | `haskelly.buttons.ghci` | `GHCi` button shows in the bottom bar | `true` | 70 | | `haskelly.buttons.runfile` | `Run file` button shows in the bottom bar | `true` | 71 | | `haskelly.buttons.quickcheck` | `QuickCheck` button shows in the bottom bar | `true` | 72 | | `haskelly.buttons.stackBuild` | `Stack build` button shows in the bottom bar | `true` | 73 | | `haskelly.buttons.stackBuildParams` | Parameters passed to `stack build` command| `--fast` | 74 | | `haskelly.buttons.stackRun` | `Stack run` button shows in the bottom bar | `true` | 75 | | `haskelly.buttons.stackRunParams` | Parameters passed to `stack run` command | `null` | 76 | | `haskelly.buttons.stackTest` | `Stack test` button shows in the bottom bar | `true` | 77 | | `haskelly.buttons.stackTestParams` | Parameters passed to `stack test` command | `null` | 78 | | `haskelly.snippets.important` | Hide code completion for which there's already a snippet | `false` | 79 | | `haskelly.snippets.custom` | Add your custom snippets following the structure of this [file](https://github.com/haskelly-dev/Haskelly/tree/master/languages/snippets/haskell.json)| `null` | 80 | | `haskelly.exec.reuseTerminal` | Reuse the currently opened terminal to run Stack commands | false | 81 | 82 | ## Contributing 83 | 84 | If you'd like to contribute to Haskelly, this is what you can do: 85 | 86 | * __Bugs__: This extension is in alpha, so some bugs might be present. We would really appreciate if you 87 | could post any issue on the Github repository [issues section](https://github.com/haskelly-dev/Haskelly/issues) or contact us at: [zcabmse@ucl.ac.uk](mailto:zcabmse@ucl.ac.uk?Subject=Haskelly%20feedback). 88 | * __Ideas and feature requests__: We want to get everyone's opinion on what we're building so feel free to use the two mentioned channels for any comment or suggestion. 89 | * __Documentation__: Found a typo or strangely worded sentences? Submit a PR! 90 | * __Code__: Contribute bug fixes, features or design changes. 91 | 92 | 93 | ## License: [GNU 3](https://github.com/haskelly-dev/Haskelly/blob/master/License.txt) 94 | -------------------------------------------------------------------------------- /src/helpers/testCode.ts: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const exec = require('child_process').exec; 3 | const path = require('path'); 4 | const uuidV4 = require('uuid/v4'); 5 | 6 | /* Parsing */ 7 | function parseStdout(out) { 8 | const rawOut = out.split('\n'); 9 | const passedTests = []; 10 | const failedTests = []; 11 | 12 | let i = 0; 13 | while (i < rawOut.length) { 14 | const splitLine = rawOut[i].split(' '); 15 | 16 | // Start of a test 17 | if (splitLine[0] === '===') { 18 | i++; 19 | const passed = rawOut[i].slice(0, 3) === '+++'; 20 | const test = { 21 | name: splitLine[1], 22 | }; 23 | 24 | if (passed) { 25 | passedTests.push(test); 26 | i++; 27 | } else { 28 | const failedInput = []; 29 | i++; 30 | 31 | // Find test name 32 | while (rawOut[i] !== '') { 33 | failedInput.push(rawOut[i]); 34 | i++; 35 | } 36 | 37 | test['failedInput'] = failedInput; 38 | failedTests.push(test); 39 | } 40 | } 41 | 42 | i++; 43 | } 44 | return { passedTests, failedTests }; 45 | } 46 | 47 | function parseStackStdout(out) { 48 | const rawOut = out.split('\n'); 49 | const passedTests = []; 50 | const failedTests = []; 51 | 52 | // Checks if line is a QuickCheck test 53 | const isTest = (line) => { 54 | return line.slice(0, 3) === '+++' || line.slice(0, 3) === '***'; 55 | } 56 | 57 | let i = 0; 58 | while (i < rawOut.length) { 59 | const splitLine = rawOut[i].split(' '); 60 | 61 | // Ignore empty line or with next line not being a test 62 | if (rawOut[i] == '' || (!isTest(rawOut[i]) && !isTest(rawOut[i + 1]))) { 63 | i++; 64 | continue; 65 | } 66 | 67 | // Start of test 68 | else { 69 | i++; 70 | const passed = rawOut[i].slice(0, 3) === '+++'; 71 | const name = isTest(rawOut[i - 1]) ? `Test ${passedTests.length + failedTests.length + 1}` : rawOut[i - 1]; 72 | const test = { 73 | name: rawOut[i - 1], 74 | }; 75 | 76 | if (passed) { 77 | passedTests.push(test); 78 | i++; 79 | } else { 80 | const failedInput = []; 81 | i++; 82 | 83 | while (rawOut[i] !== '') { 84 | failedInput.push(rawOut[i]); 85 | i++; 86 | } 87 | 88 | test['failedInput'] = failedInput; 89 | failedTests.push(test); 90 | } 91 | } 92 | } 93 | return { passedTests, failedTests }; 94 | } 95 | 96 | /* Testing */ 97 | function shell(command, options) { 98 | return new Promise((resolve, reject) => { 99 | exec(command, options, (error, stdout, stderr) => { 100 | if (error) { 101 | reject(error); 102 | } 103 | resolve([stdout, stderr]); 104 | }); 105 | }); 106 | } 107 | 108 | function removeMainFunction(data) { 109 | const dataArray = data.toString().split('\n'); 110 | 111 | let start; 112 | let end; 113 | for (let i = 0; i < dataArray.length; i++) { 114 | if (dataArray[i].slice(0, 6) === 'main =') { 115 | start = i; 116 | end = i; 117 | } else if (start !== undefined) { 118 | if (dataArray[i] === '') { 119 | break; 120 | } else { 121 | end++; 122 | } 123 | } 124 | } 125 | 126 | dataArray.splice(start, end - start + 1); 127 | return dataArray.join('\n'); 128 | } 129 | 130 | export function testHaskellFile(filePath, stackWd) { 131 | return new Promise((resolve, reject) => { 132 | const newPath = `${path.dirname(filePath)}/${uuidV4()}.hs`; 133 | 134 | // Not Stack project 135 | if (stackWd === undefined) { 136 | fs.createReadStream(filePath).pipe(fs.createWriteStream(newPath)); 137 | fs.readFile(newPath, 'utf-8', (err, data) => { 138 | if (err) reject(err); 139 | 140 | const newValue = '{-# LANGUAGE TemplateHaskell #-}\nimport Test.QuickCheck.All\n' + removeMainFunction(data) 141 | + '\nreturn []\nrunTests = $quickCheckAll\nmain = runTests'; 142 | 143 | fs.writeFile(newPath, newValue, 'utf-8', err => { 144 | if (err) reject(err); 145 | console.log('QuickCheking...'); 146 | 147 | shell(`stack runhaskell "${newPath}"`, {}).then(std => { 148 | console.log(std[0]); 149 | fs.unlinkSync(newPath); 150 | resolve(parseStdout(std[0])); 151 | }).catch(error => { 152 | fs.unlinkSync(newPath); 153 | reject(error); 154 | }); 155 | }); 156 | }); 157 | } else { 158 | shell('stack test', { cwd: stackWd}).then(std => { 159 | resolve(parseStackStdout(std[0])); 160 | }).catch(error => { 161 | reject(error); 162 | }); 163 | } 164 | }); 165 | } 166 | -------------------------------------------------------------------------------- /languages/snippets/haskell.json: -------------------------------------------------------------------------------- 1 | { 2 | "_comment": "Original file taken from https://github.com/JustusAdam/language-haskell/blob/master/snippets/haskell.json", 3 | "main": { 4 | "prefix": "main", 5 | "body": [ 6 | "module Main (main) where", 7 | "", 8 | "", 9 | "main :: IO ()", 10 | "main = ${0:return ()}", 11 | "" 12 | ], 13 | "description": "Main function snippet." 14 | }, 15 | "module": { 16 | "prefix": "module", 17 | "body": [ 18 | "module ${module:MyModule} (", 19 | "\t${export:myFunction}", 20 | "\t) where" 21 | ], 22 | "description": "Module declaration snippet." 23 | }, 24 | "Lambda (trigger does not work)": { 25 | "prefix": "lambda", 26 | "body": "\\${inputs} -> ${body}", 27 | "description": "Lambda expression snippet." 28 | }, 29 | "case": { 30 | "prefix": "case", 31 | "body": [ 32 | "case ${var} of", 33 | "\t${alt:Just a} -> ${body}", 34 | "\t${otehrwise:_} -> ${remaining}" 35 | ], 36 | "description": "Case expression snippet." 37 | }, 38 | "class": { 39 | "prefix": "class", 40 | "body": [ 41 | "class ${name:MyClass} where", 42 | "\t${fname:myFunction} :: ${type:String}" 43 | ], 44 | "description": "Type class definition snippet." 45 | }, 46 | "instance": { 47 | "prefix": "instance", 48 | "body": [ 49 | "instance ${class:Show} ${type:String} where", 50 | "\t${function:function} = ${impl:id}" 51 | ], 52 | "description": "Instance a typeclas snippet." 53 | }, 54 | "for": { 55 | "prefix": "for", 56 | "body": [ 57 | "for ${coll} $ \\\\${element:element} ->", 58 | "\t${element:element}" 59 | ], 60 | "description": "For function snippet." 61 | }, 62 | "for_": { 63 | "prefix": "for_", 64 | "body": [ 65 | "for_ ${coll} $ \\\\${element:element} ->", 66 | "\t${element:element}" 67 | ], 68 | "description": "For_ function snippet." 69 | }, 70 | "map": { 71 | "prefix": "map", 72 | "body": [ 73 | "map (\\\\${element} -> ${element}) ${collection}" 74 | ], 75 | "description": "Map function snippet." 76 | }, 77 | "fold": { 78 | "prefix": "fold", 79 | "body": [ 80 | "fold (\\\\${x} ${element} -> ${x} + ${element}) ${acc} ${collection}" 81 | ], 82 | "description": "Fold function snippet." 83 | }, 84 | "foldl": { 85 | "prefix": "foldl", 86 | "body": [ 87 | "foldl (\\\\${x} ${element} -> ${x} + ${element}) ${acc} ${collection}" 88 | ], 89 | "description": "Foldl function snippet." 90 | }, 91 | "foldr": { 92 | "prefix": "foldr", 93 | "body": [ 94 | "foldr (\\\\${element} ${x} -> ${x} + ${element}) ${acc} ${collection}" 95 | ], 96 | "description": "Foldr function snippet." 97 | }, 98 | "do": { 99 | "prefix": "do", 100 | "body": [ 101 | "do", 102 | "\t${body:return value}" 103 | ], 104 | "description": "Do notation snippet." 105 | }, 106 | "type": { 107 | "prefix": "type", 108 | "body": [ 109 | "type ${t1:MyType} = ${t2:Original}" 110 | ], 111 | "description": "Type alias snippet." 112 | }, 113 | "data": { 114 | "prefix": "data", 115 | "body": [ 116 | "data ${name:MyType} = ${alt1:Record {}} | ${alt2:Algebraic}" 117 | ], 118 | "description": "Data type declaration snippet." 119 | }, 120 | "newtype": { 121 | "prefix": "newtype", 122 | "body": [ 123 | "newtype ${name:MyType} = ${name:MyType} { un${name:MyType} :: ${original:String} }" 124 | ], 125 | "description": "Newtype declaration snippet." 126 | }, 127 | "if": { 128 | "prefix": "if", 129 | "body": [ 130 | "if ${cond}", 131 | "\tthen ${branch1}", 132 | "\telse ${branch2}" 133 | ], 134 | "description": "If expression snippet." 135 | }, 136 | "Pragma": { 137 | "prefix": "prag", 138 | "body": [ 139 | "{-# $1 #-}" 140 | ], 141 | "description": "Pragma declaration snippet." 142 | }, 143 | "Language Pragma": { 144 | "prefix": "language", 145 | "body": [ 146 | "{-# LANGUAGE $1 #-}" 147 | ], 148 | "description": "Language extension snippet." 149 | }, 150 | "let": { 151 | "prefix": "let", 152 | "body": [ 153 | "let", 154 | "\t${name} = ${value}", 155 | "in", 156 | "\t${expr}" 157 | ], 158 | "description": "Let binding snippet." 159 | }, 160 | "where": { 161 | "prefix": "where", 162 | "body": [ 163 | "where ${name} = ${value}" 164 | ], 165 | "description": "Where binding snippet." 166 | }, 167 | "Function": { 168 | "prefix": "fun", 169 | "body": [ 170 | "${name} :: ${type1:Int} -> ${type2:Int}", 171 | "${name} ${val} = ${expr1}", 172 | "${name} ${val2:_} = ${expr2}" 173 | ], 174 | "description": "Function declaration snippet." 175 | } 176 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "haskelly", 3 | "displayName": "Haskelly", 4 | "description": "Complete support for casual and expert Haskell development.", 5 | "version": "0.5.5", 6 | "icon": "resources/icon.png", 7 | "publisher": "UCL", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/haskelly-dev/Haskelly" 11 | }, 12 | "bugs": { 13 | "url": "https://github.com/haskelly-dev/Haskelly/issues" 14 | }, 15 | "galleryBanner": { 16 | "color": "#8F4D8B", 17 | "theme": "dark" 18 | }, 19 | "engines": { 20 | "vscode": "^1.5.0" 21 | }, 22 | "categories": [ 23 | "Languages", 24 | "Snippets" 25 | ], 26 | "keywords": [ 27 | "intero", 28 | "haskell", 29 | "highlight", 30 | "snippets", 31 | "stack" 32 | ], 33 | "activationEvents": [ 34 | "onCommand:editor.runHaskell", 35 | "onCommand:editor.runQuickCheck", 36 | "onCommand:editor.ghci", 37 | "onCommand:editor.stackTest", 38 | "onCommand:editor.stackRun", 39 | "onLanguage:haskell" 40 | ], 41 | "main": "./out/src/extension", 42 | "contributes": { 43 | "commands": [ 44 | { 45 | "command": "editor.runHaskell", 46 | "title": "Run File", 47 | "category": "Haskell" 48 | }, 49 | { 50 | "command": "editor.runQuickCheck", 51 | "title": "QuickCheck", 52 | "category": "Haskell" 53 | }, 54 | { 55 | "command": "editor.ghci", 56 | "title": "Load GHCi", 57 | "category": "Haskell" 58 | }, 59 | { 60 | "command": "editor.stackTest", 61 | "title": "Stack Test", 62 | "category": "Haskell" 63 | }, 64 | { 65 | "command": "editor.stackBuild", 66 | "title": "Stack Build", 67 | "category": "Haskell" 68 | }, 69 | { 70 | "command": "editor.stackRun", 71 | "title": "Stack Run", 72 | "category": "Haskell" 73 | } 74 | ], 75 | "languages": [ 76 | { 77 | "id": "haskell", 78 | "aliases": [ 79 | "Haskell", 80 | "haskell" 81 | ], 82 | "extensions": [ 83 | ".hs", 84 | ".lhs" 85 | ], 86 | "configuration": "./languages/configurations/haskell.json" 87 | }, 88 | { 89 | "id": "cabal", 90 | "aliases": [ 91 | "Cabal", 92 | "cabal" 93 | ], 94 | "extensions": [ 95 | ".cabal" 96 | ], 97 | "configuration": "./languages/configurations/cabal.json" 98 | } 99 | ], 100 | "snippets": [ 101 | { 102 | "language": "haskell", 103 | "path": "./languages/snippets/haskell.json" 104 | } 105 | ], 106 | "configuration": { 107 | "type": "object", 108 | "title": "Haskelly configuration", 109 | "properties": { 110 | "haskelly.codeCompletion": { 111 | "type": "boolean", 112 | "default": true, 113 | "description": "Provide code completion." 114 | }, 115 | "haskelly.buttons.ghci": { 116 | "type": "boolean", 117 | "default": true, 118 | "description": "Show the GHCi button." 119 | }, 120 | "haskelly.buttons.runFile": { 121 | "type": "boolean", 122 | "default": true, 123 | "description": "Show the Run file button." 124 | }, 125 | "haskelly.buttons.quickcheck": { 126 | "type": "boolean", 127 | "default": true, 128 | "description": "Show the QuickCheck button." 129 | }, 130 | "haskelly.buttons.stackRun": { 131 | "type": "boolean", 132 | "default": true, 133 | "description": "Show the Stack run button." 134 | }, 135 | "haskelly.buttons.stackRunParams": { 136 | "type": "string", 137 | "default": "", 138 | "description": "Additional parameters passed to stack run command." 139 | }, 140 | "haskelly.buttons.stackBuild": { 141 | "type": "boolean", 142 | "default": true, 143 | "description": "Show the Stack build button." 144 | }, 145 | "haskelly.buttons.stackBuildParams": { 146 | "type": "string", 147 | "default": "--fast", 148 | "description": "Additional parameters passed to stack build command." 149 | }, 150 | "haskelly.buttons.stackTest": { 151 | "type": "boolean", 152 | "default": true, 153 | "description": "Show the Stack test button." 154 | }, 155 | "haskelly.buttons.stackTestParams": { 156 | "type": "string", 157 | "default": "", 158 | "description": "Additional parameters passed to stack test command." 159 | }, 160 | "haskelly.exec.reuseTerminal": { 161 | "type": "boolean", 162 | "default": false, 163 | "description": "Haskelly will reuse the currently opened terminal to run Stack commands." 164 | }, 165 | "haskelly.snippets.important": { 166 | "type": "boolean", 167 | "default": false, 168 | "description": "Hide code completion suggestion if there's a snippet." 169 | }, 170 | "haskelly.snippets.custom": { 171 | "type": "object", 172 | "default": {}, 173 | "description": "Add your custom snippets following the appropiate syntax." 174 | } 175 | } 176 | } 177 | }, 178 | "scripts": { 179 | "vscode:prepublish": "tsc -p ./", 180 | "compile": "tsc -watch -p ./", 181 | "postinstall": "node ./node_modules/vscode/bin/install", 182 | "test": "node ./node_modules/vscode/bin/test" 183 | }, 184 | "devDependencies": { 185 | "@types/mocha": "^2.2.48", 186 | "@types/node": "^6.0.109", 187 | "mocha": "^2.3.3", 188 | "typescript": "^2.8.3", 189 | "vscode": "^1.1.17" 190 | }, 191 | "extensionDependencies": [ 192 | "justusadam.language-haskell" 193 | ], 194 | "dependencies": { 195 | "stream-splitter": "^0.3.2", 196 | "uuid": "^3.2.1" 197 | } 198 | } 199 | -------------------------------------------------------------------------------- /src/Basic/commands.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | 3 | import { testHaskellFile } from '../helpers/testCode'; 4 | import { getWorkDir } from '../utils/workDir' 5 | 6 | const fs = require('fs'); 7 | const path = require('path'); 8 | const uuidV4 = require('uuid/v4'); 9 | 10 | let reuseTerminal = vscode.workspace.getConfiguration('haskelly')['exec']['reuseTerminal']; 11 | let commandsParams = vscode.workspace.getConfiguration('haskelly')['buttons']; 12 | 13 | let terminal : vscode.Terminal; 14 | 15 | function getTerminal(name) { 16 | if (reuseTerminal) { 17 | if (terminal) { 18 | terminal.dispose(); 19 | } 20 | 21 | terminal = vscode.window.createTerminal(name); 22 | 23 | return terminal; 24 | } else { 25 | return vscode.window.createTerminal(name); 26 | } 27 | } 28 | 29 | 30 | /* GHCi */ 31 | function loadGHCi(extPath, src) { 32 | const term = getTerminal('Haskell GHCi'); 33 | const folder = path.dirname(src); 34 | const file = path.basename(src); 35 | term.sendText(`cd "${folder}"`); 36 | term.show(); 37 | term.sendText(`stack ghci --ghci-options ${file}`); 38 | } 39 | 40 | /* Run Haskell */ 41 | function runHaskell(extPath, src) { 42 | const term = getTerminal('Haskell Run'); 43 | term.show(); 44 | term.sendText(`stack runhaskell "${src}"`); 45 | } 46 | 47 | /* Stack Build */ 48 | function stackBuild(stackWd) { 49 | const term = getTerminal('Stack Build'); 50 | term.sendText(`cd "${stackWd}"`); 51 | term.sendText(`stack build ${commandsParams.stackBuildParams || ""}`); 52 | term.show(); 53 | } 54 | 55 | /* Stack Run */ 56 | function stackRun(stackWd) { 57 | const term = getTerminal('Stack Run'); 58 | term.sendText(`cd "${stackWd}"`); 59 | term.sendText(`stack run ${commandsParams.stackRunParams || ""}`); 60 | term.show(); 61 | } 62 | 63 | /* Stack test */ 64 | function stackTest(stackWd) { 65 | const term = getTerminal('Stack Run'); 66 | term.sendText(`cd "${stackWd}"`); 67 | term.sendText(`stack test ${commandsParams.stackTestParams || ""}`); 68 | term.show(); 69 | } 70 | 71 | /* QuickCheck */ 72 | function showTestError(error, extPath) { 73 | vscode.window.showErrorMessage('VS Code can\'t execute this file. Check the terminal.'); 74 | 75 | let errorFilePath = `${extPath}/${uuidV4()}.txt`; 76 | fs.writeFile(errorFilePath, '-------- Error --------\n' + error + '------------------------', 'utf-8', err => { 77 | const term = vscode.window.createTerminal('Haskell Tests'); 78 | 79 | // Windows 80 | if (/^win/.test(process.platform)) { 81 | errorFilePath = errorFilePath.replace(/\//g, "\\"); 82 | term.sendText(`type ${errorFilePath}`); 83 | } else { 84 | term.sendText(`cat ${errorFilePath}`); 85 | } 86 | 87 | term.show(); 88 | setTimeout(() => fs.unlinkSync(errorFilePath), 3000); 89 | }); 90 | } 91 | 92 | function showTestOutput(passed, failed) { 93 | if (failed.length > 0) { 94 | if (failed.length === 1) { 95 | vscode.window.showErrorMessage(`${failed[0].name} test failed!`); 96 | } else { 97 | vscode.window.showErrorMessage(`${failed.length} tests failed!`); 98 | } 99 | } else if (passed.length > 0) { 100 | vscode.window.showInformationMessage('All tests passed!'); 101 | } else { 102 | vscode.window.showErrorMessage('No tests were found!'); 103 | } 104 | } 105 | 106 | function testHaskell(extPath, src, stackWd) { 107 | let counter = -1; 108 | let doneTesting = false; 109 | const loader = () => { 110 | counter = (counter + 1) % 4; 111 | const sign = ['|', '/', '-', '\\'][counter]; 112 | 113 | if (!doneTesting) setTimeout(loader, 200); 114 | 115 | const text = stackWd ? 'Stack test' : 'QuickCheck'; 116 | vscode.window.setStatusBarMessage(`${sign} Running ${text}`, 200); 117 | } 118 | 119 | loader(); 120 | 121 | testHaskellFile(src, stackWd).then(testResults => { 122 | doneTesting = true; 123 | showTestOutput(testResults['passedTests'], testResults['failedTests']); 124 | }).catch(error => { 125 | doneTesting = true; 126 | showTestError(error, extPath); 127 | }); 128 | } 129 | 130 | export default function initCommands(context: vscode.ExtensionContext) { 131 | const documentPath = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri.fsPath 132 | : vscode.workspace.textDocuments[0].uri.fsPath; 133 | let stackWd = getWorkDir(documentPath)["cwd"]; 134 | let isStack = stackWd !== undefined; 135 | 136 | vscode.window.onDidChangeActiveTextEditor((editor: vscode.TextEditor) => { 137 | if (editor) { 138 | stackWd = getWorkDir(editor.document.uri.fsPath)["cwd"]; 139 | isStack = stackWd !== undefined; 140 | } 141 | }); 142 | 143 | /* Register Commands */ 144 | context.subscriptions.push(vscode.commands.registerTextEditorCommand('editor.ghci', editor => { 145 | editor.document.save() 146 | .then(() => { 147 | vscode.window.setStatusBarMessage('Loading module in GHCi...', 1000); 148 | loadGHCi(context.extensionPath, editor.document.uri.fsPath); 149 | }); 150 | })); 151 | 152 | context.subscriptions.push(vscode.commands.registerTextEditorCommand('editor.runHaskell', editor => { 153 | editor.document.save() 154 | .then(() => { 155 | if (isStack) { 156 | vscode.window.showErrorMessage('Not supported inside a Stack project.'); 157 | } else { 158 | vscode.window.setStatusBarMessage('Running your code...', 1000); 159 | runHaskell(context.extensionPath, editor.document.uri.fsPath); 160 | } 161 | }); 162 | })); 163 | 164 | context.subscriptions.push(vscode.commands.registerTextEditorCommand('editor.runQuickCheck', editor => { 165 | editor.document.save() 166 | .then(() => { 167 | if (isStack) { 168 | vscode.window.showErrorMessage('Not supported inside a Stack project.'); 169 | } else { 170 | testHaskell(context.extensionPath, editor.document.uri.fsPath, undefined); 171 | } 172 | }); 173 | })); 174 | 175 | context.subscriptions.push(vscode.commands.registerTextEditorCommand('editor.stackBuild', editor => { 176 | editor.document.save() 177 | .then(() => { 178 | if (isStack) { 179 | stackBuild(stackWd); 180 | } else { 181 | vscode.window.showErrorMessage('No Stack project was found.'); 182 | } 183 | }); 184 | })); 185 | 186 | context.subscriptions.push(vscode.commands.registerTextEditorCommand('editor.stackRun', editor => { 187 | editor.document.save() 188 | .then(() => { 189 | if (isStack) { 190 | stackRun(stackWd); 191 | } else { 192 | vscode.window.showErrorMessage('No Stack project was found.'); 193 | } 194 | }); 195 | })); 196 | 197 | context.subscriptions.push(vscode.commands.registerTextEditorCommand('editor.stackTest', editor => { 198 | editor.document.save() 199 | .then(() => { 200 | if (isStack) { 201 | stackTest(stackWd); 202 | } else { 203 | vscode.window.showErrorMessage('No Stack project was found.'); 204 | } 205 | }); 206 | })); 207 | } -------------------------------------------------------------------------------- /src/Providers/InteroSpawn.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import SyncSpawn from '../utils/syncSpawn'; 3 | import InitIntero from './InitIntero'; 4 | 5 | import { getWorkDir } from '../utils/workDir' 6 | import { normalizePath } from '../utils/document'; 7 | import { WordInfo } from '../utils/other'; 8 | import { delay } from '../utils/promise'; 9 | const StreamSplitter = require('stream-splitter'); 10 | 11 | export default class InteroSpawn { 12 | private static _instance: InteroSpawn = new InteroSpawn(); 13 | 14 | private shell; 15 | private requestingCompletion; 16 | private requestingType; 17 | private interoOutput: String; 18 | private openedDocument: String; 19 | private loading: boolean; 20 | 21 | private constructor() { 22 | if (InteroSpawn._instance) { 23 | throw new Error("Error: Instantiation failed: Use SingletonClass.getInstance() instead of new."); 24 | } 25 | InteroSpawn._instance = this; 26 | this.listenChanges(); 27 | } 28 | 29 | public static getInstance(): InteroSpawn { 30 | return InteroSpawn._instance; 31 | } 32 | 33 | /** 34 | * Initialize Spawn process with Stack and Intero 35 | */ 36 | public tryNewIntero(documentPath: String) { 37 | return new Promise((resolve, reject) => { 38 | // Load GHCi in temp shell 39 | const filePath = normalizePath(documentPath); 40 | const workDir = getWorkDir(filePath); 41 | const isStack = workDir["cwd"] !== undefined; 42 | 43 | console.log(`Trying new Intero for document ${filePath} and workDir ${workDir["cwd"]}`); 44 | this.loadIntero(isStack, workDir, filePath) 45 | .then(result => { 46 | console.log('Intero loaded correctly'); 47 | resolve(); 48 | }) 49 | .catch(error => { 50 | console.log('Intero failed to load'); 51 | reject(error); 52 | }) 53 | .then(() => { 54 | this.loading = false; 55 | }); 56 | }); 57 | } 58 | 59 | public loadIntero(isStack: boolean, workDir: Object, documentPath: String) { 60 | return new Promise((resolve, reject) => { 61 | let stackLoaded; 62 | 63 | if (!this.loading) { 64 | this.loading = true; 65 | const intero = new InitIntero(['stack', 'ghci', '--with-ghc', 'intero'], workDir, isStack, (failed) => { 66 | if (!stackLoaded) { 67 | if (failed) { 68 | intero.killProcess(); 69 | reject(); 70 | } else if (isStack) { 71 | stackLoaded = true; 72 | this.killCurrentShell(); 73 | this.openedDocument = workDir["cwd"]; 74 | this.shell = intero.getShell(); 75 | this.shellOutput(); 76 | resolve(); 77 | } else { 78 | stackLoaded = true; 79 | let fileLoaded = false; 80 | 81 | intero.runCommand(`:l "${this.normaliseFilePath(documentPath)}"`, (error) => { 82 | if (!fileLoaded) { 83 | fileLoaded = true; 84 | 85 | if (error) { 86 | intero.killProcess(); 87 | reject(); 88 | return; 89 | } else { 90 | this.killCurrentShell(); 91 | this.openedDocument = documentPath; 92 | this.shell = intero.getShell(); 93 | this.shellOutput(); 94 | resolve(); 95 | return; 96 | } 97 | } 98 | }); 99 | } 100 | } 101 | }); 102 | } 103 | }); 104 | } 105 | 106 | private listenChanges() { 107 | const reload = (document: vscode.TextDocument) => { 108 | this.tryNewIntero(document.uri.fsPath) 109 | .catch(e => console.error(e)); 110 | } 111 | 112 | vscode.workspace.onDidSaveTextDocument((document) => { 113 | if (document.languageId == 'haskell') { 114 | reload(document); 115 | } 116 | }); 117 | 118 | vscode.window.onDidChangeActiveTextEditor((editor: vscode.TextEditor) => { 119 | if (editor && editor.document.languageId === 'haskell') { 120 | const stackDir = getWorkDir(editor.document.uri.fsPath)["cwd"]; 121 | 122 | // Avoid reload if opened document from same Stack project 123 | if (stackDir && (this.openedDocument !== stackDir)) { 124 | this.openedDocument = stackDir; 125 | reload(editor.document); 126 | } else if (!stackDir && (this.openedDocument !== editor.document.uri.fsPath)) { 127 | this.openedDocument = editor.document.uri.fsPath; 128 | reload(editor.document); 129 | } 130 | } 131 | }); 132 | } 133 | 134 | public killCurrentShell() { 135 | if (this.shell) { 136 | this.shell.stdin.pause(); 137 | this.shell.kill(); 138 | } 139 | 140 | return Promise.resolve(); 141 | } 142 | 143 | /** 144 | * Intero requests 145 | */ 146 | public requestCompletions(filePath: String, position: vscode.Position, word: String) { 147 | return new Promise((resolve, reject) => { 148 | if (this.shell && !this.loading) { 149 | this.requestingCompletion = true; 150 | 151 | this.shell.stdin.write(`:complete-at "${this.normaliseFilePath(filePath)}" ${position.line} ${position.character} ${position.line} ${position.character} "${word}"\n`); 152 | 153 | if (this.interoOutput) { 154 | setTimeout(() => { 155 | const suggestions = this.interoOutput.split('\n'); 156 | const completionItems:Array = []; 157 | suggestions.forEach(suggestion => { 158 | if (suggestion) { 159 | completionItems.push(new vscode.CompletionItem(suggestion.trim().replace(/\s+/g, ' '))); 160 | } 161 | }); 162 | resolve(completionItems); 163 | }, 35); 164 | } else { 165 | resolve([]); 166 | } 167 | } 168 | }); 169 | } 170 | 171 | public async requestType(filePath: string, position: vscode.Position, wordInfo: WordInfo): Promise { 172 | try { 173 | const command = this.buildCommand('type-at', filePath, position, wordInfo); 174 | const output = await this.executeCommandOnIntero(command); 175 | return new vscode.Hover({language: 'haskell', value: output}); 176 | } catch (e) { 177 | return new vscode.Hover('Type not available.'); 178 | } 179 | } 180 | 181 | public requestDefinition(filePath: string, position: vscode.Position, wordInfo: WordInfo): Promise { 182 | const command = this.buildCommand('loc-at', filePath, position, wordInfo); 183 | return this.executeCommandOnIntero(command); 184 | } 185 | 186 | public requestReferences(filePath: string, position: vscode.Position, wordInfo: WordInfo): Promise { 187 | const command = this.buildCommand('uses', filePath, position, wordInfo); 188 | return this.executeCommandOnIntero(command); 189 | } 190 | 191 | private buildCommand(commandSign: string, filePath: string, position: vscode.Position, wordInfo: WordInfo): string { 192 | const word = wordInfo['word']; 193 | const start = wordInfo['start']; 194 | const end = wordInfo['end']; 195 | return `:${commandSign} "${this.normaliseFilePath(filePath)}" ${position.line + 1} ${start + 1} ${position.line + 1} ${end + 1} "${word}"`; 196 | } 197 | 198 | private normaliseFilePath(filePath: String): string { 199 | return filePath.replace(/\\/g, "\\\\"); 200 | } 201 | 202 | private async executeCommandOnIntero(command: string): Promise { 203 | if (!this.shell || this.loading) return ''; 204 | 205 | this.interoOutput = undefined; 206 | this.shell.stdin.write(`${command}\n`); 207 | 208 | await delay(50); 209 | 210 | if (this.interoOutput !== ' ' && this.interoOutput !== undefined) { 211 | return this.interoOutput.trim().replace(/\s+/g, ' '); 212 | } else { 213 | throw new Error('Command output not available'); 214 | } 215 | } 216 | 217 | /** 218 | * Intero output parser 219 | */ 220 | private shellOutput() { 221 | const splitter = this.shell.stdout.pipe(StreamSplitter("lambda>")); 222 | splitter.encoding = 'utf8'; 223 | 224 | splitter.on('token', (token) => { 225 | this.interoOutput = token; 226 | }); 227 | 228 | splitter.on('done', () => { 229 | console.log("Intero spawn terminated.") 230 | }); 231 | 232 | splitter.on('error', (e) => { 233 | console.log("error: ", e) 234 | }); 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /License.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------